@firebase/firestore 3.4.7-canary.e9e5f6b3c → 3.4.8-canary.7b58dabdf

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 (57) hide show
  1. package/CHANGELOG.md +10 -0
  2. package/dist/firestore/src/core/target.d.ts +2 -0
  3. package/dist/firestore/src/local/index_manager.d.ts +19 -3
  4. package/dist/firestore/src/local/indexeddb_index_manager.d.ts +3 -2
  5. package/dist/firestore/src/local/indexeddb_remote_document_cache.d.ts +9 -0
  6. package/dist/firestore/src/local/memory_index_manager.d.ts +2 -2
  7. package/dist/firestore/src/local/simple_db.d.ts +2 -0
  8. package/dist/firestore/test/unit/local/test_index_manager.d.ts +2 -2
  9. package/dist/firestore/test/unit/local/test_remote_document_cache.d.ts +0 -4
  10. package/dist/index.esm2017.js +2998 -2965
  11. package/dist/index.esm2017.js.map +1 -1
  12. package/dist/index.esm5.js +3303 -3272
  13. package/dist/index.esm5.js.map +1 -1
  14. package/dist/index.node.cjs.js +1575 -1508
  15. package/dist/index.node.cjs.js.map +1 -1
  16. package/dist/index.node.mjs +1575 -1508
  17. package/dist/index.node.mjs.map +1 -1
  18. package/dist/index.rn.js +3138 -3105
  19. package/dist/index.rn.js.map +1 -1
  20. package/dist/internal.d.ts +20 -3
  21. package/dist/lite/firestore/src/core/target.d.ts +2 -0
  22. package/dist/lite/firestore/src/local/index_manager.d.ts +19 -3
  23. package/dist/lite/firestore/src/local/indexeddb_index_manager.d.ts +3 -2
  24. package/dist/lite/firestore/src/local/indexeddb_remote_document_cache.d.ts +9 -0
  25. package/dist/lite/firestore/src/local/memory_index_manager.d.ts +2 -2
  26. package/dist/lite/firestore/src/local/simple_db.d.ts +2 -0
  27. package/dist/lite/firestore/test/unit/local/test_index_manager.d.ts +2 -2
  28. package/dist/lite/firestore/test/unit/local/test_remote_document_cache.d.ts +0 -4
  29. package/dist/lite/index.browser.esm2017.js +2 -2
  30. package/dist/lite/index.browser.esm2017.js.map +1 -1
  31. package/dist/lite/index.browser.esm5.js +2 -2
  32. package/dist/lite/index.browser.esm5.js.map +1 -1
  33. package/dist/lite/index.node.cjs.js +2 -2
  34. package/dist/lite/index.node.cjs.js.map +1 -1
  35. package/dist/lite/index.node.mjs +2 -2
  36. package/dist/lite/index.node.mjs.map +1 -1
  37. package/dist/lite/index.rn.esm2017.js +1143 -1143
  38. package/dist/lite/index.rn.esm2017.js.map +1 -1
  39. package/dist/lite/packages/firestore/src/core/target.d.ts +2 -0
  40. package/dist/lite/packages/firestore/src/local/index_manager.d.ts +19 -3
  41. package/dist/lite/packages/firestore/src/local/indexeddb_index_manager.d.ts +3 -2
  42. package/dist/lite/packages/firestore/src/local/indexeddb_remote_document_cache.d.ts +9 -0
  43. package/dist/lite/packages/firestore/src/local/memory_index_manager.d.ts +2 -2
  44. package/dist/lite/packages/firestore/src/local/simple_db.d.ts +2 -0
  45. package/dist/lite/packages/firestore/test/unit/local/test_index_manager.d.ts +2 -2
  46. package/dist/lite/packages/firestore/test/unit/local/test_remote_document_cache.d.ts +0 -4
  47. package/dist/packages/firestore/dist/index.esm2017.d.ts +53 -53
  48. package/dist/packages/firestore/src/core/target.d.ts +2 -0
  49. package/dist/packages/firestore/src/local/index_manager.d.ts +19 -3
  50. package/dist/packages/firestore/src/local/indexeddb_index_manager.d.ts +3 -2
  51. package/dist/packages/firestore/src/local/indexeddb_remote_document_cache.d.ts +9 -0
  52. package/dist/packages/firestore/src/local/memory_index_manager.d.ts +2 -2
  53. package/dist/packages/firestore/src/local/simple_db.d.ts +2 -0
  54. package/dist/packages/firestore/test/unit/local/test_index_manager.d.ts +2 -2
  55. package/dist/packages/firestore/test/unit/local/test_remote_document_cache.d.ts +0 -4
  56. package/dist/private.d.ts +20 -3
  57. package/package.json +9 -9
@@ -33,7 +33,7 @@ var grpc__namespace = /*#__PURE__*/_interopNamespace(grpc);
33
33
  var protoLoader__namespace = /*#__PURE__*/_interopNamespace(protoLoader);
34
34
 
35
35
  const name = "@firebase/firestore";
36
- const version$1 = "3.4.7-canary.e9e5f6b3c";
36
+ const version$1 = "3.4.8-canary.7b58dabdf";
37
37
 
38
38
  /**
39
39
  * @license
@@ -86,7 +86,7 @@ User.GOOGLE_CREDENTIALS = new User('google-credentials-uid');
86
86
  User.FIRST_PARTY = new User('first-party-uid');
87
87
  User.MOCK_USER = new User('mock-user');
88
88
 
89
- const version = "9.6.10-canary.e9e5f6b3c";
89
+ const version = "9.6.11-canary.7b58dabdf";
90
90
 
91
91
  /**
92
92
  * @license
@@ -2311,9 +2311,7 @@ class SimpleDbStore {
2311
2311
  cursor.continue(controller.skipToKey);
2312
2312
  }
2313
2313
  };
2314
- }).next(() => {
2315
- return PersistencePromise.waitFor(results);
2316
- });
2314
+ }).next(() => PersistencePromise.waitFor(results));
2317
2315
  }
2318
2316
  options(indexOrRange, range) {
2319
2317
  let indexName = undefined;
@@ -4337,7 +4335,7 @@ function indexOffsetComparator(left, right) {
4337
4335
 
4338
4336
  /**
4339
4337
  * @license
4340
- * Copyright 2019 Google LLC
4338
+ * Copyright 2017 Google LLC
4341
4339
  *
4342
4340
  * Licensed under the Apache License, Version 2.0 (the "License");
4343
4341
  * you may not use this file except in compliance with the License.
@@ -4351,609 +4349,445 @@ function indexOffsetComparator(left, right) {
4351
4349
  * See the License for the specific language governing permissions and
4352
4350
  * limitations under the License.
4353
4351
  */
4354
- // Visible for testing
4355
- class TargetImpl {
4356
- constructor(path, collectionGroup = null, orderBy = [], filters = [], limit = null, startAt = null, endAt = null) {
4357
- this.path = path;
4358
- this.collectionGroup = collectionGroup;
4359
- this.orderBy = orderBy;
4360
- this.filters = filters;
4361
- this.limit = limit;
4362
- this.startAt = startAt;
4363
- this.endAt = endAt;
4364
- this.memoizedCanonicalId = null;
4352
+ // An immutable sorted map implementation, based on a Left-leaning Red-Black
4353
+ // tree.
4354
+ class SortedMap {
4355
+ constructor(comparator, root) {
4356
+ this.comparator = comparator;
4357
+ this.root = root ? root : LLRBNode.EMPTY;
4365
4358
  }
4366
- }
4367
- /**
4368
- * Initializes a Target with a path and optional additional query constraints.
4369
- * Path must currently be empty if this is a collection group query.
4370
- *
4371
- * NOTE: you should always construct `Target` from `Query.toTarget` instead of
4372
- * using this factory method, because `Query` provides an implicit `orderBy`
4373
- * property.
4374
- */
4375
- function newTarget(path, collectionGroup = null, orderBy = [], filters = [], limit = null, startAt = null, endAt = null) {
4376
- return new TargetImpl(path, collectionGroup, orderBy, filters, limit, startAt, endAt);
4377
- }
4378
- function canonifyTarget(target) {
4379
- const targetImpl = debugCast(target);
4380
- if (targetImpl.memoizedCanonicalId === null) {
4381
- let str = targetImpl.path.canonicalString();
4382
- if (targetImpl.collectionGroup !== null) {
4383
- str += '|cg:' + targetImpl.collectionGroup;
4384
- }
4385
- str += '|f:';
4386
- str += targetImpl.filters.map(f => canonifyFilter(f)).join(',');
4387
- str += '|ob:';
4388
- str += targetImpl.orderBy.map(o => canonifyOrderBy(o)).join(',');
4389
- if (!isNullOrUndefined(targetImpl.limit)) {
4390
- str += '|l:';
4391
- str += targetImpl.limit;
4392
- }
4393
- if (targetImpl.startAt) {
4394
- str += '|lb:';
4395
- str += targetImpl.startAt.inclusive ? 'b:' : 'a:';
4396
- str += targetImpl.startAt.position.map(p => canonicalId(p)).join(',');
4397
- }
4398
- if (targetImpl.endAt) {
4399
- str += '|ub:';
4400
- str += targetImpl.endAt.inclusive ? 'a:' : 'b:';
4401
- str += targetImpl.endAt.position.map(p => canonicalId(p)).join(',');
4402
- }
4403
- targetImpl.memoizedCanonicalId = str;
4359
+ // Returns a copy of the map, with the specified key/value added or replaced.
4360
+ insert(key, value) {
4361
+ return new SortedMap(this.comparator, this.root
4362
+ .insert(key, value, this.comparator)
4363
+ .copy(null, null, LLRBNode.BLACK, null, null));
4404
4364
  }
4405
- return targetImpl.memoizedCanonicalId;
4406
- }
4407
- function stringifyTarget(target) {
4408
- let str = target.path.canonicalString();
4409
- if (target.collectionGroup !== null) {
4410
- str += ' collectionGroup=' + target.collectionGroup;
4365
+ // Returns a copy of the map, with the specified key removed.
4366
+ remove(key) {
4367
+ return new SortedMap(this.comparator, this.root
4368
+ .remove(key, this.comparator)
4369
+ .copy(null, null, LLRBNode.BLACK, null, null));
4411
4370
  }
4412
- if (target.filters.length > 0) {
4413
- str += `, filters: [${target.filters
4414
- .map(f => stringifyFilter(f))
4415
- .join(', ')}]`;
4371
+ // Returns the value of the node with the given key, or null.
4372
+ get(key) {
4373
+ let node = this.root;
4374
+ while (!node.isEmpty()) {
4375
+ const cmp = this.comparator(key, node.key);
4376
+ if (cmp === 0) {
4377
+ return node.value;
4378
+ }
4379
+ else if (cmp < 0) {
4380
+ node = node.left;
4381
+ }
4382
+ else if (cmp > 0) {
4383
+ node = node.right;
4384
+ }
4385
+ }
4386
+ return null;
4416
4387
  }
4417
- if (!isNullOrUndefined(target.limit)) {
4418
- str += ', limit: ' + target.limit;
4388
+ // Returns the index of the element in this sorted map, or -1 if it doesn't
4389
+ // exist.
4390
+ indexOf(key) {
4391
+ // Number of nodes that were pruned when descending right
4392
+ let prunedNodes = 0;
4393
+ let node = this.root;
4394
+ while (!node.isEmpty()) {
4395
+ const cmp = this.comparator(key, node.key);
4396
+ if (cmp === 0) {
4397
+ return prunedNodes + node.left.size;
4398
+ }
4399
+ else if (cmp < 0) {
4400
+ node = node.left;
4401
+ }
4402
+ else {
4403
+ // Count all nodes left of the node plus the node itself
4404
+ prunedNodes += node.left.size + 1;
4405
+ node = node.right;
4406
+ }
4407
+ }
4408
+ // Node not found
4409
+ return -1;
4419
4410
  }
4420
- if (target.orderBy.length > 0) {
4421
- str += `, orderBy: [${target.orderBy
4422
- .map(o => stringifyOrderBy(o))
4423
- .join(', ')}]`;
4411
+ isEmpty() {
4412
+ return this.root.isEmpty();
4424
4413
  }
4425
- if (target.startAt) {
4426
- str += ', startAt: ';
4427
- str += target.startAt.inclusive ? 'b:' : 'a:';
4428
- str += target.startAt.position.map(p => canonicalId(p)).join(',');
4414
+ // Returns the total number of nodes in the map.
4415
+ get size() {
4416
+ return this.root.size;
4429
4417
  }
4430
- if (target.endAt) {
4431
- str += ', endAt: ';
4432
- str += target.endAt.inclusive ? 'a:' : 'b:';
4433
- str += target.endAt.position.map(p => canonicalId(p)).join(',');
4418
+ // Returns the minimum key in the map.
4419
+ minKey() {
4420
+ return this.root.minKey();
4434
4421
  }
4435
- return `Target(${str})`;
4436
- }
4437
- function targetEquals(left, right) {
4438
- if (left.limit !== right.limit) {
4439
- return false;
4422
+ // Returns the maximum key in the map.
4423
+ maxKey() {
4424
+ return this.root.maxKey();
4440
4425
  }
4441
- if (left.orderBy.length !== right.orderBy.length) {
4442
- return false;
4426
+ // Traverses the map in key order and calls the specified action function
4427
+ // for each key/value pair. If action returns true, traversal is aborted.
4428
+ // Returns the first truthy value returned by action, or the last falsey
4429
+ // value returned by action.
4430
+ inorderTraversal(action) {
4431
+ return this.root.inorderTraversal(action);
4443
4432
  }
4444
- for (let i = 0; i < left.orderBy.length; i++) {
4445
- if (!orderByEquals(left.orderBy[i], right.orderBy[i])) {
4433
+ forEach(fn) {
4434
+ this.inorderTraversal((k, v) => {
4435
+ fn(k, v);
4446
4436
  return false;
4447
- }
4448
- }
4449
- if (left.filters.length !== right.filters.length) {
4450
- return false;
4437
+ });
4451
4438
  }
4452
- for (let i = 0; i < left.filters.length; i++) {
4453
- if (!filterEquals(left.filters[i], right.filters[i])) {
4439
+ toString() {
4440
+ const descriptions = [];
4441
+ this.inorderTraversal((k, v) => {
4442
+ descriptions.push(`${k}:${v}`);
4454
4443
  return false;
4455
- }
4456
- }
4457
- if (left.collectionGroup !== right.collectionGroup) {
4458
- return false;
4444
+ });
4445
+ return `{${descriptions.join(', ')}}`;
4459
4446
  }
4460
- if (!left.path.isEqual(right.path)) {
4461
- return false;
4447
+ // Traverses the map in reverse key order and calls the specified action
4448
+ // function for each key/value pair. If action returns true, traversal is
4449
+ // aborted.
4450
+ // Returns the first truthy value returned by action, or the last falsey
4451
+ // value returned by action.
4452
+ reverseTraversal(action) {
4453
+ return this.root.reverseTraversal(action);
4462
4454
  }
4463
- if (!boundEquals(left.startAt, right.startAt)) {
4464
- return false;
4455
+ // Returns an iterator over the SortedMap.
4456
+ getIterator() {
4457
+ return new SortedMapIterator(this.root, null, this.comparator, false);
4465
4458
  }
4466
- return boundEquals(left.endAt, right.endAt);
4467
- }
4468
- function targetIsDocumentTarget(target) {
4469
- return (DocumentKey.isDocumentKey(target.path) &&
4470
- target.collectionGroup === null &&
4471
- target.filters.length === 0);
4472
- }
4473
- /** Returns the field filters that target the given field path. */
4474
- function targetGetFieldFiltersForPath(target, path) {
4475
- return target.filters.filter(f => f instanceof FieldFilter && f.field.isEqual(path));
4476
- }
4477
- /**
4478
- * Returns the values that are used in ARRAY_CONTAINS or ARRAY_CONTAINS_ANY
4479
- * filters. Returns `null` if there are no such filters.
4480
- */
4481
- function targetGetArrayValues(target, fieldIndex) {
4482
- const segment = fieldIndexGetArraySegment(fieldIndex);
4483
- if (segment === undefined) {
4484
- return null;
4459
+ getIteratorFrom(key) {
4460
+ return new SortedMapIterator(this.root, key, this.comparator, false);
4485
4461
  }
4486
- for (const fieldFilter of targetGetFieldFiltersForPath(target, segment.fieldPath)) {
4487
- switch (fieldFilter.op) {
4488
- case "array-contains-any" /* ARRAY_CONTAINS_ANY */:
4489
- return fieldFilter.value.arrayValue.values || [];
4490
- case "array-contains" /* ARRAY_CONTAINS */:
4491
- return [fieldFilter.value];
4492
- // Remaining filters are not array filters.
4493
- }
4462
+ getReverseIterator() {
4463
+ return new SortedMapIterator(this.root, null, this.comparator, true);
4494
4464
  }
4495
- return null;
4496
- }
4497
- /**
4498
- * Returns the list of values that are used in != or NOT_IN filters. Returns
4499
- * `null` if there are no such filters.
4500
- */
4501
- function targetGetNotInValues(target, fieldIndex) {
4502
- const values = new Map();
4503
- for (const segment of fieldIndexGetDirectionalSegments(fieldIndex)) {
4504
- for (const fieldFilter of targetGetFieldFiltersForPath(target, segment.fieldPath)) {
4505
- switch (fieldFilter.op) {
4506
- case "==" /* EQUAL */:
4507
- case "in" /* IN */:
4508
- // Encode equality prefix, which is encoded in the index value before
4509
- // the inequality (e.g. `a == 'a' && b != 'b'` is encoded to
4510
- // `value != 'ab'`).
4511
- values.set(segment.fieldPath.canonicalString(), fieldFilter.value);
4512
- break;
4513
- case "not-in" /* NOT_IN */:
4514
- case "!=" /* NOT_EQUAL */:
4515
- // NotIn/NotEqual is always a suffix. There cannot be any remaining
4516
- // segments and hence we can return early here.
4517
- values.set(segment.fieldPath.canonicalString(), fieldFilter.value);
4518
- return Array.from(values.values());
4519
- // Remaining filters cannot be used as notIn bounds.
4520
- }
4521
- }
4465
+ getReverseIteratorFrom(key) {
4466
+ return new SortedMapIterator(this.root, key, this.comparator, true);
4522
4467
  }
4523
- return null;
4524
- }
4525
- /**
4526
- * Returns a lower bound of field values that can be used as a starting point to
4527
- * scan the index defined by `fieldIndex`. Returns `null` if no lower bound
4528
- * exists.
4529
- */
4530
- function targetGetLowerBound(target, fieldIndex) {
4531
- const values = [];
4532
- let inclusive = true;
4533
- // For each segment, retrieve a lower bound if there is a suitable filter or
4534
- // startAt.
4535
- for (const segment of fieldIndexGetDirectionalSegments(fieldIndex)) {
4536
- const segmentBound = segment.kind === 0 /* ASCENDING */
4537
- ? targetGetLowerBoundForField(target, segment.fieldPath, target.startAt)
4538
- : targetGetUpperBoundForField(target, segment.fieldPath, target.startAt);
4539
- if (!segmentBound.value) {
4540
- // No lower bound exists
4541
- return null;
4542
- }
4543
- values.push(segmentBound.value);
4544
- inclusive && (inclusive = segmentBound.inclusive);
4545
- }
4546
- return new Bound(values, inclusive);
4547
- }
4548
- /**
4549
- * Returns an upper bound of field values that can be used as an ending point
4550
- * when scanning the index defined by `fieldIndex`. Returns `null` if no
4551
- * upper bound exists.
4552
- */
4553
- function targetGetUpperBound(target, fieldIndex) {
4554
- const values = [];
4555
- let inclusive = true;
4556
- // For each segment, retrieve an upper bound if there is a suitable filter or
4557
- // endAt.
4558
- for (const segment of fieldIndexGetDirectionalSegments(fieldIndex)) {
4559
- const segmentBound = segment.kind === 0 /* ASCENDING */
4560
- ? targetGetUpperBoundForField(target, segment.fieldPath, target.endAt)
4561
- : targetGetLowerBoundForField(target, segment.fieldPath, target.endAt);
4562
- if (!segmentBound.value) {
4563
- // No upper bound exists
4564
- return null;
4565
- }
4566
- values.push(segmentBound.value);
4567
- inclusive && (inclusive = segmentBound.inclusive);
4568
- }
4569
- return new Bound(values, inclusive);
4570
- }
4571
- /**
4572
- * Returns the value to use as the lower bound for ascending index segment at
4573
- * the provided `fieldPath` (or the upper bound for an descending segment).
4574
- */
4575
- function targetGetLowerBoundForField(target, fieldPath, bound) {
4576
- let value = undefined;
4577
- let inclusive = true;
4578
- // Process all filters to find a value for the current field segment
4579
- for (const fieldFilter of targetGetFieldFiltersForPath(target, fieldPath)) {
4580
- let filterValue = undefined;
4581
- let filterInclusive = true;
4582
- switch (fieldFilter.op) {
4583
- case "<" /* LESS_THAN */:
4584
- case "<=" /* LESS_THAN_OR_EQUAL */:
4585
- filterValue = valuesGetLowerBound(fieldFilter.value);
4586
- break;
4587
- case "==" /* EQUAL */:
4588
- case "in" /* IN */:
4589
- case ">=" /* GREATER_THAN_OR_EQUAL */:
4590
- filterValue = fieldFilter.value;
4591
- break;
4592
- case ">" /* GREATER_THAN */:
4593
- filterValue = fieldFilter.value;
4594
- filterInclusive = false;
4595
- break;
4596
- case "!=" /* NOT_EQUAL */:
4597
- case "not-in" /* NOT_IN */:
4598
- filterValue = MIN_VALUE;
4599
- break;
4600
- // Remaining filters cannot be used as lower bounds.
4601
- }
4602
- if (valuesMax(value, filterValue) === filterValue) {
4603
- value = filterValue;
4604
- inclusive = filterInclusive;
4605
- }
4606
- }
4607
- // If there is an additional bound, compare the values against the existing
4608
- // range to see if we can narrow the scope.
4609
- if (bound !== null) {
4610
- for (let i = 0; i < target.orderBy.length; ++i) {
4611
- const orderBy = target.orderBy[i];
4612
- if (orderBy.field.isEqual(fieldPath)) {
4613
- const cursorValue = bound.position[i];
4614
- if (valuesMax(value, cursorValue) === cursorValue) {
4615
- value = cursorValue;
4616
- inclusive = bound.inclusive;
4468
+ } // end SortedMap
4469
+ // An iterator over an LLRBNode.
4470
+ class SortedMapIterator {
4471
+ constructor(node, startKey, comparator, isReverse) {
4472
+ this.isReverse = isReverse;
4473
+ this.nodeStack = [];
4474
+ let cmp = 1;
4475
+ while (!node.isEmpty()) {
4476
+ cmp = startKey ? comparator(node.key, startKey) : 1;
4477
+ // flip the comparison if we're going in reverse
4478
+ if (startKey && isReverse) {
4479
+ cmp *= -1;
4480
+ }
4481
+ if (cmp < 0) {
4482
+ // This node is less than our start key. ignore it
4483
+ if (this.isReverse) {
4484
+ node = node.left;
4485
+ }
4486
+ else {
4487
+ node = node.right;
4617
4488
  }
4618
- break;
4619
4489
  }
4620
- }
4621
- }
4622
- return { value, inclusive };
4623
- }
4624
- /**
4625
- * Returns the value to use as the upper bound for ascending index segment at
4626
- * the provided `fieldPath` (or the lower bound for an descending segment).
4627
- */
4628
- function targetGetUpperBoundForField(target, fieldPath, bound) {
4629
- let value = undefined;
4630
- let inclusive = true;
4631
- // Process all filters to find a value for the current field segment
4632
- for (const fieldFilter of targetGetFieldFiltersForPath(target, fieldPath)) {
4633
- let filterValue = undefined;
4634
- let filterInclusive = true;
4635
- switch (fieldFilter.op) {
4636
- case ">=" /* GREATER_THAN_OR_EQUAL */:
4637
- case ">" /* GREATER_THAN */:
4638
- filterValue = valuesGetUpperBound(fieldFilter.value);
4639
- filterInclusive = false;
4640
- break;
4641
- case "==" /* EQUAL */:
4642
- case "in" /* IN */:
4643
- case "<=" /* LESS_THAN_OR_EQUAL */:
4644
- filterValue = fieldFilter.value;
4645
- break;
4646
- case "<" /* LESS_THAN */:
4647
- filterValue = fieldFilter.value;
4648
- filterInclusive = false;
4649
- break;
4650
- case "!=" /* NOT_EQUAL */:
4651
- case "not-in" /* NOT_IN */:
4652
- filterValue = MAX_VALUE;
4490
+ else if (cmp === 0) {
4491
+ // This node is exactly equal to our start key. Push it on the stack,
4492
+ // but stop iterating;
4493
+ this.nodeStack.push(node);
4653
4494
  break;
4654
- // Remaining filters cannot be used as upper bounds.
4655
- }
4656
- if (valuesMin(value, filterValue) === filterValue) {
4657
- value = filterValue;
4658
- inclusive = filterInclusive;
4659
- }
4660
- }
4661
- // If there is an additional bound, compare the values against the existing
4662
- // range to see if we can narrow the scope.
4663
- if (bound !== null) {
4664
- for (let i = 0; i < target.orderBy.length; ++i) {
4665
- const orderBy = target.orderBy[i];
4666
- if (orderBy.field.isEqual(fieldPath)) {
4667
- const cursorValue = bound.position[i];
4668
- if (valuesMin(value, cursorValue) === cursorValue) {
4669
- value = cursorValue;
4670
- inclusive = bound.inclusive;
4495
+ }
4496
+ else {
4497
+ // This node is greater than our start key, add it to the stack and move
4498
+ // to the next one
4499
+ this.nodeStack.push(node);
4500
+ if (this.isReverse) {
4501
+ node = node.right;
4502
+ }
4503
+ else {
4504
+ node = node.left;
4671
4505
  }
4672
- break;
4673
4506
  }
4674
4507
  }
4675
4508
  }
4676
- return { value, inclusive };
4677
- }
4678
- class Filter {
4679
- }
4680
- class FieldFilter extends Filter {
4681
- constructor(field, op, value) {
4682
- super();
4683
- this.field = field;
4684
- this.op = op;
4685
- this.value = value;
4686
- }
4687
- /**
4688
- * Creates a filter based on the provided arguments.
4689
- */
4690
- static create(field, op, value) {
4691
- if (field.isKeyField()) {
4692
- if (op === "in" /* IN */ || op === "not-in" /* NOT_IN */) {
4693
- return this.createKeyFieldInFilter(field, op, value);
4694
- }
4695
- else {
4696
- return new KeyFieldFilter(field, op, value);
4509
+ getNext() {
4510
+ let node = this.nodeStack.pop();
4511
+ const result = { key: node.key, value: node.value };
4512
+ if (this.isReverse) {
4513
+ node = node.left;
4514
+ while (!node.isEmpty()) {
4515
+ this.nodeStack.push(node);
4516
+ node = node.right;
4697
4517
  }
4698
4518
  }
4699
- else if (op === "array-contains" /* ARRAY_CONTAINS */) {
4700
- return new ArrayContainsFilter(field, value);
4701
- }
4702
- else if (op === "in" /* IN */) {
4703
- return new InFilter(field, value);
4704
- }
4705
- else if (op === "not-in" /* NOT_IN */) {
4706
- return new NotInFilter(field, value);
4707
- }
4708
- else if (op === "array-contains-any" /* ARRAY_CONTAINS_ANY */) {
4709
- return new ArrayContainsAnyFilter(field, value);
4710
- }
4711
4519
  else {
4712
- return new FieldFilter(field, op, value);
4520
+ node = node.right;
4521
+ while (!node.isEmpty()) {
4522
+ this.nodeStack.push(node);
4523
+ node = node.left;
4524
+ }
4713
4525
  }
4526
+ return result;
4714
4527
  }
4715
- static createKeyFieldInFilter(field, op, value) {
4716
- return op === "in" /* IN */
4717
- ? new KeyFieldInFilter(field, value)
4718
- : new KeyFieldNotInFilter(field, value);
4719
- }
4720
- matches(doc) {
4721
- const other = doc.data.field(this.field);
4722
- // Types do not have to match in NOT_EQUAL filters.
4723
- if (this.op === "!=" /* NOT_EQUAL */) {
4724
- return (other !== null &&
4725
- this.matchesComparison(valueCompare(other, this.value)));
4726
- }
4727
- // Only compare types with matching backend order (such as double and int).
4728
- return (other !== null &&
4729
- typeOrder(this.value) === typeOrder(other) &&
4730
- this.matchesComparison(valueCompare(other, this.value)));
4528
+ hasNext() {
4529
+ return this.nodeStack.length > 0;
4731
4530
  }
4732
- matchesComparison(comparison) {
4733
- switch (this.op) {
4734
- case "<" /* LESS_THAN */:
4735
- return comparison < 0;
4736
- case "<=" /* LESS_THAN_OR_EQUAL */:
4737
- return comparison <= 0;
4738
- case "==" /* EQUAL */:
4739
- return comparison === 0;
4740
- case "!=" /* NOT_EQUAL */:
4741
- return comparison !== 0;
4742
- case ">" /* GREATER_THAN */:
4743
- return comparison > 0;
4744
- case ">=" /* GREATER_THAN_OR_EQUAL */:
4745
- return comparison >= 0;
4746
- default:
4747
- return fail();
4531
+ peek() {
4532
+ if (this.nodeStack.length === 0) {
4533
+ return null;
4748
4534
  }
4535
+ const node = this.nodeStack[this.nodeStack.length - 1];
4536
+ return { key: node.key, value: node.value };
4749
4537
  }
4750
- isInequality() {
4751
- return ([
4752
- "<" /* LESS_THAN */,
4753
- "<=" /* LESS_THAN_OR_EQUAL */,
4754
- ">" /* GREATER_THAN */,
4755
- ">=" /* GREATER_THAN_OR_EQUAL */,
4756
- "!=" /* NOT_EQUAL */,
4757
- "not-in" /* NOT_IN */
4758
- ].indexOf(this.op) >= 0);
4538
+ } // end SortedMapIterator
4539
+ // Represents a node in a Left-leaning Red-Black tree.
4540
+ class LLRBNode {
4541
+ constructor(key, value, color, left, right) {
4542
+ this.key = key;
4543
+ this.value = value;
4544
+ this.color = color != null ? color : LLRBNode.RED;
4545
+ this.left = left != null ? left : LLRBNode.EMPTY;
4546
+ this.right = right != null ? right : LLRBNode.EMPTY;
4547
+ this.size = this.left.size + 1 + this.right.size;
4759
4548
  }
4760
- }
4761
- function canonifyFilter(filter) {
4762
- // TODO(b/29183165): Technically, this won't be unique if two values have
4763
- // the same description, such as the int 3 and the string "3". So we should
4764
- // add the types in here somehow, too.
4765
- return (filter.field.canonicalString() +
4766
- filter.op.toString() +
4767
- canonicalId(filter.value));
4768
- }
4769
- function filterEquals(f1, f2) {
4770
- return (f1.op === f2.op &&
4771
- f1.field.isEqual(f2.field) &&
4772
- valueEquals(f1.value, f2.value));
4773
- }
4774
- /** Returns a debug description for `filter`. */
4775
- function stringifyFilter(filter) {
4776
- return `${filter.field.canonicalString()} ${filter.op} ${canonicalId(filter.value)}`;
4777
- }
4778
- /** Filter that matches on key fields (i.e. '__name__'). */
4779
- class KeyFieldFilter extends FieldFilter {
4780
- constructor(field, op, value) {
4781
- super(field, op, value);
4782
- this.key = DocumentKey.fromName(value.referenceValue);
4549
+ // Returns a copy of the current node, optionally replacing pieces of it.
4550
+ copy(key, value, color, left, right) {
4551
+ 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);
4783
4552
  }
4784
- matches(doc) {
4785
- const comparison = DocumentKey.comparator(doc.key, this.key);
4786
- return this.matchesComparison(comparison);
4553
+ isEmpty() {
4554
+ return false;
4787
4555
  }
4788
- }
4789
- /** Filter that matches on key fields within an array. */
4790
- class KeyFieldInFilter extends FieldFilter {
4791
- constructor(field, value) {
4792
- super(field, "in" /* IN */, value);
4793
- this.keys = extractDocumentKeysFromArrayValue("in" /* IN */, value);
4556
+ // Traverses the tree in key order and calls the specified action function
4557
+ // for each node. If action returns true, traversal is aborted.
4558
+ // Returns the first truthy value returned by action, or the last falsey
4559
+ // value returned by action.
4560
+ inorderTraversal(action) {
4561
+ return (this.left.inorderTraversal(action) ||
4562
+ action(this.key, this.value) ||
4563
+ this.right.inorderTraversal(action));
4794
4564
  }
4795
- matches(doc) {
4796
- return this.keys.some(key => key.isEqual(doc.key));
4565
+ // Traverses the tree in reverse key order and calls the specified action
4566
+ // function for each node. If action returns true, traversal is aborted.
4567
+ // Returns the first truthy value returned by action, or the last falsey
4568
+ // value returned by action.
4569
+ reverseTraversal(action) {
4570
+ return (this.right.reverseTraversal(action) ||
4571
+ action(this.key, this.value) ||
4572
+ this.left.reverseTraversal(action));
4797
4573
  }
4798
- }
4799
- /** Filter that matches on key fields not present within an array. */
4800
- class KeyFieldNotInFilter extends FieldFilter {
4801
- constructor(field, value) {
4802
- super(field, "not-in" /* NOT_IN */, value);
4803
- this.keys = extractDocumentKeysFromArrayValue("not-in" /* NOT_IN */, value);
4574
+ // Returns the minimum node in the tree.
4575
+ min() {
4576
+ if (this.left.isEmpty()) {
4577
+ return this;
4578
+ }
4579
+ else {
4580
+ return this.left.min();
4581
+ }
4804
4582
  }
4805
- matches(doc) {
4806
- return !this.keys.some(key => key.isEqual(doc.key));
4583
+ // Returns the maximum key in the tree.
4584
+ minKey() {
4585
+ return this.min().key;
4807
4586
  }
4808
- }
4809
- function extractDocumentKeysFromArrayValue(op, value) {
4810
- var _a;
4811
- return (((_a = value.arrayValue) === null || _a === void 0 ? void 0 : _a.values) || []).map(v => {
4812
- return DocumentKey.fromName(v.referenceValue);
4813
- });
4814
- }
4815
- /** A Filter that implements the array-contains operator. */
4816
- class ArrayContainsFilter extends FieldFilter {
4817
- constructor(field, value) {
4818
- super(field, "array-contains" /* ARRAY_CONTAINS */, value);
4587
+ // Returns the maximum key in the tree.
4588
+ maxKey() {
4589
+ if (this.right.isEmpty()) {
4590
+ return this.key;
4591
+ }
4592
+ else {
4593
+ return this.right.maxKey();
4594
+ }
4819
4595
  }
4820
- matches(doc) {
4821
- const other = doc.data.field(this.field);
4822
- return isArray(other) && arrayValueContains(other.arrayValue, this.value);
4596
+ // Returns new tree, with the key/value added.
4597
+ insert(key, value, comparator) {
4598
+ let n = this;
4599
+ const cmp = comparator(key, n.key);
4600
+ if (cmp < 0) {
4601
+ n = n.copy(null, null, null, n.left.insert(key, value, comparator), null);
4602
+ }
4603
+ else if (cmp === 0) {
4604
+ n = n.copy(null, value, null, null, null);
4605
+ }
4606
+ else {
4607
+ n = n.copy(null, null, null, null, n.right.insert(key, value, comparator));
4608
+ }
4609
+ return n.fixUp();
4823
4610
  }
4824
- }
4825
- /** A Filter that implements the IN operator. */
4826
- class InFilter extends FieldFilter {
4827
- constructor(field, value) {
4828
- super(field, "in" /* IN */, value);
4611
+ removeMin() {
4612
+ if (this.left.isEmpty()) {
4613
+ return LLRBNode.EMPTY;
4614
+ }
4615
+ let n = this;
4616
+ if (!n.left.isRed() && !n.left.left.isRed()) {
4617
+ n = n.moveRedLeft();
4618
+ }
4619
+ n = n.copy(null, null, null, n.left.removeMin(), null);
4620
+ return n.fixUp();
4829
4621
  }
4830
- matches(doc) {
4831
- const other = doc.data.field(this.field);
4832
- return other !== null && arrayValueContains(this.value.arrayValue, other);
4622
+ // Returns new tree, with the specified item removed.
4623
+ remove(key, comparator) {
4624
+ let smallest;
4625
+ let n = this;
4626
+ if (comparator(key, n.key) < 0) {
4627
+ if (!n.left.isEmpty() && !n.left.isRed() && !n.left.left.isRed()) {
4628
+ n = n.moveRedLeft();
4629
+ }
4630
+ n = n.copy(null, null, null, n.left.remove(key, comparator), null);
4631
+ }
4632
+ else {
4633
+ if (n.left.isRed()) {
4634
+ n = n.rotateRight();
4635
+ }
4636
+ if (!n.right.isEmpty() && !n.right.isRed() && !n.right.left.isRed()) {
4637
+ n = n.moveRedRight();
4638
+ }
4639
+ if (comparator(key, n.key) === 0) {
4640
+ if (n.right.isEmpty()) {
4641
+ return LLRBNode.EMPTY;
4642
+ }
4643
+ else {
4644
+ smallest = n.right.min();
4645
+ n = n.copy(smallest.key, smallest.value, null, null, n.right.removeMin());
4646
+ }
4647
+ }
4648
+ n = n.copy(null, null, null, null, n.right.remove(key, comparator));
4649
+ }
4650
+ return n.fixUp();
4833
4651
  }
4834
- }
4835
- /** A Filter that implements the not-in operator. */
4836
- class NotInFilter extends FieldFilter {
4837
- constructor(field, value) {
4838
- super(field, "not-in" /* NOT_IN */, value);
4652
+ isRed() {
4653
+ return this.color;
4839
4654
  }
4840
- matches(doc) {
4841
- if (arrayValueContains(this.value.arrayValue, { nullValue: 'NULL_VALUE' })) {
4842
- return false;
4655
+ // Returns new tree after performing any needed rotations.
4656
+ fixUp() {
4657
+ let n = this;
4658
+ if (n.right.isRed() && !n.left.isRed()) {
4659
+ n = n.rotateLeft();
4843
4660
  }
4844
- const other = doc.data.field(this.field);
4845
- return other !== null && !arrayValueContains(this.value.arrayValue, other);
4661
+ if (n.left.isRed() && n.left.left.isRed()) {
4662
+ n = n.rotateRight();
4663
+ }
4664
+ if (n.left.isRed() && n.right.isRed()) {
4665
+ n = n.colorFlip();
4666
+ }
4667
+ return n;
4846
4668
  }
4847
- }
4848
- /** A Filter that implements the array-contains-any operator. */
4849
- class ArrayContainsAnyFilter extends FieldFilter {
4850
- constructor(field, value) {
4851
- super(field, "array-contains-any" /* ARRAY_CONTAINS_ANY */, value);
4669
+ moveRedLeft() {
4670
+ let n = this.colorFlip();
4671
+ if (n.right.left.isRed()) {
4672
+ n = n.copy(null, null, null, null, n.right.rotateRight());
4673
+ n = n.rotateLeft();
4674
+ n = n.colorFlip();
4675
+ }
4676
+ return n;
4852
4677
  }
4853
- matches(doc) {
4854
- const other = doc.data.field(this.field);
4855
- if (!isArray(other) || !other.arrayValue.values) {
4856
- return false;
4678
+ moveRedRight() {
4679
+ let n = this.colorFlip();
4680
+ if (n.left.left.isRed()) {
4681
+ n = n.rotateRight();
4682
+ n = n.colorFlip();
4857
4683
  }
4858
- return other.arrayValue.values.some(val => arrayValueContains(this.value.arrayValue, val));
4684
+ return n;
4859
4685
  }
4860
- }
4861
- /**
4862
- * Represents a bound of a query.
4863
- *
4864
- * The bound is specified with the given components representing a position and
4865
- * whether it's just before or just after the position (relative to whatever the
4866
- * query order is).
4867
- *
4868
- * The position represents a logical index position for a query. It's a prefix
4869
- * of values for the (potentially implicit) order by clauses of a query.
4870
- *
4871
- * Bound provides a function to determine whether a document comes before or
4872
- * after a bound. This is influenced by whether the position is just before or
4873
- * just after the provided values.
4874
- */
4875
- class Bound {
4876
- constructor(position, inclusive) {
4877
- this.position = position;
4878
- this.inclusive = inclusive;
4686
+ rotateLeft() {
4687
+ const nl = this.copy(null, null, LLRBNode.RED, null, this.right.left);
4688
+ return this.right.copy(null, null, this.color, nl, null);
4879
4689
  }
4880
- }
4881
- /**
4882
- * An ordering on a field, in some Direction. Direction defaults to ASCENDING.
4883
- */
4884
- class OrderBy {
4885
- constructor(field, dir = "asc" /* ASCENDING */) {
4886
- this.field = field;
4887
- this.dir = dir;
4690
+ rotateRight() {
4691
+ const nr = this.copy(null, null, LLRBNode.RED, this.left.right, null);
4692
+ return this.left.copy(null, null, this.color, null, nr);
4888
4693
  }
4889
- }
4890
- function canonifyOrderBy(orderBy) {
4891
- // TODO(b/29183165): Make this collision robust.
4892
- return orderBy.field.canonicalString() + orderBy.dir;
4893
- }
4894
- function stringifyOrderBy(orderBy) {
4895
- return `${orderBy.field.canonicalString()} (${orderBy.dir})`;
4896
- }
4897
- function orderByEquals(left, right) {
4898
- return left.dir === right.dir && left.field.isEqual(right.field);
4899
- }
4900
- function boundCompareToDocument(bound, orderBy, doc) {
4901
- let comparison = 0;
4902
- for (let i = 0; i < bound.position.length; i++) {
4903
- const orderByComponent = orderBy[i];
4904
- const component = bound.position[i];
4905
- if (orderByComponent.field.isKeyField()) {
4906
- comparison = DocumentKey.comparator(DocumentKey.fromName(component.referenceValue), doc.key);
4694
+ colorFlip() {
4695
+ const left = this.left.copy(null, null, !this.left.color, null, null);
4696
+ const right = this.right.copy(null, null, !this.right.color, null, null);
4697
+ return this.copy(null, null, !this.color, left, right);
4698
+ }
4699
+ // For testing.
4700
+ checkMaxDepth() {
4701
+ const blackDepth = this.check();
4702
+ if (Math.pow(2.0, blackDepth) <= this.size + 1) {
4703
+ return true;
4907
4704
  }
4908
4705
  else {
4909
- const docValue = doc.data.field(orderByComponent.field);
4910
- comparison = valueCompare(component, docValue);
4706
+ return false;
4911
4707
  }
4912
- if (orderByComponent.dir === "desc" /* DESCENDING */) {
4913
- comparison = comparison * -1;
4708
+ }
4709
+ // In a balanced RB tree, the black-depth (number of black nodes) from root to
4710
+ // leaves is equal on both sides. This function verifies that or asserts.
4711
+ check() {
4712
+ if (this.isRed() && this.left.isRed()) {
4713
+ throw fail();
4914
4714
  }
4915
- if (comparison !== 0) {
4916
- break;
4715
+ if (this.right.isRed()) {
4716
+ throw fail();
4717
+ }
4718
+ const blackDepth = this.left.check();
4719
+ if (blackDepth !== this.right.check()) {
4720
+ throw fail();
4721
+ }
4722
+ else {
4723
+ return blackDepth + (this.isRed() ? 0 : 1);
4917
4724
  }
4918
4725
  }
4919
- return comparison;
4920
- }
4921
- /**
4922
- * Returns true if a document sorts after a bound using the provided sort
4923
- * order.
4924
- */
4925
- function boundSortsAfterDocument(bound, orderBy, doc) {
4926
- const comparison = boundCompareToDocument(bound, orderBy, doc);
4927
- return bound.inclusive ? comparison >= 0 : comparison > 0;
4928
- }
4929
- /**
4930
- * Returns true if a document sorts before a bound using the provided sort
4931
- * order.
4932
- */
4933
- function boundSortsBeforeDocument(bound, orderBy, doc) {
4934
- const comparison = boundCompareToDocument(bound, orderBy, doc);
4935
- return bound.inclusive ? comparison <= 0 : comparison < 0;
4936
- }
4937
- function boundEquals(left, right) {
4938
- if (left === null) {
4939
- return right === null;
4726
+ } // end LLRBNode
4727
+ // Empty node is shared between all LLRB trees.
4728
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
4729
+ LLRBNode.EMPTY = null;
4730
+ LLRBNode.RED = true;
4731
+ LLRBNode.BLACK = false;
4732
+ // Represents an empty node (a leaf node in the Red-Black Tree).
4733
+ class LLRBEmptyNode {
4734
+ constructor() {
4735
+ this.size = 0;
4940
4736
  }
4941
- else if (right === null) {
4737
+ get key() {
4738
+ throw fail();
4739
+ }
4740
+ get value() {
4741
+ throw fail();
4742
+ }
4743
+ get color() {
4744
+ throw fail();
4745
+ }
4746
+ get left() {
4747
+ throw fail();
4748
+ }
4749
+ get right() {
4750
+ throw fail();
4751
+ }
4752
+ // Returns a copy of the current node.
4753
+ copy(key, value, color, left, right) {
4754
+ return this;
4755
+ }
4756
+ // Returns a copy of the tree, with the specified key/value added.
4757
+ insert(key, value, comparator) {
4758
+ return new LLRBNode(key, value);
4759
+ }
4760
+ // Returns a copy of the tree, with the specified key removed.
4761
+ remove(key, comparator) {
4762
+ return this;
4763
+ }
4764
+ isEmpty() {
4765
+ return true;
4766
+ }
4767
+ inorderTraversal(action) {
4942
4768
  return false;
4943
4769
  }
4944
- if (left.inclusive !== right.inclusive ||
4945
- left.position.length !== right.position.length) {
4770
+ reverseTraversal(action) {
4946
4771
  return false;
4947
4772
  }
4948
- for (let i = 0; i < left.position.length; i++) {
4949
- const leftPosition = left.position[i];
4950
- const rightPosition = right.position[i];
4951
- if (!valueEquals(leftPosition, rightPosition)) {
4952
- return false;
4953
- }
4773
+ minKey() {
4774
+ return null;
4954
4775
  }
4955
- return true;
4956
- }
4776
+ maxKey() {
4777
+ return null;
4778
+ }
4779
+ isRed() {
4780
+ return false;
4781
+ }
4782
+ // For testing.
4783
+ checkMaxDepth() {
4784
+ return true;
4785
+ }
4786
+ check() {
4787
+ return 0;
4788
+ }
4789
+ } // end LLRBEmptyNode
4790
+ LLRBNode.EMPTY = new LLRBEmptyNode();
4957
4791
 
4958
4792
  /**
4959
4793
  * @license
@@ -4972,325 +4806,223 @@ function boundEquals(left, right) {
4972
4806
  * limitations under the License.
4973
4807
  */
4974
4808
  /**
4975
- * Query encapsulates all the query attributes we support in the SDK. It can
4976
- * be run against the LocalStore, as well as be converted to a `Target` to
4977
- * query the RemoteStore results.
4809
+ * SortedSet is an immutable (copy-on-write) collection that holds elements
4810
+ * in order specified by the provided comparator.
4978
4811
  *
4979
- * Visible for testing.
4812
+ * NOTE: if provided comparator returns 0 for two elements, we consider them to
4813
+ * be equal!
4980
4814
  */
4981
- class QueryImpl {
4982
- /**
4983
- * Initializes a Query with a path and optional additional query constraints.
4984
- * Path must currently be empty if this is a collection group query.
4985
- */
4986
- constructor(path, collectionGroup = null, explicitOrderBy = [], filters = [], limit = null, limitType = "F" /* First */, startAt = null, endAt = null) {
4987
- this.path = path;
4988
- this.collectionGroup = collectionGroup;
4989
- this.explicitOrderBy = explicitOrderBy;
4990
- this.filters = filters;
4991
- this.limit = limit;
4992
- this.limitType = limitType;
4993
- this.startAt = startAt;
4994
- this.endAt = endAt;
4995
- this.memoizedOrderBy = null;
4996
- // The corresponding `Target` of this `Query` instance.
4997
- this.memoizedTarget = null;
4998
- if (this.startAt) ;
4999
- if (this.endAt) ;
4815
+ class SortedSet {
4816
+ constructor(comparator) {
4817
+ this.comparator = comparator;
4818
+ this.data = new SortedMap(this.comparator);
5000
4819
  }
5001
- }
5002
- /** Creates a new Query instance with the options provided. */
5003
- function newQuery(path, collectionGroup, explicitOrderBy, filters, limit, limitType, startAt, endAt) {
5004
- return new QueryImpl(path, collectionGroup, explicitOrderBy, filters, limit, limitType, startAt, endAt);
5005
- }
5006
- /** Creates a new Query for a query that matches all documents at `path` */
5007
- function newQueryForPath(path) {
5008
- return new QueryImpl(path);
5009
- }
5010
- /**
5011
- * Helper to convert a collection group query into a collection query at a
5012
- * specific path. This is used when executing collection group queries, since
5013
- * we have to split the query into a set of collection queries at multiple
5014
- * paths.
5015
- */
5016
- function asCollectionQueryAtPath(query, path) {
5017
- return new QueryImpl(path,
5018
- /*collectionGroup=*/ null, query.explicitOrderBy.slice(), query.filters.slice(), query.limit, query.limitType, query.startAt, query.endAt);
5019
- }
5020
- /**
5021
- * Returns true if this query does not specify any query constraints that
5022
- * could remove results.
5023
- */
5024
- function matchesAllDocuments(query) {
5025
- return (query.filters.length === 0 &&
5026
- query.limit === null &&
5027
- query.startAt == null &&
5028
- query.endAt == null &&
5029
- (query.explicitOrderBy.length === 0 ||
5030
- (query.explicitOrderBy.length === 1 &&
5031
- query.explicitOrderBy[0].field.isKeyField())));
5032
- }
5033
- function hasLimitToFirst(query) {
5034
- return !isNullOrUndefined(query.limit) && query.limitType === "F" /* First */;
5035
- }
5036
- function hasLimitToLast(query) {
5037
- return !isNullOrUndefined(query.limit) && query.limitType === "L" /* Last */;
5038
- }
5039
- function getFirstOrderByField(query) {
5040
- return query.explicitOrderBy.length > 0
5041
- ? query.explicitOrderBy[0].field
5042
- : null;
5043
- }
5044
- function getInequalityFilterField(query) {
5045
- for (const filter of query.filters) {
5046
- if (filter.isInequality()) {
5047
- return filter.field;
5048
- }
4820
+ has(elem) {
4821
+ return this.data.get(elem) !== null;
5049
4822
  }
5050
- return null;
5051
- }
5052
- /**
5053
- * Checks if any of the provided Operators are included in the query and
5054
- * returns the first one that is, or null if none are.
5055
- */
5056
- function findFilterOperator(query, operators) {
5057
- for (const filter of query.filters) {
5058
- if (operators.indexOf(filter.op) >= 0) {
5059
- return filter.op;
5060
- }
4823
+ first() {
4824
+ return this.data.minKey();
5061
4825
  }
5062
- return null;
5063
- }
5064
- /**
5065
- * Creates a new Query for a collection group query that matches all documents
5066
- * within the provided collection group.
5067
- */
5068
- function newQueryForCollectionGroup(collectionId) {
5069
- return new QueryImpl(ResourcePath.emptyPath(), collectionId);
5070
- }
5071
- /**
5072
- * Returns whether the query matches a single document by path (rather than a
5073
- * collection).
5074
- */
5075
- function isDocumentQuery$1(query) {
5076
- return (DocumentKey.isDocumentKey(query.path) &&
5077
- query.collectionGroup === null &&
5078
- query.filters.length === 0);
5079
- }
5080
- /**
5081
- * Returns whether the query matches a collection group rather than a specific
5082
- * collection.
5083
- */
5084
- function isCollectionGroupQuery(query) {
5085
- return query.collectionGroup !== null;
5086
- }
5087
- /**
5088
- * Returns the implicit order by constraint that is used to execute the Query,
5089
- * which can be different from the order by constraints the user provided (e.g.
5090
- * the SDK and backend always orders by `__name__`).
5091
- */
5092
- function queryOrderBy(query) {
5093
- const queryImpl = debugCast(query);
5094
- if (queryImpl.memoizedOrderBy === null) {
5095
- queryImpl.memoizedOrderBy = [];
5096
- const inequalityField = getInequalityFilterField(queryImpl);
5097
- const firstOrderByField = getFirstOrderByField(queryImpl);
5098
- if (inequalityField !== null && firstOrderByField === null) {
5099
- // In order to implicitly add key ordering, we must also add the
5100
- // inequality filter field for it to be a valid query.
5101
- // Note that the default inequality field and key ordering is ascending.
5102
- if (!inequalityField.isKeyField()) {
5103
- queryImpl.memoizedOrderBy.push(new OrderBy(inequalityField));
5104
- }
5105
- queryImpl.memoizedOrderBy.push(new OrderBy(FieldPath$1.keyField(), "asc" /* ASCENDING */));
5106
- }
5107
- else {
5108
- let foundKeyOrdering = false;
5109
- for (const orderBy of queryImpl.explicitOrderBy) {
5110
- queryImpl.memoizedOrderBy.push(orderBy);
5111
- if (orderBy.field.isKeyField()) {
5112
- foundKeyOrdering = true;
5113
- }
5114
- }
5115
- if (!foundKeyOrdering) {
5116
- // The order of the implicit key ordering always matches the last
5117
- // explicit order by
5118
- const lastDirection = queryImpl.explicitOrderBy.length > 0
5119
- ? queryImpl.explicitOrderBy[queryImpl.explicitOrderBy.length - 1]
5120
- .dir
5121
- : "asc" /* ASCENDING */;
5122
- queryImpl.memoizedOrderBy.push(new OrderBy(FieldPath$1.keyField(), lastDirection));
4826
+ last() {
4827
+ return this.data.maxKey();
4828
+ }
4829
+ get size() {
4830
+ return this.data.size;
4831
+ }
4832
+ indexOf(elem) {
4833
+ return this.data.indexOf(elem);
4834
+ }
4835
+ /** Iterates elements in order defined by "comparator" */
4836
+ forEach(cb) {
4837
+ this.data.inorderTraversal((k, v) => {
4838
+ cb(k);
4839
+ return false;
4840
+ });
4841
+ }
4842
+ /** Iterates over `elem`s such that: range[0] &lt;= elem &lt; range[1]. */
4843
+ forEachInRange(range, cb) {
4844
+ const iter = this.data.getIteratorFrom(range[0]);
4845
+ while (iter.hasNext()) {
4846
+ const elem = iter.getNext();
4847
+ if (this.comparator(elem.key, range[1]) >= 0) {
4848
+ return;
5123
4849
  }
4850
+ cb(elem.key);
5124
4851
  }
5125
4852
  }
5126
- return queryImpl.memoizedOrderBy;
5127
- }
5128
- /**
5129
- * Converts this `Query` instance to it's corresponding `Target` representation.
5130
- */
5131
- function queryToTarget(query) {
5132
- const queryImpl = debugCast(query);
5133
- if (!queryImpl.memoizedTarget) {
5134
- if (queryImpl.limitType === "F" /* First */) {
5135
- queryImpl.memoizedTarget = newTarget(queryImpl.path, queryImpl.collectionGroup, queryOrderBy(queryImpl), queryImpl.filters, queryImpl.limit, queryImpl.startAt, queryImpl.endAt);
4853
+ /**
4854
+ * Iterates over `elem`s such that: start &lt;= elem until false is returned.
4855
+ */
4856
+ forEachWhile(cb, start) {
4857
+ let iter;
4858
+ if (start !== undefined) {
4859
+ iter = this.data.getIteratorFrom(start);
5136
4860
  }
5137
4861
  else {
5138
- // Flip the orderBy directions since we want the last results
5139
- const orderBys = [];
5140
- for (const orderBy of queryOrderBy(queryImpl)) {
5141
- const dir = orderBy.dir === "desc" /* DESCENDING */
5142
- ? "asc" /* ASCENDING */
5143
- : "desc" /* DESCENDING */;
5144
- orderBys.push(new OrderBy(orderBy.field, dir));
4862
+ iter = this.data.getIterator();
4863
+ }
4864
+ while (iter.hasNext()) {
4865
+ const elem = iter.getNext();
4866
+ const result = cb(elem.key);
4867
+ if (!result) {
4868
+ return;
5145
4869
  }
5146
- // We need to swap the cursors to match the now-flipped query ordering.
5147
- const startAt = queryImpl.endAt
5148
- ? new Bound(queryImpl.endAt.position, !queryImpl.endAt.inclusive)
5149
- : null;
5150
- const endAt = queryImpl.startAt
5151
- ? new Bound(queryImpl.startAt.position, !queryImpl.startAt.inclusive)
5152
- : null;
5153
- // Now return as a LimitType.First query.
5154
- queryImpl.memoizedTarget = newTarget(queryImpl.path, queryImpl.collectionGroup, orderBys, queryImpl.filters, queryImpl.limit, startAt, endAt);
5155
4870
  }
5156
4871
  }
5157
- return queryImpl.memoizedTarget;
5158
- }
5159
- function queryWithAddedFilter(query, filter) {
5160
- const newFilters = query.filters.concat([filter]);
5161
- return new QueryImpl(query.path, query.collectionGroup, query.explicitOrderBy.slice(), newFilters, query.limit, query.limitType, query.startAt, query.endAt);
5162
- }
5163
- function queryWithAddedOrderBy(query, orderBy) {
5164
- // TODO(dimond): validate that orderBy does not list the same key twice.
5165
- const newOrderBy = query.explicitOrderBy.concat([orderBy]);
5166
- return new QueryImpl(query.path, query.collectionGroup, newOrderBy, query.filters.slice(), query.limit, query.limitType, query.startAt, query.endAt);
5167
- }
5168
- function queryWithLimit(query, limit, limitType) {
5169
- return new QueryImpl(query.path, query.collectionGroup, query.explicitOrderBy.slice(), query.filters.slice(), limit, limitType, query.startAt, query.endAt);
5170
- }
5171
- function queryWithStartAt(query, bound) {
5172
- return new QueryImpl(query.path, query.collectionGroup, query.explicitOrderBy.slice(), query.filters.slice(), query.limit, query.limitType, bound, query.endAt);
5173
- }
5174
- function queryWithEndAt(query, bound) {
5175
- return new QueryImpl(query.path, query.collectionGroup, query.explicitOrderBy.slice(), query.filters.slice(), query.limit, query.limitType, query.startAt, bound);
5176
- }
5177
- function queryEquals(left, right) {
5178
- return (targetEquals(queryToTarget(left), queryToTarget(right)) &&
5179
- left.limitType === right.limitType);
5180
- }
5181
- // TODO(b/29183165): This is used to get a unique string from a query to, for
5182
- // example, use as a dictionary key, but the implementation is subject to
5183
- // collisions. Make it collision-free.
5184
- function canonifyQuery(query) {
5185
- return `${canonifyTarget(queryToTarget(query))}|lt:${query.limitType}`;
5186
- }
5187
- function stringifyQuery(query) {
5188
- return `Query(target=${stringifyTarget(queryToTarget(query))}; limitType=${query.limitType})`;
5189
- }
5190
- /** Returns whether `doc` matches the constraints of `query`. */
5191
- function queryMatches(query, doc) {
5192
- return (doc.isFoundDocument() &&
5193
- queryMatchesPathAndCollectionGroup(query, doc) &&
5194
- queryMatchesOrderBy(query, doc) &&
5195
- queryMatchesFilters(query, doc) &&
5196
- queryMatchesBounds(query, doc));
5197
- }
5198
- function queryMatchesPathAndCollectionGroup(query, doc) {
5199
- const docPath = doc.key.path;
5200
- if (query.collectionGroup !== null) {
5201
- // NOTE: this.path is currently always empty since we don't expose Collection
5202
- // Group queries rooted at a document path yet.
5203
- return (doc.key.hasCollectionId(query.collectionGroup) &&
5204
- query.path.isPrefixOf(docPath));
4872
+ /** Finds the least element greater than or equal to `elem`. */
4873
+ firstAfterOrEqual(elem) {
4874
+ const iter = this.data.getIteratorFrom(elem);
4875
+ return iter.hasNext() ? iter.getNext().key : null;
5205
4876
  }
5206
- else if (DocumentKey.isDocumentKey(query.path)) {
5207
- // exact match for document queries
5208
- return query.path.isEqual(docPath);
4877
+ getIterator() {
4878
+ return new SortedSetIterator(this.data.getIterator());
5209
4879
  }
5210
- else {
5211
- // shallow ancestor queries by default
5212
- return query.path.isImmediateParentOf(docPath);
4880
+ getIteratorFrom(key) {
4881
+ return new SortedSetIterator(this.data.getIteratorFrom(key));
5213
4882
  }
5214
- }
5215
- /**
5216
- * A document must have a value for every ordering clause in order to show up
5217
- * in the results.
5218
- */
5219
- function queryMatchesOrderBy(query, doc) {
5220
- for (const orderBy of query.explicitOrderBy) {
5221
- // order by key always matches
5222
- if (!orderBy.field.isKeyField() && doc.data.field(orderBy.field) === null) {
5223
- return false;
4883
+ /** Inserts or updates an element */
4884
+ add(elem) {
4885
+ return this.copy(this.data.remove(elem).insert(elem, true));
4886
+ }
4887
+ /** Deletes an element */
4888
+ delete(elem) {
4889
+ if (!this.has(elem)) {
4890
+ return this;
5224
4891
  }
4892
+ return this.copy(this.data.remove(elem));
5225
4893
  }
5226
- return true;
5227
- }
5228
- function queryMatchesFilters(query, doc) {
5229
- for (const filter of query.filters) {
5230
- if (!filter.matches(doc)) {
4894
+ isEmpty() {
4895
+ return this.data.isEmpty();
4896
+ }
4897
+ unionWith(other) {
4898
+ let result = this;
4899
+ // Make sure `result` always refers to the larger one of the two sets.
4900
+ if (result.size < other.size) {
4901
+ result = other;
4902
+ other = this;
4903
+ }
4904
+ other.forEach(elem => {
4905
+ result = result.add(elem);
4906
+ });
4907
+ return result;
4908
+ }
4909
+ isEqual(other) {
4910
+ if (!(other instanceof SortedSet)) {
4911
+ return false;
4912
+ }
4913
+ if (this.size !== other.size) {
5231
4914
  return false;
5232
4915
  }
4916
+ const thisIt = this.data.getIterator();
4917
+ const otherIt = other.data.getIterator();
4918
+ while (thisIt.hasNext()) {
4919
+ const thisElem = thisIt.getNext().key;
4920
+ const otherElem = otherIt.getNext().key;
4921
+ if (this.comparator(thisElem, otherElem) !== 0) {
4922
+ return false;
4923
+ }
4924
+ }
4925
+ return true;
4926
+ }
4927
+ toArray() {
4928
+ const res = [];
4929
+ this.forEach(targetId => {
4930
+ res.push(targetId);
4931
+ });
4932
+ return res;
4933
+ }
4934
+ toString() {
4935
+ const result = [];
4936
+ this.forEach(elem => result.push(elem));
4937
+ return 'SortedSet(' + result.toString() + ')';
4938
+ }
4939
+ copy(data) {
4940
+ const result = new SortedSet(this.comparator);
4941
+ result.data = data;
4942
+ return result;
5233
4943
  }
5234
- return true;
5235
4944
  }
5236
- /** Makes sure a document is within the bounds, if provided. */
5237
- function queryMatchesBounds(query, doc) {
5238
- if (query.startAt &&
5239
- !boundSortsBeforeDocument(query.startAt, queryOrderBy(query), doc)) {
5240
- return false;
4945
+ class SortedSetIterator {
4946
+ constructor(iter) {
4947
+ this.iter = iter;
5241
4948
  }
5242
- if (query.endAt &&
5243
- !boundSortsAfterDocument(query.endAt, queryOrderBy(query), doc)) {
5244
- return false;
4949
+ getNext() {
4950
+ return this.iter.getNext().key;
4951
+ }
4952
+ hasNext() {
4953
+ return this.iter.hasNext();
5245
4954
  }
5246
- return true;
5247
4955
  }
5248
4956
  /**
5249
- * Returns the collection group that this query targets.
4957
+ * Compares two sorted sets for equality using their natural ordering. The
4958
+ * method computes the intersection and invokes `onAdd` for every element that
4959
+ * is in `after` but not `before`. `onRemove` is invoked for every element in
4960
+ * `before` but missing from `after`.
5250
4961
  *
5251
- * PORTING NOTE: This is only used in the Web SDK to facilitate multi-tab
5252
- * synchronization for query results.
5253
- */
5254
- function queryCollectionGroup(query) {
5255
- return (query.collectionGroup ||
5256
- (query.path.length % 2 === 1
5257
- ? query.path.lastSegment()
5258
- : query.path.get(query.path.length - 2)));
5259
- }
5260
- /**
5261
- * Returns a new comparator function that can be used to compare two documents
5262
- * based on the Query's ordering constraint.
4962
+ * The method creates a copy of both `before` and `after` and runs in O(n log
4963
+ * n), where n is the size of the two lists.
4964
+ *
4965
+ * @param before - The elements that exist in the original set.
4966
+ * @param after - The elements to diff against the original set.
4967
+ * @param comparator - The comparator for the elements in before and after.
4968
+ * @param onAdd - A function to invoke for every element that is part of `
4969
+ * after` but not `before`.
4970
+ * @param onRemove - A function to invoke for every element that is part of
4971
+ * `before` but not `after`.
5263
4972
  */
5264
- function newQueryComparator(query) {
5265
- return (d1, d2) => {
5266
- let comparedOnKeyField = false;
5267
- for (const orderBy of queryOrderBy(query)) {
5268
- const comp = compareDocs(orderBy, d1, d2);
5269
- if (comp !== 0) {
5270
- return comp;
4973
+ function diffSortedSets(before, after, comparator, onAdd, onRemove) {
4974
+ const beforeIt = before.getIterator();
4975
+ const afterIt = after.getIterator();
4976
+ let beforeValue = advanceIterator(beforeIt);
4977
+ let afterValue = advanceIterator(afterIt);
4978
+ // Walk through the two sets at the same time, using the ordering defined by
4979
+ // `comparator`.
4980
+ while (beforeValue || afterValue) {
4981
+ let added = false;
4982
+ let removed = false;
4983
+ if (beforeValue && afterValue) {
4984
+ const cmp = comparator(beforeValue, afterValue);
4985
+ if (cmp < 0) {
4986
+ // The element was removed if the next element in our ordered
4987
+ // walkthrough is only in `before`.
4988
+ removed = true;
4989
+ }
4990
+ else if (cmp > 0) {
4991
+ // The element was added if the next element in our ordered walkthrough
4992
+ // is only in `after`.
4993
+ added = true;
5271
4994
  }
5272
- comparedOnKeyField = comparedOnKeyField || orderBy.field.isKeyField();
5273
4995
  }
5274
- return 0;
5275
- };
5276
- }
5277
- function compareDocs(orderBy, d1, d2) {
5278
- const comparison = orderBy.field.isKeyField()
5279
- ? DocumentKey.comparator(d1.key, d2.key)
5280
- : compareDocumentsByField(orderBy.field, d1, d2);
5281
- switch (orderBy.dir) {
5282
- case "asc" /* ASCENDING */:
5283
- return comparison;
5284
- case "desc" /* DESCENDING */:
5285
- return -1 * comparison;
5286
- default:
5287
- return fail();
4996
+ else if (beforeValue != null) {
4997
+ removed = true;
4998
+ }
4999
+ else {
5000
+ added = true;
5001
+ }
5002
+ if (added) {
5003
+ onAdd(afterValue);
5004
+ afterValue = advanceIterator(afterIt);
5005
+ }
5006
+ else if (removed) {
5007
+ onRemove(beforeValue);
5008
+ beforeValue = advanceIterator(beforeIt);
5009
+ }
5010
+ else {
5011
+ beforeValue = advanceIterator(beforeIt);
5012
+ afterValue = advanceIterator(afterIt);
5013
+ }
5288
5014
  }
5015
+ }
5016
+ /**
5017
+ * Returns the next element from the iterator or `undefined` if none available.
5018
+ */
5019
+ function advanceIterator(it) {
5020
+ return it.hasNext() ? it.getNext() : undefined;
5289
5021
  }
5290
5022
 
5291
5023
  /**
5292
5024
  * @license
5293
- * Copyright 2017 Google LLC
5025
+ * Copyright 2019 Google LLC
5294
5026
  *
5295
5027
  * Licensed under the Apache License, Version 2.0 (the "License");
5296
5028
  * you may not use this file except in compliance with the License.
@@ -5304,785 +5036,1084 @@ function compareDocs(orderBy, d1, d2) {
5304
5036
  * See the License for the specific language governing permissions and
5305
5037
  * limitations under the License.
5306
5038
  */
5039
+ // Visible for testing
5040
+ class TargetImpl {
5041
+ constructor(path, collectionGroup = null, orderBy = [], filters = [], limit = null, startAt = null, endAt = null) {
5042
+ this.path = path;
5043
+ this.collectionGroup = collectionGroup;
5044
+ this.orderBy = orderBy;
5045
+ this.filters = filters;
5046
+ this.limit = limit;
5047
+ this.startAt = startAt;
5048
+ this.endAt = endAt;
5049
+ this.memoizedCanonicalId = null;
5050
+ }
5051
+ }
5307
5052
  /**
5308
- * A map implementation that uses objects as keys. Objects must have an
5309
- * associated equals function and must be immutable. Entries in the map are
5310
- * stored together with the key being produced from the mapKeyFn. This map
5311
- * automatically handles collisions of keys.
5053
+ * Initializes a Target with a path and optional additional query constraints.
5054
+ * Path must currently be empty if this is a collection group query.
5055
+ *
5056
+ * NOTE: you should always construct `Target` from `Query.toTarget` instead of
5057
+ * using this factory method, because `Query` provides an implicit `orderBy`
5058
+ * property.
5312
5059
  */
5313
- class ObjectMap {
5314
- constructor(mapKeyFn, equalsFn) {
5315
- this.mapKeyFn = mapKeyFn;
5316
- this.equalsFn = equalsFn;
5317
- /**
5318
- * The inner map for a key/value pair. Due to the possibility of collisions we
5319
- * keep a list of entries that we do a linear search through to find an actual
5320
- * match. Note that collisions should be rare, so we still expect near
5321
- * constant time lookups in practice.
5322
- */
5323
- this.inner = {};
5324
- /** The number of entries stored in the map */
5325
- this.innerSize = 0;
5326
- }
5327
- /** Get a value for this key, or undefined if it does not exist. */
5328
- get(key) {
5329
- const id = this.mapKeyFn(key);
5330
- const matches = this.inner[id];
5331
- if (matches === undefined) {
5332
- return undefined;
5060
+ function newTarget(path, collectionGroup = null, orderBy = [], filters = [], limit = null, startAt = null, endAt = null) {
5061
+ return new TargetImpl(path, collectionGroup, orderBy, filters, limit, startAt, endAt);
5062
+ }
5063
+ function canonifyTarget(target) {
5064
+ const targetImpl = debugCast(target);
5065
+ if (targetImpl.memoizedCanonicalId === null) {
5066
+ let str = targetImpl.path.canonicalString();
5067
+ if (targetImpl.collectionGroup !== null) {
5068
+ str += '|cg:' + targetImpl.collectionGroup;
5333
5069
  }
5334
- for (const [otherKey, value] of matches) {
5335
- if (this.equalsFn(otherKey, key)) {
5336
- return value;
5337
- }
5070
+ str += '|f:';
5071
+ str += targetImpl.filters.map(f => canonifyFilter(f)).join(',');
5072
+ str += '|ob:';
5073
+ str += targetImpl.orderBy.map(o => canonifyOrderBy(o)).join(',');
5074
+ if (!isNullOrUndefined(targetImpl.limit)) {
5075
+ str += '|l:';
5076
+ str += targetImpl.limit;
5338
5077
  }
5339
- return undefined;
5340
- }
5341
- has(key) {
5342
- return this.get(key) !== undefined;
5343
- }
5344
- /** Put this key and value in the map. */
5345
- set(key, value) {
5346
- const id = this.mapKeyFn(key);
5347
- const matches = this.inner[id];
5348
- if (matches === undefined) {
5349
- this.inner[id] = [[key, value]];
5350
- this.innerSize++;
5351
- return;
5078
+ if (targetImpl.startAt) {
5079
+ str += '|lb:';
5080
+ str += targetImpl.startAt.inclusive ? 'b:' : 'a:';
5081
+ str += targetImpl.startAt.position.map(p => canonicalId(p)).join(',');
5352
5082
  }
5353
- for (let i = 0; i < matches.length; i++) {
5354
- if (this.equalsFn(matches[i][0], key)) {
5355
- // This is updating an existing entry and does not increase `innerSize`.
5356
- matches[i] = [key, value];
5357
- return;
5358
- }
5083
+ if (targetImpl.endAt) {
5084
+ str += '|ub:';
5085
+ str += targetImpl.endAt.inclusive ? 'a:' : 'b:';
5086
+ str += targetImpl.endAt.position.map(p => canonicalId(p)).join(',');
5359
5087
  }
5360
- matches.push([key, value]);
5361
- this.innerSize++;
5088
+ targetImpl.memoizedCanonicalId = str;
5362
5089
  }
5363
- /**
5364
- * Remove this key from the map. Returns a boolean if anything was deleted.
5365
- */
5366
- delete(key) {
5367
- const id = this.mapKeyFn(key);
5368
- const matches = this.inner[id];
5369
- if (matches === undefined) {
5090
+ return targetImpl.memoizedCanonicalId;
5091
+ }
5092
+ function stringifyTarget(target) {
5093
+ let str = target.path.canonicalString();
5094
+ if (target.collectionGroup !== null) {
5095
+ str += ' collectionGroup=' + target.collectionGroup;
5096
+ }
5097
+ if (target.filters.length > 0) {
5098
+ str += `, filters: [${target.filters
5099
+ .map(f => stringifyFilter(f))
5100
+ .join(', ')}]`;
5101
+ }
5102
+ if (!isNullOrUndefined(target.limit)) {
5103
+ str += ', limit: ' + target.limit;
5104
+ }
5105
+ if (target.orderBy.length > 0) {
5106
+ str += `, orderBy: [${target.orderBy
5107
+ .map(o => stringifyOrderBy(o))
5108
+ .join(', ')}]`;
5109
+ }
5110
+ if (target.startAt) {
5111
+ str += ', startAt: ';
5112
+ str += target.startAt.inclusive ? 'b:' : 'a:';
5113
+ str += target.startAt.position.map(p => canonicalId(p)).join(',');
5114
+ }
5115
+ if (target.endAt) {
5116
+ str += ', endAt: ';
5117
+ str += target.endAt.inclusive ? 'a:' : 'b:';
5118
+ str += target.endAt.position.map(p => canonicalId(p)).join(',');
5119
+ }
5120
+ return `Target(${str})`;
5121
+ }
5122
+ function targetEquals(left, right) {
5123
+ if (left.limit !== right.limit) {
5124
+ return false;
5125
+ }
5126
+ if (left.orderBy.length !== right.orderBy.length) {
5127
+ return false;
5128
+ }
5129
+ for (let i = 0; i < left.orderBy.length; i++) {
5130
+ if (!orderByEquals(left.orderBy[i], right.orderBy[i])) {
5370
5131
  return false;
5371
5132
  }
5372
- for (let i = 0; i < matches.length; i++) {
5373
- if (this.equalsFn(matches[i][0], key)) {
5374
- if (matches.length === 1) {
5375
- delete this.inner[id];
5376
- }
5377
- else {
5378
- matches.splice(i, 1);
5379
- }
5380
- this.innerSize--;
5381
- return true;
5382
- }
5133
+ }
5134
+ if (left.filters.length !== right.filters.length) {
5135
+ return false;
5136
+ }
5137
+ for (let i = 0; i < left.filters.length; i++) {
5138
+ if (!filterEquals(left.filters[i], right.filters[i])) {
5139
+ return false;
5383
5140
  }
5141
+ }
5142
+ if (left.collectionGroup !== right.collectionGroup) {
5384
5143
  return false;
5385
5144
  }
5386
- forEach(fn) {
5387
- forEach(this.inner, (_, entries) => {
5388
- for (const [k, v] of entries) {
5389
- fn(k, v);
5390
- }
5391
- });
5392
- }
5393
- isEmpty() {
5394
- return isEmpty(this.inner);
5145
+ if (!left.path.isEqual(right.path)) {
5146
+ return false;
5395
5147
  }
5396
- size() {
5397
- return this.innerSize;
5148
+ if (!boundEquals(left.startAt, right.startAt)) {
5149
+ return false;
5398
5150
  }
5399
- }
5400
-
5151
+ return boundEquals(left.endAt, right.endAt);
5152
+ }
5153
+ function targetIsDocumentTarget(target) {
5154
+ return (DocumentKey.isDocumentKey(target.path) &&
5155
+ target.collectionGroup === null &&
5156
+ target.filters.length === 0);
5157
+ }
5158
+ /** Returns the field filters that target the given field path. */
5159
+ function targetGetFieldFiltersForPath(target, path) {
5160
+ return target.filters.filter(f => f instanceof FieldFilter && f.field.isEqual(path));
5161
+ }
5401
5162
  /**
5402
- * @license
5403
- * Copyright 2017 Google LLC
5404
- *
5405
- * Licensed under the Apache License, Version 2.0 (the "License");
5406
- * you may not use this file except in compliance with the License.
5407
- * You may obtain a copy of the License at
5408
- *
5409
- * http://www.apache.org/licenses/LICENSE-2.0
5410
- *
5411
- * Unless required by applicable law or agreed to in writing, software
5412
- * distributed under the License is distributed on an "AS IS" BASIS,
5413
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
5414
- * See the License for the specific language governing permissions and
5415
- * limitations under the License.
5163
+ * Returns the values that are used in ARRAY_CONTAINS or ARRAY_CONTAINS_ANY
5164
+ * filters. Returns `null` if there are no such filters.
5416
5165
  */
5417
- // An immutable sorted map implementation, based on a Left-leaning Red-Black
5418
- // tree.
5419
- class SortedMap {
5420
- constructor(comparator, root) {
5421
- this.comparator = comparator;
5422
- this.root = root ? root : LLRBNode.EMPTY;
5423
- }
5424
- // Returns a copy of the map, with the specified key/value added or replaced.
5425
- insert(key, value) {
5426
- return new SortedMap(this.comparator, this.root
5427
- .insert(key, value, this.comparator)
5428
- .copy(null, null, LLRBNode.BLACK, null, null));
5429
- }
5430
- // Returns a copy of the map, with the specified key removed.
5431
- remove(key) {
5432
- return new SortedMap(this.comparator, this.root
5433
- .remove(key, this.comparator)
5434
- .copy(null, null, LLRBNode.BLACK, null, null));
5435
- }
5436
- // Returns the value of the node with the given key, or null.
5437
- get(key) {
5438
- let node = this.root;
5439
- while (!node.isEmpty()) {
5440
- const cmp = this.comparator(key, node.key);
5441
- if (cmp === 0) {
5442
- return node.value;
5443
- }
5444
- else if (cmp < 0) {
5445
- node = node.left;
5446
- }
5447
- else if (cmp > 0) {
5448
- node = node.right;
5449
- }
5450
- }
5166
+ function targetGetArrayValues(target, fieldIndex) {
5167
+ const segment = fieldIndexGetArraySegment(fieldIndex);
5168
+ if (segment === undefined) {
5451
5169
  return null;
5452
5170
  }
5453
- // Returns the index of the element in this sorted map, or -1 if it doesn't
5454
- // exist.
5455
- indexOf(key) {
5456
- // Number of nodes that were pruned when descending right
5457
- let prunedNodes = 0;
5458
- let node = this.root;
5459
- while (!node.isEmpty()) {
5460
- const cmp = this.comparator(key, node.key);
5461
- if (cmp === 0) {
5462
- return prunedNodes + node.left.size;
5463
- }
5464
- else if (cmp < 0) {
5465
- node = node.left;
5466
- }
5467
- else {
5468
- // Count all nodes left of the node plus the node itself
5469
- prunedNodes += node.left.size + 1;
5470
- node = node.right;
5471
- }
5171
+ for (const fieldFilter of targetGetFieldFiltersForPath(target, segment.fieldPath)) {
5172
+ switch (fieldFilter.op) {
5173
+ case "array-contains-any" /* ARRAY_CONTAINS_ANY */:
5174
+ return fieldFilter.value.arrayValue.values || [];
5175
+ case "array-contains" /* ARRAY_CONTAINS */:
5176
+ return [fieldFilter.value];
5177
+ // Remaining filters are not array filters.
5472
5178
  }
5473
- // Node not found
5474
- return -1;
5475
5179
  }
5476
- isEmpty() {
5477
- return this.root.isEmpty();
5478
- }
5479
- // Returns the total number of nodes in the map.
5480
- get size() {
5481
- return this.root.size;
5482
- }
5483
- // Returns the minimum key in the map.
5484
- minKey() {
5485
- return this.root.minKey();
5486
- }
5487
- // Returns the maximum key in the map.
5488
- maxKey() {
5489
- return this.root.maxKey();
5490
- }
5491
- // Traverses the map in key order and calls the specified action function
5492
- // for each key/value pair. If action returns true, traversal is aborted.
5493
- // Returns the first truthy value returned by action, or the last falsey
5494
- // value returned by action.
5495
- inorderTraversal(action) {
5496
- return this.root.inorderTraversal(action);
5497
- }
5498
- forEach(fn) {
5499
- this.inorderTraversal((k, v) => {
5500
- fn(k, v);
5501
- return false;
5502
- });
5503
- }
5504
- toString() {
5505
- const descriptions = [];
5506
- this.inorderTraversal((k, v) => {
5507
- descriptions.push(`${k}:${v}`);
5508
- return false;
5509
- });
5510
- return `{${descriptions.join(', ')}}`;
5511
- }
5512
- // Traverses the map in reverse key order and calls the specified action
5513
- // function for each key/value pair. If action returns true, traversal is
5514
- // aborted.
5515
- // Returns the first truthy value returned by action, or the last falsey
5516
- // value returned by action.
5517
- reverseTraversal(action) {
5518
- return this.root.reverseTraversal(action);
5519
- }
5520
- // Returns an iterator over the SortedMap.
5521
- getIterator() {
5522
- return new SortedMapIterator(this.root, null, this.comparator, false);
5523
- }
5524
- getIteratorFrom(key) {
5525
- return new SortedMapIterator(this.root, key, this.comparator, false);
5526
- }
5527
- getReverseIterator() {
5528
- return new SortedMapIterator(this.root, null, this.comparator, true);
5529
- }
5530
- getReverseIteratorFrom(key) {
5531
- return new SortedMapIterator(this.root, key, this.comparator, true);
5532
- }
5533
- } // end SortedMap
5534
- // An iterator over an LLRBNode.
5535
- class SortedMapIterator {
5536
- constructor(node, startKey, comparator, isReverse) {
5537
- this.isReverse = isReverse;
5538
- this.nodeStack = [];
5539
- let cmp = 1;
5540
- while (!node.isEmpty()) {
5541
- cmp = startKey ? comparator(node.key, startKey) : 1;
5542
- // flip the comparison if we're going in reverse
5543
- if (startKey && isReverse) {
5544
- cmp *= -1;
5545
- }
5546
- if (cmp < 0) {
5547
- // This node is less than our start key. ignore it
5548
- if (this.isReverse) {
5549
- node = node.left;
5550
- }
5551
- else {
5552
- node = node.right;
5553
- }
5554
- }
5555
- else if (cmp === 0) {
5556
- // This node is exactly equal to our start key. Push it on the stack,
5557
- // but stop iterating;
5558
- this.nodeStack.push(node);
5559
- break;
5560
- }
5561
- else {
5562
- // This node is greater than our start key, add it to the stack and move
5563
- // to the next one
5564
- this.nodeStack.push(node);
5565
- if (this.isReverse) {
5566
- node = node.right;
5567
- }
5568
- else {
5569
- node = node.left;
5570
- }
5180
+ return null;
5181
+ }
5182
+ /**
5183
+ * Returns the list of values that are used in != or NOT_IN filters. Returns
5184
+ * `null` if there are no such filters.
5185
+ */
5186
+ function targetGetNotInValues(target, fieldIndex) {
5187
+ const values = new Map();
5188
+ for (const segment of fieldIndexGetDirectionalSegments(fieldIndex)) {
5189
+ for (const fieldFilter of targetGetFieldFiltersForPath(target, segment.fieldPath)) {
5190
+ switch (fieldFilter.op) {
5191
+ case "==" /* EQUAL */:
5192
+ case "in" /* IN */:
5193
+ // Encode equality prefix, which is encoded in the index value before
5194
+ // the inequality (e.g. `a == 'a' && b != 'b'` is encoded to
5195
+ // `value != 'ab'`).
5196
+ values.set(segment.fieldPath.canonicalString(), fieldFilter.value);
5197
+ break;
5198
+ case "not-in" /* NOT_IN */:
5199
+ case "!=" /* NOT_EQUAL */:
5200
+ // NotIn/NotEqual is always a suffix. There cannot be any remaining
5201
+ // segments and hence we can return early here.
5202
+ values.set(segment.fieldPath.canonicalString(), fieldFilter.value);
5203
+ return Array.from(values.values());
5204
+ // Remaining filters cannot be used as notIn bounds.
5571
5205
  }
5572
5206
  }
5573
5207
  }
5574
- getNext() {
5575
- let node = this.nodeStack.pop();
5576
- const result = { key: node.key, value: node.value };
5577
- if (this.isReverse) {
5578
- node = node.left;
5579
- while (!node.isEmpty()) {
5580
- this.nodeStack.push(node);
5581
- node = node.right;
5582
- }
5583
- }
5584
- else {
5585
- node = node.right;
5586
- while (!node.isEmpty()) {
5587
- this.nodeStack.push(node);
5588
- node = node.left;
5589
- }
5208
+ return null;
5209
+ }
5210
+ /**
5211
+ * Returns a lower bound of field values that can be used as a starting point to
5212
+ * scan the index defined by `fieldIndex`. Returns `null` if no lower bound
5213
+ * exists.
5214
+ */
5215
+ function targetGetLowerBound(target, fieldIndex) {
5216
+ const values = [];
5217
+ let inclusive = true;
5218
+ // For each segment, retrieve a lower bound if there is a suitable filter or
5219
+ // startAt.
5220
+ for (const segment of fieldIndexGetDirectionalSegments(fieldIndex)) {
5221
+ const segmentBound = segment.kind === 0 /* ASCENDING */
5222
+ ? targetGetAscendingBound(target, segment.fieldPath, target.startAt)
5223
+ : targetGetDescendingBound(target, segment.fieldPath, target.startAt);
5224
+ if (!segmentBound.value) {
5225
+ // No lower bound exists
5226
+ return null;
5590
5227
  }
5591
- return result;
5592
- }
5593
- hasNext() {
5594
- return this.nodeStack.length > 0;
5228
+ values.push(segmentBound.value);
5229
+ inclusive && (inclusive = segmentBound.inclusive);
5595
5230
  }
5596
- peek() {
5597
- if (this.nodeStack.length === 0) {
5231
+ return new Bound(values, inclusive);
5232
+ }
5233
+ /**
5234
+ * Returns an upper bound of field values that can be used as an ending point
5235
+ * when scanning the index defined by `fieldIndex`. Returns `null` if no
5236
+ * upper bound exists.
5237
+ */
5238
+ function targetGetUpperBound(target, fieldIndex) {
5239
+ const values = [];
5240
+ let inclusive = true;
5241
+ // For each segment, retrieve an upper bound if there is a suitable filter or
5242
+ // endAt.
5243
+ for (const segment of fieldIndexGetDirectionalSegments(fieldIndex)) {
5244
+ const segmentBound = segment.kind === 0 /* ASCENDING */
5245
+ ? targetGetDescendingBound(target, segment.fieldPath, target.endAt)
5246
+ : targetGetAscendingBound(target, segment.fieldPath, target.endAt);
5247
+ if (!segmentBound.value) {
5248
+ // No upper bound exists
5598
5249
  return null;
5599
5250
  }
5600
- const node = this.nodeStack[this.nodeStack.length - 1];
5601
- return { key: node.key, value: node.value };
5602
- }
5603
- } // end SortedMapIterator
5604
- // Represents a node in a Left-leaning Red-Black tree.
5605
- class LLRBNode {
5606
- constructor(key, value, color, left, right) {
5607
- this.key = key;
5608
- this.value = value;
5609
- this.color = color != null ? color : LLRBNode.RED;
5610
- this.left = left != null ? left : LLRBNode.EMPTY;
5611
- this.right = right != null ? right : LLRBNode.EMPTY;
5612
- this.size = this.left.size + 1 + this.right.size;
5613
- }
5614
- // Returns a copy of the current node, optionally replacing pieces of it.
5615
- copy(key, value, color, left, right) {
5616
- return new LLRBNode(key != null ? key : this.key, value != null ? value : this.value, color != null ? color : this.color, left != null ? left : this.left, right != null ? right : this.right);
5617
- }
5618
- isEmpty() {
5619
- return false;
5620
- }
5621
- // Traverses the tree in key order and calls the specified action function
5622
- // for each node. If action returns true, traversal is aborted.
5623
- // Returns the first truthy value returned by action, or the last falsey
5624
- // value returned by action.
5625
- inorderTraversal(action) {
5626
- return (this.left.inorderTraversal(action) ||
5627
- action(this.key, this.value) ||
5628
- this.right.inorderTraversal(action));
5629
- }
5630
- // Traverses the tree in reverse key order and calls the specified action
5631
- // function for each node. If action returns true, traversal is aborted.
5632
- // Returns the first truthy value returned by action, or the last falsey
5633
- // value returned by action.
5634
- reverseTraversal(action) {
5635
- return (this.right.reverseTraversal(action) ||
5636
- action(this.key, this.value) ||
5637
- this.left.reverseTraversal(action));
5251
+ values.push(segmentBound.value);
5252
+ inclusive && (inclusive = segmentBound.inclusive);
5638
5253
  }
5639
- // Returns the minimum node in the tree.
5640
- min() {
5641
- if (this.left.isEmpty()) {
5642
- return this;
5254
+ return new Bound(values, inclusive);
5255
+ }
5256
+ /**
5257
+ * Returns the value to use as the lower bound for ascending index segment at
5258
+ * the provided `fieldPath` (or the upper bound for an descending segment).
5259
+ */
5260
+ function targetGetAscendingBound(target, fieldPath, bound) {
5261
+ let value = undefined;
5262
+ let inclusive = true;
5263
+ // Process all filters to find a value for the current field segment
5264
+ for (const fieldFilter of targetGetFieldFiltersForPath(target, fieldPath)) {
5265
+ let filterValue = undefined;
5266
+ let filterInclusive = true;
5267
+ switch (fieldFilter.op) {
5268
+ case "<" /* LESS_THAN */:
5269
+ case "<=" /* LESS_THAN_OR_EQUAL */:
5270
+ filterValue = valuesGetLowerBound(fieldFilter.value);
5271
+ break;
5272
+ case "==" /* EQUAL */:
5273
+ case "in" /* IN */:
5274
+ case ">=" /* GREATER_THAN_OR_EQUAL */:
5275
+ filterValue = fieldFilter.value;
5276
+ break;
5277
+ case ">" /* GREATER_THAN */:
5278
+ filterValue = fieldFilter.value;
5279
+ filterInclusive = false;
5280
+ break;
5281
+ case "!=" /* NOT_EQUAL */:
5282
+ case "not-in" /* NOT_IN */:
5283
+ filterValue = MIN_VALUE;
5284
+ break;
5285
+ // Remaining filters cannot be used as lower bounds.
5643
5286
  }
5644
- else {
5645
- return this.left.min();
5287
+ if (valuesMax(value, filterValue) === filterValue) {
5288
+ value = filterValue;
5289
+ inclusive = filterInclusive;
5646
5290
  }
5647
5291
  }
5648
- // Returns the maximum key in the tree.
5649
- minKey() {
5650
- return this.min().key;
5292
+ // If there is an additional bound, compare the values against the existing
5293
+ // range to see if we can narrow the scope.
5294
+ if (bound !== null) {
5295
+ for (let i = 0; i < target.orderBy.length; ++i) {
5296
+ const orderBy = target.orderBy[i];
5297
+ if (orderBy.field.isEqual(fieldPath)) {
5298
+ const cursorValue = bound.position[i];
5299
+ if (valuesMax(value, cursorValue) === cursorValue) {
5300
+ value = cursorValue;
5301
+ inclusive = bound.inclusive;
5302
+ }
5303
+ break;
5304
+ }
5305
+ }
5651
5306
  }
5652
- // Returns the maximum key in the tree.
5653
- maxKey() {
5654
- if (this.right.isEmpty()) {
5655
- return this.key;
5307
+ return { value, inclusive };
5308
+ }
5309
+ /**
5310
+ * Returns the value to use as the upper bound for ascending index segment at
5311
+ * the provided `fieldPath` (or the lower bound for a descending segment).
5312
+ */
5313
+ function targetGetDescendingBound(target, fieldPath, bound) {
5314
+ let value = undefined;
5315
+ let inclusive = true;
5316
+ // Process all filters to find a value for the current field segment
5317
+ for (const fieldFilter of targetGetFieldFiltersForPath(target, fieldPath)) {
5318
+ let filterValue = undefined;
5319
+ let filterInclusive = true;
5320
+ switch (fieldFilter.op) {
5321
+ case ">=" /* GREATER_THAN_OR_EQUAL */:
5322
+ case ">" /* GREATER_THAN */:
5323
+ filterValue = valuesGetUpperBound(fieldFilter.value);
5324
+ filterInclusive = false;
5325
+ break;
5326
+ case "==" /* EQUAL */:
5327
+ case "in" /* IN */:
5328
+ case "<=" /* LESS_THAN_OR_EQUAL */:
5329
+ filterValue = fieldFilter.value;
5330
+ break;
5331
+ case "<" /* LESS_THAN */:
5332
+ filterValue = fieldFilter.value;
5333
+ filterInclusive = false;
5334
+ break;
5335
+ case "!=" /* NOT_EQUAL */:
5336
+ case "not-in" /* NOT_IN */:
5337
+ filterValue = MAX_VALUE;
5338
+ break;
5339
+ // Remaining filters cannot be used as upper bounds.
5656
5340
  }
5657
- else {
5658
- return this.right.maxKey();
5341
+ if (valuesMin(value, filterValue) === filterValue) {
5342
+ value = filterValue;
5343
+ inclusive = filterInclusive;
5344
+ }
5345
+ }
5346
+ // If there is an additional bound, compare the values against the existing
5347
+ // range to see if we can narrow the scope.
5348
+ if (bound !== null) {
5349
+ for (let i = 0; i < target.orderBy.length; ++i) {
5350
+ const orderBy = target.orderBy[i];
5351
+ if (orderBy.field.isEqual(fieldPath)) {
5352
+ const cursorValue = bound.position[i];
5353
+ if (valuesMin(value, cursorValue) === cursorValue) {
5354
+ value = cursorValue;
5355
+ inclusive = bound.inclusive;
5356
+ }
5357
+ break;
5358
+ }
5659
5359
  }
5660
5360
  }
5661
- // Returns new tree, with the key/value added.
5662
- insert(key, value, comparator) {
5663
- let n = this;
5664
- const cmp = comparator(key, n.key);
5665
- if (cmp < 0) {
5666
- n = n.copy(null, null, null, n.left.insert(key, value, comparator), null);
5361
+ return { value, inclusive };
5362
+ }
5363
+ /** Returns the number of segments of a perfect index for this target. */
5364
+ function targetGetSegmentCount(target) {
5365
+ let fields = new SortedSet(FieldPath$1.comparator);
5366
+ let hasArraySegment = false;
5367
+ for (const filter of target.filters) {
5368
+ // TODO(orquery): Use the flattened filters here
5369
+ const fieldFilter = filter;
5370
+ // __name__ is not an explicit segment of any index, so we don't need to
5371
+ // count it.
5372
+ if (fieldFilter.field.isKeyField()) {
5373
+ continue;
5667
5374
  }
5668
- else if (cmp === 0) {
5669
- n = n.copy(null, value, null, null, null);
5375
+ // ARRAY_CONTAINS or ARRAY_CONTAINS_ANY filters must be counted separately.
5376
+ // For instance, it is possible to have an index for "a ARRAY a ASC". Even
5377
+ // though these are on the same field, they should be counted as two
5378
+ // separate segments in an index.
5379
+ if (fieldFilter.op === "array-contains" /* ARRAY_CONTAINS */ ||
5380
+ fieldFilter.op === "array-contains-any" /* ARRAY_CONTAINS_ANY */) {
5381
+ hasArraySegment = true;
5670
5382
  }
5671
5383
  else {
5672
- n = n.copy(null, null, null, null, n.right.insert(key, value, comparator));
5384
+ fields = fields.add(fieldFilter.field);
5673
5385
  }
5674
- return n.fixUp();
5675
5386
  }
5676
- removeMin() {
5677
- if (this.left.isEmpty()) {
5678
- return LLRBNode.EMPTY;
5679
- }
5680
- let n = this;
5681
- if (!n.left.isRed() && !n.left.left.isRed()) {
5682
- n = n.moveRedLeft();
5387
+ for (const orderBy of target.orderBy) {
5388
+ // __name__ is not an explicit segment of any index, so we don't need to
5389
+ // count it.
5390
+ if (!orderBy.field.isKeyField()) {
5391
+ fields = fields.add(orderBy.field);
5683
5392
  }
5684
- n = n.copy(null, null, null, n.left.removeMin(), null);
5685
- return n.fixUp();
5686
5393
  }
5687
- // Returns new tree, with the specified item removed.
5688
- remove(key, comparator) {
5689
- let smallest;
5690
- let n = this;
5691
- if (comparator(key, n.key) < 0) {
5692
- if (!n.left.isEmpty() && !n.left.isRed() && !n.left.left.isRed()) {
5693
- n = n.moveRedLeft();
5694
- }
5695
- n = n.copy(null, null, null, n.left.remove(key, comparator), null);
5696
- }
5697
- else {
5698
- if (n.left.isRed()) {
5699
- n = n.rotateRight();
5700
- }
5701
- if (!n.right.isEmpty() && !n.right.isRed() && !n.right.left.isRed()) {
5702
- n = n.moveRedRight();
5394
+ return fields.size + (hasArraySegment ? 1 : 0);
5395
+ }
5396
+ class Filter {
5397
+ }
5398
+ class FieldFilter extends Filter {
5399
+ constructor(field, op, value) {
5400
+ super();
5401
+ this.field = field;
5402
+ this.op = op;
5403
+ this.value = value;
5404
+ }
5405
+ /**
5406
+ * Creates a filter based on the provided arguments.
5407
+ */
5408
+ static create(field, op, value) {
5409
+ if (field.isKeyField()) {
5410
+ if (op === "in" /* IN */ || op === "not-in" /* NOT_IN */) {
5411
+ return this.createKeyFieldInFilter(field, op, value);
5703
5412
  }
5704
- if (comparator(key, n.key) === 0) {
5705
- if (n.right.isEmpty()) {
5706
- return LLRBNode.EMPTY;
5707
- }
5708
- else {
5709
- smallest = n.right.min();
5710
- n = n.copy(smallest.key, smallest.value, null, null, n.right.removeMin());
5711
- }
5413
+ else {
5414
+ return new KeyFieldFilter(field, op, value);
5712
5415
  }
5713
- n = n.copy(null, null, null, null, n.right.remove(key, comparator));
5714
5416
  }
5715
- return n.fixUp();
5716
- }
5717
- isRed() {
5718
- return this.color;
5719
- }
5720
- // Returns new tree after performing any needed rotations.
5721
- fixUp() {
5722
- let n = this;
5723
- if (n.right.isRed() && !n.left.isRed()) {
5724
- n = n.rotateLeft();
5417
+ else if (op === "array-contains" /* ARRAY_CONTAINS */) {
5418
+ return new ArrayContainsFilter(field, value);
5725
5419
  }
5726
- if (n.left.isRed() && n.left.left.isRed()) {
5727
- n = n.rotateRight();
5420
+ else if (op === "in" /* IN */) {
5421
+ return new InFilter(field, value);
5728
5422
  }
5729
- if (n.left.isRed() && n.right.isRed()) {
5730
- n = n.colorFlip();
5423
+ else if (op === "not-in" /* NOT_IN */) {
5424
+ return new NotInFilter(field, value);
5425
+ }
5426
+ else if (op === "array-contains-any" /* ARRAY_CONTAINS_ANY */) {
5427
+ return new ArrayContainsAnyFilter(field, value);
5428
+ }
5429
+ else {
5430
+ return new FieldFilter(field, op, value);
5731
5431
  }
5732
- return n;
5733
5432
  }
5734
- moveRedLeft() {
5735
- let n = this.colorFlip();
5736
- if (n.right.left.isRed()) {
5737
- n = n.copy(null, null, null, null, n.right.rotateRight());
5738
- n = n.rotateLeft();
5739
- n = n.colorFlip();
5433
+ static createKeyFieldInFilter(field, op, value) {
5434
+ return op === "in" /* IN */
5435
+ ? new KeyFieldInFilter(field, value)
5436
+ : new KeyFieldNotInFilter(field, value);
5437
+ }
5438
+ matches(doc) {
5439
+ const other = doc.data.field(this.field);
5440
+ // Types do not have to match in NOT_EQUAL filters.
5441
+ if (this.op === "!=" /* NOT_EQUAL */) {
5442
+ return (other !== null &&
5443
+ this.matchesComparison(valueCompare(other, this.value)));
5740
5444
  }
5741
- return n;
5445
+ // Only compare types with matching backend order (such as double and int).
5446
+ return (other !== null &&
5447
+ typeOrder(this.value) === typeOrder(other) &&
5448
+ this.matchesComparison(valueCompare(other, this.value)));
5742
5449
  }
5743
- moveRedRight() {
5744
- let n = this.colorFlip();
5745
- if (n.left.left.isRed()) {
5746
- n = n.rotateRight();
5747
- n = n.colorFlip();
5450
+ matchesComparison(comparison) {
5451
+ switch (this.op) {
5452
+ case "<" /* LESS_THAN */:
5453
+ return comparison < 0;
5454
+ case "<=" /* LESS_THAN_OR_EQUAL */:
5455
+ return comparison <= 0;
5456
+ case "==" /* EQUAL */:
5457
+ return comparison === 0;
5458
+ case "!=" /* NOT_EQUAL */:
5459
+ return comparison !== 0;
5460
+ case ">" /* GREATER_THAN */:
5461
+ return comparison > 0;
5462
+ case ">=" /* GREATER_THAN_OR_EQUAL */:
5463
+ return comparison >= 0;
5464
+ default:
5465
+ return fail();
5748
5466
  }
5749
- return n;
5750
5467
  }
5751
- rotateLeft() {
5752
- const nl = this.copy(null, null, LLRBNode.RED, null, this.right.left);
5753
- return this.right.copy(null, null, this.color, nl, null);
5468
+ isInequality() {
5469
+ return ([
5470
+ "<" /* LESS_THAN */,
5471
+ "<=" /* LESS_THAN_OR_EQUAL */,
5472
+ ">" /* GREATER_THAN */,
5473
+ ">=" /* GREATER_THAN_OR_EQUAL */,
5474
+ "!=" /* NOT_EQUAL */,
5475
+ "not-in" /* NOT_IN */
5476
+ ].indexOf(this.op) >= 0);
5754
5477
  }
5755
- rotateRight() {
5756
- const nr = this.copy(null, null, LLRBNode.RED, this.left.right, null);
5757
- return this.left.copy(null, null, this.color, null, nr);
5478
+ }
5479
+ function canonifyFilter(filter) {
5480
+ // TODO(b/29183165): Technically, this won't be unique if two values have
5481
+ // the same description, such as the int 3 and the string "3". So we should
5482
+ // add the types in here somehow, too.
5483
+ return (filter.field.canonicalString() +
5484
+ filter.op.toString() +
5485
+ canonicalId(filter.value));
5486
+ }
5487
+ function filterEquals(f1, f2) {
5488
+ return (f1.op === f2.op &&
5489
+ f1.field.isEqual(f2.field) &&
5490
+ valueEquals(f1.value, f2.value));
5491
+ }
5492
+ /** Returns a debug description for `filter`. */
5493
+ function stringifyFilter(filter) {
5494
+ return `${filter.field.canonicalString()} ${filter.op} ${canonicalId(filter.value)}`;
5495
+ }
5496
+ /** Filter that matches on key fields (i.e. '__name__'). */
5497
+ class KeyFieldFilter extends FieldFilter {
5498
+ constructor(field, op, value) {
5499
+ super(field, op, value);
5500
+ this.key = DocumentKey.fromName(value.referenceValue);
5758
5501
  }
5759
- colorFlip() {
5760
- const left = this.left.copy(null, null, !this.left.color, null, null);
5761
- const right = this.right.copy(null, null, !this.right.color, null, null);
5762
- return this.copy(null, null, !this.color, left, right);
5502
+ matches(doc) {
5503
+ const comparison = DocumentKey.comparator(doc.key, this.key);
5504
+ return this.matchesComparison(comparison);
5763
5505
  }
5764
- // For testing.
5765
- checkMaxDepth() {
5766
- const blackDepth = this.check();
5767
- if (Math.pow(2.0, blackDepth) <= this.size + 1) {
5768
- return true;
5769
- }
5770
- else {
5771
- return false;
5772
- }
5506
+ }
5507
+ /** Filter that matches on key fields within an array. */
5508
+ class KeyFieldInFilter extends FieldFilter {
5509
+ constructor(field, value) {
5510
+ super(field, "in" /* IN */, value);
5511
+ this.keys = extractDocumentKeysFromArrayValue("in" /* IN */, value);
5773
5512
  }
5774
- // In a balanced RB tree, the black-depth (number of black nodes) from root to
5775
- // leaves is equal on both sides. This function verifies that or asserts.
5776
- check() {
5777
- if (this.isRed() && this.left.isRed()) {
5778
- throw fail();
5779
- }
5780
- if (this.right.isRed()) {
5781
- throw fail();
5782
- }
5783
- const blackDepth = this.left.check();
5784
- if (blackDepth !== this.right.check()) {
5785
- throw fail();
5786
- }
5787
- else {
5788
- return blackDepth + (this.isRed() ? 0 : 1);
5789
- }
5513
+ matches(doc) {
5514
+ return this.keys.some(key => key.isEqual(doc.key));
5790
5515
  }
5791
- } // end LLRBNode
5792
- // Empty node is shared between all LLRB trees.
5793
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
5794
- LLRBNode.EMPTY = null;
5795
- LLRBNode.RED = true;
5796
- LLRBNode.BLACK = false;
5797
- // Represents an empty node (a leaf node in the Red-Black Tree).
5798
- class LLRBEmptyNode {
5799
- constructor() {
5800
- this.size = 0;
5516
+ }
5517
+ /** Filter that matches on key fields not present within an array. */
5518
+ class KeyFieldNotInFilter extends FieldFilter {
5519
+ constructor(field, value) {
5520
+ super(field, "not-in" /* NOT_IN */, value);
5521
+ this.keys = extractDocumentKeysFromArrayValue("not-in" /* NOT_IN */, value);
5522
+ }
5523
+ matches(doc) {
5524
+ return !this.keys.some(key => key.isEqual(doc.key));
5525
+ }
5526
+ }
5527
+ function extractDocumentKeysFromArrayValue(op, value) {
5528
+ var _a;
5529
+ return (((_a = value.arrayValue) === null || _a === void 0 ? void 0 : _a.values) || []).map(v => {
5530
+ return DocumentKey.fromName(v.referenceValue);
5531
+ });
5532
+ }
5533
+ /** A Filter that implements the array-contains operator. */
5534
+ class ArrayContainsFilter extends FieldFilter {
5535
+ constructor(field, value) {
5536
+ super(field, "array-contains" /* ARRAY_CONTAINS */, value);
5537
+ }
5538
+ matches(doc) {
5539
+ const other = doc.data.field(this.field);
5540
+ return isArray(other) && arrayValueContains(other.arrayValue, this.value);
5541
+ }
5542
+ }
5543
+ /** A Filter that implements the IN operator. */
5544
+ class InFilter extends FieldFilter {
5545
+ constructor(field, value) {
5546
+ super(field, "in" /* IN */, value);
5801
5547
  }
5802
- get key() {
5803
- throw fail();
5548
+ matches(doc) {
5549
+ const other = doc.data.field(this.field);
5550
+ return other !== null && arrayValueContains(this.value.arrayValue, other);
5804
5551
  }
5805
- get value() {
5806
- throw fail();
5552
+ }
5553
+ /** A Filter that implements the not-in operator. */
5554
+ class NotInFilter extends FieldFilter {
5555
+ constructor(field, value) {
5556
+ super(field, "not-in" /* NOT_IN */, value);
5807
5557
  }
5808
- get color() {
5809
- throw fail();
5558
+ matches(doc) {
5559
+ if (arrayValueContains(this.value.arrayValue, { nullValue: 'NULL_VALUE' })) {
5560
+ return false;
5561
+ }
5562
+ const other = doc.data.field(this.field);
5563
+ return other !== null && !arrayValueContains(this.value.arrayValue, other);
5810
5564
  }
5811
- get left() {
5812
- throw fail();
5565
+ }
5566
+ /** A Filter that implements the array-contains-any operator. */
5567
+ class ArrayContainsAnyFilter extends FieldFilter {
5568
+ constructor(field, value) {
5569
+ super(field, "array-contains-any" /* ARRAY_CONTAINS_ANY */, value);
5813
5570
  }
5814
- get right() {
5815
- throw fail();
5571
+ matches(doc) {
5572
+ const other = doc.data.field(this.field);
5573
+ if (!isArray(other) || !other.arrayValue.values) {
5574
+ return false;
5575
+ }
5576
+ return other.arrayValue.values.some(val => arrayValueContains(this.value.arrayValue, val));
5816
5577
  }
5817
- // Returns a copy of the current node.
5818
- copy(key, value, color, left, right) {
5819
- return this;
5578
+ }
5579
+ /**
5580
+ * Represents a bound of a query.
5581
+ *
5582
+ * The bound is specified with the given components representing a position and
5583
+ * whether it's just before or just after the position (relative to whatever the
5584
+ * query order is).
5585
+ *
5586
+ * The position represents a logical index position for a query. It's a prefix
5587
+ * of values for the (potentially implicit) order by clauses of a query.
5588
+ *
5589
+ * Bound provides a function to determine whether a document comes before or
5590
+ * after a bound. This is influenced by whether the position is just before or
5591
+ * just after the provided values.
5592
+ */
5593
+ class Bound {
5594
+ constructor(position, inclusive) {
5595
+ this.position = position;
5596
+ this.inclusive = inclusive;
5820
5597
  }
5821
- // Returns a copy of the tree, with the specified key/value added.
5822
- insert(key, value, comparator) {
5823
- return new LLRBNode(key, value);
5598
+ }
5599
+ /**
5600
+ * An ordering on a field, in some Direction. Direction defaults to ASCENDING.
5601
+ */
5602
+ class OrderBy {
5603
+ constructor(field, dir = "asc" /* ASCENDING */) {
5604
+ this.field = field;
5605
+ this.dir = dir;
5824
5606
  }
5825
- // Returns a copy of the tree, with the specified key removed.
5826
- remove(key, comparator) {
5827
- return this;
5607
+ }
5608
+ function canonifyOrderBy(orderBy) {
5609
+ // TODO(b/29183165): Make this collision robust.
5610
+ return orderBy.field.canonicalString() + orderBy.dir;
5611
+ }
5612
+ function stringifyOrderBy(orderBy) {
5613
+ return `${orderBy.field.canonicalString()} (${orderBy.dir})`;
5614
+ }
5615
+ function orderByEquals(left, right) {
5616
+ return left.dir === right.dir && left.field.isEqual(right.field);
5617
+ }
5618
+ function boundCompareToDocument(bound, orderBy, doc) {
5619
+ let comparison = 0;
5620
+ for (let i = 0; i < bound.position.length; i++) {
5621
+ const orderByComponent = orderBy[i];
5622
+ const component = bound.position[i];
5623
+ if (orderByComponent.field.isKeyField()) {
5624
+ comparison = DocumentKey.comparator(DocumentKey.fromName(component.referenceValue), doc.key);
5625
+ }
5626
+ else {
5627
+ const docValue = doc.data.field(orderByComponent.field);
5628
+ comparison = valueCompare(component, docValue);
5629
+ }
5630
+ if (orderByComponent.dir === "desc" /* DESCENDING */) {
5631
+ comparison = comparison * -1;
5632
+ }
5633
+ if (comparison !== 0) {
5634
+ break;
5635
+ }
5828
5636
  }
5829
- isEmpty() {
5830
- return true;
5637
+ return comparison;
5638
+ }
5639
+ /**
5640
+ * Returns true if a document sorts after a bound using the provided sort
5641
+ * order.
5642
+ */
5643
+ function boundSortsAfterDocument(bound, orderBy, doc) {
5644
+ const comparison = boundCompareToDocument(bound, orderBy, doc);
5645
+ return bound.inclusive ? comparison >= 0 : comparison > 0;
5646
+ }
5647
+ /**
5648
+ * Returns true if a document sorts before a bound using the provided sort
5649
+ * order.
5650
+ */
5651
+ function boundSortsBeforeDocument(bound, orderBy, doc) {
5652
+ const comparison = boundCompareToDocument(bound, orderBy, doc);
5653
+ return bound.inclusive ? comparison <= 0 : comparison < 0;
5654
+ }
5655
+ function boundEquals(left, right) {
5656
+ if (left === null) {
5657
+ return right === null;
5831
5658
  }
5832
- inorderTraversal(action) {
5659
+ else if (right === null) {
5833
5660
  return false;
5834
5661
  }
5835
- reverseTraversal(action) {
5662
+ if (left.inclusive !== right.inclusive ||
5663
+ left.position.length !== right.position.length) {
5836
5664
  return false;
5837
5665
  }
5838
- minKey() {
5839
- return null;
5840
- }
5841
- maxKey() {
5842
- return null;
5666
+ for (let i = 0; i < left.position.length; i++) {
5667
+ const leftPosition = left.position[i];
5668
+ const rightPosition = right.position[i];
5669
+ if (!valueEquals(leftPosition, rightPosition)) {
5670
+ return false;
5671
+ }
5843
5672
  }
5844
- isRed() {
5845
- return false;
5673
+ return true;
5674
+ }
5675
+
5676
+ /**
5677
+ * @license
5678
+ * Copyright 2017 Google LLC
5679
+ *
5680
+ * Licensed under the Apache License, Version 2.0 (the "License");
5681
+ * you may not use this file except in compliance with the License.
5682
+ * You may obtain a copy of the License at
5683
+ *
5684
+ * http://www.apache.org/licenses/LICENSE-2.0
5685
+ *
5686
+ * Unless required by applicable law or agreed to in writing, software
5687
+ * distributed under the License is distributed on an "AS IS" BASIS,
5688
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
5689
+ * See the License for the specific language governing permissions and
5690
+ * limitations under the License.
5691
+ */
5692
+ /**
5693
+ * Query encapsulates all the query attributes we support in the SDK. It can
5694
+ * be run against the LocalStore, as well as be converted to a `Target` to
5695
+ * query the RemoteStore results.
5696
+ *
5697
+ * Visible for testing.
5698
+ */
5699
+ class QueryImpl {
5700
+ /**
5701
+ * Initializes a Query with a path and optional additional query constraints.
5702
+ * Path must currently be empty if this is a collection group query.
5703
+ */
5704
+ constructor(path, collectionGroup = null, explicitOrderBy = [], filters = [], limit = null, limitType = "F" /* First */, startAt = null, endAt = null) {
5705
+ this.path = path;
5706
+ this.collectionGroup = collectionGroup;
5707
+ this.explicitOrderBy = explicitOrderBy;
5708
+ this.filters = filters;
5709
+ this.limit = limit;
5710
+ this.limitType = limitType;
5711
+ this.startAt = startAt;
5712
+ this.endAt = endAt;
5713
+ this.memoizedOrderBy = null;
5714
+ // The corresponding `Target` of this `Query` instance.
5715
+ this.memoizedTarget = null;
5716
+ if (this.startAt) ;
5717
+ if (this.endAt) ;
5846
5718
  }
5847
- // For testing.
5848
- checkMaxDepth() {
5849
- return true;
5719
+ }
5720
+ /** Creates a new Query instance with the options provided. */
5721
+ function newQuery(path, collectionGroup, explicitOrderBy, filters, limit, limitType, startAt, endAt) {
5722
+ return new QueryImpl(path, collectionGroup, explicitOrderBy, filters, limit, limitType, startAt, endAt);
5723
+ }
5724
+ /** Creates a new Query for a query that matches all documents at `path` */
5725
+ function newQueryForPath(path) {
5726
+ return new QueryImpl(path);
5727
+ }
5728
+ /**
5729
+ * Helper to convert a collection group query into a collection query at a
5730
+ * specific path. This is used when executing collection group queries, since
5731
+ * we have to split the query into a set of collection queries at multiple
5732
+ * paths.
5733
+ */
5734
+ function asCollectionQueryAtPath(query, path) {
5735
+ return new QueryImpl(path,
5736
+ /*collectionGroup=*/ null, query.explicitOrderBy.slice(), query.filters.slice(), query.limit, query.limitType, query.startAt, query.endAt);
5737
+ }
5738
+ /**
5739
+ * Returns true if this query does not specify any query constraints that
5740
+ * could remove results.
5741
+ */
5742
+ function matchesAllDocuments(query) {
5743
+ return (query.filters.length === 0 &&
5744
+ query.limit === null &&
5745
+ query.startAt == null &&
5746
+ query.endAt == null &&
5747
+ (query.explicitOrderBy.length === 0 ||
5748
+ (query.explicitOrderBy.length === 1 &&
5749
+ query.explicitOrderBy[0].field.isKeyField())));
5750
+ }
5751
+ function hasLimitToFirst(query) {
5752
+ return !isNullOrUndefined(query.limit) && query.limitType === "F" /* First */;
5753
+ }
5754
+ function hasLimitToLast(query) {
5755
+ return !isNullOrUndefined(query.limit) && query.limitType === "L" /* Last */;
5756
+ }
5757
+ function getFirstOrderByField(query) {
5758
+ return query.explicitOrderBy.length > 0
5759
+ ? query.explicitOrderBy[0].field
5760
+ : null;
5761
+ }
5762
+ function getInequalityFilterField(query) {
5763
+ for (const filter of query.filters) {
5764
+ if (filter.isInequality()) {
5765
+ return filter.field;
5766
+ }
5850
5767
  }
5851
- check() {
5852
- return 0;
5768
+ return null;
5769
+ }
5770
+ /**
5771
+ * Checks if any of the provided Operators are included in the query and
5772
+ * returns the first one that is, or null if none are.
5773
+ */
5774
+ function findFilterOperator(query, operators) {
5775
+ for (const filter of query.filters) {
5776
+ if (operators.indexOf(filter.op) >= 0) {
5777
+ return filter.op;
5778
+ }
5853
5779
  }
5854
- } // end LLRBEmptyNode
5855
- LLRBNode.EMPTY = new LLRBEmptyNode();
5856
-
5780
+ return null;
5781
+ }
5857
5782
  /**
5858
- * @license
5859
- * Copyright 2017 Google LLC
5860
- *
5861
- * Licensed under the Apache License, Version 2.0 (the "License");
5862
- * you may not use this file except in compliance with the License.
5863
- * You may obtain a copy of the License at
5864
- *
5865
- * http://www.apache.org/licenses/LICENSE-2.0
5866
- *
5867
- * Unless required by applicable law or agreed to in writing, software
5868
- * distributed under the License is distributed on an "AS IS" BASIS,
5869
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
5870
- * See the License for the specific language governing permissions and
5871
- * limitations under the License.
5783
+ * Creates a new Query for a collection group query that matches all documents
5784
+ * within the provided collection group.
5872
5785
  */
5786
+ function newQueryForCollectionGroup(collectionId) {
5787
+ return new QueryImpl(ResourcePath.emptyPath(), collectionId);
5788
+ }
5873
5789
  /**
5874
- * SortedSet is an immutable (copy-on-write) collection that holds elements
5875
- * in order specified by the provided comparator.
5876
- *
5877
- * NOTE: if provided comparator returns 0 for two elements, we consider them to
5878
- * be equal!
5790
+ * Returns whether the query matches a single document by path (rather than a
5791
+ * collection).
5879
5792
  */
5880
- class SortedSet {
5881
- constructor(comparator) {
5882
- this.comparator = comparator;
5883
- this.data = new SortedMap(this.comparator);
5884
- }
5885
- has(elem) {
5886
- return this.data.get(elem) !== null;
5887
- }
5888
- first() {
5889
- return this.data.minKey();
5890
- }
5891
- last() {
5892
- return this.data.maxKey();
5893
- }
5894
- get size() {
5895
- return this.data.size;
5896
- }
5897
- indexOf(elem) {
5898
- return this.data.indexOf(elem);
5899
- }
5900
- /** Iterates elements in order defined by "comparator" */
5901
- forEach(cb) {
5902
- this.data.inorderTraversal((k, v) => {
5903
- cb(k);
5904
- return false;
5905
- });
5906
- }
5907
- /** Iterates over `elem`s such that: range[0] &lt;= elem &lt; range[1]. */
5908
- forEachInRange(range, cb) {
5909
- const iter = this.data.getIteratorFrom(range[0]);
5910
- while (iter.hasNext()) {
5911
- const elem = iter.getNext();
5912
- if (this.comparator(elem.key, range[1]) >= 0) {
5913
- return;
5793
+ function isDocumentQuery$1(query) {
5794
+ return (DocumentKey.isDocumentKey(query.path) &&
5795
+ query.collectionGroup === null &&
5796
+ query.filters.length === 0);
5797
+ }
5798
+ /**
5799
+ * Returns whether the query matches a collection group rather than a specific
5800
+ * collection.
5801
+ */
5802
+ function isCollectionGroupQuery(query) {
5803
+ return query.collectionGroup !== null;
5804
+ }
5805
+ /**
5806
+ * Returns the implicit order by constraint that is used to execute the Query,
5807
+ * which can be different from the order by constraints the user provided (e.g.
5808
+ * the SDK and backend always orders by `__name__`).
5809
+ */
5810
+ function queryOrderBy(query) {
5811
+ const queryImpl = debugCast(query);
5812
+ if (queryImpl.memoizedOrderBy === null) {
5813
+ queryImpl.memoizedOrderBy = [];
5814
+ const inequalityField = getInequalityFilterField(queryImpl);
5815
+ const firstOrderByField = getFirstOrderByField(queryImpl);
5816
+ if (inequalityField !== null && firstOrderByField === null) {
5817
+ // In order to implicitly add key ordering, we must also add the
5818
+ // inequality filter field for it to be a valid query.
5819
+ // Note that the default inequality field and key ordering is ascending.
5820
+ if (!inequalityField.isKeyField()) {
5821
+ queryImpl.memoizedOrderBy.push(new OrderBy(inequalityField));
5914
5822
  }
5915
- cb(elem.key);
5916
- }
5917
- }
5918
- /**
5919
- * Iterates over `elem`s such that: start &lt;= elem until false is returned.
5920
- */
5921
- forEachWhile(cb, start) {
5922
- let iter;
5923
- if (start !== undefined) {
5924
- iter = this.data.getIteratorFrom(start);
5823
+ queryImpl.memoizedOrderBy.push(new OrderBy(FieldPath$1.keyField(), "asc" /* ASCENDING */));
5925
5824
  }
5926
5825
  else {
5927
- iter = this.data.getIterator();
5928
- }
5929
- while (iter.hasNext()) {
5930
- const elem = iter.getNext();
5931
- const result = cb(elem.key);
5932
- if (!result) {
5933
- return;
5826
+ let foundKeyOrdering = false;
5827
+ for (const orderBy of queryImpl.explicitOrderBy) {
5828
+ queryImpl.memoizedOrderBy.push(orderBy);
5829
+ if (orderBy.field.isKeyField()) {
5830
+ foundKeyOrdering = true;
5831
+ }
5832
+ }
5833
+ if (!foundKeyOrdering) {
5834
+ // The order of the implicit key ordering always matches the last
5835
+ // explicit order by
5836
+ const lastDirection = queryImpl.explicitOrderBy.length > 0
5837
+ ? queryImpl.explicitOrderBy[queryImpl.explicitOrderBy.length - 1]
5838
+ .dir
5839
+ : "asc" /* ASCENDING */;
5840
+ queryImpl.memoizedOrderBy.push(new OrderBy(FieldPath$1.keyField(), lastDirection));
5934
5841
  }
5935
5842
  }
5936
5843
  }
5937
- /** Finds the least element greater than or equal to `elem`. */
5938
- firstAfterOrEqual(elem) {
5939
- const iter = this.data.getIteratorFrom(elem);
5940
- return iter.hasNext() ? iter.getNext().key : null;
5941
- }
5942
- getIterator() {
5943
- return new SortedSetIterator(this.data.getIterator());
5944
- }
5945
- getIteratorFrom(key) {
5946
- return new SortedSetIterator(this.data.getIteratorFrom(key));
5947
- }
5948
- /** Inserts or updates an element */
5949
- add(elem) {
5950
- return this.copy(this.data.remove(elem).insert(elem, true));
5951
- }
5952
- /** Deletes an element */
5953
- delete(elem) {
5954
- if (!this.has(elem)) {
5955
- return this;
5956
- }
5957
- return this.copy(this.data.remove(elem));
5958
- }
5959
- isEmpty() {
5960
- return this.data.isEmpty();
5961
- }
5962
- unionWith(other) {
5963
- let result = this;
5964
- // Make sure `result` always refers to the larger one of the two sets.
5965
- if (result.size < other.size) {
5966
- result = other;
5967
- other = this;
5968
- }
5969
- other.forEach(elem => {
5970
- result = result.add(elem);
5971
- });
5972
- return result;
5973
- }
5974
- isEqual(other) {
5975
- if (!(other instanceof SortedSet)) {
5976
- return false;
5977
- }
5978
- if (this.size !== other.size) {
5979
- return false;
5844
+ return queryImpl.memoizedOrderBy;
5845
+ }
5846
+ /**
5847
+ * Converts this `Query` instance to it's corresponding `Target` representation.
5848
+ */
5849
+ function queryToTarget(query) {
5850
+ const queryImpl = debugCast(query);
5851
+ if (!queryImpl.memoizedTarget) {
5852
+ if (queryImpl.limitType === "F" /* First */) {
5853
+ queryImpl.memoizedTarget = newTarget(queryImpl.path, queryImpl.collectionGroup, queryOrderBy(queryImpl), queryImpl.filters, queryImpl.limit, queryImpl.startAt, queryImpl.endAt);
5980
5854
  }
5981
- const thisIt = this.data.getIterator();
5982
- const otherIt = other.data.getIterator();
5983
- while (thisIt.hasNext()) {
5984
- const thisElem = thisIt.getNext().key;
5985
- const otherElem = otherIt.getNext().key;
5986
- if (this.comparator(thisElem, otherElem) !== 0) {
5987
- return false;
5855
+ else {
5856
+ // Flip the orderBy directions since we want the last results
5857
+ const orderBys = [];
5858
+ for (const orderBy of queryOrderBy(queryImpl)) {
5859
+ const dir = orderBy.dir === "desc" /* DESCENDING */
5860
+ ? "asc" /* ASCENDING */
5861
+ : "desc" /* DESCENDING */;
5862
+ orderBys.push(new OrderBy(orderBy.field, dir));
5988
5863
  }
5864
+ // We need to swap the cursors to match the now-flipped query ordering.
5865
+ const startAt = queryImpl.endAt
5866
+ ? new Bound(queryImpl.endAt.position, !queryImpl.endAt.inclusive)
5867
+ : null;
5868
+ const endAt = queryImpl.startAt
5869
+ ? new Bound(queryImpl.startAt.position, !queryImpl.startAt.inclusive)
5870
+ : null;
5871
+ // Now return as a LimitType.First query.
5872
+ queryImpl.memoizedTarget = newTarget(queryImpl.path, queryImpl.collectionGroup, orderBys, queryImpl.filters, queryImpl.limit, startAt, endAt);
5989
5873
  }
5990
- return true;
5991
5874
  }
5992
- toArray() {
5993
- const res = [];
5994
- this.forEach(targetId => {
5995
- res.push(targetId);
5996
- });
5997
- return res;
5875
+ return queryImpl.memoizedTarget;
5876
+ }
5877
+ function queryWithAddedFilter(query, filter) {
5878
+ const newFilters = query.filters.concat([filter]);
5879
+ return new QueryImpl(query.path, query.collectionGroup, query.explicitOrderBy.slice(), newFilters, query.limit, query.limitType, query.startAt, query.endAt);
5880
+ }
5881
+ function queryWithAddedOrderBy(query, orderBy) {
5882
+ // TODO(dimond): validate that orderBy does not list the same key twice.
5883
+ const newOrderBy = query.explicitOrderBy.concat([orderBy]);
5884
+ return new QueryImpl(query.path, query.collectionGroup, newOrderBy, query.filters.slice(), query.limit, query.limitType, query.startAt, query.endAt);
5885
+ }
5886
+ function queryWithLimit(query, limit, limitType) {
5887
+ return new QueryImpl(query.path, query.collectionGroup, query.explicitOrderBy.slice(), query.filters.slice(), limit, limitType, query.startAt, query.endAt);
5888
+ }
5889
+ function queryWithStartAt(query, bound) {
5890
+ return new QueryImpl(query.path, query.collectionGroup, query.explicitOrderBy.slice(), query.filters.slice(), query.limit, query.limitType, bound, query.endAt);
5891
+ }
5892
+ function queryWithEndAt(query, bound) {
5893
+ return new QueryImpl(query.path, query.collectionGroup, query.explicitOrderBy.slice(), query.filters.slice(), query.limit, query.limitType, query.startAt, bound);
5894
+ }
5895
+ function queryEquals(left, right) {
5896
+ return (targetEquals(queryToTarget(left), queryToTarget(right)) &&
5897
+ left.limitType === right.limitType);
5898
+ }
5899
+ // TODO(b/29183165): This is used to get a unique string from a query to, for
5900
+ // example, use as a dictionary key, but the implementation is subject to
5901
+ // collisions. Make it collision-free.
5902
+ function canonifyQuery(query) {
5903
+ return `${canonifyTarget(queryToTarget(query))}|lt:${query.limitType}`;
5904
+ }
5905
+ function stringifyQuery(query) {
5906
+ return `Query(target=${stringifyTarget(queryToTarget(query))}; limitType=${query.limitType})`;
5907
+ }
5908
+ /** Returns whether `doc` matches the constraints of `query`. */
5909
+ function queryMatches(query, doc) {
5910
+ return (doc.isFoundDocument() &&
5911
+ queryMatchesPathAndCollectionGroup(query, doc) &&
5912
+ queryMatchesOrderBy(query, doc) &&
5913
+ queryMatchesFilters(query, doc) &&
5914
+ queryMatchesBounds(query, doc));
5915
+ }
5916
+ function queryMatchesPathAndCollectionGroup(query, doc) {
5917
+ const docPath = doc.key.path;
5918
+ if (query.collectionGroup !== null) {
5919
+ // NOTE: this.path is currently always empty since we don't expose Collection
5920
+ // Group queries rooted at a document path yet.
5921
+ return (doc.key.hasCollectionId(query.collectionGroup) &&
5922
+ query.path.isPrefixOf(docPath));
5923
+ }
5924
+ else if (DocumentKey.isDocumentKey(query.path)) {
5925
+ // exact match for document queries
5926
+ return query.path.isEqual(docPath);
5998
5927
  }
5999
- toString() {
6000
- const result = [];
6001
- this.forEach(elem => result.push(elem));
6002
- return 'SortedSet(' + result.toString() + ')';
5928
+ else {
5929
+ // shallow ancestor queries by default
5930
+ return query.path.isImmediateParentOf(docPath);
6003
5931
  }
6004
- copy(data) {
6005
- const result = new SortedSet(this.comparator);
6006
- result.data = data;
6007
- return result;
5932
+ }
5933
+ /**
5934
+ * A document must have a value for every ordering clause in order to show up
5935
+ * in the results.
5936
+ */
5937
+ function queryMatchesOrderBy(query, doc) {
5938
+ for (const orderBy of query.explicitOrderBy) {
5939
+ // order by key always matches
5940
+ if (!orderBy.field.isKeyField() && doc.data.field(orderBy.field) === null) {
5941
+ return false;
5942
+ }
6008
5943
  }
5944
+ return true;
6009
5945
  }
6010
- class SortedSetIterator {
6011
- constructor(iter) {
6012
- this.iter = iter;
5946
+ function queryMatchesFilters(query, doc) {
5947
+ for (const filter of query.filters) {
5948
+ if (!filter.matches(doc)) {
5949
+ return false;
5950
+ }
6013
5951
  }
6014
- getNext() {
6015
- return this.iter.getNext().key;
5952
+ return true;
5953
+ }
5954
+ /** Makes sure a document is within the bounds, if provided. */
5955
+ function queryMatchesBounds(query, doc) {
5956
+ if (query.startAt &&
5957
+ !boundSortsBeforeDocument(query.startAt, queryOrderBy(query), doc)) {
5958
+ return false;
6016
5959
  }
6017
- hasNext() {
6018
- return this.iter.hasNext();
5960
+ if (query.endAt &&
5961
+ !boundSortsAfterDocument(query.endAt, queryOrderBy(query), doc)) {
5962
+ return false;
6019
5963
  }
5964
+ return true;
6020
5965
  }
6021
5966
  /**
6022
- * Compares two sorted sets for equality using their natural ordering. The
6023
- * method computes the intersection and invokes `onAdd` for every element that
6024
- * is in `after` but not `before`. `onRemove` is invoked for every element in
6025
- * `before` but missing from `after`.
6026
- *
6027
- * The method creates a copy of both `before` and `after` and runs in O(n log
6028
- * n), where n is the size of the two lists.
5967
+ * Returns the collection group that this query targets.
6029
5968
  *
6030
- * @param before - The elements that exist in the original set.
6031
- * @param after - The elements to diff against the original set.
6032
- * @param comparator - The comparator for the elements in before and after.
6033
- * @param onAdd - A function to invoke for every element that is part of `
6034
- * after` but not `before`.
6035
- * @param onRemove - A function to invoke for every element that is part of
6036
- * `before` but not `after`.
5969
+ * PORTING NOTE: This is only used in the Web SDK to facilitate multi-tab
5970
+ * synchronization for query results.
6037
5971
  */
6038
- function diffSortedSets(before, after, comparator, onAdd, onRemove) {
6039
- const beforeIt = before.getIterator();
6040
- const afterIt = after.getIterator();
6041
- let beforeValue = advanceIterator(beforeIt);
6042
- let afterValue = advanceIterator(afterIt);
6043
- // Walk through the two sets at the same time, using the ordering defined by
6044
- // `comparator`.
6045
- while (beforeValue || afterValue) {
6046
- let added = false;
6047
- let removed = false;
6048
- if (beforeValue && afterValue) {
6049
- const cmp = comparator(beforeValue, afterValue);
6050
- if (cmp < 0) {
6051
- // The element was removed if the next element in our ordered
6052
- // walkthrough is only in `before`.
6053
- removed = true;
6054
- }
6055
- else if (cmp > 0) {
6056
- // The element was added if the next element in our ordered walkthrough
6057
- // is only in `after`.
6058
- added = true;
5972
+ function queryCollectionGroup(query) {
5973
+ return (query.collectionGroup ||
5974
+ (query.path.length % 2 === 1
5975
+ ? query.path.lastSegment()
5976
+ : query.path.get(query.path.length - 2)));
5977
+ }
5978
+ /**
5979
+ * Returns a new comparator function that can be used to compare two documents
5980
+ * based on the Query's ordering constraint.
5981
+ */
5982
+ function newQueryComparator(query) {
5983
+ return (d1, d2) => {
5984
+ let comparedOnKeyField = false;
5985
+ for (const orderBy of queryOrderBy(query)) {
5986
+ const comp = compareDocs(orderBy, d1, d2);
5987
+ if (comp !== 0) {
5988
+ return comp;
6059
5989
  }
5990
+ comparedOnKeyField = comparedOnKeyField || orderBy.field.isKeyField();
6060
5991
  }
6061
- else if (beforeValue != null) {
6062
- removed = true;
5992
+ return 0;
5993
+ };
5994
+ }
5995
+ function compareDocs(orderBy, d1, d2) {
5996
+ const comparison = orderBy.field.isKeyField()
5997
+ ? DocumentKey.comparator(d1.key, d2.key)
5998
+ : compareDocumentsByField(orderBy.field, d1, d2);
5999
+ switch (orderBy.dir) {
6000
+ case "asc" /* ASCENDING */:
6001
+ return comparison;
6002
+ case "desc" /* DESCENDING */:
6003
+ return -1 * comparison;
6004
+ default:
6005
+ return fail();
6006
+ }
6007
+ }
6008
+
6009
+ /**
6010
+ * @license
6011
+ * Copyright 2017 Google LLC
6012
+ *
6013
+ * Licensed under the Apache License, Version 2.0 (the "License");
6014
+ * you may not use this file except in compliance with the License.
6015
+ * You may obtain a copy of the License at
6016
+ *
6017
+ * http://www.apache.org/licenses/LICENSE-2.0
6018
+ *
6019
+ * Unless required by applicable law or agreed to in writing, software
6020
+ * distributed under the License is distributed on an "AS IS" BASIS,
6021
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
6022
+ * See the License for the specific language governing permissions and
6023
+ * limitations under the License.
6024
+ */
6025
+ /**
6026
+ * A map implementation that uses objects as keys. Objects must have an
6027
+ * associated equals function and must be immutable. Entries in the map are
6028
+ * stored together with the key being produced from the mapKeyFn. This map
6029
+ * automatically handles collisions of keys.
6030
+ */
6031
+ class ObjectMap {
6032
+ constructor(mapKeyFn, equalsFn) {
6033
+ this.mapKeyFn = mapKeyFn;
6034
+ this.equalsFn = equalsFn;
6035
+ /**
6036
+ * The inner map for a key/value pair. Due to the possibility of collisions we
6037
+ * keep a list of entries that we do a linear search through to find an actual
6038
+ * match. Note that collisions should be rare, so we still expect near
6039
+ * constant time lookups in practice.
6040
+ */
6041
+ this.inner = {};
6042
+ /** The number of entries stored in the map */
6043
+ this.innerSize = 0;
6044
+ }
6045
+ /** Get a value for this key, or undefined if it does not exist. */
6046
+ get(key) {
6047
+ const id = this.mapKeyFn(key);
6048
+ const matches = this.inner[id];
6049
+ if (matches === undefined) {
6050
+ return undefined;
6063
6051
  }
6064
- else {
6065
- added = true;
6052
+ for (const [otherKey, value] of matches) {
6053
+ if (this.equalsFn(otherKey, key)) {
6054
+ return value;
6055
+ }
6066
6056
  }
6067
- if (added) {
6068
- onAdd(afterValue);
6069
- afterValue = advanceIterator(afterIt);
6057
+ return undefined;
6058
+ }
6059
+ has(key) {
6060
+ return this.get(key) !== undefined;
6061
+ }
6062
+ /** Put this key and value in the map. */
6063
+ set(key, value) {
6064
+ const id = this.mapKeyFn(key);
6065
+ const matches = this.inner[id];
6066
+ if (matches === undefined) {
6067
+ this.inner[id] = [[key, value]];
6068
+ this.innerSize++;
6069
+ return;
6070
6070
  }
6071
- else if (removed) {
6072
- onRemove(beforeValue);
6073
- beforeValue = advanceIterator(beforeIt);
6071
+ for (let i = 0; i < matches.length; i++) {
6072
+ if (this.equalsFn(matches[i][0], key)) {
6073
+ // This is updating an existing entry and does not increase `innerSize`.
6074
+ matches[i] = [key, value];
6075
+ return;
6076
+ }
6074
6077
  }
6075
- else {
6076
- beforeValue = advanceIterator(beforeIt);
6077
- afterValue = advanceIterator(afterIt);
6078
+ matches.push([key, value]);
6079
+ this.innerSize++;
6080
+ }
6081
+ /**
6082
+ * Remove this key from the map. Returns a boolean if anything was deleted.
6083
+ */
6084
+ delete(key) {
6085
+ const id = this.mapKeyFn(key);
6086
+ const matches = this.inner[id];
6087
+ if (matches === undefined) {
6088
+ return false;
6089
+ }
6090
+ for (let i = 0; i < matches.length; i++) {
6091
+ if (this.equalsFn(matches[i][0], key)) {
6092
+ if (matches.length === 1) {
6093
+ delete this.inner[id];
6094
+ }
6095
+ else {
6096
+ matches.splice(i, 1);
6097
+ }
6098
+ this.innerSize--;
6099
+ return true;
6100
+ }
6078
6101
  }
6102
+ return false;
6103
+ }
6104
+ forEach(fn) {
6105
+ forEach(this.inner, (_, entries) => {
6106
+ for (const [k, v] of entries) {
6107
+ fn(k, v);
6108
+ }
6109
+ });
6110
+ }
6111
+ isEmpty() {
6112
+ return isEmpty(this.inner);
6113
+ }
6114
+ size() {
6115
+ return this.innerSize;
6079
6116
  }
6080
- }
6081
- /**
6082
- * Returns the next element from the iterator or `undefined` if none available.
6083
- */
6084
- function advanceIterator(it) {
6085
- return it.hasNext() ? it.getNext() : undefined;
6086
6117
  }
6087
6118
 
6088
6119
  /**
@@ -10000,9 +10031,9 @@ class MemoryIndexManager {
10000
10031
  // Field indices are not supported with memory persistence.
10001
10032
  return PersistencePromise.resolve(null);
10002
10033
  }
10003
- getFieldIndex(transaction, target) {
10034
+ getIndexType(transaction, target) {
10004
10035
  // Field indices are not supported with memory persistence.
10005
- return PersistencePromise.resolve(null);
10036
+ return PersistencePromise.resolve(0 /* NONE */);
10006
10037
  }
10007
10038
  getFieldIndexes(transaction, collectionGroup) {
10008
10039
  // Field indices are not supported with memory persistence.
@@ -10267,10 +10298,27 @@ class IndexedDbIndexManager {
10267
10298
  ? target.collectionGroup
10268
10299
  : target.path.lastSegment();
10269
10300
  return this.getFieldIndexes(transaction, collectionGroup).next(indexes => {
10270
- const matchingIndexes = indexes.filter(i => targetIndexMatcher.servedByIndex(i));
10271
- // Return the index that matches the most number of segments.
10272
- matchingIndexes.sort((l, r) => r.fields.length - l.fields.length);
10273
- return matchingIndexes.length > 0 ? matchingIndexes[0] : null;
10301
+ // Return the index with the most number of segments.
10302
+ let index = null;
10303
+ for (const candidate of indexes) {
10304
+ const matches = targetIndexMatcher.servedByIndex(candidate);
10305
+ if (matches &&
10306
+ (!index || candidate.fields.length > index.fields.length)) {
10307
+ index = candidate;
10308
+ }
10309
+ }
10310
+ return index;
10311
+ });
10312
+ }
10313
+ getIndexType(transaction, target) {
10314
+ // TODO(orqueries): We should look at the subtargets here
10315
+ return this.getFieldIndex(transaction, target).next(index => {
10316
+ if (!index) {
10317
+ return 0 /* NONE */;
10318
+ }
10319
+ return index.fields.length < targetGetSegmentCount(target)
10320
+ ? 1 /* PARTIAL */
10321
+ : 2 /* FULL */;
10274
10322
  });
10275
10323
  }
10276
10324
  /**
@@ -12327,12 +12375,31 @@ function dbCollectionGroupKey(collectionGroup, offset) {
12327
12375
  }
12328
12376
  /**
12329
12377
  * Comparator that compares document keys according to the primary key sorting
12330
- * used by the `DbRemoteDocumentDocument` store (by collection path and then
12331
- * document ID).
12378
+ * used by the `DbRemoteDocumentDocument` store (by prefix path, collection id
12379
+ * and then document ID).
12380
+ *
12381
+ * Visible for testing.
12332
12382
  */
12333
12383
  function dbKeyComparator(l, r) {
12334
- const cmp = l.path.length - r.path.length;
12335
- return cmp !== 0 ? cmp : DocumentKey.comparator(l, r);
12384
+ const left = l.path.toArray();
12385
+ const right = r.path.toArray();
12386
+ // The ordering is based on https://chromium.googlesource.com/chromium/blink/+/fe5c21fef94dae71c1c3344775b8d8a7f7e6d9ec/Source/modules/indexeddb/IDBKey.cpp#74
12387
+ let cmp = 0;
12388
+ for (let i = 0; i < left.length - 2 && i < right.length - 2; ++i) {
12389
+ cmp = primitiveComparator(left[i], right[i]);
12390
+ if (cmp) {
12391
+ return cmp;
12392
+ }
12393
+ }
12394
+ cmp = primitiveComparator(left.length, right.length);
12395
+ if (cmp) {
12396
+ return cmp;
12397
+ }
12398
+ cmp = primitiveComparator(left[left.length - 2], right[right.length - 2]);
12399
+ if (cmp) {
12400
+ return cmp;
12401
+ }
12402
+ return primitiveComparator(left[left.length - 1], right[right.length - 1]);
12336
12403
  }
12337
12404
  /**
12338
12405
  * Schema Version for the Web client: