@firebase/firestore 3.4.13 → 3.4.14-canary.04dcdbb0f

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 (102) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/dist/firestore/src/api/credentials.d.ts +13 -3
  3. package/dist/firestore/src/api/database.d.ts +34 -3
  4. package/dist/firestore/src/api/index_configuration.d.ts +7 -8
  5. package/dist/firestore/src/api.d.ts +1 -1
  6. package/dist/firestore/src/core/database_info.d.ts +4 -0
  7. package/dist/firestore/src/lite-api/database.d.ts +51 -7
  8. package/dist/firestore/src/local/indexeddb_schema.d.ts +1 -3
  9. package/dist/firestore/src/local/local_store_impl.d.ts +2 -0
  10. package/dist/firestore/src/util/array.d.ts +18 -0
  11. package/dist/firestore/test/integration/api/provider.test.d.ts +17 -0
  12. package/dist/firestore/test/integration/util/firebase_export.d.ts +2 -1
  13. package/dist/firestore/test/integration/util/helpers.d.ts +1 -0
  14. package/dist/firestore/test/unit/local/counting_query_engine.d.ts +11 -0
  15. package/dist/firestore/test/unit/local/local_store_indexeddb.test.d.ts +17 -0
  16. package/dist/firestore/test/unit/specs/index_spec.test.d.ts +17 -0
  17. package/dist/firestore/test/unit/specs/spec_builder.d.ts +5 -0
  18. package/dist/firestore/test/unit/specs/spec_test_runner.d.ts +8 -0
  19. package/dist/firestore/test/unit/util/array.test.d.ts +17 -0
  20. package/dist/index.d.ts +15 -4
  21. package/dist/index.esm2017.js +3793 -3646
  22. package/dist/index.esm2017.js.map +1 -1
  23. package/dist/index.esm5.js +3762 -3648
  24. package/dist/index.esm5.js.map +1 -1
  25. package/dist/index.node.cjs.js +295 -93
  26. package/dist/index.node.cjs.js.map +1 -1
  27. package/dist/index.node.mjs +295 -93
  28. package/dist/index.node.mjs.map +1 -1
  29. package/dist/index.rn.js +3732 -3586
  30. package/dist/index.rn.js.map +1 -1
  31. package/dist/internal.d.ts +53 -19
  32. package/dist/lite/firestore/src/api/credentials.d.ts +13 -3
  33. package/dist/lite/firestore/src/api/database.d.ts +34 -3
  34. package/dist/lite/firestore/src/api/index_configuration.d.ts +7 -8
  35. package/dist/lite/firestore/src/api.d.ts +1 -1
  36. package/dist/lite/firestore/src/core/database_info.d.ts +4 -0
  37. package/dist/lite/firestore/src/lite-api/database.d.ts +51 -7
  38. package/dist/lite/firestore/src/local/indexeddb_schema.d.ts +1 -3
  39. package/dist/lite/firestore/src/local/local_store_impl.d.ts +2 -0
  40. package/dist/lite/firestore/src/util/array.d.ts +18 -0
  41. package/dist/lite/firestore/test/integration/api/provider.test.d.ts +17 -0
  42. package/dist/lite/firestore/test/integration/util/firebase_export.d.ts +2 -1
  43. package/dist/lite/firestore/test/integration/util/helpers.d.ts +1 -0
  44. package/dist/lite/firestore/test/unit/local/counting_query_engine.d.ts +11 -0
  45. package/dist/lite/firestore/test/unit/local/local_store_indexeddb.test.d.ts +17 -0
  46. package/dist/lite/firestore/test/unit/specs/index_spec.test.d.ts +17 -0
  47. package/dist/lite/firestore/test/unit/specs/spec_builder.d.ts +5 -0
  48. package/dist/lite/firestore/test/unit/specs/spec_test_runner.d.ts +8 -0
  49. package/dist/lite/firestore/test/unit/util/array.test.d.ts +17 -0
  50. package/dist/lite/index.browser.esm2017.js +273 -277
  51. package/dist/lite/index.browser.esm2017.js.map +1 -1
  52. package/dist/lite/index.browser.esm5.js +506 -493
  53. package/dist/lite/index.browser.esm5.js.map +1 -1
  54. package/dist/lite/index.d.ts +15 -4
  55. package/dist/lite/index.node.cjs.js +71 -61
  56. package/dist/lite/index.node.cjs.js.map +1 -1
  57. package/dist/lite/index.node.mjs +71 -61
  58. package/dist/lite/index.node.mjs.map +1 -1
  59. package/dist/lite/index.rn.esm2017.js +273 -277
  60. package/dist/lite/index.rn.esm2017.js.map +1 -1
  61. package/dist/lite/internal.d.ts +58 -7
  62. package/dist/lite/packages/firestore/dist/lite/index.browser.esm2017.d.ts +29 -66
  63. package/dist/lite/packages/firestore/src/api/credentials.d.ts +13 -3
  64. package/dist/lite/packages/firestore/src/api/database.d.ts +34 -3
  65. package/dist/lite/packages/firestore/src/api/index_configuration.d.ts +7 -8
  66. package/dist/lite/packages/firestore/src/api.d.ts +1 -1
  67. package/dist/lite/packages/firestore/src/core/database_info.d.ts +4 -0
  68. package/dist/lite/packages/firestore/src/lite-api/database.d.ts +51 -7
  69. package/dist/lite/packages/firestore/src/local/indexeddb_schema.d.ts +1 -3
  70. package/dist/lite/packages/firestore/src/local/local_store_impl.d.ts +2 -0
  71. package/dist/lite/packages/firestore/src/util/array.d.ts +18 -0
  72. package/dist/lite/packages/firestore/test/integration/api/provider.test.d.ts +17 -0
  73. package/dist/lite/packages/firestore/test/integration/util/firebase_export.d.ts +2 -1
  74. package/dist/lite/packages/firestore/test/integration/util/helpers.d.ts +1 -0
  75. package/dist/lite/packages/firestore/test/unit/local/counting_query_engine.d.ts +11 -0
  76. package/dist/lite/packages/firestore/test/unit/local/local_store_indexeddb.test.d.ts +17 -0
  77. package/dist/lite/packages/firestore/test/unit/specs/index_spec.test.d.ts +17 -0
  78. package/dist/lite/packages/firestore/test/unit/specs/spec_builder.d.ts +5 -0
  79. package/dist/lite/packages/firestore/test/unit/specs/spec_test_runner.d.ts +8 -0
  80. package/dist/lite/packages/firestore/test/unit/util/array.test.d.ts +17 -0
  81. package/dist/lite/private.d.ts +25 -7
  82. package/dist/packages/firestore/dist/index.esm2017.d.ts +208 -203
  83. package/dist/packages/firestore/src/api/credentials.d.ts +13 -3
  84. package/dist/packages/firestore/src/api/database.d.ts +34 -3
  85. package/dist/packages/firestore/src/api/index_configuration.d.ts +7 -8
  86. package/dist/packages/firestore/src/api.d.ts +1 -1
  87. package/dist/packages/firestore/src/core/database_info.d.ts +4 -0
  88. package/dist/packages/firestore/src/lite-api/database.d.ts +51 -7
  89. package/dist/packages/firestore/src/local/indexeddb_schema.d.ts +1 -3
  90. package/dist/packages/firestore/src/local/local_store_impl.d.ts +2 -0
  91. package/dist/packages/firestore/src/util/array.d.ts +18 -0
  92. package/dist/packages/firestore/test/integration/api/provider.test.d.ts +17 -0
  93. package/dist/packages/firestore/test/integration/util/firebase_export.d.ts +2 -1
  94. package/dist/packages/firestore/test/integration/util/helpers.d.ts +1 -0
  95. package/dist/packages/firestore/test/unit/local/counting_query_engine.d.ts +11 -0
  96. package/dist/packages/firestore/test/unit/local/local_store_indexeddb.test.d.ts +17 -0
  97. package/dist/packages/firestore/test/unit/specs/index_spec.test.d.ts +17 -0
  98. package/dist/packages/firestore/test/unit/specs/spec_builder.d.ts +5 -0
  99. package/dist/packages/firestore/test/unit/specs/spec_test_runner.d.ts +8 -0
  100. package/dist/packages/firestore/test/unit/util/array.test.d.ts +17 -0
  101. package/dist/private.d.ts +25 -8
  102. package/package.json +11 -9
@@ -8,7 +8,7 @@ import * as grpc from '@grpc/grpc-js';
8
8
  import * as protoLoader from '@grpc/proto-loader';
9
9
 
10
10
  const name = "@firebase/firestore";
11
- const version$1 = "3.4.13";
11
+ const version$1 = "3.4.14-canary.04dcdbb0f";
12
12
 
13
13
  /**
14
14
  * @license
@@ -61,7 +61,7 @@ User.GOOGLE_CREDENTIALS = new User('google-credentials-uid');
61
61
  User.FIRST_PARTY = new User('first-party-uid');
62
62
  User.MOCK_USER = new User('mock-user');
63
63
 
64
- const version = "9.9.1";
64
+ const version = "9.9.3-canary.04dcdbb0f";
65
65
 
66
66
  /**
67
67
  * @license
@@ -616,19 +616,41 @@ class FirebaseAuthCredentialsProvider {
616
616
  * safer to keep the implementation as-is.
617
617
  */
618
618
  class FirstPartyToken {
619
- constructor(gapi, sessionIndex, iamToken) {
619
+ constructor(gapi, sessionIndex, iamToken, authTokenFactory) {
620
+ this.gapi = gapi;
621
+ this.sessionIndex = sessionIndex;
622
+ this.iamToken = iamToken;
623
+ this.authTokenFactory = authTokenFactory;
620
624
  this.type = 'FirstParty';
621
625
  this.user = User.FIRST_PARTY;
622
- this.headers = new Map();
623
- this.headers.set('X-Goog-AuthUser', sessionIndex);
624
- const authHeader = gapi['auth']['getAuthHeaderValueForFirstParty']([]);
625
- if (authHeader) {
626
- this.headers.set('Authorization', authHeader);
626
+ this._headers = new Map();
627
+ }
628
+ /** Gets an authorization token, using a provided factory function, or falling back to First Party GAPI. */
629
+ getAuthToken() {
630
+ if (this.authTokenFactory) {
631
+ return this.authTokenFactory();
627
632
  }
628
- if (iamToken) {
629
- this.headers.set('X-Goog-Iam-Authorization-Token', iamToken);
633
+ else {
634
+ // Make sure this really is a Gapi client.
635
+ hardAssert(!!(typeof this.gapi === 'object' &&
636
+ this.gapi !== null &&
637
+ this.gapi['auth'] &&
638
+ this.gapi['auth']['getAuthHeaderValueForFirstParty']));
639
+ return this.gapi['auth']['getAuthHeaderValueForFirstParty']([]);
630
640
  }
631
641
  }
642
+ get headers() {
643
+ this._headers.set('X-Goog-AuthUser', this.sessionIndex);
644
+ // Use array notation to prevent minification
645
+ const authHeaderTokenValue = this.getAuthToken();
646
+ if (authHeaderTokenValue) {
647
+ this._headers.set('Authorization', authHeaderTokenValue);
648
+ }
649
+ if (this.iamToken) {
650
+ this._headers.set('X-Goog-Iam-Authorization-Token', this.iamToken);
651
+ }
652
+ return this._headers;
653
+ }
632
654
  }
633
655
  /*
634
656
  * Provides user credentials required for the Firestore JavaScript SDK
@@ -636,13 +658,14 @@ class FirstPartyToken {
636
658
  * to applications hosted by Google.
637
659
  */
638
660
  class FirstPartyAuthCredentialsProvider {
639
- constructor(gapi, sessionIndex, iamToken) {
661
+ constructor(gapi, sessionIndex, iamToken, authTokenFactory) {
640
662
  this.gapi = gapi;
641
663
  this.sessionIndex = sessionIndex;
642
664
  this.iamToken = iamToken;
665
+ this.authTokenFactory = authTokenFactory;
643
666
  }
644
667
  getToken() {
645
- return Promise.resolve(new FirstPartyToken(this.gapi, this.sessionIndex, this.iamToken));
668
+ return Promise.resolve(new FirstPartyToken(this.gapi, this.sessionIndex, this.iamToken, this.authTokenFactory));
646
669
  }
647
670
  start(asyncQueue, changeListener) {
648
671
  // Fire with initial uid.
@@ -753,12 +776,7 @@ function makeAuthCredentialsProvider(credentials) {
753
776
  switch (credentials['type']) {
754
777
  case 'gapi':
755
778
  const client = credentials['client'];
756
- // Make sure this really is a Gapi client.
757
- hardAssert(!!(typeof client === 'object' &&
758
- client !== null &&
759
- client['auth'] &&
760
- client['auth']['getAuthHeaderValueForFirstParty']));
761
- return new FirstPartyAuthCredentialsProvider(client, credentials['sessionIndex'] || '0', credentials['iamToken'] || null);
779
+ return new FirstPartyAuthCredentialsProvider(client, credentials['sessionIndex'] || '0', credentials['iamToken'] || null, credentials['authTokenFactory'] || null);
762
780
  case 'provider':
763
781
  return credentials['client'];
764
782
  default:
@@ -1498,6 +1516,23 @@ function fieldIndexGetKeyOrder(fieldIndex) {
1498
1516
  ? 0 /* ASCENDING */
1499
1517
  : directionalSegments[directionalSegments.length - 1].kind;
1500
1518
  }
1519
+ /**
1520
+ * Compares indexes by collection group and segments. Ignores update time and
1521
+ * index ID.
1522
+ */
1523
+ function fieldIndexSemanticComparator(left, right) {
1524
+ let cmp = primitiveComparator(left.collectionGroup, right.collectionGroup);
1525
+ if (cmp !== 0) {
1526
+ return cmp;
1527
+ }
1528
+ for (let i = 0; i < Math.min(left.fields.length, right.fields.length); ++i) {
1529
+ cmp = indexSegmentComparator(left.fields[i], right.fields[i]);
1530
+ if (cmp !== 0) {
1531
+ return cmp;
1532
+ }
1533
+ }
1534
+ return primitiveComparator(left.fields.length, right.fields.length);
1535
+ }
1501
1536
  /** Returns a debug representation of the field index */
1502
1537
  function fieldIndexToString(fieldIndex) {
1503
1538
  return `id=${fieldIndex.indexId}|cg=${fieldIndex.collectionGroup}|f=${fieldIndex.fields.map(f => `${f.fieldPath}:${f.kind}`).join(',')}`;
@@ -1513,6 +1548,13 @@ class IndexSegment {
1513
1548
  this.kind = kind;
1514
1549
  }
1515
1550
  }
1551
+ function indexSegmentComparator(left, right) {
1552
+ const cmp = FieldPath$1.comparator(left.fieldPath, right.fieldPath);
1553
+ if (cmp !== 0) {
1554
+ return cmp;
1555
+ }
1556
+ return primitiveComparator(left.kind, right.kind);
1557
+ }
1516
1558
  /**
1517
1559
  * Stores the "high water mark" that indicates how updated the Index is for the
1518
1560
  * current user.
@@ -1599,31 +1641,6 @@ function indexOffsetComparator(left, right) {
1599
1641
  }
1600
1642
  return primitiveComparator(left.largestBatchId, right.largestBatchId);
1601
1643
  }
1602
- /**
1603
- * Schema Version for the Web client:
1604
- * 1. Initial version including Mutation Queue, Query Cache, and Remote
1605
- * Document Cache
1606
- * 2. Used to ensure a targetGlobal object exists and add targetCount to it. No
1607
- * longer required because migration 3 unconditionally clears it.
1608
- * 3. Dropped and re-created Query Cache to deal with cache corruption related
1609
- * to limbo resolution. Addresses
1610
- * https://github.com/firebase/firebase-ios-sdk/issues/1548
1611
- * 4. Multi-Tab Support.
1612
- * 5. Removal of held write acks.
1613
- * 6. Create document global for tracking document cache size.
1614
- * 7. Ensure every cached document has a sentinel row with a sequence number.
1615
- * 8. Add collection-parent index for Collection Group queries.
1616
- * 9. Change RemoteDocumentChanges store to be keyed by readTime rather than
1617
- * an auto-incrementing ID. This is required for Index-Free queries.
1618
- * 10. Rewrite the canonical IDs to the explicit Protobuf-based format.
1619
- * 11. Add bundles and named_queries for bundle support.
1620
- * 12. Add document overlays.
1621
- * 13. Rewrite the keys of the remote document cache to allow for efficient
1622
- * document lookup via `getAll()`.
1623
- * 14. Add overlays.
1624
- * 15. Add indexing support.
1625
- */
1626
- const SCHEMA_VERSION = 14;
1627
1644
 
1628
1645
  /**
1629
1646
  * @license
@@ -2583,6 +2600,8 @@ function checkForAndReportiOSError(error) {
2583
2600
  }
2584
2601
 
2585
2602
  const LOG_TAG$h = 'IndexBackiller';
2603
+ /** How long we wait to try running index backfill after SDK initialization. */
2604
+ const INITIAL_BACKFILL_DELAY_MS = 15;
2586
2605
  /** Minimum amount of time between backfill checks, after the first one. */
2587
2606
  const REGULAR_BACKFILL_DELAY_MS = 1;
2588
2607
  /** The maximum number of documents to process each time backfill() is called. */
@@ -2595,6 +2614,7 @@ class IndexBackfillerScheduler {
2595
2614
  this.task = null;
2596
2615
  }
2597
2616
  start() {
2617
+ this.schedule(INITIAL_BACKFILL_DELAY_MS);
2598
2618
  }
2599
2619
  stop() {
2600
2620
  if (this.task) {
@@ -4323,6 +4343,12 @@ class DatabaseId {
4323
4343
  other.projectId === this.projectId &&
4324
4344
  other.database === this.database);
4325
4345
  }
4346
+ }
4347
+ function databaseIdFromApp(app, database) {
4348
+ if (!Object.prototype.hasOwnProperty.apply(app.options, ['projectId'])) {
4349
+ throw new FirestoreError(Code.INVALID_ARGUMENT, '"projectId" not provided in firebase.initializeApp.');
4350
+ }
4351
+ return new DatabaseId(app.options.projectId, database);
4326
4352
  }
4327
4353
 
4328
4354
  /**
@@ -12710,6 +12736,48 @@ function dbKeyComparator(l, r) {
12710
12736
  return primitiveComparator(left[left.length - 1], right[right.length - 1]);
12711
12737
  }
12712
12738
 
12739
+ /**
12740
+ * @license
12741
+ * Copyright 2017 Google LLC
12742
+ *
12743
+ * Licensed under the Apache License, Version 2.0 (the "License");
12744
+ * you may not use this file except in compliance with the License.
12745
+ * You may obtain a copy of the License at
12746
+ *
12747
+ * http://www.apache.org/licenses/LICENSE-2.0
12748
+ *
12749
+ * Unless required by applicable law or agreed to in writing, software
12750
+ * distributed under the License is distributed on an "AS IS" BASIS,
12751
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12752
+ * See the License for the specific language governing permissions and
12753
+ * limitations under the License.
12754
+ */
12755
+ /**
12756
+ * Schema Version for the Web client:
12757
+ * 1. Initial version including Mutation Queue, Query Cache, and Remote
12758
+ * Document Cache
12759
+ * 2. Used to ensure a targetGlobal object exists and add targetCount to it. No
12760
+ * longer required because migration 3 unconditionally clears it.
12761
+ * 3. Dropped and re-created Query Cache to deal with cache corruption related
12762
+ * to limbo resolution. Addresses
12763
+ * https://github.com/firebase/firebase-ios-sdk/issues/1548
12764
+ * 4. Multi-Tab Support.
12765
+ * 5. Removal of held write acks.
12766
+ * 6. Create document global for tracking document cache size.
12767
+ * 7. Ensure every cached document has a sentinel row with a sequence number.
12768
+ * 8. Add collection-parent index for Collection Group queries.
12769
+ * 9. Change RemoteDocumentChanges store to be keyed by readTime rather than
12770
+ * an auto-incrementing ID. This is required for Index-Free queries.
12771
+ * 10. Rewrite the canonical IDs to the explicit Protobuf-based format.
12772
+ * 11. Add bundles and named_queries for bundle support.
12773
+ * 12. Add document overlays.
12774
+ * 13. Rewrite the keys of the remote document cache to allow for efficient
12775
+ * document lookup via `getAll()`.
12776
+ * 14. Add overlays.
12777
+ * 15. Add indexing support.
12778
+ */
12779
+ const SCHEMA_VERSION = 15;
12780
+
12713
12781
  /**
12714
12782
  * @license
12715
12783
  * Copyright 2022 Google LLC
@@ -15248,6 +15316,73 @@ async function indexedDbClearPersistence(persistenceKey) {
15248
15316
  await SimpleDb.delete(dbName);
15249
15317
  }
15250
15318
 
15319
+ /**
15320
+ * @license
15321
+ * Copyright 2017 Google LLC
15322
+ *
15323
+ * Licensed under the Apache License, Version 2.0 (the "License");
15324
+ * you may not use this file except in compliance with the License.
15325
+ * You may obtain a copy of the License at
15326
+ *
15327
+ * http://www.apache.org/licenses/LICENSE-2.0
15328
+ *
15329
+ * Unless required by applicable law or agreed to in writing, software
15330
+ * distributed under the License is distributed on an "AS IS" BASIS,
15331
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15332
+ * See the License for the specific language governing permissions and
15333
+ * limitations under the License.
15334
+ */
15335
+ /**
15336
+ * Compares two array for equality using comparator. The method computes the
15337
+ * intersection and invokes `onAdd` for every element that is in `after` but not
15338
+ * `before`. `onRemove` is invoked for every element in `before` but missing
15339
+ * from `after`.
15340
+ *
15341
+ * The method creates a copy of both `before` and `after` and runs in O(n log
15342
+ * n), where n is the size of the two lists.
15343
+ *
15344
+ * @param before - The elements that exist in the original array.
15345
+ * @param after - The elements to diff against the original array.
15346
+ * @param comparator - The comparator for the elements in before and after.
15347
+ * @param onAdd - A function to invoke for every element that is part of `
15348
+ * after` but not `before`.
15349
+ * @param onRemove - A function to invoke for every element that is part of
15350
+ * `before` but not `after`.
15351
+ */
15352
+ function diffArrays(before, after, comparator, onAdd, onRemove) {
15353
+ before = [...before];
15354
+ after = [...after];
15355
+ before.sort(comparator);
15356
+ after.sort(comparator);
15357
+ const bLen = before.length;
15358
+ const aLen = after.length;
15359
+ let a = 0;
15360
+ let b = 0;
15361
+ while (a < aLen && b < bLen) {
15362
+ const cmp = comparator(before[b], after[a]);
15363
+ if (cmp < 0) {
15364
+ // The element was removed if the next element in our ordered
15365
+ // walkthrough is only in `before`.
15366
+ onRemove(before[b++]);
15367
+ }
15368
+ else if (cmp > 0) {
15369
+ // The element was added if the next element in our ordered walkthrough
15370
+ // is only in `after`.
15371
+ onAdd(after[a++]);
15372
+ }
15373
+ else {
15374
+ a++;
15375
+ b++;
15376
+ }
15377
+ }
15378
+ while (a < aLen) {
15379
+ onAdd(after[a++]);
15380
+ }
15381
+ while (b < bLen) {
15382
+ onRemove(before[b++]);
15383
+ }
15384
+ }
15385
+
15251
15386
  /**
15252
15387
  * @license
15253
15388
  * Copyright 2020 Google LLC
@@ -16097,6 +16232,19 @@ async function localStoreSaveNamedQuery(localStore, query, documents = documentK
16097
16232
  .next(() => localStoreImpl.targetCache.addMatchingKeys(transaction, documents, allocated.targetId))
16098
16233
  .next(() => localStoreImpl.bundleCache.saveNamedQuery(transaction, query));
16099
16234
  });
16235
+ }
16236
+ async function localStoreConfigureFieldIndexes(localStore, newFieldIndexes) {
16237
+ const localStoreImpl = debugCast(localStore);
16238
+ const indexManager = localStoreImpl.indexManager;
16239
+ const promises = [];
16240
+ return localStoreImpl.persistence.runTransaction('Configure indexes', 'readwrite', transaction => indexManager
16241
+ .getFieldIndexes(transaction)
16242
+ .next(oldFieldIndexes => diffArrays(oldFieldIndexes, newFieldIndexes, fieldIndexSemanticComparator, fieldIndex => {
16243
+ promises.push(indexManager.addFieldIndex(transaction, fieldIndex));
16244
+ }, fieldIndex => {
16245
+ promises.push(indexManager.deleteFieldIndex(transaction, fieldIndex));
16246
+ }))
16247
+ .next(() => PersistencePromise.waitFor(promises)));
16100
16248
  }
16101
16249
 
16102
16250
  /**
@@ -16176,9 +16324,56 @@ class QueryEngine {
16176
16324
  * persisted index values. Returns `null` if an index is not available.
16177
16325
  */
16178
16326
  performQueryUsingIndex(transaction, query) {
16179
- {
16327
+ if (queryMatchesAllDocuments(query)) {
16328
+ // Queries that match all documents don't benefit from using
16329
+ // key-based lookups. It is more efficient to scan all documents in a
16330
+ // collection, rather than to perform individual lookups.
16180
16331
  return PersistencePromise.resolve(null);
16181
16332
  }
16333
+ let target = queryToTarget(query);
16334
+ return this.indexManager
16335
+ .getIndexType(transaction, target)
16336
+ .next(indexType => {
16337
+ if (indexType === 0 /* NONE */) {
16338
+ // The target cannot be served from any index.
16339
+ return null;
16340
+ }
16341
+ if (query.limit !== null && indexType === 1 /* PARTIAL */) {
16342
+ // We cannot apply a limit for targets that are served using a partial
16343
+ // index. If a partial index will be used to serve the target, the
16344
+ // query may return a superset of documents that match the target
16345
+ // (e.g. if the index doesn't include all the target's filters), or
16346
+ // may return the correct set of documents in the wrong order (e.g. if
16347
+ // the index doesn't include a segment for one of the orderBys).
16348
+ // Therefore, a limit should not be applied in such cases.
16349
+ query = queryWithLimit(query, null, "F" /* First */);
16350
+ target = queryToTarget(query);
16351
+ }
16352
+ return this.indexManager
16353
+ .getDocumentsMatchingTarget(transaction, target)
16354
+ .next(keys => {
16355
+ const sortedKeys = documentKeySet(...keys);
16356
+ return this.localDocumentsView
16357
+ .getDocuments(transaction, sortedKeys)
16358
+ .next(indexedDocuments => {
16359
+ return this.indexManager
16360
+ .getMinOffset(transaction, target)
16361
+ .next(offset => {
16362
+ const previousResults = this.applyQuery(query, indexedDocuments);
16363
+ if (this.needsRefill(query, previousResults, sortedKeys, offset.readTime)) {
16364
+ // A limit query whose boundaries change due to local
16365
+ // edits can be re-run against the cache by excluding the
16366
+ // limit. This ensures that all documents that match the
16367
+ // query's filters are included in the result set. The SDK
16368
+ // can then apply the limit once all local edits are
16369
+ // incorporated.
16370
+ return this.performQueryUsingIndex(transaction, queryWithLimit(query, null, "F" /* First */));
16371
+ }
16372
+ return this.appendRemainingResults(transaction, previousResults, query, offset);
16373
+ });
16374
+ });
16375
+ });
16376
+ });
16182
16377
  }
16183
16378
  /**
16184
16379
  * Performs a query based on the target's persisted query mapping. Returns
@@ -24273,7 +24468,7 @@ class AsyncObserver {
24273
24468
  this.scheduleEvent(this.observer.error, error);
24274
24469
  }
24275
24470
  else {
24276
- console.error('Uncaught Error in snapshot listener:', error);
24471
+ logError('Uncaught Error in snapshot listener:', error);
24277
24472
  }
24278
24473
  }
24279
24474
  mute() {
@@ -24569,7 +24764,7 @@ class Transaction$2 {
24569
24764
  docVersion = doc.version;
24570
24765
  }
24571
24766
  else if (doc.isNoDocument()) {
24572
- // For deleted docs, we must use baseVersion 0 when we overwrite them.
24767
+ // Represent a deleted doc using SnapshotVersion.min().
24573
24768
  docVersion = SnapshotVersion.min();
24574
24769
  }
24575
24770
  else {
@@ -24593,7 +24788,12 @@ class Transaction$2 {
24593
24788
  precondition(key) {
24594
24789
  const version = this.readVersions.get(key.toString());
24595
24790
  if (!this.writtenDocs.has(key.toString()) && version) {
24596
- return Precondition.updateTime(version);
24791
+ if (version.isEqual(SnapshotVersion.min())) {
24792
+ return Precondition.exists(false);
24793
+ }
24794
+ else {
24795
+ return Precondition.updateTime(version);
24796
+ }
24597
24797
  }
24598
24798
  else {
24599
24799
  return Precondition.none();
@@ -25288,9 +25488,11 @@ class FirestoreSettingsImpl {
25288
25488
  */
25289
25489
  class Firestore$1 {
25290
25490
  /** @hideconstructor */
25291
- constructor(databaseIdOrApp, _authCredentials, _appCheckCredentials) {
25491
+ constructor(_authCredentials, _appCheckCredentials, _databaseId, _app) {
25292
25492
  this._authCredentials = _authCredentials;
25293
25493
  this._appCheckCredentials = _appCheckCredentials;
25494
+ this._databaseId = _databaseId;
25495
+ this._app = _app;
25294
25496
  /**
25295
25497
  * Whether it's a Firestore or Firestore Lite instance.
25296
25498
  */
@@ -25298,13 +25500,6 @@ class Firestore$1 {
25298
25500
  this._persistenceKey = '(lite)';
25299
25501
  this._settings = new FirestoreSettingsImpl({});
25300
25502
  this._settingsFrozen = false;
25301
- if (databaseIdOrApp instanceof DatabaseId) {
25302
- this._databaseId = databaseIdOrApp;
25303
- }
25304
- else {
25305
- this._app = databaseIdOrApp;
25306
- this._databaseId = databaseIdFromApp(databaseIdOrApp);
25307
- }
25308
25503
  }
25309
25504
  /**
25310
25505
  * The {@link @firebase/app#FirebaseApp} associated with this `Firestore` service
@@ -25367,12 +25562,6 @@ class Firestore$1 {
25367
25562
  return Promise.resolve();
25368
25563
  }
25369
25564
  }
25370
- function databaseIdFromApp(app) {
25371
- if (!Object.prototype.hasOwnProperty.apply(app.options, ['projectId'])) {
25372
- throw new FirestoreError(Code.INVALID_ARGUMENT, '"projectId" not provided in firebase.initializeApp.');
25373
- }
25374
- return new DatabaseId(app.options.projectId);
25375
- }
25376
25565
  /**
25377
25566
  * Modify this instance to communicate with the Cloud Firestore emulator.
25378
25567
  *
@@ -26041,15 +26230,14 @@ const CACHE_SIZE_UNLIMITED = LRU_COLLECTION_DISABLED;
26041
26230
  */
26042
26231
  class Firestore extends Firestore$1 {
26043
26232
  /** @hideconstructor */
26044
- constructor(databaseIdOrApp, authCredentialsProvider, appCheckCredentialsProvider) {
26045
- super(databaseIdOrApp, authCredentialsProvider, appCheckCredentialsProvider);
26233
+ constructor(authCredentialsProvider, appCheckCredentialsProvider, databaseId, app) {
26234
+ super(authCredentialsProvider, appCheckCredentialsProvider, databaseId, app);
26046
26235
  /**
26047
26236
  * Whether it's a {@link Firestore} or Firestore Lite instance.
26048
26237
  */
26049
26238
  this.type = 'firestore';
26050
26239
  this._queue = newAsyncQueue();
26051
- this._persistenceKey =
26052
- 'name' in databaseIdOrApp ? databaseIdOrApp.name : '[DEFAULT]';
26240
+ this._persistenceKey = (app === null || app === void 0 ? void 0 : app.name) || '[DEFAULT]';
26053
26241
  }
26054
26242
  _terminate() {
26055
26243
  if (!this._firestoreClient) {
@@ -26069,13 +26257,19 @@ class Firestore extends Firestore$1 {
26069
26257
  * @param app - The {@link @firebase/app#FirebaseApp} with which the {@link Firestore} instance will
26070
26258
  * be associated.
26071
26259
  * @param settings - A settings object to configure the {@link Firestore} instance.
26260
+ * @param databaseId - The name of database.
26072
26261
  * @returns A newly initialized {@link Firestore} instance.
26073
26262
  */
26074
- function initializeFirestore(app, settings) {
26263
+ function initializeFirestore(app, settings, databaseId) {
26264
+ if (!databaseId) {
26265
+ databaseId = DEFAULT_DATABASE_NAME;
26266
+ }
26075
26267
  const provider = _getProvider(app, 'firestore');
26076
- if (provider.isInitialized()) {
26077
- const existingInstance = provider.getImmediate();
26078
- const initialSettings = provider.getOptions();
26268
+ if (provider.isInitialized(databaseId)) {
26269
+ const existingInstance = provider.getImmediate({
26270
+ identifier: databaseId
26271
+ });
26272
+ const initialSettings = provider.getOptions(databaseId);
26079
26273
  if (deepEqual(initialSettings, settings)) {
26080
26274
  return existingInstance;
26081
26275
  }
@@ -26091,19 +26285,19 @@ function initializeFirestore(app, settings) {
26091
26285
  settings.cacheSizeBytes < LRU_MINIMUM_CACHE_SIZE_BYTES) {
26092
26286
  throw new FirestoreError(Code.INVALID_ARGUMENT, `cacheSizeBytes must be at least ${LRU_MINIMUM_CACHE_SIZE_BYTES}`);
26093
26287
  }
26094
- return provider.initialize({ options: settings });
26288
+ return provider.initialize({
26289
+ options: settings,
26290
+ instanceIdentifier: databaseId
26291
+ });
26095
26292
  }
26096
- /**
26097
- * Returns the existing {@link Firestore} instance that is associated with the
26098
- * provided {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new
26099
- * instance with default settings.
26100
- *
26101
- * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned {@link Firestore}
26102
- * instance is associated with.
26103
- * @returns The {@link Firestore} instance of the provided app.
26104
- */
26105
- function getFirestore(app = getApp()) {
26106
- return _getProvider(app, 'firestore').getImmediate();
26293
+ function getFirestore(appOrDatabaseId, optionalDatabaseId) {
26294
+ const app = typeof appOrDatabaseId === 'object' ? appOrDatabaseId : getApp();
26295
+ const databaseId = typeof appOrDatabaseId === 'string'
26296
+ ? appOrDatabaseId
26297
+ : optionalDatabaseId || DEFAULT_DATABASE_NAME;
26298
+ return _getProvider(app, 'firestore').getImmediate({
26299
+ identifier: databaseId
26300
+ });
26107
26301
  }
26108
26302
  /**
26109
26303
  * @internal
@@ -26204,7 +26398,7 @@ function setPersistenceProviders(client, onlineComponentProvider, offlineCompone
26204
26398
  if (!canFallbackFromIndexedDbError(error)) {
26205
26399
  throw error;
26206
26400
  }
26207
- console.warn('Error enabling offline persistence. Falling back to ' +
26401
+ logWarn('Error enabling offline persistence. Falling back to ' +
26208
26402
  'persistence disabled: ' +
26209
26403
  error);
26210
26404
  persistenceResult.reject(error);
@@ -26349,7 +26543,7 @@ function disableNetwork(firestore) {
26349
26543
  * terminated.
26350
26544
  */
26351
26545
  function terminate(firestore) {
26352
- _removeServiceInstance(firestore.app, 'firestore');
26546
+ _removeServiceInstance(firestore.app, 'firestore', firestore._databaseId.database);
26353
26547
  return firestore._delete();
26354
26548
  }
26355
26549
  /**
@@ -26418,13 +26612,13 @@ function verifyNotInitialized(firestore) {
26418
26612
  */
26419
26613
  function registerFirestore(variant, useFetchStreams = true) {
26420
26614
  setSDKVersion(SDK_VERSION$1);
26421
- _registerComponent(new Component('firestore', (container, { options: settings }) => {
26615
+ _registerComponent(new Component('firestore', (container, { instanceIdentifier: databaseId, options: settings }) => {
26422
26616
  const app = container.getProvider('app').getImmediate();
26423
- const firestoreInstance = new Firestore(app, new FirebaseAuthCredentialsProvider(container.getProvider('auth-internal')), new FirebaseAppCheckTokenProvider(container.getProvider('app-check-internal')));
26617
+ const firestoreInstance = new Firestore(new FirebaseAuthCredentialsProvider(container.getProvider('auth-internal')), new FirebaseAppCheckTokenProvider(container.getProvider('app-check-internal')), databaseIdFromApp(app, databaseId), app);
26424
26618
  settings = Object.assign({ useFetchStreams }, settings);
26425
26619
  firestoreInstance._setSettings(settings);
26426
26620
  return firestoreInstance;
26427
- }, 'PUBLIC'));
26621
+ }, 'PUBLIC').setMultipleInstances(true));
26428
26622
  registerVersion(name, version$1, variant);
26429
26623
  // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation
26430
26624
  registerVersion(name, version$1, 'esm2017');
@@ -29118,14 +29312,23 @@ function writeBatch(firestore) {
29118
29312
  * limitations under the License.
29119
29313
  */
29120
29314
  function setIndexConfiguration(firestore, jsonOrConfiguration) {
29315
+ var _a;
29121
29316
  firestore = cast(firestore, Firestore);
29122
- ensureFirestoreConfigured(firestore);
29317
+ const client = ensureFirestoreConfigured(firestore);
29318
+ // PORTING NOTE: We don't return an error if the user has not enabled
29319
+ // persistence since `enableIndexeddbPersistence()` can fail on the Web.
29320
+ if (!((_a = client.offlineComponents) === null || _a === void 0 ? void 0 : _a.indexBackfillerScheduler)) {
29321
+ logWarn('Cannot enable indexes when persistence is disabled');
29322
+ return Promise.resolve();
29323
+ }
29324
+ const parsedIndexes = parseIndexes(jsonOrConfiguration);
29325
+ return getLocalStore(client).then(localStore => localStoreConfigureFieldIndexes(localStore, parsedIndexes));
29326
+ }
29327
+ function parseIndexes(jsonOrConfiguration) {
29123
29328
  const indexConfiguration = typeof jsonOrConfiguration === 'string'
29124
29329
  ? tryParseJson(jsonOrConfiguration)
29125
29330
  : jsonOrConfiguration;
29126
29331
  const parsedIndexes = [];
29127
- // PORTING NOTE: We don't return an error if the user has not enabled
29128
- // persistence since `enableIndexeddbPersistence()` can fail on the Web.
29129
29332
  if (Array.isArray(indexConfiguration.indexes)) {
29130
29333
  for (const index of indexConfiguration.indexes) {
29131
29334
  const collectionGroup = tryGetString(index, 'collectionGroup');
@@ -29148,8 +29351,7 @@ function setIndexConfiguration(firestore, jsonOrConfiguration) {
29148
29351
  parsedIndexes.push(new FieldIndex(FieldIndex.UNKNOWN_ID, collectionGroup, segments, IndexState.empty()));
29149
29352
  }
29150
29353
  }
29151
- // TODO(indexing): Configure indexes
29152
- return Promise.resolve();
29354
+ return parsedIndexes;
29153
29355
  }
29154
29356
  function tryParseJson(json) {
29155
29357
  var _a;
@@ -29157,7 +29359,7 @@ function tryParseJson(json) {
29157
29359
  return JSON.parse(json);
29158
29360
  }
29159
29361
  catch (e) {
29160
- throw new FirestoreError(Code.INVALID_ARGUMENT, 'Failed to parse JSON:' + ((_a = e) === null || _a === void 0 ? void 0 : _a.message));
29362
+ throw new FirestoreError(Code.INVALID_ARGUMENT, 'Failed to parse JSON: ' + ((_a = e) === null || _a === void 0 ? void 0 : _a.message));
29161
29363
  }
29162
29364
  }
29163
29365
  function tryGetString(data, property) {
@@ -29185,5 +29387,5 @@ function tryGetString(data, property) {
29185
29387
  */
29186
29388
  registerFirestore('node');
29187
29389
 
29188
- export { AbstractUserDataWriter, Bytes, CACHE_SIZE_UNLIMITED, CollectionReference, DocumentReference, DocumentSnapshot, FieldPath, FieldValue, Firestore, FirestoreError, GeoPoint, LoadBundleTask, Query, QueryConstraint, QueryDocumentSnapshot, QuerySnapshot, SnapshotMetadata, Timestamp, Transaction, WriteBatch, DatabaseId as _DatabaseId, DocumentKey as _DocumentKey, EmptyAppCheckTokenProvider as _EmptyAppCheckTokenProvider, EmptyAuthCredentialsProvider as _EmptyAuthCredentialsProvider, FieldPath$1 as _FieldPath, cast as _cast, debugAssert as _debugAssert, isBase64Available as _isBase64Available, logWarn as _logWarn, setIndexConfiguration as _setIndexConfiguration, validateIsNotUsedTogether as _validateIsNotUsedTogether, addDoc, arrayRemove, arrayUnion, clearIndexedDbPersistence, collection, collectionGroup, connectFirestoreEmulator, deleteDoc, deleteField, disableNetwork, doc, documentId, enableIndexedDbPersistence, enableMultiTabIndexedDbPersistence, enableNetwork, endAt, endBefore, ensureFirestoreConfigured, executeWrite, getDoc, getDocFromCache, getDocFromServer, getDocs, getDocsFromCache, getDocsFromServer, getFirestore, increment, initializeFirestore, limit, limitToLast, loadBundle, namedQuery, onSnapshot, onSnapshotsInSync, orderBy, query, queryEqual, refEqual, runTransaction, serverTimestamp, setDoc, setLogLevel, snapshotEqual, startAfter, startAt, terminate, updateDoc, waitForPendingWrites, where, writeBatch };
29390
+ export { AbstractUserDataWriter, Bytes, CACHE_SIZE_UNLIMITED, CollectionReference, DocumentReference, DocumentSnapshot, FieldPath, FieldValue, Firestore, FirestoreError, GeoPoint, LoadBundleTask, Query, QueryConstraint, QueryDocumentSnapshot, QuerySnapshot, SnapshotMetadata, Timestamp, Transaction, WriteBatch, DatabaseId as _DatabaseId, DocumentKey as _DocumentKey, EmptyAppCheckTokenProvider as _EmptyAppCheckTokenProvider, EmptyAuthCredentialsProvider as _EmptyAuthCredentialsProvider, FieldPath$1 as _FieldPath, cast as _cast, debugAssert as _debugAssert, isBase64Available as _isBase64Available, logWarn as _logWarn, validateIsNotUsedTogether as _validateIsNotUsedTogether, addDoc, arrayRemove, arrayUnion, clearIndexedDbPersistence, collection, collectionGroup, connectFirestoreEmulator, deleteDoc, deleteField, disableNetwork, doc, documentId, enableIndexedDbPersistence, enableMultiTabIndexedDbPersistence, enableNetwork, endAt, endBefore, ensureFirestoreConfigured, executeWrite, getDoc, getDocFromCache, getDocFromServer, getDocs, getDocsFromCache, getDocsFromServer, getFirestore, increment, initializeFirestore, limit, limitToLast, loadBundle, namedQuery, onSnapshot, onSnapshotsInSync, orderBy, query, queryEqual, refEqual, runTransaction, serverTimestamp, setDoc, setIndexConfiguration, setLogLevel, snapshotEqual, startAfter, startAt, terminate, updateDoc, waitForPendingWrites, where, writeBatch };
29189
29391
  //# sourceMappingURL=index.node.mjs.map