From 8eff962cab608341a6f2fedc640a0e32d96f26e2 Mon Sep 17 00:00:00 2001 From: altaf-creator Date: Sun, 9 Nov 2025 11:15:19 +0800 Subject: pain --- .../firestore/dist/lite/firestore/lite/index.d.ts | 29 + .../dist/lite/firestore/lite/register.d.ts | 23 + .../firestore/dist/lite/firestore/src/api.d.ts | 65 + .../dist/lite/firestore/src/api/aggregate.d.ts | 77 + .../dist/lite/firestore/src/api/bundle.d.ts | 94 + .../dist/lite/firestore/src/api/bytes.d.ts | 17 + .../dist/lite/firestore/src/api/cache_config.d.ts | 222 + .../dist/lite/firestore/src/api/credentials.d.ts | 222 + .../dist/lite/firestore/src/api/database.d.ts | 279 + .../dist/lite/firestore/src/api/field_path.d.ts | 17 + .../dist/lite/firestore/src/api/field_value.d.ts | 17 + .../lite/firestore/src/api/field_value_impl.d.ts | 17 + .../dist/lite/firestore/src/api/filter.d.ts | 17 + .../dist/lite/firestore/src/api/geo_point.d.ts | 17 + .../firestore/src/api/index_configuration.d.ts | 139 + .../firestore/src/api/long_polling_options.d.ts | 55 + .../dist/lite/firestore/src/api/observer.d.ts | 29 + .../dist/lite/firestore/src/api/parse_context.d.ts | 21 + .../src/api/persistent_cache_index_manager.d.ts | 59 + .../dist/lite/firestore/src/api/reference.d.ts | 17 + .../lite/firestore/src/api/reference_impl.d.ts | 536 ++ .../dist/lite/firestore/src/api/settings.d.ts | 108 + .../dist/lite/firestore/src/api/snapshot.d.ts | 550 ++ .../dist/lite/firestore/src/api/timestamp.d.ts | 17 + .../dist/lite/firestore/src/api/transaction.d.ts | 61 + .../firestore/src/api/transaction_options.d.ts | 17 + .../dist/lite/firestore/src/api/write_batch.d.ts | 31 + .../dist/lite/firestore/src/auth/user.d.ts | 36 + .../dist/lite/firestore/src/core/aggregate.d.ts | 38 + .../dist/lite/firestore/src/core/bound.d.ts | 49 + .../dist/lite/firestore/src/core/bundle.d.ts | 80 + .../dist/lite/firestore/src/core/bundle_impl.d.ts | 88 + .../firestore/src/core/component_provider.d.ts | 146 + .../lite/firestore/src/core/database_info.d.ts | 64 + .../lite/firestore/src/core/event_manager.d.ts | 133 + .../dist/lite/firestore/src/core/filter.d.ts | 130 + .../lite/firestore/src/core/firestore_client.d.ts | 138 + .../lite/firestore/src/core/listen_sequence.d.ts | 39 + .../dist/lite/firestore/src/core/order_by.d.ts | 35 + .../dist/lite/firestore/src/core/query.d.ts | 142 + .../lite/firestore/src/core/snapshot_version.d.ts | 34 + .../dist/lite/firestore/src/core/sync_engine.d.ts | 37 + .../lite/firestore/src/core/sync_engine_impl.d.ts | 255 + .../dist/lite/firestore/src/core/target.d.ts | 89 + .../firestore/src/core/target_id_generator.d.ts | 38 + .../dist/lite/firestore/src/core/transaction.d.ts | 60 + .../firestore/src/core/transaction_options.d.ts | 25 + .../firestore/src/core/transaction_runner.d.ts | 41 + .../dist/lite/firestore/src/core/types.d.ts | 65 + .../dist/lite/firestore/src/core/version.d.ts | 18 + .../dist/lite/firestore/src/core/view.d.ts | 152 + .../lite/firestore/src/core/view_snapshot.d.ts | 59 + .../firestore/dist/lite/firestore/src/index.d.ts | 28 + .../dist/lite/firestore/src/index.node.d.ts | 17 + .../dist/lite/firestore/src/index.rn.d.ts | 17 + .../src/index/directional_index_byte_encoder.d.ts | 24 + .../src/index/firestore_index_value_writer.d.ts | 34 + .../firestore/src/index/index_byte_encoder.d.ts | 31 + .../dist/lite/firestore/src/index/index_entry.d.ts | 49 + .../firestore/src/index/ordered_code_writer.d.ts | 60 + .../lite/firestore/src/lite-api/aggregate.d.ts | 100 + .../firestore/src/lite-api/aggregate_types.d.ts | 86 + .../dist/lite/firestore/src/lite-api/bytes.d.ts | 83 + .../lite/firestore/src/lite-api/components.d.ts | 49 + .../dist/lite/firestore/src/lite-api/database.d.ts | 179 + .../lite/firestore/src/lite-api/field_path.d.ts | 48 + .../lite/firestore/src/lite-api/field_value.d.ts | 33 + .../firestore/src/lite-api/field_value_impl.d.ts | 81 + .../lite/firestore/src/lite-api/geo_point.d.ts | 79 + .../dist/lite/firestore/src/lite-api/query.d.ts | 404 + .../lite/firestore/src/lite-api/reference.d.ts | 362 + .../firestore/src/lite-api/reference_impl.d.ts | 172 + .../dist/lite/firestore/src/lite-api/settings.d.ts | 77 + .../dist/lite/firestore/src/lite-api/snapshot.d.ts | 367 + .../lite/firestore/src/lite-api/timestamp.d.ts | 134 + .../lite/firestore/src/lite-api/transaction.d.ts | 122 + .../src/lite-api/transaction_options.d.ts | 23 + .../dist/lite/firestore/src/lite-api/types.d.ts | 61 + .../firestore/src/lite-api/user_data_reader.d.ts | 224 + .../firestore/src/lite-api/user_data_writer.d.ts | 48 + .../lite/firestore/src/lite-api/vector_value.d.ts | 58 + .../lite/firestore/src/lite-api/write_batch.d.ts | 125 + .../lite/firestore/src/local/bundle_cache.d.ts | 44 + .../src/local/document_overlay_cache.d.ts | 76 + .../firestore/src/local/encoded_resource_path.d.ts | 73 + .../lite/firestore/src/local/globals_cache.d.ts | 39 + .../lite/firestore/src/local/index_backfiller.d.ts | 44 + .../lite/firestore/src/local/index_manager.d.ts | 124 + .../src/local/indexeddb_bundle_cache.d.ts | 27 + .../local/indexeddb_document_overlay_cache.d.ts | 45 + .../src/local/indexeddb_globals_cache.d.ts | 25 + .../src/local/indexeddb_index_manager.d.ts | 136 + .../src/local/indexeddb_lru_delegate.d.ts | 22 + .../src/local/indexeddb_lru_delegate_impl.d.ts | 56 + .../src/local/indexeddb_mutation_batch_impl.d.ts | 35 + .../src/local/indexeddb_mutation_queue.d.ts | 99 + .../firestore/src/local/indexeddb_persistence.d.ts | 270 + .../src/local/indexeddb_remote_document_cache.d.ts | 36 + .../lite/firestore/src/local/indexeddb_schema.d.ts | 509 + .../src/local/indexeddb_schema_converter.d.ts | 43 + .../src/local/indexeddb_schema_legacy.d.ts | 29 + .../firestore/src/local/indexeddb_sentinels.d.ts | 267 + .../src/local/indexeddb_target_cache.d.ts | 81 + .../firestore/src/local/indexeddb_transaction.d.ts | 25 + .../firestore/src/local/local_documents_view.d.ts | 127 + .../lite/firestore/src/local/local_serializer.d.ts | 80 + .../dist/lite/firestore/src/local/local_store.d.ts | 41 + .../lite/firestore/src/local/local_store_impl.d.ts | 208 + .../firestore/src/local/local_view_changes.d.ts | 32 + .../firestore/src/local/lru_garbage_collector.d.ts | 102 + .../src/local/lru_garbage_collector_impl.d.ts | 37 + .../firestore/src/local/memory_bundle_cache.d.ts | 32 + .../src/local/memory_document_overlay_cache.d.ts | 37 + .../firestore/src/local/memory_globals_cache.d.ts | 25 + .../firestore/src/local/memory_index_manager.d.ts | 55 + .../firestore/src/local/memory_mutation_queue.d.ts | 80 + .../firestore/src/local/memory_persistence.d.ts | 134 + .../src/local/memory_remote_document_cache.d.ts | 33 + .../firestore/src/local/memory_target_cache.d.ts | 65 + .../lite/firestore/src/local/mutation_queue.d.ts | 123 + .../firestore/src/local/overlayed_document.d.ts | 40 + .../dist/lite/firestore/src/local/persistence.d.ts | 217 + .../firestore/src/local/persistence_promise.d.ts | 83 + .../src/local/persistence_transaction.d.ts | 34 + .../lite/firestore/src/local/query_context.d.ts | 28 + .../lite/firestore/src/local/query_engine.d.ts | 110 + .../lite/firestore/src/local/reference_set.d.ts | 68 + .../firestore/src/local/remote_document_cache.d.ts | 91 + .../src/local/remote_document_change_buffer.d.ts | 88 + .../firestore/src/local/shared_client_state.d.ts | 312 + .../src/local/shared_client_state_schema.d.ts | 84 + .../src/local/shared_client_state_syncer.d.ts | 40 + .../dist/lite/firestore/src/local/simple_db.d.ts | 233 + .../lite/firestore/src/local/target_cache.d.ts | 130 + .../dist/lite/firestore/src/local/target_data.d.ts | 127 + .../dist/lite/firestore/src/model/collections.d.ts | 50 + .../dist/lite/firestore/src/model/document.d.ts | 150 + .../firestore/src/model/document_comparator.d.ts | 19 + .../lite/firestore/src/model/document_key.d.ts | 45 + .../lite/firestore/src/model/document_set.d.ts | 57 + .../dist/lite/firestore/src/model/field_index.d.ts | 171 + .../dist/lite/firestore/src/model/field_mask.d.ts | 45 + .../dist/lite/firestore/src/model/mutation.d.ts | 270 + .../lite/firestore/src/model/mutation_batch.d.ts | 88 + .../dist/lite/firestore/src/model/normalize.d.ts | 33 + .../lite/firestore/src/model/object_value.d.ts | 78 + .../dist/lite/firestore/src/model/overlay.d.ts | 32 + .../dist/lite/firestore/src/model/path.d.ts | 121 + .../firestore/src/model/server_timestamps.d.ts | 34 + .../firestore/src/model/target_index_matcher.d.ts | 76 + .../firestore/src/model/transform_operation.d.ts | 75 + .../dist/lite/firestore/src/model/type_order.d.ts | 38 + .../dist/lite/firestore/src/model/values.d.ts | 114 + .../dist/lite/firestore/src/platform/base64.d.ts | 25 + .../firestore/src/platform/browser/base64.d.ts | 22 + .../src/platform/browser/byte_stream_reader.d.ts | 21 + .../firestore/src/platform/browser/connection.d.ts | 23 + .../src/platform/browser/connectivity_monitor.d.ts | 33 + .../lite/firestore/src/platform/browser/dom.d.ts | 20 + .../src/platform/browser/format_json.d.ts | 18 + .../src/platform/browser/random_bytes.d.ts | 22 + .../firestore/src/platform/browser/serializer.d.ts | 20 + .../src/platform/browser/snapshot_to_json.d.ts | 23 + .../src/platform/browser/text_serializer.d.ts | 24 + .../platform/browser/webchannel_connection.d.ts | 47 + .../src/platform/browser_lite/base64.d.ts | 17 + .../platform/browser_lite/byte_stream_reader.d.ts | 17 + .../src/platform/browser_lite/connection.d.ts | 21 + .../firestore/src/platform/browser_lite/dom.d.ts | 17 + .../platform/browser_lite/fetch_connection.d.ts | 28 + .../src/platform/browser_lite/format_json.d.ts | 17 + .../src/platform/browser_lite/random_bytes.d.ts | 17 + .../src/platform/browser_lite/serializer.d.ts | 17 + .../platform/browser_lite/snapshot_to_json.d.ts | 17 + .../src/platform/browser_lite/text_serializer.d.ts | 17 + .../firestore/src/platform/byte_stream_reader.d.ts | 18 + .../lite/firestore/src/platform/connection.d.ts | 21 + .../dist/lite/firestore/src/platform/dom.d.ts | 20 + .../lite/firestore/src/platform/format_json.d.ts | 18 + .../lite/firestore/src/platform/node/base64.d.ts | 22 + .../src/platform/node/byte_stream_reader.d.ts | 21 + .../firestore/src/platform/node/connection.d.ts | 23 + .../dist/lite/firestore/src/platform/node/dom.d.ts | 20 + .../firestore/src/platform/node/format_json.d.ts | 18 + .../src/platform/node/grpc_connection.d.ts | 43 + .../firestore/src/platform/node/load_protos.d.ts | 28 + .../firestore/src/platform/node/random_bytes.d.ts | 22 + .../firestore/src/platform/node/serializer.d.ts | 20 + .../src/platform/node/snapshot_to_json.d.ts | 23 + .../src/platform/node/text_serializer.d.ts | 25 + .../firestore/src/platform/node_lite/base64.d.ts | 17 + .../src/platform/node_lite/byte_stream_reader.d.ts | 17 + .../src/platform/node_lite/connection.d.ts | 21 + .../lite/firestore/src/platform/node_lite/dom.d.ts | 17 + .../src/platform/node_lite/format_json.d.ts | 17 + .../src/platform/node_lite/random_bytes.d.ts | 17 + .../src/platform/node_lite/serializer.d.ts | 17 + .../src/platform/node_lite/snapshot_to_json.d.ts | 17 + .../src/platform/node_lite/text_serializer.d.ts | 17 + .../lite/firestore/src/platform/random_bytes.d.ts | 22 + .../lite/firestore/src/platform/rn/base64.d.ts | 22 + .../src/platform/rn/byte_stream_reader.d.ts | 17 + .../lite/firestore/src/platform/rn/connection.d.ts | 17 + .../dist/lite/firestore/src/platform/rn/dom.d.ts | 17 + .../firestore/src/platform/rn/format_json.d.ts | 17 + .../firestore/src/platform/rn/random_bytes.d.ts | 17 + .../lite/firestore/src/platform/rn/serializer.d.ts | 17 + .../src/platform/rn/snapshot_to_json.d.ts | 17 + .../firestore/src/platform/rn/text_serializer.d.ts | 17 + .../firestore/src/platform/rn_lite/base64.d.ts | 17 + .../src/platform/rn_lite/byte_stream_reader.d.ts | 17 + .../firestore/src/platform/rn_lite/connection.d.ts | 17 + .../lite/firestore/src/platform/rn_lite/dom.d.ts | 17 + .../src/platform/rn_lite/format_json.d.ts | 17 + .../src/platform/rn_lite/random_bytes.d.ts | 17 + .../firestore/src/platform/rn_lite/serializer.d.ts | 17 + .../src/platform/rn_lite/snapshot_to_json.d.ts | 17 + .../src/platform/rn_lite/text_serializer.d.ts | 17 + .../lite/firestore/src/platform/serializer.d.ts | 19 + .../firestore/src/platform/snapshot_to_json.d.ts | 28 + .../firestore/src/platform/text_serializer.d.ts | 24 + .../src/protos/firestore_bundle_proto.d.ts | 72 + .../firestore/src/protos/firestore_proto_api.d.ts | 836 ++ .../dist/lite/firestore/src/register.d.ts | 17 + .../dist/lite/firestore/src/remote/backoff.d.ts | 106 + .../lite/firestore/src/remote/bloom_filter.d.ts | 34 + .../dist/lite/firestore/src/remote/connection.d.ts | 99 + .../firestore/src/remote/connectivity_monitor.d.ts | 47 + .../src/remote/connectivity_monitor_noop.d.ts | 21 + .../dist/lite/firestore/src/remote/datastore.d.ts | 44 + .../firestore/src/remote/existence_filter.d.ts | 22 + .../firestore/src/remote/internal_serializer.d.ts | 46 + .../firestore/src/remote/number_serializer.d.ts | 36 + .../firestore/src/remote/online_state_tracker.d.ts | 81 + .../firestore/src/remote/persistent_stream.d.ts | 308 + .../lite/firestore/src/remote/remote_event.d.ts | 156 + .../lite/firestore/src/remote/remote_store.d.ts | 85 + .../lite/firestore/src/remote/remote_syncer.d.ts | 68 + .../lite/firestore/src/remote/rest_connection.d.ts | 53 + .../dist/lite/firestore/src/remote/rpc_error.d.ts | 74 + .../dist/lite/firestore/src/remote/serializer.d.ts | 124 + .../lite/firestore/src/remote/stream_bridge.d.ts | 45 + .../lite/firestore/src/remote/watch_change.d.ts | 231 + .../dist/lite/firestore/src/util/array.d.ts | 70 + .../dist/lite/firestore/src/util/assert.d.ts | 78 + .../lite/firestore/src/util/async_observer.d.ts | 31 + .../dist/lite/firestore/src/util/async_queue.d.ts | 180 + .../lite/firestore/src/util/async_queue_impl.d.ts | 75 + .../firestore/src/util/base64_decode_error.d.ts | 22 + .../firestore/src/util/bundle_builder_impl.d.ts | 97 + .../lite/firestore/src/util/bundle_reader.d.ts | 67 + .../firestore/src/util/bundle_reader_impl.d.ts | 19 + .../src/util/bundle_reader_sync_impl.d.ts | 59 + .../dist/lite/firestore/src/util/byte_stream.d.ts | 29 + .../dist/lite/firestore/src/util/byte_string.d.ts | 46 + .../dist/lite/firestore/src/util/debug_uid.d.ts | 28 + .../dist/lite/firestore/src/util/error.d.ts | 195 + .../lite/firestore/src/util/input_validation.d.ts | 56 + .../lite/firestore/src/util/json_validation.d.ts | 70 + .../dist/lite/firestore/src/util/log.d.ts | 39 + .../dist/lite/firestore/src/util/logic_utils.d.ts | 52 + .../dist/lite/firestore/src/util/misc.d.ts | 46 + .../dist/lite/firestore/src/util/node_api.d.ts | 58 + .../dist/lite/firestore/src/util/obj.d.ts | 23 + .../dist/lite/firestore/src/util/obj_map.d.ts | 48 + .../dist/lite/firestore/src/util/promise.d.ts | 34 + .../dist/lite/firestore/src/util/sorted_map.d.ts | 100 + .../dist/lite/firestore/src/util/sorted_set.d.ts | 80 + .../lite/firestore/src/util/testing_hooks.d.ts | 52 + .../lite/firestore/src/util/testing_hooks_spi.d.ts | 93 + .../dist/lite/firestore/src/util/types.d.ts | 45 + .../test/integration/api/aggregation.test.d.ts | 17 + .../integration/api/array_transforms.test.d.ts | 17 + .../test/integration/api/batch_writes.test.d.ts | 17 + .../test/integration/api/bundle.test.d.ts | 17 + .../api/composite_index_query.test.d.ts | 17 + .../test/integration/api/cursor.test.d.ts | 17 + .../test/integration/api/database.test.d.ts | 17 + .../test/integration/api/fields.test.d.ts | 17 + .../test/integration/api/get_options.test.d.ts | 17 + .../integration/api/index_configuration.test.d.ts | 17 + .../integration/api/numeric_transforms.test.d.ts | 17 + .../api/persistent_cache_index_manager.test.d.ts | 17 + .../test/integration/api/provider.test.d.ts | 17 + .../firestore/test/integration/api/query.test.d.ts | 18 + .../integration/api/server_timestamp.test.d.ts | 17 + .../firestore/test/integration/api/smoke.test.d.ts | 17 + .../api/snapshot_listener_source.test.d.ts | 17 + .../test/integration/api/transactions.test.d.ts | 17 + .../firestore/test/integration/api/type.test.d.ts | 17 + .../test/integration/api/validation.test.d.ts | 17 + .../test/integration/api_internal/auth.test.d.ts | 17 + .../integration/api_internal/database.test.d.ts | 17 + .../api_internal/idle_timeout.test.d.ts | 17 + .../integration/api_internal/transaction.test.d.ts | 17 + .../lite/firestore/test/integration/bootstrap.d.ts | 17 + .../test/integration/browser/indexeddb.test.d.ts | 17 + .../test/integration/browser/webchannel.test.d.ts | 17 + .../test/integration/prime_backend.test.d.ts | 17 + .../test/integration/remote/remote.test.d.ts | 17 + .../test/integration/remote/stream.test.d.ts | 54 + .../util/composite_index_test_helper.d.ts | 41 + .../test/integration/util/events_accumulator.d.ts | 39 + .../test/integration/util/firebase_export.d.ts | 23 + .../firestore/test/integration/util/helpers.d.ts | 138 + .../test/integration/util/internal_helpers.d.ts | 34 + .../firestore/test/integration/util/settings.d.ts | 24 + .../test/integration/util/testing_hooks_util.d.ts | 44 + .../dist/lite/firestore/test/lite/bootstrap.d.ts | 17 + .../dist/lite/firestore/test/lite/helpers.d.ts | 41 + .../lite/firestore/test/lite/integration.test.d.ts | 17 + .../dist/lite/firestore/test/register.d.ts | 17 + .../firestore/test/unit/api/aggregate.test.d.ts | 17 + .../lite/firestore/test/unit/api/bytes.test.d.ts | 17 + .../firestore/test/unit/api/database.test.d.ts | 17 + .../test/unit/api/document_change.test.d.ts | 17 + .../firestore/test/unit/api/field_path.test.d.ts | 17 + .../firestore/test/unit/api/field_value.test.d.ts | 17 + .../firestore/test/unit/api/geo_point.test.d.ts | 17 + .../test/unit/api/long_polling_options.test.d.ts | 17 + .../firestore/test/unit/api/timestamp.test.d.ts | 17 + .../firestore/test/unit/api/vector_value.test.d.ts | 17 + .../dist/lite/firestore/test/unit/bootstrap.d.ts | 24 + .../test/unit/core/event_manager.test.d.ts | 17 + .../lite/firestore/test/unit/core/filter.test.d.ts | 17 + .../test/unit/core/listen_sequence.test.d.ts | 17 + .../lite/firestore/test/unit/core/query.test.d.ts | 17 + .../lite/firestore/test/unit/core/view.test.d.ts | 17 + .../test/unit/core/webchannel_wrapper.test.d.ts | 17 + .../index/firestore_index_value_writer.test.d.ts | 1 + .../test/unit/index/ordered_code_writer.test.d.ts | 1 + .../firestore/test/unit/lite-api/types.test.d.ts | 1 + .../test/unit/local/bundle_cache.test.d.ts | 17 + .../test/unit/local/counting_query_engine.d.ts | 60 + .../unit/local/document_overlay_cache.test.d.ts | 1 + .../unit/local/encoded_resource_path.test.d.ts | 17 + .../test/unit/local/globals_cache.test.d.ts | 17 + .../test/unit/local/index_backfiller.test.d.ts | 17 + .../test/unit/local/index_manager.test.d.ts | 17 + .../unit/local/indexeddb_persistence.test.d.ts | 17 + .../test/unit/local/local_serializer.test.d.ts | 17 + .../test/unit/local/local_store.test.d.ts | 24 + .../unit/local/local_store_indexeddb.test.d.ts | 17 + .../unit/local/lru_garbage_collector.test.d.ts | 17 + .../test/unit/local/mutation_queue.test.d.ts | 17 + .../test/unit/local/persistence_promise.test.d.ts | 17 + .../test/unit/local/persistence_test_helpers.d.ts | 67 + .../unit/local/persistence_transaction.test.d.ts | 17 + .../test/unit/local/query_engine.test.d.ts | 17 + .../test/unit/local/reference_set.test.d.ts | 17 + .../unit/local/remote_document_cache.test.d.ts | 17 + .../local/remote_document_change_buffer.test.d.ts | 17 + .../firestore/test/unit/local/simple_db.test.d.ts | 17 + .../test/unit/local/target_cache.test.d.ts | 17 + .../test/unit/local/test_bundle_cache.d.ts | 32 + .../unit/local/test_document_overlay_cache.d.ts | 39 + .../test/unit/local/test_globals_cache.d.ts | 29 + .../test/unit/local/test_index_manager.d.ts | 44 + .../test/unit/local/test_mutation_queue.d.ts | 43 + .../unit/local/test_remote_document_cache.d.ts | 54 + .../local/test_remote_document_change_buffer.d.ts | 34 + .../test/unit/local/test_target_cache.d.ts | 46 + .../web_storage_shared_client_state.test.d.ts | 17 + .../firestore/test/unit/model/document.test.d.ts | 17 + .../test/unit/model/document_set.test.d.ts | 17 + .../test/unit/model/field_index.test.d.ts | 17 + .../firestore/test/unit/model/mutation.test.d.ts | 17 + .../test/unit/model/object_value.test.d.ts | 17 + .../test/unit/model/object_value_builder.test.d.ts | 17 + .../lite/firestore/test/unit/model/path.test.d.ts | 17 + .../firestore/test/unit/model/target.test.d.ts | 17 + .../test/unit/model/target_index_matcher.test.d.ts | 17 + .../firestore/test/unit/model/values.test.d.ts | 17 + .../test/unit/remote/bloom_filter.test.d.ts | 1 + .../bloom_filter_golden_test_data/index.d.ts | 40 + .../firestore/test/unit/remote/datastore.test.d.ts | 17 + .../test/unit/remote/fetch_connection.test.d.ts | 17 + .../test/unit/remote/remote_event.test.d.ts | 17 + .../test/unit/remote/rest_connection.test.d.ts | 28 + .../test/unit/remote/serializer.browser.test.d.ts | 17 + .../test/unit/remote/serializer.helper.d.ts | 25 + .../test/unit/remote/serializer.node.test.d.ts | 21 + .../test/unit/specs/bundle_spec.test.d.ts | 36 + .../test/unit/specs/collection_spec.test.d.ts | 17 + .../firestore/test/unit/specs/describe_spec.d.ts | 44 + .../unit/specs/existence_filter_spec.test.d.ts | 17 + .../unit/specs/garbage_collection_spec.test.d.ts | 17 + .../firestore/test/unit/specs/index_spec.test.d.ts | 17 + .../firestore/test/unit/specs/limbo_spec.test.d.ts | 17 + .../firestore/test/unit/specs/limit_spec.test.d.ts | 17 + .../test/unit/specs/listen_source_spec.test.d.ts | 17 + .../test/unit/specs/listen_spec.test.d.ts | 17 + .../test/unit/specs/offline_spec.test.d.ts | 17 + .../test/unit/specs/orderby_spec.test.d.ts | 17 + .../firestore/test/unit/specs/perf_spec.test.d.ts | 17 + .../test/unit/specs/persistence_spec.test.d.ts | 17 + .../firestore/test/unit/specs/query_spec.test.d.ts | 17 + .../test/unit/specs/recovery_spec.test.d.ts | 17 + .../test/unit/specs/remote_store_spec.test.d.ts | 17 + .../test/unit/specs/resume_token_spec.test.d.ts | 17 + .../firestore/test/unit/specs/spec_builder.d.ts | 287 + .../firestore/test/unit/specs/spec_rpc_error.d.ts | 24 + .../test/unit/specs/spec_test_components.d.ts | 156 + .../test/unit/specs/spec_test_runner.d.ts | 323 + .../firestore/test/unit/specs/write_spec.test.d.ts | 17 + .../lite/firestore/test/unit/util/array.test.d.ts | 17 + .../lite/firestore/test/unit/util/assert.test.d.ts | 17 + .../firestore/test/unit/util/async_queue.test.d.ts | 17 + .../lite/firestore/test/unit/util/base64.test.d.ts | 17 + .../lite/firestore/test/unit/util/bundle.test.d.ts | 8 + .../lite/firestore/test/unit/util/bundle_data.d.ts | 50 + .../firestore/test/unit/util/logic_utils.test.d.ts | 17 + .../lite/firestore/test/unit/util/misc.test.d.ts | 17 + .../firestore/test/unit/util/node_api.test.d.ts | 17 + .../firestore/test/unit/util/obj_map.test.d.ts | 17 + .../firestore/test/unit/util/sorted_map.test.d.ts | 17 + .../firestore/test/unit/util/sorted_set.test.d.ts | 17 + .../dist/lite/firestore/test/util/api_helpers.d.ts | 49 + .../lite/firestore/test/util/equality_matcher.d.ts | 33 + .../dist/lite/firestore/test/util/helpers.d.ts | 206 + .../lite/firestore/test/util/node_persistence.d.ts | 17 + .../dist/lite/firestore/test/util/promise.d.ts | 28 + .../firestore/test/util/spec_test_helpers.d.ts | 19 + .../lite/firestore/test/util/test_platform.d.ts | 61 + .../firestore/dist/lite/index.browser.esm.js | 7660 +++++++++++++++ .../firestore/dist/lite/index.browser.esm.js.map | 1 + .../@firebase/firestore/dist/lite/index.cjs.js | 7660 +++++++++++++++ .../@firebase/firestore/dist/lite/index.cjs.js.map | 1 + .../@firebase/firestore/dist/lite/index.d.ts | 2030 ++++ .../firestore/dist/lite/index.node.cjs.js | 9870 ++++++++++++++++++++ .../firestore/dist/lite/index.node.cjs.js.map | 1 + .../@firebase/firestore/dist/lite/index.node.mjs | 9798 +++++++++++++++++++ .../firestore/dist/lite/index.node.mjs.map | 1 + .../@firebase/firestore/dist/lite/index.rn.esm.js | 7672 +++++++++++++++ .../firestore/dist/lite/index.rn.esm.js.map | 1 + .../@firebase/firestore/dist/lite/internal.d.ts | 6201 ++++++++++++ .../@firebase/firestore/dist/lite/private.d.ts | 5939 ++++++++++++ 437 files changed, 81265 insertions(+) create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/lite/index.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/lite/register.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/aggregate.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/bundle.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/bytes.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/cache_config.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/credentials.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/database.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/field_path.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/field_value.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/field_value_impl.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/filter.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/geo_point.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/index_configuration.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/long_polling_options.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/observer.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/parse_context.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/persistent_cache_index_manager.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/reference.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/reference_impl.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/settings.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/snapshot.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/timestamp.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/transaction.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/transaction_options.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/write_batch.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/auth/user.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/aggregate.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/bound.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/bundle.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/bundle_impl.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/component_provider.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/database_info.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/event_manager.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/filter.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/firestore_client.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/listen_sequence.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/order_by.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/query.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/snapshot_version.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/sync_engine.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/sync_engine_impl.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/target.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/target_id_generator.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/transaction.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/transaction_options.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/transaction_runner.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/types.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/version.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/view.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/view_snapshot.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/index.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/index.node.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/index.rn.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/index/directional_index_byte_encoder.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/index/firestore_index_value_writer.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/index/index_byte_encoder.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/index/index_entry.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/index/ordered_code_writer.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/aggregate.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/aggregate_types.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/bytes.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/components.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/database.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/field_path.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/field_value.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/field_value_impl.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/geo_point.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/query.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/reference.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/reference_impl.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/settings.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/snapshot.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/timestamp.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/transaction.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/transaction_options.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/types.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/user_data_reader.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/user_data_writer.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/vector_value.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/write_batch.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/bundle_cache.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/document_overlay_cache.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/encoded_resource_path.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/globals_cache.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/index_backfiller.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/index_manager.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_bundle_cache.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_document_overlay_cache.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_globals_cache.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_index_manager.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_lru_delegate.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_lru_delegate_impl.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_mutation_batch_impl.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_mutation_queue.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_persistence.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_remote_document_cache.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_schema.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_schema_converter.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_schema_legacy.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_sentinels.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_target_cache.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_transaction.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/local_documents_view.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/local_serializer.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/local_store.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/local_store_impl.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/local_view_changes.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/lru_garbage_collector.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/lru_garbage_collector_impl.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/memory_bundle_cache.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/memory_document_overlay_cache.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/memory_globals_cache.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/memory_index_manager.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/memory_mutation_queue.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/memory_persistence.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/memory_remote_document_cache.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/memory_target_cache.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/mutation_queue.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/overlayed_document.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/persistence.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/persistence_promise.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/persistence_transaction.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/query_context.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/query_engine.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/reference_set.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/remote_document_cache.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/remote_document_change_buffer.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/shared_client_state.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/shared_client_state_schema.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/shared_client_state_syncer.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/simple_db.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/target_cache.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/target_data.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/collections.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/document.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/document_comparator.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/document_key.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/document_set.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/field_index.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/field_mask.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/mutation.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/mutation_batch.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/normalize.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/object_value.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/overlay.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/path.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/server_timestamps.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/target_index_matcher.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/transform_operation.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/type_order.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/values.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/base64.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser/base64.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser/byte_stream_reader.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser/connection.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser/connectivity_monitor.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser/dom.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser/format_json.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser/random_bytes.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser/serializer.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser/snapshot_to_json.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser/text_serializer.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser/webchannel_connection.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser_lite/base64.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser_lite/byte_stream_reader.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser_lite/connection.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser_lite/dom.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser_lite/fetch_connection.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser_lite/format_json.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser_lite/random_bytes.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser_lite/serializer.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser_lite/snapshot_to_json.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser_lite/text_serializer.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/byte_stream_reader.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/connection.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/dom.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/format_json.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node/base64.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node/byte_stream_reader.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node/connection.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node/dom.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node/format_json.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node/grpc_connection.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node/load_protos.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node/random_bytes.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node/serializer.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node/snapshot_to_json.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node/text_serializer.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node_lite/base64.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node_lite/byte_stream_reader.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node_lite/connection.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node_lite/dom.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node_lite/format_json.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node_lite/random_bytes.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node_lite/serializer.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node_lite/snapshot_to_json.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node_lite/text_serializer.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/random_bytes.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn/base64.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn/byte_stream_reader.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn/connection.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn/dom.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn/format_json.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn/random_bytes.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn/serializer.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn/snapshot_to_json.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn/text_serializer.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn_lite/base64.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn_lite/byte_stream_reader.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn_lite/connection.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn_lite/dom.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn_lite/format_json.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn_lite/random_bytes.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn_lite/serializer.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn_lite/snapshot_to_json.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn_lite/text_serializer.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/serializer.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/snapshot_to_json.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/text_serializer.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/protos/firestore_bundle_proto.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/protos/firestore_proto_api.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/register.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/backoff.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/bloom_filter.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/connection.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/connectivity_monitor.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/connectivity_monitor_noop.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/datastore.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/existence_filter.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/internal_serializer.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/number_serializer.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/online_state_tracker.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/persistent_stream.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/remote_event.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/remote_store.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/remote_syncer.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/rest_connection.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/rpc_error.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/serializer.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/stream_bridge.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/watch_change.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/array.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/assert.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/async_observer.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/async_queue.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/async_queue_impl.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/base64_decode_error.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/bundle_builder_impl.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/bundle_reader.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/bundle_reader_impl.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/bundle_reader_sync_impl.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/byte_stream.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/byte_string.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/debug_uid.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/error.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/input_validation.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/json_validation.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/log.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/logic_utils.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/misc.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/node_api.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/obj.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/obj_map.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/promise.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/sorted_map.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/sorted_set.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/testing_hooks.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/testing_hooks_spi.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/types.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/aggregation.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/array_transforms.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/batch_writes.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/bundle.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/composite_index_query.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/cursor.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/database.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/fields.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/get_options.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/index_configuration.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/numeric_transforms.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/persistent_cache_index_manager.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/provider.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/query.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/server_timestamp.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/smoke.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/snapshot_listener_source.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/transactions.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/type.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/validation.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api_internal/auth.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api_internal/database.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api_internal/idle_timeout.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api_internal/transaction.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/bootstrap.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/browser/indexeddb.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/browser/webchannel.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/prime_backend.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/remote/remote.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/remote/stream.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/util/composite_index_test_helper.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/util/events_accumulator.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/util/firebase_export.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/util/helpers.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/util/internal_helpers.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/util/settings.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/util/testing_hooks_util.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/lite/bootstrap.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/lite/helpers.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/lite/integration.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/register.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/api/aggregate.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/api/bytes.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/api/database.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/api/document_change.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/api/field_path.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/api/field_value.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/api/geo_point.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/api/long_polling_options.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/api/timestamp.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/api/vector_value.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/bootstrap.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/core/event_manager.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/core/filter.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/core/listen_sequence.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/core/query.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/core/view.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/core/webchannel_wrapper.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/index/firestore_index_value_writer.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/index/ordered_code_writer.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/lite-api/types.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/bundle_cache.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/counting_query_engine.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/document_overlay_cache.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/encoded_resource_path.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/globals_cache.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/index_backfiller.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/index_manager.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/indexeddb_persistence.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/local_serializer.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/local_store.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/local_store_indexeddb.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/lru_garbage_collector.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/mutation_queue.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/persistence_promise.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/persistence_test_helpers.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/persistence_transaction.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/query_engine.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/reference_set.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/remote_document_cache.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/remote_document_change_buffer.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/simple_db.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/target_cache.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/test_bundle_cache.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/test_document_overlay_cache.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/test_globals_cache.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/test_index_manager.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/test_mutation_queue.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/test_remote_document_cache.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/test_remote_document_change_buffer.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/test_target_cache.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/web_storage_shared_client_state.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/model/document.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/model/document_set.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/model/field_index.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/model/mutation.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/model/object_value.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/model/object_value_builder.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/model/path.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/model/target.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/model/target_index_matcher.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/model/values.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/remote/bloom_filter.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/remote/bloom_filter_golden_test_data/index.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/remote/datastore.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/remote/fetch_connection.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/remote/remote_event.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/remote/rest_connection.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/remote/serializer.browser.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/remote/serializer.helper.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/remote/serializer.node.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/bundle_spec.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/collection_spec.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/describe_spec.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/existence_filter_spec.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/garbage_collection_spec.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/index_spec.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/limbo_spec.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/limit_spec.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/listen_source_spec.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/listen_spec.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/offline_spec.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/orderby_spec.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/perf_spec.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/persistence_spec.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/query_spec.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/recovery_spec.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/remote_store_spec.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/resume_token_spec.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/spec_builder.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/spec_rpc_error.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/spec_test_components.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/spec_test_runner.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/write_spec.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/util/array.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/util/assert.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/util/async_queue.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/util/base64.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/util/bundle.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/util/bundle_data.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/util/logic_utils.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/util/misc.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/util/node_api.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/util/obj_map.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/util/sorted_map.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/util/sorted_set.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/util/api_helpers.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/util/equality_matcher.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/util/helpers.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/util/node_persistence.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/util/promise.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/util/spec_test_helpers.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/util/test_platform.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/index.browser.esm.js create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/index.browser.esm.js.map create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/index.cjs.js create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/index.cjs.js.map create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/index.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/index.node.cjs.js create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/index.node.cjs.js.map create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/index.node.mjs create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/index.node.mjs.map create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/index.rn.esm.js create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/index.rn.esm.js.map create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/internal.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/private.d.ts (limited to 'frontend-old/node_modules/@firebase/firestore/dist/lite') diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/lite/index.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/lite/index.d.ts new file mode 100644 index 0000000..86dd215 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/lite/index.d.ts @@ -0,0 +1,29 @@ +/** + * Firestore Lite + * + * @remarks Firestore Lite is a small online-only SDK that allows read + * and write access to your Firestore database. All operations connect + * directly to the backend, and `onSnapshot()` APIs are not supported. + * @packageDocumentation + */ +export { aggregateQuerySnapshotEqual, getCount, getAggregate, count, sum, average, aggregateFieldEqual } from '../src/lite-api/aggregate'; +export { AggregateField, AggregateFieldType, AggregateSpec, AggregateSpecData, AggregateQuerySnapshot, AggregateType } from '../src/lite-api/aggregate_types'; +export { FirestoreSettings as Settings } from '../src/lite-api/settings'; +export { Firestore as Firestore, EmulatorMockTokenOptions, initializeFirestore, getFirestore, terminate, connectFirestoreEmulator } from '../src/lite-api/database'; +export { DocumentData, UpdateData, WithFieldValue, PartialWithFieldValue, SetOptions, DocumentReference, Query, CollectionReference, collection, collectionGroup, doc, refEqual, queryEqual } from '../src/lite-api/reference'; +export { and, endAt, endBefore, startAt, startAfter, limit, limitToLast, where, or, orderBy, query, QueryConstraint, QueryConstraintType, QueryCompositeFilterConstraint, QueryFilterConstraint, QueryFieldFilterConstraint, QueryOrderByConstraint, QueryLimitConstraint, QueryNonFilterConstraint, QueryStartAtConstraint, QueryEndAtConstraint, OrderByDirection, WhereFilterOp } from '../src/lite-api/query'; +export { addDoc, deleteDoc, updateDoc, setDoc, getDoc, getDocs } from '../src/lite-api/reference_impl'; +export { Primitive, NestedUpdateFields, ChildUpdateFields, AddPrefixToKeys, UnionToIntersection } from '../src/lite-api/types'; +export { FieldPath, documentId } from '../src/lite-api/field_path'; +export { FieldValue } from '../src/lite-api/field_value'; +export { increment, arrayRemove, arrayUnion, serverTimestamp, deleteField, vector } from '../src/lite-api/field_value_impl'; +export { FirestoreDataConverter, DocumentSnapshot, QueryDocumentSnapshot, QuerySnapshot, snapshotEqual } from '../src/lite-api/snapshot'; +export { VectorValue } from '../src/lite-api/vector_value'; +export { WriteBatch, writeBatch } from '../src/lite-api/write_batch'; +export { TransactionOptions } from '../src/lite-api/transaction_options'; +export { Transaction, runTransaction } from '../src/lite-api/transaction'; +export { setLogLevel, LogLevelString as LogLevel } from '../src/util/log'; +export { Bytes } from '../src/lite-api/bytes'; +export { GeoPoint } from '../src/lite-api/geo_point'; +export { Timestamp } from '../src/lite-api/timestamp'; +export { FirestoreErrorCode, FirestoreError } from '../src/util/error'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/lite/register.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/lite/register.d.ts new file mode 100644 index 0000000..21b4ab3 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/lite/register.d.ts @@ -0,0 +1,23 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Firestore } from '../src/lite-api/database'; +declare module '@firebase/component' { + interface NameServiceMapping { + 'firestore/lite': Firestore; + } +} +export declare function registerFirestore(): void; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api.d.ts new file mode 100644 index 0000000..f5d6e02 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api.d.ts @@ -0,0 +1,65 @@ +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export { aggregateFieldEqual, aggregateQuerySnapshotEqual, average, count, getAggregateFromServer, getCountFromServer, sum } from './api/aggregate'; +export { AggregateField, AggregateFieldType, AggregateQuerySnapshot, AggregateSpec, AggregateSpecData, AggregateType } from './lite-api/aggregate_types'; +export { FirestoreLocalCache, MemoryCacheSettings, MemoryEagerGarbageCollector, memoryEagerGarbageCollector, MemoryGarbageCollector, MemoryLocalCache, memoryLocalCache, MemoryLruGarbageCollector, memoryLruGarbageCollector, PersistentCacheSettings, PersistentLocalCache, persistentLocalCache, PersistentMultipleTabManager, persistentMultipleTabManager, PersistentSingleTabManager, persistentSingleTabManager, PersistentSingleTabManagerSettings, PersistentTabManager } from './api/cache_config'; +export { documentId, FieldPath } from './api/field_path'; +export { clearIndexedDbPersistence, connectFirestoreEmulator, disableNetwork, EmulatorMockTokenOptions, enableIndexedDbPersistence, enableMultiTabIndexedDbPersistence, enableNetwork, ensureFirestoreConfigured, Firestore, getFirestore, initializeFirestore, loadBundle, namedQuery, terminate, waitForPendingWrites } from './api/database'; +export { LoadBundleTask, LoadBundleTaskProgress, TaskState } from './api/bundle'; +export { FirestoreSettings, PersistenceSettings } from './api/settings'; +export type { PrivateSettings } from './lite-api/settings'; +export { ExperimentalLongPollingOptions } from './api/long_polling_options'; +export { DocumentChange, DocumentChangeType, DocumentSnapshot, documentSnapshotFromJSON, FirestoreDataConverter, QueryDocumentSnapshot, QuerySnapshot, querySnapshotFromJSON, snapshotEqual, SnapshotMetadata, SnapshotOptions } from './api/snapshot'; +export { collection, collectionGroup, CollectionReference, doc, DocumentData, DocumentReference, PartialWithFieldValue, Query, queryEqual, refEqual, SetOptions, UpdateData, WithFieldValue } from './api/reference'; +export { and, endAt, endBefore, limit, limitToLast, or, orderBy, OrderByDirection, query, QueryCompositeFilterConstraint, QueryConstraint, QueryConstraintType, QueryEndAtConstraint, QueryFieldFilterConstraint, QueryFilterConstraint, QueryLimitConstraint, QueryNonFilterConstraint, QueryOrderByConstraint, QueryStartAtConstraint, startAfter, startAt, where, WhereFilterOp } from './api/filter'; +export { ListenSource, SnapshotListenOptions, Unsubscribe } from './api/reference_impl'; +export { TransactionOptions } from './api/transaction_options'; +export { runTransaction, Transaction } from './api/transaction'; +export { addDoc, deleteDoc, executeWrite, getDoc, getDocFromCache, getDocFromServer, getDocs, getDocsFromCache, getDocsFromServer, onSnapshot, onSnapshotsInSync, onSnapshotResume, setDoc, updateDoc } from './api/reference_impl'; +export { FieldValue } from './api/field_value'; +export { arrayRemove, arrayUnion, deleteField, increment, serverTimestamp, vector } from './api/field_value_impl'; +export { VectorValue } from './lite-api/vector_value'; +export { LogLevelString as LogLevel, setLogLevel } from './util/log'; +export { Bytes } from './api/bytes'; +export { WriteBatch, writeBatch } from './api/write_batch'; +export { GeoPoint } from './api/geo_point'; +export { Timestamp } from './api/timestamp'; +export { CACHE_SIZE_UNLIMITED } from './api/database'; +export { FirestoreError, FirestoreErrorCode } from './util/error'; +export { AbstractUserDataWriter } from './lite-api/user_data_writer'; +export { AddPrefixToKeys, ChildUpdateFields, NestedUpdateFields, Primitive, UnionToIntersection } from '../src/lite-api/types'; +export { Index, IndexConfiguration, IndexField, setIndexConfiguration } from './api/index_configuration'; +export { PersistentCacheIndexManager, getPersistentCacheIndexManager, deleteAllPersistentCacheIndexes, enablePersistentCacheIndexAutoCreation, disablePersistentCacheIndexAutoCreation } from './api/persistent_cache_index_manager'; +/** + * Internal exports + */ +export { isBase64Available as _isBase64Available } from './platform/base64'; +export { DatabaseId as _DatabaseId } from './core/database_info'; +export { _internalQueryToProtoQueryTarget, _internalAggregationQueryToProtoRunAggregationQueryRequest } from './remote/internal_serializer'; +export { cast as _cast, validateIsNotUsedTogether as _validateIsNotUsedTogether } from './util/input_validation'; +export { DocumentKey as _DocumentKey } from './model/document_key'; +export { debugAssert as _debugAssert } from './util/assert'; +export { FieldPath as _FieldPath } from './model/path'; +export type { ResourcePath as _ResourcePath } from './model/path'; +export { ByteString as _ByteString } from './util/byte_string'; +export { logWarn as _logWarn } from './util/log'; +export { AutoId as _AutoId } from './util/misc'; +export type { AuthTokenFactory, FirstPartyCredentialsSettings } from './api/credentials'; +export { EmptyAuthCredentialsProvider as _EmptyAuthCredentialsProvider } from './api/credentials'; +export { EmptyAppCheckTokenProvider as _EmptyAppCheckTokenProvider } from './api/credentials'; +export { ExistenceFilterMismatchCallback as _TestingHooksExistenceFilterMismatchCallback, TestingHooks as _TestingHooks } from './util/testing_hooks'; +export { ExistenceFilterMismatchInfo as _TestingHooksExistenceFilterMismatchInfo } from './util/testing_hooks_spi'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/aggregate.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/aggregate.d.ts new file mode 100644 index 0000000..39bd4b4 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/aggregate.d.ts @@ -0,0 +1,77 @@ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { AggregateField, AggregateSpec, DocumentData, Query } from '../api'; +import { AggregateQuerySnapshot } from '../lite-api/aggregate_types'; +export { aggregateQuerySnapshotEqual, count, sum, average, aggregateFieldEqual } from '../lite-api/aggregate'; +/** + * Calculates the number of documents in the result set of the given query + * without actually downloading the documents. + * + * Using this function to count the documents is efficient because only the + * final count, not the documents' data, is downloaded. This function can + * count the documents in cases where the result set is prohibitively large to + * download entirely (thousands of documents). + * + * The result received from the server is presented, unaltered, without + * considering any local state. That is, documents in the local cache are not + * taken into consideration, neither are local modifications not yet + * synchronized with the server. Previously-downloaded results, if any, are not + * used. Every invocation of this function necessarily involves a round trip to + * the server. + * + * @param query The query whose result set size is calculated. + * @returns A Promise that will be resolved with the count; the count can be + * retrieved from `snapshot.data().count`, where `snapshot` is the + * `AggregateQuerySnapshot` to which the returned Promise resolves. + */ +export declare function getCountFromServer(query: Query): Promise; +}, AppModelType, DbModelType>>; +/** + * Calculates the specified aggregations over the documents in the result + * set of the given query without actually downloading the documents. + * + * Using this function to perform aggregations is efficient because only the + * final aggregation values, not the documents' data, are downloaded. This + * function can perform aggregations of the documents in cases where the result + * set is prohibitively large to download entirely (thousands of documents). + * + * The result received from the server is presented, unaltered, without + * considering any local state. That is, documents in the local cache are not + * taken into consideration, neither are local modifications not yet + * synchronized with the server. Previously-downloaded results, if any, are not + * used. Every invocation of this function necessarily involves a round trip to + * the server. + * + * @param query The query whose result set is aggregated over. + * @param aggregateSpec An `AggregateSpec` object that specifies the aggregates + * to perform over the result set. The AggregateSpec specifies aliases for each + * aggregate, which can be used to retrieve the aggregate result. + * @example + * ```typescript + * const aggregateSnapshot = await getAggregateFromServer(query, { + * countOfDocs: count(), + * totalHours: sum('hours'), + * averageScore: average('score') + * }); + * + * const countOfDocs: number = aggregateSnapshot.data().countOfDocs; + * const totalHours: number = aggregateSnapshot.data().totalHours; + * const averageScore: number | null = aggregateSnapshot.data().averageScore; + * ``` + */ +export declare function getAggregateFromServer(query: Query, aggregateSpec: AggregateSpecType): Promise>; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/bundle.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/bundle.d.ts new file mode 100644 index 0000000..15c33af --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/bundle.d.ts @@ -0,0 +1,94 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { FirestoreError } from '../util/error'; +/** + * Represents the state of bundle loading tasks. + * + * Both 'Error' and 'Success' are sinking state: task will abort or complete and there will + * be no more updates after they are reported. + */ +export type TaskState = 'Error' | 'Running' | 'Success'; +/** + * Represents a progress update or a final state from loading bundles. + */ +export interface LoadBundleTaskProgress { + /** How many documents have been loaded. */ + documentsLoaded: number; + /** How many documents are in the bundle being loaded. */ + totalDocuments: number; + /** How many bytes have been loaded. */ + bytesLoaded: number; + /** How many bytes are in the bundle being loaded. */ + totalBytes: number; + /** Current task state. */ + taskState: TaskState; +} +/** + * Represents the task of loading a Firestore bundle. It provides progress of bundle + * loading, as well as task completion and error events. + * + * The API is compatible with `Promise`. + */ +export declare class LoadBundleTask implements PromiseLike { + private _progressObserver; + private _taskCompletionResolver; + private _lastProgress; + /** + * Registers functions to listen to bundle loading progress events. + * @param next - Called when there is a progress update from bundle loading. Typically `next` calls occur + * each time a Firestore document is loaded from the bundle. + * @param error - Called when an error occurs during bundle loading. The task aborts after reporting the + * error, and there should be no more updates after this. + * @param complete - Called when the loading task is complete. + */ + onProgress(next?: (progress: LoadBundleTaskProgress) => unknown, error?: (err: Error) => unknown, complete?: () => void): void; + /** + * Implements the `Promise.catch` interface. + * + * @param onRejected - Called when an error occurs during bundle loading. + */ + catch(onRejected: (a: Error) => R | PromiseLike): Promise; + /** + * Implements the `Promise.then` interface. + * + * @param onFulfilled - Called on the completion of the loading task with a final `LoadBundleTaskProgress` update. + * The update will always have its `taskState` set to `"Success"`. + * @param onRejected - Called when an error occurs during bundle loading. + */ + then(onFulfilled?: (a: LoadBundleTaskProgress) => T | PromiseLike, onRejected?: (a: Error) => R | PromiseLike): Promise; + /** + * Notifies all observers that bundle loading has completed, with a provided + * `LoadBundleTaskProgress` object. + * + * @private + */ + _completeWith(progress: LoadBundleTaskProgress): void; + /** + * Notifies all observers that bundle loading has failed, with a provided + * `Error` as the reason. + * + * @private + */ + _failWith(error: FirestoreError): void; + /** + * Notifies a progress update of loading a bundle. + * @param progress - The new progress. + * + * @private + */ + _updateProgress(progress: LoadBundleTaskProgress): void; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/bytes.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/bytes.d.ts new file mode 100644 index 0000000..0c9f5fd --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/bytes.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export { Bytes } from '../lite-api/bytes'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/cache_config.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/cache_config.d.ts new file mode 100644 index 0000000..936f21e --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/cache_config.d.ts @@ -0,0 +1,222 @@ +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { OfflineComponentProviderFactory, OnlineComponentProviderFactory } from '../core/component_provider'; +/** + * Provides an in-memory cache to the SDK. This is the default cache unless explicitly + * configured otherwise. + * + * To use, create an instance using the factory function {@link memoryLocalCache()}, then + * set the instance to `FirestoreSettings.cache` and call `initializeFirestore` using + * the settings object. + */ +export type MemoryLocalCache = { + kind: 'memory'; + /** + * @internal + */ + _onlineComponentProvider: OnlineComponentProviderFactory; + /** + * @internal + */ + _offlineComponentProvider: OfflineComponentProviderFactory; +}; +/** + * Provides a persistent cache backed by IndexedDb to the SDK. + * + * To use, create an instance using the factory function {@link persistentLocalCache()}, then + * set the instance to `FirestoreSettings.cache` and call `initializeFirestore` using + * the settings object. + */ +export type PersistentLocalCache = { + kind: 'persistent'; + /** + * @internal + */ + _onlineComponentProvider: OnlineComponentProviderFactory; + /** + * @internal + */ + _offlineComponentProvider: OfflineComponentProviderFactory; +}; +/** + * Union type from all supported SDK cache layer. + */ +export type FirestoreLocalCache = MemoryLocalCache | PersistentLocalCache; +/** + * Union type from all support garbage collectors for memory local cache. + */ +export type MemoryGarbageCollector = MemoryEagerGarbageCollector | MemoryLruGarbageCollector; +/** + * A garbage collector deletes documents whenever they are not part of any + * active queries, and have no local mutations attached to them. + * + * This collector tries to ensure lowest memory footprints from the SDK, + * at the risk of documents not being cached for offline queries or for + * direct queries to the cache. + * + * Use factory function {@link memoryEagerGarbageCollector()} to create an + * instance of this collector. + */ +export type MemoryEagerGarbageCollector = { + kind: 'memoryEager'; + /** + * @internal + */ + _offlineComponentProvider: OfflineComponentProviderFactory; +}; +/** + * A garbage collector deletes Least-Recently-Used documents in multiple + * batches. + * + * This collector is configured with a target size, and will only perform + * collection when the cached documents exceed the target size. It avoids + * querying backend repeated for the same query or document, at the risk + * of having a larger memory footprint. + * + * Use factory function {@link memoryLruGarbageCollector()} to create a + * instance of this collector. + */ +export type MemoryLruGarbageCollector = { + kind: 'memoryLru'; + /** + * @internal + */ + _offlineComponentProvider: OfflineComponentProviderFactory; +}; +/** + * Creates an instance of `MemoryEagerGarbageCollector`. This is also the + * default garbage collector unless it is explicitly specified otherwise. + */ +export declare function memoryEagerGarbageCollector(): MemoryEagerGarbageCollector; +/** + * Creates an instance of `MemoryLruGarbageCollector`. + * + * A target size can be specified as part of the setting parameter. The + * collector will start deleting documents once the cache size exceeds + * the given size. The default cache size is 40MB (40 * 1024 * 1024 bytes). + */ +export declare function memoryLruGarbageCollector(settings?: { + cacheSizeBytes?: number; +}): MemoryLruGarbageCollector; +/** + * An settings object to configure an `MemoryLocalCache` instance. + */ +export type MemoryCacheSettings = { + /** + * The garbage collector to use, for the memory cache layer. + * A `MemoryEagerGarbageCollector` is used when this is undefined. + */ + garbageCollector?: MemoryGarbageCollector; +}; +/** + * Creates an instance of `MemoryLocalCache`. The instance can be set to + * `FirestoreSettings.cache` to tell the SDK which cache layer to use. + */ +export declare function memoryLocalCache(settings?: MemoryCacheSettings): MemoryLocalCache; +/** + * An settings object to configure an `PersistentLocalCache` instance. + * + * Persistent cache cannot be used in a Node.js environment. + */ +export type PersistentCacheSettings = { + /** + * An approximate cache size threshold for the on-disk data. If the cache + * grows beyond this size, Firestore will start removing data that hasn't been + * recently used. The SDK does not guarantee that the cache will stay below + * that size, only that if the cache exceeds the given size, cleanup will be + * attempted. + * + * The default value is 40 MB. The threshold must be set to at least 1 MB, and + * can be set to `CACHE_SIZE_UNLIMITED` to disable garbage collection. + */ + cacheSizeBytes?: number; + /** + * Specifies how multiple tabs/windows will be managed by the SDK. + */ + tabManager?: PersistentTabManager; +}; +/** + * Creates an instance of `PersistentLocalCache`. The instance can be set to + * `FirestoreSettings.cache` to tell the SDK which cache layer to use. + * + * Persistent cache cannot be used in a Node.js environment. + */ +export declare function persistentLocalCache(settings?: PersistentCacheSettings): PersistentLocalCache; +/** + * A tab manager supporting only one tab, no synchronization will be + * performed across tabs. + */ +export type PersistentSingleTabManager = { + kind: 'persistentSingleTab'; + /** + * @internal + */ + _initialize: (settings: Omit | undefined) => void; + /** + * @internal + */ + _onlineComponentProvider?: OnlineComponentProviderFactory; + /** + * @internal + */ + _offlineComponentProvider?: OfflineComponentProviderFactory; +}; +/** + * A tab manager supporting multiple tabs. SDK will synchronize queries and + * mutations done across all tabs using the SDK. + */ +export type PersistentMultipleTabManager = { + kind: 'PersistentMultipleTab'; + /** + * @internal + */ + _initialize: (settings: Omit) => void; + /** + * @internal + */ + _onlineComponentProvider?: OnlineComponentProviderFactory; + /** + * @internal + */ + _offlineComponentProvider?: OfflineComponentProviderFactory; +}; +/** + * A union of all available tab managers. + */ +export type PersistentTabManager = PersistentSingleTabManager | PersistentMultipleTabManager; +/** + * Type to configure an `PersistentSingleTabManager` instance. + */ +export type PersistentSingleTabManagerSettings = { + /** + * Whether to force-enable persistent (IndexedDB) cache for the client. This + * cannot be used with multi-tab synchronization and is primarily intended for + * use with Web Workers. Setting this to `true` will enable IndexedDB, but cause + * other tabs using IndexedDB cache to fail. + */ + forceOwnership?: boolean; +}; +/** + * Creates an instance of `PersistentSingleTabManager`. + * + * @param settings Configures the created tab manager. + */ +export declare function persistentSingleTabManager(settings: PersistentSingleTabManagerSettings | undefined): PersistentSingleTabManager; +/** + * Creates an instance of `PersistentMultipleTabManager`. + */ +export declare function persistentMultipleTabManager(): PersistentMultipleTabManager; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/credentials.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/credentials.d.ts new file mode 100644 index 0000000..98ed3c2 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/credentials.d.ts @@ -0,0 +1,222 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { FirebaseApp } from '@firebase/app'; +import { AppCheckInternalComponentName } from '@firebase/app-check-interop-types'; +import { FirebaseAuthInternalName } from '@firebase/auth-interop-types'; +import { Provider } from '@firebase/component'; +import { User } from '../auth/user'; +import { AsyncQueue } from '../util/async_queue'; +/** + * @internal + */ +export type AuthTokenFactory = () => string; +/** + * @internal + */ +export interface FirstPartyCredentialsSettings { + ['type']: 'firstParty'; + ['sessionIndex']: string; + ['iamToken']: string | null; + ['authTokenFactory']: AuthTokenFactory | null; +} +export interface ProviderCredentialsSettings { + ['type']: 'provider'; + ['client']: CredentialsProvider; +} +/** Settings for private credentials */ +export type CredentialsSettings = FirstPartyCredentialsSettings | ProviderCredentialsSettings; +export type TokenType = 'OAuth' | 'FirstParty' | 'AppCheck'; +export interface Token { + /** Type of token. */ + type: TokenType; + /** + * The user with which the token is associated (used for persisting user + * state on disk, etc.). + * This will be null for Tokens of the type 'AppCheck'. + */ + user?: User; + /** Header values to set for this token */ + headers: Map; +} +export declare class OAuthToken implements Token { + user: User; + type: TokenType; + headers: Map; + constructor(value: string, user: User); +} +/** + * A Listener for credential change events. The listener should fetch a new + * token and may need to invalidate other state if the current user has also + * changed. + */ +export type CredentialChangeListener = (credential: T) => Promise; +/** + * Provides methods for getting the uid and token for the current user and + * listening for changes. + */ +export interface CredentialsProvider { + /** + * Starts the credentials provider and specifies a listener to be notified of + * credential changes (sign-in / sign-out, token changes). It is immediately + * called once with the initial user. + * + * The change listener is invoked on the provided AsyncQueue. + */ + start(asyncQueue: AsyncQueue, changeListener: CredentialChangeListener): void; + /** Requests a token for the current user. */ + getToken(): Promise; + /** + * Marks the last retrieved token as invalid, making the next GetToken request + * force-refresh the token. + */ + invalidateToken(): void; + shutdown(): void; +} +/** + * A CredentialsProvider that always yields an empty token. + * @internal + */ +export declare class EmptyAuthCredentialsProvider implements CredentialsProvider { + getToken(): Promise; + invalidateToken(): void; + start(asyncQueue: AsyncQueue, changeListener: CredentialChangeListener): void; + shutdown(): void; +} +/** + * A CredentialsProvider that always returns a constant token. Used for + * emulator token mocking. + */ +export declare class EmulatorAuthCredentialsProvider implements CredentialsProvider { + private token; + constructor(token: Token); + /** + * Stores the listener registered with setChangeListener() + * This isn't actually necessary since the UID never changes, but we use this + * to verify the listen contract is adhered to in tests. + */ + private changeListener; + getToken(): Promise; + invalidateToken(): void; + start(asyncQueue: AsyncQueue, changeListener: CredentialChangeListener): void; + shutdown(): void; +} +/** Credential provider for the Lite SDK. */ +export declare class LiteAuthCredentialsProvider implements CredentialsProvider { + private auth; + constructor(authProvider: Provider); + getToken(): Promise; + invalidateToken(): void; + start(asyncQueue: AsyncQueue, changeListener: CredentialChangeListener): void; + shutdown(): void; +} +export declare class FirebaseAuthCredentialsProvider implements CredentialsProvider { + private authProvider; + /** + * The auth token listener registered with FirebaseApp, retained here so we + * can unregister it. + */ + private tokenListener; + /** Tracks the current User. */ + private currentUser; + /** + * Counter used to detect if the token changed while a getToken request was + * outstanding. + */ + private tokenCounter; + private forceRefresh; + private auth; + constructor(authProvider: Provider); + start(asyncQueue: AsyncQueue, changeListener: CredentialChangeListener): void; + getToken(): Promise; + invalidateToken(): void; + shutdown(): void; + private getUser; +} +export declare class FirstPartyToken implements Token { + private readonly sessionIndex; + private readonly iamToken; + private readonly authTokenFactory; + type: TokenType; + user: User; + private _headers; + constructor(sessionIndex: string, iamToken: string | null, authTokenFactory: AuthTokenFactory | null); + /** + * Gets an authorization token, using a provided factory function, or return + * null. + */ + private getAuthToken; + get headers(): Map; +} +export declare class FirstPartyAuthCredentialsProvider implements CredentialsProvider { + private sessionIndex; + private iamToken; + private authTokenFactory; + constructor(sessionIndex: string, iamToken: string | null, authTokenFactory: AuthTokenFactory | null); + getToken(): Promise; + start(asyncQueue: AsyncQueue, changeListener: CredentialChangeListener): void; + shutdown(): void; + invalidateToken(): void; +} +export declare class AppCheckToken implements Token { + private value; + type: TokenType; + headers: Map; + constructor(value: string); +} +export declare class FirebaseAppCheckTokenProvider implements CredentialsProvider { + private appCheckProvider; + /** + * The AppCheck token listener registered with FirebaseApp, retained here so + * we can unregister it. + */ + private tokenListener; + private forceRefresh; + private appCheck; + private latestAppCheckToken; + private serverAppAppCheckToken; + constructor(app: FirebaseApp, appCheckProvider: Provider); + start(asyncQueue: AsyncQueue, changeListener: CredentialChangeListener): void; + getToken(): Promise; + invalidateToken(): void; + shutdown(): void; +} +/** + * An AppCheck token provider that always yields an empty token. + * @internal + */ +export declare class EmptyAppCheckTokenProvider implements CredentialsProvider { + getToken(): Promise; + invalidateToken(): void; + start(asyncQueue: AsyncQueue, changeListener: CredentialChangeListener): void; + shutdown(): void; +} +/** AppCheck token provider for the Lite SDK. */ +export declare class LiteAppCheckTokenProvider implements CredentialsProvider { + private appCheckProvider; + private appCheck; + private serverAppAppCheckToken; + constructor(app: FirebaseApp, appCheckProvider: Provider); + getToken(): Promise; + invalidateToken(): void; + start(asyncQueue: AsyncQueue, changeListener: CredentialChangeListener): void; + shutdown(): void; +} +/** + * Builds a CredentialsProvider depending on the type of + * the credentials passed in. + */ +export declare function makeAuthCredentialsProvider(credentials?: CredentialsSettings): CredentialsProvider; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/database.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/database.d.ts new file mode 100644 index 0000000..8004dae --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/database.d.ts @@ -0,0 +1,279 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { FirebaseApp } from '@firebase/app'; +import { User } from '../auth/user'; +import { OfflineComponentProviderFactory, OnlineComponentProviderFactory } from '../core/component_provider'; +import { DatabaseId } from '../core/database_info'; +import { FirestoreClient } from '../core/firestore_client'; +import { Firestore as LiteFirestore } from '../lite-api/database'; +import { Query } from '../lite-api/reference'; +import { AsyncQueue } from '../util/async_queue'; +import { LoadBundleTask } from './bundle'; +import { CredentialsProvider } from './credentials'; +import { FirestoreSettings, PersistenceSettings } from './settings'; +export { connectFirestoreEmulator, EmulatorMockTokenOptions } from '../lite-api/database'; +declare module '@firebase/component' { + interface NameServiceMapping { + 'firestore': Firestore; + } +} +/** + * Constant used to indicate the LRU garbage collection should be disabled. + * Set this value as the `cacheSizeBytes` on the settings passed to the + * {@link Firestore} instance. + */ +export declare const CACHE_SIZE_UNLIMITED = -1; +/** + * The Cloud Firestore service interface. + * + * Do not call this constructor directly. Instead, use {@link (getFirestore:1)}. + */ +export declare class Firestore extends LiteFirestore { + /** + * Whether it's a {@link Firestore} or Firestore Lite instance. + */ + type: 'firestore-lite' | 'firestore'; + _queue: AsyncQueue; + readonly _persistenceKey: string; + _firestoreClient: FirestoreClient | undefined; + _componentsProvider?: { + _offline: OfflineComponentProviderFactory; + _online: OnlineComponentProviderFactory; + }; + /** @hideconstructor */ + constructor(authCredentialsProvider: CredentialsProvider, appCheckCredentialsProvider: CredentialsProvider, databaseId: DatabaseId, app?: FirebaseApp); + protected _terminate(): Promise; +} +/** + * Initializes a new instance of {@link Firestore} with the provided settings. + * Can only be called before any other function, including + * {@link (getFirestore:1)}. If the custom settings are empty, this function is + * equivalent to calling {@link (getFirestore:1)}. + * + * @param app - The {@link @firebase/app#FirebaseApp} with which the {@link Firestore} instance will + * be associated. + * @param settings - A settings object to configure the {@link Firestore} instance. + * @param databaseId - The name of the database. + * @returns A newly initialized {@link Firestore} instance. + */ +export declare function initializeFirestore(app: FirebaseApp, settings: FirestoreSettings, databaseId?: string): Firestore; +/** + * Returns the existing default {@link Firestore} instance that is associated with the + * default {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new + * instance with default settings. + * + * @returns The default {@link Firestore} instance of the default app. + */ +export declare function getFirestore(): Firestore; +/** + * Returns the existing default {@link Firestore} instance that is associated with the + * provided {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new + * instance with default settings. + * + * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned {@link Firestore} + * instance is associated with. + * @returns The default {@link Firestore} instance of the provided app. + */ +export declare function getFirestore(app: FirebaseApp): Firestore; +/** + * Returns the existing named {@link Firestore} instance that is associated with the + * default {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new + * instance with default settings. + * + * @param databaseId - The name of the database. + * @returns The named {@link Firestore} instance of the default app. + * @beta + */ +export declare function getFirestore(databaseId: string): Firestore; +/** + * Returns the existing named {@link Firestore} instance that is associated with the + * provided {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new + * instance with default settings. + * + * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned {@link Firestore} + * instance is associated with. + * @param databaseId - The name of the database. + * @returns The named {@link Firestore} instance of the provided app. + * @beta + */ +export declare function getFirestore(app: FirebaseApp, databaseId: string): Firestore; +/** + * @internal + */ +export declare function ensureFirestoreConfigured(firestore: Firestore): FirestoreClient; +export declare function configureFirestore(firestore: Firestore): void; +/** + * Attempts to enable persistent storage, if possible. + * + * On failure, `enableIndexedDbPersistence()` will reject the promise or + * throw an exception. There are several reasons why this can fail, which can be + * identified by the `code` on the error. + * + * * failed-precondition: The app is already open in another browser tab. + * * unimplemented: The browser is incompatible with the offline persistence + * implementation. + * + * Note that even after a failure, the {@link Firestore} instance will remain + * usable, however offline persistence will be disabled. + * + * Note: `enableIndexedDbPersistence()` must be called before any other functions + * (other than {@link initializeFirestore}, {@link (getFirestore:1)} or + * {@link clearIndexedDbPersistence}. + * + * Persistence cannot be used in a Node.js environment. + * + * @param firestore - The {@link Firestore} instance to enable persistence for. + * @param persistenceSettings - Optional settings object to configure + * persistence. + * @returns A `Promise` that represents successfully enabling persistent storage. + * @deprecated This function will be removed in a future major release. Instead, set + * `FirestoreSettings.localCache` to an instance of `PersistentLocalCache` to + * turn on IndexedDb cache. Calling this function when `FirestoreSettings.localCache` + * is already specified will throw an exception. + */ +export declare function enableIndexedDbPersistence(firestore: Firestore, persistenceSettings?: PersistenceSettings): Promise; +/** + * Attempts to enable multi-tab persistent storage, if possible. If enabled + * across all tabs, all operations share access to local persistence, including + * shared execution of queries and latency-compensated local document updates + * across all connected instances. + * + * On failure, `enableMultiTabIndexedDbPersistence()` will reject the promise or + * throw an exception. There are several reasons why this can fail, which can be + * identified by the `code` on the error. + * + * * failed-precondition: The app is already open in another browser tab and + * multi-tab is not enabled. + * * unimplemented: The browser is incompatible with the offline persistence + * implementation. + * + * Note that even after a failure, the {@link Firestore} instance will remain + * usable, however offline persistence will be disabled. + * + * @param firestore - The {@link Firestore} instance to enable persistence for. + * @returns A `Promise` that represents successfully enabling persistent + * storage. + * @deprecated This function will be removed in a future major release. Instead, set + * `FirestoreSettings.localCache` to an instance of `PersistentLocalCache` to + * turn on indexeddb cache. Calling this function when `FirestoreSettings.localCache` + * is already specified will throw an exception. + */ +export declare function enableMultiTabIndexedDbPersistence(firestore: Firestore): Promise; +/** + * Clears the persistent storage. This includes pending writes and cached + * documents. + * + * Must be called while the {@link Firestore} instance is not started (after the app is + * terminated or when the app is first initialized). On startup, this function + * must be called before other functions (other than {@link + * initializeFirestore} or {@link (getFirestore:1)})). If the {@link Firestore} + * instance is still running, the promise will be rejected with the error code + * of `failed-precondition`. + * + * Note: `clearIndexedDbPersistence()` is primarily intended to help write + * reliable tests that use Cloud Firestore. It uses an efficient mechanism for + * dropping existing data but does not attempt to securely overwrite or + * otherwise make cached data unrecoverable. For applications that are sensitive + * to the disclosure of cached data in between user sessions, we strongly + * recommend not enabling persistence at all. + * + * @param firestore - The {@link Firestore} instance to clear persistence for. + * @returns A `Promise` that is resolved when the persistent storage is + * cleared. Otherwise, the promise is rejected with an error. + */ +export declare function clearIndexedDbPersistence(firestore: Firestore): Promise; +/** + * Waits until all currently pending writes for the active user have been + * acknowledged by the backend. + * + * The returned promise resolves immediately if there are no outstanding writes. + * Otherwise, the promise waits for all previously issued writes (including + * those written in a previous app session), but it does not wait for writes + * that were added after the function is called. If you want to wait for + * additional writes, call `waitForPendingWrites()` again. + * + * Any outstanding `waitForPendingWrites()` promises are rejected during user + * changes. + * + * @returns A `Promise` which resolves when all currently pending writes have been + * acknowledged by the backend. + */ +export declare function waitForPendingWrites(firestore: Firestore): Promise; +/** + * Re-enables use of the network for this {@link Firestore} instance after a prior + * call to {@link disableNetwork}. + * + * @returns A `Promise` that is resolved once the network has been enabled. + */ +export declare function enableNetwork(firestore: Firestore): Promise; +/** + * Disables network usage for this instance. It can be re-enabled via {@link + * enableNetwork}. While the network is disabled, any snapshot listeners, + * `getDoc()` or `getDocs()` calls will return results from cache, and any write + * operations will be queued until the network is restored. + * + * @returns A `Promise` that is resolved once the network has been disabled. + */ +export declare function disableNetwork(firestore: Firestore): Promise; +/** + * Terminates the provided {@link Firestore} instance. + * + * After calling `terminate()` only the `clearIndexedDbPersistence()` function + * may be used. Any other function will throw a `FirestoreError`. + * + * To restart after termination, create a new instance of FirebaseFirestore with + * {@link (getFirestore:1)}. + * + * Termination does not cancel any pending writes, and any promises that are + * awaiting a response from the server will not be resolved. If you have + * persistence enabled, the next time you start this instance, it will resume + * sending these writes to the server. + * + * Note: Under normal circumstances, calling `terminate()` is not required. This + * function is useful only when you want to force this instance to release all + * of its resources or in combination with `clearIndexedDbPersistence()` to + * ensure that all local state is destroyed between test runs. + * + * @returns A `Promise` that is resolved when the instance has been successfully + * terminated. + */ +export declare function terminate(firestore: Firestore): Promise; +/** + * Loads a Firestore bundle into the local cache. + * + * @param firestore - The {@link Firestore} instance to load bundles for. + * @param bundleData - An object representing the bundle to be loaded. Valid + * objects are `ArrayBuffer`, `ReadableStream` or `string`. + * + * @returns A `LoadBundleTask` object, which notifies callers with progress + * updates, and completion or error events. It can be used as a + * `Promise`. + */ +export declare function loadBundle(firestore: Firestore, bundleData: ReadableStream | ArrayBuffer | string): LoadBundleTask; +/** + * Reads a Firestore {@link Query} from local cache, identified by the given + * name. + * + * The named queries are packaged into bundles on the server side (along + * with resulting documents), and loaded to local cache using `loadBundle`. Once + * in local cache, use this method to extract a {@link Query} by name. + * + * @param firestore - The {@link Firestore} instance to read the query from. + * @param name - The name of the query. + * @returns A `Promise` that is resolved with the Query or `null`. + */ +export declare function namedQuery(firestore: Firestore, name: string): Promise; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/field_path.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/field_path.d.ts new file mode 100644 index 0000000..7e463e5 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/field_path.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export { FieldPath, documentId } from '../lite-api/field_path'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/field_value.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/field_value.d.ts new file mode 100644 index 0000000..eded0bc --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/field_value.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export { FieldValue } from '../lite-api/field_value'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/field_value_impl.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/field_value_impl.d.ts new file mode 100644 index 0000000..aac67c3 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/field_value_impl.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export { increment, arrayRemove, arrayUnion, serverTimestamp, deleteField, vector } from '../lite-api/field_value_impl'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/filter.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/filter.d.ts new file mode 100644 index 0000000..1dee60b --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/filter.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export { and, endAt, endBefore, startAfter, startAt, limitToLast, limit, or, orderBy, OrderByDirection, where, WhereFilterOp, query, QueryCompositeFilterConstraint, QueryConstraint, QueryConstraintType, QueryFilterConstraint, QueryFieldFilterConstraint, QueryOrderByConstraint, QueryLimitConstraint, QueryStartAtConstraint, QueryEndAtConstraint, QueryNonFilterConstraint } from '../lite-api/query'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/geo_point.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/geo_point.d.ts new file mode 100644 index 0000000..b14def6 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/geo_point.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export { GeoPoint } from '../lite-api/geo_point'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/index_configuration.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/index_configuration.d.ts new file mode 100644 index 0000000..8b10775 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/index_configuration.d.ts @@ -0,0 +1,139 @@ +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { FieldIndex } from '../model/field_index'; +import { Firestore } from './database'; +export { connectFirestoreEmulator, EmulatorMockTokenOptions } from '../lite-api/database'; +/** + * A single field element in an index configuration. + * + * @deprecated Instead of creating cache indexes manually, consider using + * `enablePersistentCacheIndexAutoCreation()` to let the SDK decide whether to + * create cache indexes for queries running locally. + * + * @beta + */ +export interface IndexField { + /** The field path to index. */ + readonly fieldPath: string; + /** + * What type of array index to create. Set to `CONTAINS` for `array-contains` + * and `array-contains-any` indexes. + * + * Only one of `arrayConfig` or `order` should be set; + */ + readonly arrayConfig?: 'CONTAINS'; + /** + * What type of array index to create. Set to `ASCENDING` or 'DESCENDING` for + * `==`, `!=`, `<=`, `<=`, `in` and `not-in` filters. + * + * Only one of `arrayConfig` or `order` should be set. + */ + readonly order?: 'ASCENDING' | 'DESCENDING'; + [key: string]: unknown; +} +/** + * The SDK definition of a Firestore index. + * + * @deprecated Instead of creating cache indexes manually, consider using + * `enablePersistentCacheIndexAutoCreation()` to let the SDK decide whether to + * create cache indexes for queries running locally. + * + * @beta + */ +export interface Index { + /** The ID of the collection to index. */ + readonly collectionGroup: string; + /** A list of fields to index. */ + readonly fields?: IndexField[]; + [key: string]: unknown; +} +/** + * A list of Firestore indexes to speed up local query execution. + * + * See {@link https://firebase.google.com/docs/reference/firestore/indexes/#json_format | JSON Format} + * for a description of the format of the index definition. + * + * @deprecated Instead of creating cache indexes manually, consider using + * `enablePersistentCacheIndexAutoCreation()` to let the SDK decide whether to + * create cache indexes for queries running locally. + * + * @beta + */ +export interface IndexConfiguration { + /** A list of all Firestore indexes. */ + readonly indexes?: Index[]; + [key: string]: unknown; +} +/** + * Configures indexing for local query execution. Any previous index + * configuration is overridden. The `Promise` resolves once the index + * configuration has been persisted. + * + * The index entries themselves are created asynchronously. You can continue to + * use queries that require indexing even if the indices are not yet available. + * Query execution will automatically start using the index once the index + * entries have been written. + * + * Indexes are only supported with IndexedDb persistence. If IndexedDb is not + * enabled, any index configuration is ignored. + * + * @param firestore - The {@link Firestore} instance to configure indexes for. + * @param configuration -The index definition. + * @throws FirestoreError if the JSON format is invalid. + * @returns A `Promise` that resolves once all indices are successfully + * configured. + * + * @deprecated Instead of creating cache indexes manually, consider using + * `enablePersistentCacheIndexAutoCreation()` to let the SDK decide whether to + * create cache indexes for queries running locally. + * + * @beta + */ +export declare function setIndexConfiguration(firestore: Firestore, configuration: IndexConfiguration): Promise; +/** + * Configures indexing for local query execution. Any previous index + * configuration is overridden. The `Promise` resolves once the index + * configuration has been persisted. + * + * The index entries themselves are created asynchronously. You can continue to + * use queries that require indexing even if the indices are not yet available. + * Query execution will automatically start using the index once the index + * entries have been written. + * + * Indexes are only supported with IndexedDb persistence. Invoke either + * `enableIndexedDbPersistence()` or `enableMultiTabIndexedDbPersistence()` + * before setting an index configuration. If IndexedDb is not enabled, any + * index configuration is ignored. + * + * The method accepts the JSON format exported by the Firebase CLI (`firebase + * firestore:indexes`). If the JSON format is invalid, this method throws an + * error. + * + * @param firestore - The {@link Firestore} instance to configure indexes for. + * @param json -The JSON format exported by the Firebase CLI. + * @throws FirestoreError if the JSON format is invalid. + * @returns A `Promise` that resolves once all indices are successfully + * configured. + * + * @deprecated Instead of creating cache indexes manually, consider using + * `enablePersistentCacheIndexAutoCreation()` to let the SDK decide whether to + * create cache indexes for queries running locally. + * + * @beta + */ +export declare function setIndexConfiguration(firestore: Firestore, json: string): Promise; +export declare function parseIndexes(jsonOrConfiguration: string | IndexConfiguration): FieldIndex[]; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/long_polling_options.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/long_polling_options.d.ts new file mode 100644 index 0000000..0088194 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/long_polling_options.d.ts @@ -0,0 +1,55 @@ +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Options that configure the SDK’s underlying network transport (WebChannel) + * when long-polling is used. + * + * Note: This interface is "experimental" and is subject to change. + * + * See `FirestoreSettings.experimentalAutoDetectLongPolling`, + * `FirestoreSettings.experimentalForceLongPolling`, and + * `FirestoreSettings.experimentalLongPollingOptions`. + */ +export interface ExperimentalLongPollingOptions { + /** + * The desired maximum timeout interval, in seconds, to complete a + * long-polling GET response. Valid values are between 5 and 30, inclusive. + * Floating point values are allowed and will be rounded to the nearest + * millisecond. + * + * By default, when long-polling is used the "hanging GET" request sent by + * the client times out after 30 seconds. To request a different timeout + * from the server, set this setting with the desired timeout. + * + * Changing the default timeout may be useful, for example, if the buffering + * proxy that necessitated enabling long-polling in the first place has a + * shorter timeout for hanging GET requests, in which case setting the + * long-polling timeout to a shorter value, such as 25 seconds, may fix + * prematurely-closed hanging GET requests. + * For example, see https://github.com/firebase/firebase-js-sdk/issues/6987. + */ + timeoutSeconds?: number; +} +/** + * Compares two `ExperimentalLongPollingOptions` objects for equality. + */ +export declare function longPollingOptionsEqual(options1: ExperimentalLongPollingOptions, options2: ExperimentalLongPollingOptions): boolean; +/** + * Creates and returns a new `ExperimentalLongPollingOptions` with the same + * option values as the given instance. + */ +export declare function cloneLongPollingOptions(options: ExperimentalLongPollingOptions): ExperimentalLongPollingOptions; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/observer.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/observer.d.ts new file mode 100644 index 0000000..1aa4b85 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/observer.d.ts @@ -0,0 +1,29 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { FirestoreError } from '../util/error'; +/** + * Observer/Subscribe interfaces. + */ +export type NextFn = (value: T) => void; +export type ErrorFn = (error: FirestoreError) => void; +export type CompleteFn = () => void; +export interface PartialObserver { + next?: NextFn; + error?: ErrorFn; + complete?: CompleteFn; +} +export declare function isPartialObserver(obj: unknown): obj is PartialObserver; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/parse_context.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/parse_context.d.ts new file mode 100644 index 0000000..d2b0beb --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/parse_context.d.ts @@ -0,0 +1,21 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { DatabaseId } from '../core/database_info'; +export interface ParseContext { + readonly databaseId: DatabaseId; + readonly ignoreUndefinedProperties: boolean; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/persistent_cache_index_manager.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/persistent_cache_index_manager.d.ts new file mode 100644 index 0000000..c6e4b46 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/persistent_cache_index_manager.d.ts @@ -0,0 +1,59 @@ +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Firestore } from './database'; +/** + * A `PersistentCacheIndexManager` for configuring persistent cache indexes used + * for local query execution. + * + * To use, call `getPersistentCacheIndexManager()` to get an instance. + */ +export declare class PersistentCacheIndexManager { + readonly _firestore: Firestore; + /** A type string to uniquely identify instances of this class. */ + readonly type: 'PersistentCacheIndexManager'; + /** @hideconstructor */ + constructor(_firestore: Firestore); +} +/** + * Returns the PersistentCache Index Manager used by the given `Firestore` + * object. + * + * @return The `PersistentCacheIndexManager` instance, or `null` if local + * persistent storage is not in use. + */ +export declare function getPersistentCacheIndexManager(firestore: Firestore): PersistentCacheIndexManager | null; +/** + * Enables the SDK to create persistent cache indexes automatically for local + * query execution when the SDK believes cache indexes can help improve + * performance. + * + * This feature is disabled by default. + */ +export declare function enablePersistentCacheIndexAutoCreation(indexManager: PersistentCacheIndexManager): void; +/** + * Stops creating persistent cache indexes automatically for local query + * execution. The indexes which have been created by calling + * `enablePersistentCacheIndexAutoCreation()` still take effect. + */ +export declare function disablePersistentCacheIndexAutoCreation(indexManager: PersistentCacheIndexManager): void; +/** + * Removes all persistent cache indexes. + * + * Please note this function will also deletes indexes generated by + * `setIndexConfiguration()`, which is deprecated. + */ +export declare function deleteAllPersistentCacheIndexes(indexManager: PersistentCacheIndexManager): void; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/reference.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/reference.d.ts new file mode 100644 index 0000000..0e38648 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/reference.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export { DocumentReference, CollectionReference, Query, collection, collectionGroup, doc, queryEqual, SetOptions, DocumentData, UpdateData, WithFieldValue, PartialWithFieldValue, refEqual } from '../lite-api/reference'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/reference_impl.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/reference_impl.d.ts new file mode 100644 index 0000000..5dd95e6 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/reference_impl.d.ts @@ -0,0 +1,536 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Bytes } from '../lite-api/bytes'; +import { FieldPath } from '../lite-api/field_path'; +import { CollectionReference, DocumentData, DocumentReference, PartialWithFieldValue, Query, SetOptions, UpdateData, WithFieldValue } from '../lite-api/reference'; +import { AbstractUserDataWriter } from '../lite-api/user_data_writer'; +import { Mutation } from '../model/mutation'; +import { ByteString } from '../util/byte_string'; +import { FirestoreError } from '../util/error'; +import { Firestore } from './database'; +import { DocumentSnapshot, FirestoreDataConverter, QuerySnapshot } from './snapshot'; +/** + * An options object that can be passed to {@link (onSnapshot:1)} and {@link + * QuerySnapshot.docChanges} to control which types of changes to include in the + * result set. + */ +export interface SnapshotListenOptions { + /** + * Include a change even if only the metadata of the query or of a document + * changed. Default is false. + */ + readonly includeMetadataChanges?: boolean; + /** + * Set the source the query listens to. Default to "default", which + * listens to both cache and server. + */ + readonly source?: ListenSource; +} +/** + * Describe the source a query listens to. + * + * Set to `default` to listen to both cache and server changes. Set to `cache` + * to listen to changes in cache only. + */ +export type ListenSource = 'default' | 'cache'; +/** + * Reads the document referred to by this `DocumentReference`. + * + * Note: `getDoc()` attempts to provide up-to-date data when possible by waiting + * for data from the server, but it may return cached data or fail if you are + * offline and the server cannot be reached. To specify this behavior, invoke + * {@link getDocFromCache} or {@link getDocFromServer}. + * + * @param reference - The reference of the document to fetch. + * @returns A Promise resolved with a `DocumentSnapshot` containing the + * current document contents. + */ +export declare function getDoc(reference: DocumentReference): Promise>; +export declare class ExpUserDataWriter extends AbstractUserDataWriter { + protected firestore: Firestore; + constructor(firestore: Firestore); + protected convertBytes(bytes: ByteString): Bytes; + protected convertReference(name: string): DocumentReference; +} +/** + * Reads the document referred to by this `DocumentReference` from cache. + * Returns an error if the document is not currently cached. + * + * @returns A `Promise` resolved with a `DocumentSnapshot` containing the + * current document contents. + */ +export declare function getDocFromCache(reference: DocumentReference): Promise>; +/** + * Reads the document referred to by this `DocumentReference` from the server. + * Returns an error if the network is not available. + * + * @returns A `Promise` resolved with a `DocumentSnapshot` containing the + * current document contents. + */ +export declare function getDocFromServer(reference: DocumentReference): Promise>; +/** + * Executes the query and returns the results as a `QuerySnapshot`. + * + * Note: `getDocs()` attempts to provide up-to-date data when possible by + * waiting for data from the server, but it may return cached data or fail if + * you are offline and the server cannot be reached. To specify this behavior, + * invoke {@link getDocsFromCache} or {@link getDocsFromServer}. + * + * @returns A `Promise` that will be resolved with the results of the query. + */ +export declare function getDocs(query: Query): Promise>; +/** + * Executes the query and returns the results as a `QuerySnapshot` from cache. + * Returns an empty result set if no documents matching the query are currently + * cached. + * + * @returns A `Promise` that will be resolved with the results of the query. + */ +export declare function getDocsFromCache(query: Query): Promise>; +/** + * Executes the query and returns the results as a `QuerySnapshot` from the + * server. Returns an error if the network is not available. + * + * @returns A `Promise` that will be resolved with the results of the query. + */ +export declare function getDocsFromServer(query: Query): Promise>; +/** + * Writes to the document referred to by this `DocumentReference`. If the + * document does not yet exist, it will be created. + * + * @param reference - A reference to the document to write. + * @param data - A map of the fields and values for the document. + * @returns A `Promise` resolved once the data has been successfully written + * to the backend (note that it won't resolve while you're offline). + */ +export declare function setDoc(reference: DocumentReference, data: WithFieldValue): Promise; +/** + * Writes to the document referred to by the specified `DocumentReference`. If + * the document does not yet exist, it will be created. If you provide `merge` + * or `mergeFields`, the provided data can be merged into an existing document. + * + * @param reference - A reference to the document to write. + * @param data - A map of the fields and values for the document. + * @param options - An object to configure the set behavior. + * @returns A Promise resolved once the data has been successfully written + * to the backend (note that it won't resolve while you're offline). + */ +export declare function setDoc(reference: DocumentReference, data: PartialWithFieldValue, options: SetOptions): Promise; +/** + * Updates fields in the document referred to by the specified + * `DocumentReference`. The update will fail if applied to a document that does + * not exist. + * + * @param reference - A reference to the document to update. + * @param data - An object containing the fields and values with which to + * update the document. Fields can contain dots to reference nested fields + * within the document. + * @returns A `Promise` resolved once the data has been successfully written + * to the backend (note that it won't resolve while you're offline). + */ +export declare function updateDoc(reference: DocumentReference, data: UpdateData): Promise; +/** + * Updates fields in the document referred to by the specified + * `DocumentReference` The update will fail if applied to a document that does + * not exist. + * + * Nested fields can be updated by providing dot-separated field path + * strings or by providing `FieldPath` objects. + * + * @param reference - A reference to the document to update. + * @param field - The first field to update. + * @param value - The first value. + * @param moreFieldsAndValues - Additional key value pairs. + * @returns A `Promise` resolved once the data has been successfully written + * to the backend (note that it won't resolve while you're offline). + */ +export declare function updateDoc(reference: DocumentReference, field: string | FieldPath, value: unknown, ...moreFieldsAndValues: unknown[]): Promise; +/** + * Deletes the document referred to by the specified `DocumentReference`. + * + * @param reference - A reference to the document to delete. + * @returns A Promise resolved once the document has been successfully + * deleted from the backend (note that it won't resolve while you're offline). + */ +export declare function deleteDoc(reference: DocumentReference): Promise; +/** + * Add a new document to specified `CollectionReference` with the given data, + * assigning it a document ID automatically. + * + * @param reference - A reference to the collection to add this document to. + * @param data - An Object containing the data for the new document. + * @returns A `Promise` resolved with a `DocumentReference` pointing to the + * newly created document after it has been written to the backend (Note that it + * won't resolve while you're offline). + */ +export declare function addDoc(reference: CollectionReference, data: WithFieldValue): Promise>; +/** + * A function returned by `onSnapshot()` that removes the listener when invoked. + */ +export interface Unsubscribe { + /** Removes the listener when invoked. */ + (): void; +} +/** + * Attaches a listener for `DocumentSnapshot` events. You may either pass individual `onNext` and + * `onError` callbacks or pass a single observer object with `next` and `error` callbacks. + * + * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the + * snapshot stream is never-ending. + * + * @param reference - A reference to the document to listen to. + * @param observer - A single object containing `next` and `error` callbacks. + * @returns An unsubscribe function that can be called to cancel + * the snapshot listener. + */ +export declare function onSnapshot(reference: DocumentReference, observer: { + next?: (snapshot: DocumentSnapshot) => void; + error?: (error: FirestoreError) => void; + complete?: () => void; +}): Unsubscribe; +/** + * Attaches a listener for `DocumentSnapshot` events. You may either pass individual `onNext` and + * `onError` callbacks or pass a single observer object with `next` and `error` callbacks. + * + * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the + * snapshot stream is never-ending. + * + * @param reference - A reference to the document to listen to. + * @param options - Options controlling the listen behavior. + * @param observer - A single object containing `next` and `error` callbacks. + * @returns An unsubscribe function that can be called to cancel + * the snapshot listener. + */ +export declare function onSnapshot(reference: DocumentReference, options: SnapshotListenOptions, observer: { + next?: (snapshot: DocumentSnapshot) => void; + error?: (error: FirestoreError) => void; + complete?: () => void; +}): Unsubscribe; +/** + * Attaches a listener for `DocumentSnapshot` events. You may either pass individual `onNext` and + * `onError` callbacks or pass a single observer object with `next` and `error` callbacks. + * + * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the + * snapshot stream is never-ending. + * + * @param reference - A reference to the document to listen to. + * @param onNext - A callback to be called every time a new `DocumentSnapshot` is available. + * @param onError - A callback to be called if the listen fails or is cancelled. No further + * callbacks will occur. + * @param onCompletion - Can be provided, but will not be called since streams are never ending. + * @returns An unsubscribe function that can be called to cancel the snapshot listener. + */ +export declare function onSnapshot(reference: DocumentReference, onNext: (snapshot: DocumentSnapshot) => void, onError?: (error: FirestoreError) => void, onCompletion?: () => void): Unsubscribe; +/** + * Attaches a listener for `DocumentSnapshot` events. You may either pass individual `onNext` and + * `onError` callbacks or pass a single observer object with `next` and `error` callbacks. + * + * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the + * snapshot stream is never-ending. + * + * @param reference - A reference to the document to listen to. + * @param options - Options controlling the listen behavior. + * @param onNext - A callback to be called every time a new `DocumentSnapshot` is available. + * @param onError - A callback to be called if the listen fails or is cancelled. No further + * callbacks will occur. + * @param onCompletion - Can be provided, but will not be called since streams are never ending. + * @returns An unsubscribe function that can be called to cancel the snapshot listener. + */ +export declare function onSnapshot(reference: DocumentReference, options: SnapshotListenOptions, onNext: (snapshot: DocumentSnapshot) => void, onError?: (error: FirestoreError) => void, onCompletion?: () => void): Unsubscribe; +/** + * Attaches a listener for `QuerySnapshot` events. You may either pass individual `onNext` and + * `onError` callbacks or pass a single observer object with `next` and `error` callbacks. The + * listener can be cancelled by calling the function that is returned when `onSnapshot` is called. + * + * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the + * snapshot stream is never-ending. + * + * @param query - The query to listen to. + * @param observer - A single object containing `next` and `error` callbacks. + * @returns An unsubscribe function that can be called to cancel the snapshot listener. + */ +export declare function onSnapshot(query: Query, observer: { + next?: (snapshot: QuerySnapshot) => void; + error?: (error: FirestoreError) => void; + complete?: () => void; +}): Unsubscribe; +/** + * Attaches a listener for `QuerySnapshot` events. You may either pass individual `onNext` and + * `onError` callbacks or pass a single observer object with `next` and `error` callbacks. The + * listener can be cancelled by calling the function that is returned when `onSnapshot` is called. + * + * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the + * snapshot stream is never-ending. + * + * @param query - The query to listen to. + * @param options - Options controlling the listen behavior. + * @param observer - A single object containing `next` and `error` callbacks. + * @returns An unsubscribe function that can be called to cancel the snapshot listener. + */ +export declare function onSnapshot(query: Query, options: SnapshotListenOptions, observer: { + next?: (snapshot: QuerySnapshot) => void; + error?: (error: FirestoreError) => void; + complete?: () => void; +}): Unsubscribe; +/** + * Attaches a listener for `QuerySnapshot` events. You may either pass individual `onNext` and + * `onError` callbacks or pass a single observer object with `next` and `error` callbacks. The + * listener can be cancelled by calling the function that is returned when `onSnapshot` is called. + * + * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the + * snapshot stream is never-ending. + * + * @param query - The query to listen to. + * @param onNext - A callback to be called every time a new `QuerySnapshot` is available. + * @param onCompletion - Can be provided, but will not be called since streams are never ending. + * @param onError - A callback to be called if the listen fails or is cancelled. No further + * callbacks will occur. + * @returns An unsubscribe function that can be called to cancel the snapshot listener. + */ +export declare function onSnapshot(query: Query, onNext: (snapshot: QuerySnapshot) => void, onError?: (error: FirestoreError) => void, onCompletion?: () => void): Unsubscribe; +/** + * Attaches a listener for `QuerySnapshot` events. You may either pass individual `onNext` and + * `onError` callbacks or pass a single observer object with `next` and `error` callbacks. The + * listener can be cancelled by calling the function that is returned when `onSnapshot` is called. + * + * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the + * snapshot stream is never-ending. + * + * @param query - The query to listen to. + * @param options - Options controlling the listen behavior. + * @param onNext - A callback to be called every time a new `QuerySnapshot` is available. + * @param onCompletion - Can be provided, but will not be called since streams are never ending. + * @param onError - A callback to be called if the listen fails or is cancelled. No further + * callbacks will occur. + * @returns An unsubscribe function that can be called to cancel the snapshot listener. + */ +export declare function onSnapshot(query: Query, options: SnapshotListenOptions, onNext: (snapshot: QuerySnapshot) => void, onError?: (error: FirestoreError) => void, onCompletion?: () => void): Unsubscribe; +/** + * Attaches a listener for `QuerySnapshot` events based on data generated by invoking + * {@link QuerySnapshot.toJSON} You may either pass individual `onNext` and `onError` callbacks or + * pass a single observer object with `next` and `error` callbacks. The listener can be cancelled by + * calling the function that is returned when `onSnapshot` is called. + * + * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the + * snapshot stream is never-ending. + * + * @param firestore - The {@link Firestore} instance to enable the listener for. + * @param snapshotJson - A JSON object generated by invoking {@link QuerySnapshot.toJSON}. + * @param onNext - A callback to be called every time a new `QuerySnapshot` is available. + * @param onError - A callback to be called if the listen fails or is cancelled. No further + * callbacks will occur. + * @param onCompletion - Can be provided, but will not be called since streams are never ending. + * @param converter - An optional object that converts objects from Firestore before the onNext + * listener is invoked. + * @returns An unsubscribe function that can be called to cancel the snapshot listener. + */ +export declare function onSnapshotResume(firestore: Firestore, snapshotJson: object, onNext: (snapshot: QuerySnapshot) => void, onError?: (error: FirestoreError) => void, onCompletion?: () => void, converter?: FirestoreDataConverter): Unsubscribe; +/** + * Attaches a listener for `DocumentSnapshot` events based on data generated by invoking + * {@link DocumentSnapshot.toJSON}. You may either pass individual `onNext` and `onError` callbacks or + * pass a single observer object with `next` and `error` callbacks. The listener can be cancelled by + * calling the function that is returned when `onSnapshot` is called. + * + * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the + * snapshot stream is never-ending. + * + * @param firestore - The {@link Firestore} instance to enable the listener for. + * @param snapshotJson - A JSON object generated by invoking {@link DocumentSnapshot.toJSON}. + * @param onNext - A callback to be called every time a new `DocumentSnapshot` is available. + * @param onError - A callback to be called if the listen fails or is cancelled. No further + * callbacks will occur. + * @param onCompletion - Can be provided, but will not be called since streams are + * never ending. + * @param converter - An optional object that converts objects from Firestore before the onNext + * listener is invoked. + * @returns An unsubscribe function that can be called to cancel the snapshot listener. + */ +export declare function onSnapshotResume(firestore: Firestore, snapshotJson: object, onNext: (snapshot: DocumentSnapshot) => void, onError?: (error: FirestoreError) => void, onCompletion?: () => void, converter?: FirestoreDataConverter): Unsubscribe; +/** + * Attaches a listener for `QuerySnapshot` events based on data generated by invoking + * {@link QuerySnapshot.toJSON}. You may either pass individual `onNext` and `onError` callbacks or + * pass a single observer object with `next` and `error` callbacks. The listener can be cancelled by + * calling the function that is returned when `onSnapshot` is called. + * + * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the + * snapshot stream is never-ending. + * + * @param firestore - The {@link Firestore} instance to enable the listener for. + * @param snapshotJson - A JSON object generated by invoking {@link QuerySnapshot.toJSON}. + * @param options - Options controlling the listen behavior. + * @param onNext - A callback to be called every time a new `QuerySnapshot` is available. + * @param onError - A callback to be called if the listen fails or is cancelled. No further + * callbacks will occur. + * @param onCompletion - Can be provided, but will not be called since streams are never ending. + * @param converter - An optional object that converts objects from Firestore before the onNext + * listener is invoked. + * @returns An unsubscribe function that can be called to cancel the snapshot listener. + */ +export declare function onSnapshotResume(firestore: Firestore, snapshotJson: object, options: SnapshotListenOptions, onNext: (snapshot: QuerySnapshot) => void, onError?: (error: FirestoreError) => void, onCompletion?: () => void, converter?: FirestoreDataConverter): Unsubscribe; +/** + * Attaches a listener for `DocumentSnapshot` events based on data generated by invoking + * {@link DocumentSnapshot.toJSON}. You may either pass individual `onNext` and `onError` callbacks + * or pass a single observer object with `next` and `error` callbacks. The listener can be cancelled + * by calling the function that is returned when `onSnapshot` is called. + * + * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the + * snapshot stream is never-ending. + * + * @param firestore - The {@link Firestore} instance to enable the listener for. + * @param snapshotJson - A JSON object generated by invoking {@link DocumentSnapshot.toJSON}. + * @param options - Options controlling the listen behavior. + * @param onNext - A callback to be called every time a new `DocumentSnapshot` is available. + * @param onError - A callback to be called if the listen fails or is cancelled. No further + * callbacks will occur. + * @param onCompletion - Can be provided, but will not be called since streams are never ending. + * @param converter - An optional object that converts objects from Firestore before the onNext + * listener is invoked. + * @returns An unsubscribe function that can be called to cancel + * the snapshot listener. + */ +export declare function onSnapshotResume(firestore: Firestore, snapshotJson: object, options: SnapshotListenOptions, onNext: (snapshot: DocumentSnapshot) => void, onError?: (error: FirestoreError) => void, onCompletion?: () => void, converter?: FirestoreDataConverter): Unsubscribe; +/** + * Attaches a listener for `QuerySnapshot` events based on QuerySnapshot data generated by invoking + * {@link QuerySnapshot.toJSON}. You may either pass individual `onNext` and `onError` callbacks or + * pass a single observer object with `next` and `error` callbacks. The listener can be cancelled by + * calling the function that is returned when `onSnapshot` is called. + * + * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the + * snapshot stream is never-ending. + * + * @param firestore - The {@link Firestore} instance to enable the listener for. + * @param snapshotJson - A JSON object generated by invoking {@link QuerySnapshot.toJSON}. + * @param observer - A single object containing `next` and `error` callbacks. + * @param converter - An optional object that converts objects from Firestore before the onNext + * listener is invoked. + * @returns An unsubscribe function that can be called to cancel + * the snapshot listener. + */ +export declare function onSnapshotResume(firestore: Firestore, snapshotJson: object, observer: { + next: (snapshot: QuerySnapshot) => void; + error?: (error: FirestoreError) => void; + complete?: () => void; +}, converter?: FirestoreDataConverter): Unsubscribe; +/** + * Attaches a listener for `DocumentSnapshot` events based on data generated by invoking + * {@link DocumentSnapshot.toJSON} You may either pass individual `onNext` and `onError` callbacks + * or pass a single observer object with `next` and `error` callbacks. The listener can be cancelled + * by calling the function that is returned when `onSnapshot` is called. + * + * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the + * snapshot stream is never-ending. + * + * @param firestore - The {@link Firestore} instance to enable the listener for. + * @param snapshotJson - A JSON object generated by invoking {@link DocumentSnapshot.toJSON}. + * @param observer - A single object containing `next` and `error` callbacks. + * @param converter - An optional object that converts objects from Firestore before the onNext + * listener is invoked. + * @returns An unsubscribe function that can be called to cancel + * the snapshot listener. + */ +export declare function onSnapshotResume(firestore: Firestore, snapshotJson: object, observer: { + next: (snapshot: DocumentSnapshot) => void; + error?: (error: FirestoreError) => void; + complete?: () => void; +}, converter?: FirestoreDataConverter): Unsubscribe; +/** + * Attaches a listener for `QuerySnapshot` events based on QuerySnapshot data generated by invoking + * {@link QuerySnapshot.toJSON} You may either pass individual `onNext` and `onError` callbacks or + * pass a single observer object with `next` and `error` callbacks. The listener can be cancelled by + * calling the function that is returned when `onSnapshot` is called. + * + * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the + * snapshot stream is never-ending. + * + * @param firestore - The {@link Firestore} instance to enable the listener for. + * @param snapshotJson - A JSON object generated by invoking {@link QuerySnapshot.toJSON}. + * @param options - Options controlling the listen behavior. + * @param observer - A single object containing `next` and `error` callbacks. + * @param converter - An optional object that converts objects from Firestore before the onNext + * listener is invoked. + * @returns An unsubscribe function that can be called to cancel + * the snapshot listener. + */ +export declare function onSnapshotResume(firestore: Firestore, snapshotJson: object, options: SnapshotListenOptions, observer: { + next: (snapshot: QuerySnapshot) => void; + error?: (error: FirestoreError) => void; + complete?: () => void; +}, converter?: FirestoreDataConverter): Unsubscribe; +/** + * Attaches a listener for `DocumentSnapshot` events based on QuerySnapshot data generated by + * invoking {@link DocumentSnapshot.toJSON} You may either pass individual `onNext` and `onError` + * callbacks or pass a single observer object with `next` and `error` callbacks. The listener can be + * cancelled by calling the function that is returned when `onSnapshot` is called. + * + * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the + * snapshot stream is never-ending. + * + * @param firestore - The {@link Firestore} instance to enable the listener for. + * @param snapshotJson - A JSON object generated by invoking {@link DocumentSnapshot.toJSON}. + * @param options - Options controlling the listen behavior. + * @param observer - A single object containing `next` and `error` callbacks. + * @param converter - An optional object that converts objects from Firestore before the onNext + * listener is invoked. + * @returns An unsubscribe function that can be called to cancel the snapshot listener. + */ +export declare function onSnapshotResume(firestore: Firestore, snapshotJson: object, options: SnapshotListenOptions, observer: { + next: (snapshot: DocumentSnapshot) => void; + error?: (error: FirestoreError) => void; + complete?: () => void; +}, converter?: FirestoreDataConverter): Unsubscribe; +/** + * Attaches a listener for a snapshots-in-sync event. The snapshots-in-sync + * event indicates that all listeners affected by a given change have fired, + * even if a single server-generated change affects multiple listeners. + * + * NOTE: The snapshots-in-sync event only indicates that listeners are in sync + * with each other, but does not relate to whether those snapshots are in sync + * with the server. Use SnapshotMetadata in the individual listeners to + * determine if a snapshot is from the cache or the server. + * + * @param firestore - The instance of Firestore for synchronizing snapshots. + * @param observer - A single object containing `next` and `error` callbacks. + * @returns An unsubscribe function that can be called to cancel the snapshot + * listener. + */ +export declare function onSnapshotsInSync(firestore: Firestore, observer: { + next?: (value: void) => void; + error?: (error: FirestoreError) => void; + complete?: () => void; +}): Unsubscribe; +/** + * Attaches a listener for a snapshots-in-sync event. The snapshots-in-sync + * event indicates that all listeners affected by a given change have fired, + * even if a single server-generated change affects multiple listeners. + * + * NOTE: The snapshots-in-sync event only indicates that listeners are in sync + * with each other, but does not relate to whether those snapshots are in sync + * with the server. Use `SnapshotMetadata` in the individual listeners to + * determine if a snapshot is from the cache or the server. + * + * @param firestore - The `Firestore` instance for synchronizing snapshots. + * @param onSync - A callback to be called every time all snapshot listeners are + * in sync with each other. + * @returns An unsubscribe function that can be called to cancel the snapshot + * listener. + */ +export declare function onSnapshotsInSync(firestore: Firestore, onSync: () => void): Unsubscribe; +/** + * Locally writes `mutations` on the async queue. + * @internal + */ +export declare function executeWrite(firestore: Firestore, mutations: Mutation[]): Promise; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/settings.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/settings.d.ts new file mode 100644 index 0000000..8565811 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/settings.d.ts @@ -0,0 +1,108 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { FirestoreSettings as LiteSettings } from '../lite-api/settings'; +import { FirestoreLocalCache } from './cache_config'; +import { ExperimentalLongPollingOptions } from './long_polling_options'; +export { DEFAULT_HOST } from '../lite-api/settings'; +/** + * Settings that can be passed to `enableIndexedDbPersistence()` to configure + * Firestore persistence. + * + * Persistence cannot be used in a Node.js environment. + */ +export interface PersistenceSettings { + /** + * Whether to force enable persistence for the client. This cannot be used + * with multi-tab synchronization and is primarily intended for use with Web + * Workers. Setting this to `true` will enable persistence, but cause other + * tabs using persistence to fail. + */ + forceOwnership?: boolean; +} +/** + * Specifies custom configurations for your Cloud Firestore instance. + * You must set these before invoking any other methods. + */ +export interface FirestoreSettings extends LiteSettings { + /** + * NOTE: This field will be deprecated in a future major release. Use `cache` field + * instead to specify cache size, and other cache configurations. + * + * An approximate cache size threshold for the on-disk data. If the cache + * grows beyond this size, Firestore will start removing data that hasn't been + * recently used. The size is not a guarantee that the cache will stay below + * that size, only that if the cache exceeds the given size, cleanup will be + * attempted. + * + * The default value is 40 MB. The threshold must be set to at least 1 MB, and + * can be set to `CACHE_SIZE_UNLIMITED` to disable garbage collection. + */ + cacheSizeBytes?: number; + /** + * Specifies the cache used by the SDK. Available options are `MemoryLocalCache` + * and `PersistentLocalCache`, each with different configuration options. + * + * When unspecified, `MemoryLocalCache` will be used by default. + * + * NOTE: setting this field and `cacheSizeBytes` at the same time will throw + * exception during SDK initialization. Instead, using the configuration in + * the `FirestoreLocalCache` object to specify the cache size. + */ + localCache?: FirestoreLocalCache; + /** + * Forces the SDK’s underlying network transport (WebChannel) to use + * long-polling. Each response from the backend will be closed immediately + * after the backend sends data (by default responses are kept open in + * case the backend has more data to send). This avoids incompatibility + * issues with certain proxies, antivirus software, etc. that incorrectly + * buffer traffic indefinitely. Use of this option will cause some + * performance degradation though. + * + * This setting cannot be used with `experimentalAutoDetectLongPolling` and + * may be removed in a future release. If you find yourself using it to + * work around a specific network reliability issue, please tell us about + * it in https://github.com/firebase/firebase-js-sdk/issues/1674. + * + * This setting cannot be used in a Node.js environment. + */ + experimentalForceLongPolling?: boolean; + /** + * Configures the SDK's underlying transport (WebChannel) to automatically + * detect if long-polling should be used. This is very similar to + * `experimentalForceLongPolling`, but only uses long-polling if required. + * + * After having had a default value of `false` since its inception in 2019, + * the default value of this setting was changed in May 2023 to `true` in + * v9.22.0 of the Firebase JavaScript SDK. That is, auto-detection of long + * polling is now enabled by default. To disable it, set this setting to + * `false`, and please open a GitHub issue to share the problems that + * motivated you disabling long-polling auto-detection. + * + * This setting cannot be used in a Node.js environment. + */ + experimentalAutoDetectLongPolling?: boolean; + /** + * Options that configure the SDK’s underlying network transport (WebChannel) + * when long-polling is used. + * + * These options are only used if `experimentalForceLongPolling` is true or if + * `experimentalAutoDetectLongPolling` is true and the auto-detection + * determined that long-polling was needed. Otherwise, these options have no + * effect. + */ + experimentalLongPollingOptions?: ExperimentalLongPollingOptions; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/snapshot.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/snapshot.d.ts new file mode 100644 index 0000000..24d863e --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/snapshot.d.ts @@ -0,0 +1,550 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { ChangeType, ViewSnapshot } from '../core/view_snapshot'; +import { FieldPath } from '../lite-api/field_path'; +import { DocumentData, PartialWithFieldValue, Query, SetOptions, WithFieldValue } from '../lite-api/reference'; +import { DocumentSnapshot as LiteDocumentSnapshot, FirestoreDataConverter as LiteFirestoreDataConverter } from '../lite-api/snapshot'; +import { UntypedFirestoreDataConverter } from '../lite-api/user_data_reader'; +import { AbstractUserDataWriter } from '../lite-api/user_data_writer'; +import { Document } from '../model/document'; +import { DocumentKey } from '../model/document_key'; +import { Property } from '../util/json_validation'; +import { Firestore } from './database'; +import { SnapshotListenOptions } from './reference_impl'; +/** + * Converter used by `withConverter()` to transform user objects of type + * `AppModelType` into Firestore data of type `DbModelType`. + * + * Using the converter allows you to specify generic type arguments when + * storing and retrieving objects from Firestore. + * + * In this context, an "AppModel" is a class that is used in an application to + * package together related information and functionality. Such a class could, + * for example, have properties with complex, nested data types, properties used + * for memoization, properties of types not supported by Firestore (such as + * `symbol` and `bigint`), and helper functions that perform compound + * operations. Such classes are not suitable and/or possible to store into a + * Firestore database. Instead, instances of such classes need to be converted + * to "plain old JavaScript objects" (POJOs) with exclusively primitive + * properties, potentially nested inside other POJOs or arrays of POJOs. In this + * context, this type is referred to as the "DbModel" and would be an object + * suitable for persisting into Firestore. For convenience, applications can + * implement `FirestoreDataConverter` and register the converter with Firestore + * objects, such as `DocumentReference` or `Query`, to automatically convert + * `AppModel` to `DbModel` when storing into Firestore, and convert `DbModel` + * to `AppModel` when retrieving from Firestore. + * + * @example + * + * Simple Example + * + * ```typescript + * const numberConverter = { + * toFirestore(value: WithFieldValue) { + * return { value }; + * }, + * fromFirestore(snapshot: QueryDocumentSnapshot, options: SnapshotOptions) { + * return snapshot.data(options).value as number; + * } + * }; + * + * async function simpleDemo(db: Firestore): Promise { + * const documentRef = doc(db, 'values/value123').withConverter(numberConverter); + * + * // converters are used with `setDoc`, `addDoc`, and `getDoc` + * await setDoc(documentRef, 42); + * const snapshot1 = await getDoc(documentRef); + * assertEqual(snapshot1.data(), 42); + * + * // converters are not used when writing data with `updateDoc` + * await updateDoc(documentRef, { value: 999 }); + * const snapshot2 = await getDoc(documentRef); + * assertEqual(snapshot2.data(), 999); + * } + * ``` + * + * Advanced Example + * + * ```typescript + * // The Post class is a model that is used by our application. + * // This class may have properties and methods that are specific + * // to our application execution, which do not need to be persisted + * // to Firestore. + * class Post { + * constructor( + * readonly title: string, + * readonly author: string, + * readonly lastUpdatedMillis: number + * ) {} + * toString(): string { + * return `${this.title} by ${this.author}`; + * } + * } + * + * // The PostDbModel represents how we want our posts to be stored + * // in Firestore. This DbModel has different properties (`ttl`, + * // `aut`, and `lut`) from the Post class we use in our application. + * interface PostDbModel { + * ttl: string; + * aut: { firstName: string; lastName: string }; + * lut: Timestamp; + * } + * + * // The `PostConverter` implements `FirestoreDataConverter` and specifies + * // how the Firestore SDK can convert `Post` objects to `PostDbModel` + * // objects and vice versa. + * class PostConverter implements FirestoreDataConverter { + * toFirestore(post: WithFieldValue): WithFieldValue { + * return { + * ttl: post.title, + * aut: this._autFromAuthor(post.author), + * lut: this._lutFromLastUpdatedMillis(post.lastUpdatedMillis) + * }; + * } + * + * fromFirestore(snapshot: QueryDocumentSnapshot, options: SnapshotOptions): Post { + * const data = snapshot.data(options) as PostDbModel; + * const author = `${data.aut.firstName} ${data.aut.lastName}`; + * return new Post(data.ttl, author, data.lut.toMillis()); + * } + * + * _autFromAuthor( + * author: string | FieldValue + * ): { firstName: string; lastName: string } | FieldValue { + * if (typeof author !== 'string') { + * // `author` is a FieldValue, so just return it. + * return author; + * } + * const [firstName, lastName] = author.split(' '); + * return {firstName, lastName}; + * } + * + * _lutFromLastUpdatedMillis( + * lastUpdatedMillis: number | FieldValue + * ): Timestamp | FieldValue { + * if (typeof lastUpdatedMillis !== 'number') { + * // `lastUpdatedMillis` must be a FieldValue, so just return it. + * return lastUpdatedMillis; + * } + * return Timestamp.fromMillis(lastUpdatedMillis); + * } + * } + * + * async function advancedDemo(db: Firestore): Promise { + * // Create a `DocumentReference` with a `FirestoreDataConverter`. + * const documentRef = doc(db, 'posts/post123').withConverter(new PostConverter()); + * + * // The `data` argument specified to `setDoc()` is type checked by the + * // TypeScript compiler to be compatible with `Post`. Since the `data` + * // argument is typed as `WithFieldValue` rather than just `Post`, + * // this allows properties of the `data` argument to also be special + * // Firestore values that perform server-side mutations, such as + * // `arrayRemove()`, `deleteField()`, and `serverTimestamp()`. + * await setDoc(documentRef, { + * title: 'My Life', + * author: 'Foo Bar', + * lastUpdatedMillis: serverTimestamp() + * }); + * + * // The TypeScript compiler will fail to compile if the `data` argument to + * // `setDoc()` is _not_ compatible with `WithFieldValue`. This + * // type checking prevents the caller from specifying objects with incorrect + * // properties or property values. + * // @ts-expect-error "Argument of type { ttl: string; } is not assignable + * // to parameter of type WithFieldValue" + * await setDoc(documentRef, { ttl: 'The Title' }); + * + * // When retrieving a document with `getDoc()` the `DocumentSnapshot` + * // object's `data()` method returns a `Post`, rather than a generic object, + * // which would have been returned if the `DocumentReference` did _not_ have a + * // `FirestoreDataConverter` attached to it. + * const snapshot1: DocumentSnapshot = await getDoc(documentRef); + * const post1: Post = snapshot1.data()!; + * if (post1) { + * assertEqual(post1.title, 'My Life'); + * assertEqual(post1.author, 'Foo Bar'); + * } + * + * // The `data` argument specified to `updateDoc()` is type checked by the + * // TypeScript compiler to be compatible with `PostDbModel`. Note that + * // unlike `setDoc()`, whose `data` argument must be compatible with `Post`, + * // the `data` argument to `updateDoc()` must be compatible with + * // `PostDbModel`. Similar to `setDoc()`, since the `data` argument is typed + * // as `WithFieldValue` rather than just `PostDbModel`, this + * // allows properties of the `data` argument to also be those special + * // Firestore values, like `arrayRemove()`, `deleteField()`, and + * // `serverTimestamp()`. + * await updateDoc(documentRef, { + * 'aut.firstName': 'NewFirstName', + * lut: serverTimestamp() + * }); + * + * // The TypeScript compiler will fail to compile if the `data` argument to + * // `updateDoc()` is _not_ compatible with `WithFieldValue`. + * // This type checking prevents the caller from specifying objects with + * // incorrect properties or property values. + * // @ts-expect-error "Argument of type { title: string; } is not assignable + * // to parameter of type WithFieldValue" + * await updateDoc(documentRef, { title: 'New Title' }); + * const snapshot2: DocumentSnapshot = await getDoc(documentRef); + * const post2: Post = snapshot2.data()!; + * if (post2) { + * assertEqual(post2.title, 'My Life'); + * assertEqual(post2.author, 'NewFirstName Bar'); + * } + * } + * ``` + */ +export interface FirestoreDataConverter extends LiteFirestoreDataConverter { + /** + * Called by the Firestore SDK to convert a custom model object of type + * `AppModelType` into a plain JavaScript object (suitable for writing + * directly to the Firestore database) of type `DbModelType`. To use `set()` + * with `merge` and `mergeFields`, `toFirestore()` must be defined with + * `PartialWithFieldValue`. + * + * The `WithFieldValue` type extends `T` to also allow FieldValues such as + * {@link (deleteField:1)} to be used as property values. + */ + toFirestore(modelObject: WithFieldValue): WithFieldValue; + /** + * Called by the Firestore SDK to convert a custom model object of type + * `AppModelType` into a plain JavaScript object (suitable for writing + * directly to the Firestore database) of type `DbModelType`. Used with + * {@link (setDoc:1)}, {@link (WriteBatch.set:1)} and + * {@link (Transaction.set:1)} with `merge:true` or `mergeFields`. + * + * The `PartialWithFieldValue` type extends `Partial` to allow + * FieldValues such as {@link (arrayUnion:1)} to be used as property values. + * It also supports nested `Partial` by allowing nested fields to be + * omitted. + */ + toFirestore(modelObject: PartialWithFieldValue, options: SetOptions): PartialWithFieldValue; + /** + * Called by the Firestore SDK to convert Firestore data into an object of + * type `AppModelType`. You can access your data by calling: + * `snapshot.data(options)`. + * + * Generally, the data returned from `snapshot.data()` can be cast to + * `DbModelType`; however, this is not guaranteed because Firestore does not + * enforce a schema on the database. For example, writes from a previous + * version of the application or writes from another client that did not use a + * type converter could have written data with different properties and/or + * property types. The implementation will need to choose whether to + * gracefully recover from non-conforming data or throw an error. + * + * To override this method, see {@link (FirestoreDataConverter.fromFirestore:1)}. + * + * @param snapshot - A `QueryDocumentSnapshot` containing your data and metadata. + * @param options - The `SnapshotOptions` from the initial call to `data()`. + */ + fromFirestore(snapshot: QueryDocumentSnapshot, options?: SnapshotOptions): AppModelType; +} +/** + * Options that configure how data is retrieved from a `DocumentSnapshot` (for + * example the desired behavior for server timestamps that have not yet been set + * to their final value). + */ +export interface SnapshotOptions { + /** + * If set, controls the return value for server timestamps that have not yet + * been set to their final value. + * + * By specifying 'estimate', pending server timestamps return an estimate + * based on the local clock. This estimate will differ from the final value + * and cause these values to change once the server result becomes available. + * + * By specifying 'previous', pending timestamps will be ignored and return + * their previous value instead. + * + * If omitted or set to 'none', `null` will be returned by default until the + * server value becomes available. + */ + readonly serverTimestamps?: 'estimate' | 'previous' | 'none'; +} +/** + * Metadata about a snapshot, describing the state of the snapshot. + */ +export declare class SnapshotMetadata { + /** + * True if the snapshot contains the result of local writes (for example + * `set()` or `update()` calls) that have not yet been committed to the + * backend. If your listener has opted into metadata updates (via + * `SnapshotListenOptions`) you will receive another snapshot with + * `hasPendingWrites` equal to false once the writes have been committed to + * the backend. + */ + readonly hasPendingWrites: boolean; + /** + * True if the snapshot was created from cached data rather than guaranteed + * up-to-date server data. If your listener has opted into metadata updates + * (via `SnapshotListenOptions`) you will receive another snapshot with + * `fromCache` set to false once the client has received up-to-date data from + * the backend. + */ + readonly fromCache: boolean; + /** @hideconstructor */ + constructor(hasPendingWrites: boolean, fromCache: boolean); + /** + * Returns true if this `SnapshotMetadata` is equal to the provided one. + * + * @param other - The `SnapshotMetadata` to compare against. + * @returns true if this `SnapshotMetadata` is equal to the provided one. + */ + isEqual(other: SnapshotMetadata): boolean; +} +/** + * The type of a `DocumentChange` may be 'added', 'removed', or 'modified'. + */ +export type DocumentChangeType = 'added' | 'removed' | 'modified'; +/** + * A `DocumentChange` represents a change to the documents matching a query. + * It contains the document affected and the type of change that occurred. + */ +export interface DocumentChange { + /** The type of change ('added', 'modified', or 'removed'). */ + readonly type: DocumentChangeType; + /** The document affected by this change. */ + readonly doc: QueryDocumentSnapshot; + /** + * The index of the changed document in the result set immediately prior to + * this `DocumentChange` (i.e. supposing that all prior `DocumentChange` objects + * have been applied). Is `-1` for 'added' events. + */ + readonly oldIndex: number; + /** + * The index of the changed document in the result set immediately after + * this `DocumentChange` (i.e. supposing that all prior `DocumentChange` + * objects and the current `DocumentChange` object have been applied). + * Is -1 for 'removed' events. + */ + readonly newIndex: number; +} +/** + * A `DocumentSnapshot` contains data read from a document in your Firestore + * database. The data can be extracted with `.data()` or `.get()` to + * get a specific field. + * + * For a `DocumentSnapshot` that points to a non-existing document, any data + * access will return 'undefined'. You can use the `exists()` method to + * explicitly verify a document's existence. + */ +export declare class DocumentSnapshot extends LiteDocumentSnapshot { + readonly _firestore: Firestore; + private readonly _firestoreImpl; + /** + * Metadata about the `DocumentSnapshot`, including information about its + * source and local modifications. + */ + readonly metadata: SnapshotMetadata; + /** @hideconstructor protected */ + constructor(_firestore: Firestore, userDataWriter: AbstractUserDataWriter, key: DocumentKey, document: Document | null, metadata: SnapshotMetadata, converter: UntypedFirestoreDataConverter | null); + /** + * Returns whether or not the data exists. True if the document exists. + */ + exists(): this is QueryDocumentSnapshot; + /** + * Retrieves all fields in the document as an `Object`. Returns `undefined` if + * the document doesn't exist. + * + * By default, `serverTimestamp()` values that have not yet been + * set to their final value will be returned as `null`. You can override + * this by passing an options object. + * + * @param options - An options object to configure how data is retrieved from + * the snapshot (for example the desired behavior for server timestamps that + * have not yet been set to their final value). + * @returns An `Object` containing all fields in the document or `undefined` if + * the document doesn't exist. + */ + data(options?: SnapshotOptions): AppModelType | undefined; + /** + * Retrieves the field specified by `fieldPath`. Returns `undefined` if the + * document or field doesn't exist. + * + * By default, a `serverTimestamp()` that has not yet been set to + * its final value will be returned as `null`. You can override this by + * passing an options object. + * + * @param fieldPath - The path (for example 'foo' or 'foo.bar') to a specific + * field. + * @param options - An options object to configure how the field is retrieved + * from the snapshot (for example the desired behavior for server timestamps + * that have not yet been set to their final value). + * @returns The data at the specified field location or undefined if no such + * field exists in the document. + */ + get(fieldPath: string | FieldPath, options?: SnapshotOptions): any; + static _jsonSchemaVersion: string; + static _jsonSchema: { + type: Property<"string">; + bundleSource: Property<"string">; + bundleName: Property<"string">; + bundle: Property<"string">; + }; + /** + * Returns a JSON-serializable representation of this `DocumentSnapshot` instance. + * + * @returns a JSON representation of this object. Throws a {@link FirestoreError} if this + * `DocumentSnapshot` has pending writes. + */ + toJSON(): object; +} +/** + * Builds a `DocumentSnapshot` instance from a JSON object created by + * {@link DocumentSnapshot.toJSON}. + * + * @param firestore - The {@link Firestore} instance the snapshot should be loaded for. + * @param json - a JSON object represention of a `DocumentSnapshot` instance. + * @returns an instance of {@link DocumentSnapshot} if the JSON object could be + * parsed. Throws a {@link FirestoreError} if an error occurs. + */ +export declare function documentSnapshotFromJSON(db: Firestore, json: object): DocumentSnapshot; +/** + * Builds a `DocumentSnapshot` instance from a JSON object created by + * {@link DocumentSnapshot.toJSON}. + * + * @param firestore - The {@link Firestore} instance the snapshot should be loaded for. + * @param json - a JSON object represention of a `DocumentSnapshot` instance. + * @param converter - Converts objects to and from Firestore. + * @returns an instance of {@link DocumentSnapshot} if the JSON object could be + * parsed. Throws a {@link FirestoreError} if an error occurs. + */ +export declare function documentSnapshotFromJSON(db: Firestore, json: object, converter: FirestoreDataConverter): DocumentSnapshot; +/** + * A `QueryDocumentSnapshot` contains data read from a document in your + * Firestore database as part of a query. The document is guaranteed to exist + * and its data can be extracted with `.data()` or `.get()` to get a + * specific field. + * + * A `QueryDocumentSnapshot` offers the same API surface as a + * `DocumentSnapshot`. Since query results contain only existing documents, the + * `exists` property will always be true and `data()` will never return + * 'undefined'. + */ +export declare class QueryDocumentSnapshot extends DocumentSnapshot { + /** + * Retrieves all fields in the document as an `Object`. + * + * By default, `serverTimestamp()` values that have not yet been + * set to their final value will be returned as `null`. You can override + * this by passing an options object. + * + * @override + * @param options - An options object to configure how data is retrieved from + * the snapshot (for example the desired behavior for server timestamps that + * have not yet been set to their final value). + * @returns An `Object` containing all fields in the document. + */ + data(options?: SnapshotOptions): AppModelType; +} +/** + * A `QuerySnapshot` contains zero or more `DocumentSnapshot` objects + * representing the results of a query. The documents can be accessed as an + * array via the `docs` property or enumerated using the `forEach` method. The + * number of documents can be determined via the `empty` and `size` + * properties. + */ +export declare class QuerySnapshot { + readonly _firestore: Firestore; + readonly _userDataWriter: AbstractUserDataWriter; + readonly _snapshot: ViewSnapshot; + /** + * Metadata about this snapshot, concerning its source and if it has local + * modifications. + */ + readonly metadata: SnapshotMetadata; + /** + * The query on which you called `get` or `onSnapshot` in order to get this + * `QuerySnapshot`. + */ + readonly query: Query; + private _cachedChanges?; + private _cachedChangesIncludeMetadataChanges?; + /** @hideconstructor */ + constructor(_firestore: Firestore, _userDataWriter: AbstractUserDataWriter, query: Query, _snapshot: ViewSnapshot); + /** An array of all the documents in the `QuerySnapshot`. */ + get docs(): Array>; + /** The number of documents in the `QuerySnapshot`. */ + get size(): number; + /** True if there are no documents in the `QuerySnapshot`. */ + get empty(): boolean; + /** + * Enumerates all of the documents in the `QuerySnapshot`. + * + * @param callback - A callback to be called with a `QueryDocumentSnapshot` for + * each document in the snapshot. + * @param thisArg - The `this` binding for the callback. + */ + forEach(callback: (result: QueryDocumentSnapshot) => void, thisArg?: unknown): void; + /** + * Returns an array of the documents changes since the last snapshot. If this + * is the first snapshot, all documents will be in the list as 'added' + * changes. + * + * @param options - `SnapshotListenOptions` that control whether metadata-only + * changes (i.e. only `DocumentSnapshot.metadata` changed) should trigger + * snapshot events. + */ + docChanges(options?: SnapshotListenOptions): Array>; + static _jsonSchemaVersion: string; + static _jsonSchema: { + type: Property<"string">; + bundleSource: Property<"string">; + bundleName: Property<"string">; + bundle: Property<"string">; + }; + /** + * Returns a JSON-serializable representation of this `QuerySnapshot` instance. + * + * @returns a JSON representation of this object. Throws a {@link FirestoreError} if this + * `QuerySnapshot` has pending writes. + */ + toJSON(): object; +} +/** + * Builds a `QuerySnapshot` instance from a JSON object created by + * {@link QuerySnapshot.toJSON}. + * + * @param firestore - The {@link Firestore} instance the snapshot should be loaded for. + * @param json - a JSON object represention of a `QuerySnapshot` instance. + * @returns an instance of {@link QuerySnapshot} if the JSON object could be + * parsed. Throws a {@link FirestoreError} if an error occurs. + */ +export declare function querySnapshotFromJSON(db: Firestore, json: object): QuerySnapshot; +/** + * Builds a `QuerySnapshot` instance from a JSON object created by + * {@link QuerySnapshot.toJSON}. + * + * @param firestore - The {@link Firestore} instance the snapshot should be loaded for. + * @param json - a JSON object represention of a `QuerySnapshot` instance. + * @param converter - Converts objects to and from Firestore. + * @returns an instance of {@link QuerySnapshot} if the JSON object could be + * parsed. Throws a {@link FirestoreError} if an error occurs. + */ +export declare function querySnapshotFromJSON(db: Firestore, json: object, converter: FirestoreDataConverter): QuerySnapshot; +/** Calculates the array of `DocumentChange`s for a given `ViewSnapshot`. */ +export declare function changesFromSnapshot(querySnapshot: QuerySnapshot, includeMetadataChanges: boolean): Array>; +export declare function resultChangeType(type: ChangeType): DocumentChangeType; +/** + * Returns true if the provided snapshots are equal. + * + * @param left - A snapshot to compare. + * @param right - A snapshot to compare. + * @returns true if the snapshots are equal. + */ +export declare function snapshotEqual(left: DocumentSnapshot | QuerySnapshot, right: DocumentSnapshot | QuerySnapshot): boolean; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/timestamp.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/timestamp.d.ts new file mode 100644 index 0000000..35969cd --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/timestamp.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export { Timestamp } from '../lite-api/timestamp'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/transaction.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/transaction.d.ts new file mode 100644 index 0000000..eccd1fb --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/transaction.d.ts @@ -0,0 +1,61 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Transaction as InternalTransaction } from '../core/transaction'; +import { DocumentData, DocumentReference } from '../lite-api/reference'; +import { Transaction as LiteTransaction } from '../lite-api/transaction'; +import { Firestore } from './database'; +import { DocumentSnapshot } from './snapshot'; +import { TransactionOptions } from './transaction_options'; +/** + * A reference to a transaction. + * + * The `Transaction` object passed to a transaction's `updateFunction` provides + * the methods to read and write data within the transaction context. See + * {@link runTransaction}. + */ +export declare class Transaction extends LiteTransaction { + protected readonly _firestore: Firestore; + /** @hideconstructor */ + constructor(_firestore: Firestore, _transaction: InternalTransaction); + /** + * Reads the document referenced by the provided {@link DocumentReference}. + * + * @param documentRef - A reference to the document to be read. + * @returns A `DocumentSnapshot` with the read data. + */ + get(documentRef: DocumentReference): Promise>; +} +/** + * Executes the given `updateFunction` and then attempts to commit the changes + * applied within the transaction. If any document read within the transaction + * has changed, Cloud Firestore retries the `updateFunction`. If it fails to + * commit after 5 attempts, the transaction fails. + * + * The maximum number of writes allowed in a single transaction is 500. + * + * @param firestore - A reference to the Firestore database to run this + * transaction against. + * @param updateFunction - The function to execute within the transaction + * context. + * @param options - An options object to configure maximum number of attempts to + * commit. + * @returns If the transaction completed successfully or was explicitly aborted + * (the `updateFunction` returned a failed promise), the promise returned by the + * `updateFunction `is returned here. Otherwise, if the transaction failed, a + * rejected promise with the corresponding failure error is returned. + */ +export declare function runTransaction(firestore: Firestore, updateFunction: (transaction: Transaction) => Promise, options?: TransactionOptions): Promise; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/transaction_options.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/transaction_options.d.ts new file mode 100644 index 0000000..578e4f4 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/transaction_options.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export { TransactionOptions } from '../lite-api/transaction_options'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/write_batch.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/write_batch.d.ts new file mode 100644 index 0000000..13b31d8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/write_batch.d.ts @@ -0,0 +1,31 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { WriteBatch } from '../lite-api/write_batch'; +import { Firestore } from './database'; +export { WriteBatch }; +/** + * Creates a write batch, used for performing multiple writes as a single + * atomic operation. The maximum number of writes allowed in a single {@link WriteBatch} + * is 500. + * + * Unlike transactions, write batches are persisted offline and therefore are + * preferable when you don't need to condition your writes on read data. + * + * @returns A {@link WriteBatch} that can be used to atomically execute multiple + * writes. + */ +export declare function writeBatch(firestore: Firestore): WriteBatch; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/auth/user.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/auth/user.d.ts new file mode 100644 index 0000000..920a290 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/auth/user.d.ts @@ -0,0 +1,36 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Simple wrapper around a nullable UID. Mostly exists to make code more + * readable. + */ +export declare class User { + readonly uid: string | null; + /** A user with a null UID. */ + static readonly UNAUTHENTICATED: User; + static readonly GOOGLE_CREDENTIALS: User; + static readonly FIRST_PARTY: User; + static readonly MOCK_USER: User; + constructor(uid: string | null); + isAuthenticated(): boolean; + /** + * Returns a key representing this user, suitable for inclusion in a + * dictionary. + */ + toKey(): string; + isEqual(otherUser: User): boolean; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/aggregate.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/aggregate.d.ts new file mode 100644 index 0000000..16da2bb --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/aggregate.d.ts @@ -0,0 +1,38 @@ +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { FieldPath } from '../model/path'; +/** + * Union type representing the aggregate type to be performed. + */ +export type AggregateType = 'count' | 'avg' | 'sum'; +/** + * Represents an Aggregate to be performed over a query result set. + */ +export interface Aggregate { + readonly fieldPath?: FieldPath; + readonly alias: string; + readonly aggregateType: AggregateType; +} +/** + * Concrete implementation of the Aggregate type. + */ +export declare class AggregateImpl implements Aggregate { + readonly alias: string; + readonly aggregateType: AggregateType; + readonly fieldPath?: FieldPath | undefined; + constructor(alias: string, aggregateType: AggregateType, fieldPath?: FieldPath | undefined); +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/bound.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/bound.d.ts new file mode 100644 index 0000000..8289126 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/bound.d.ts @@ -0,0 +1,49 @@ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Document } from '../model/document'; +import { Value as ProtoValue } from '../protos/firestore_proto_api'; +import { OrderBy } from './order_by'; +/** + * Represents a bound of a query. + * + * The bound is specified with the given components representing a position and + * whether it's just before or just after the position (relative to whatever the + * query order is). + * + * The position represents a logical index position for a query. It's a prefix + * of values for the (potentially implicit) order by clauses of a query. + * + * Bound provides a function to determine whether a document comes before or + * after a bound. This is influenced by whether the position is just before or + * just after the provided values. + */ +export declare class Bound { + readonly position: ProtoValue[]; + readonly inclusive: boolean; + constructor(position: ProtoValue[], inclusive: boolean); +} +/** + * Returns true if a document sorts after a bound using the provided sort + * order. + */ +export declare function boundSortsAfterDocument(bound: Bound, orderBy: OrderBy[], doc: Document): boolean; +/** + * Returns true if a document sorts before a bound using the provided sort + * order. + */ +export declare function boundSortsBeforeDocument(bound: Bound, orderBy: OrderBy[], doc: Document): boolean; +export declare function boundEquals(left: Bound | null, right: Bound | null): boolean; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/bundle.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/bundle.d.ts new file mode 100644 index 0000000..6a81fcf --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/bundle.d.ts @@ -0,0 +1,80 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { LoadBundleTaskProgress } from '@firebase/firestore-types'; +import { DocumentMap } from '../model/collections'; +import { MutableDocument } from '../model/document'; +import { DocumentKey } from '../model/document_key'; +import { BundledDocumentMetadata as ProtoBundledDocumentMetadata } from '../protos/firestore_bundle_proto'; +import { Document as ApiDocument, Timestamp as ApiTimestamp } from '../protos/firestore_proto_api'; +import { Query } from './query'; +import { SnapshotVersion } from './snapshot_version'; +/** + * Represents a bundled document, including the metadata and the document + * itself, if it exists. + */ +export interface BundledDocument { + metadata: ProtoBundledDocumentMetadata; + document?: ApiDocument; +} +/** + * An array of `BundledDocument`. + */ +export type BundledDocuments = BundledDocument[]; +export interface BundleLoadResult { + readonly progress: LoadBundleTaskProgress; + readonly changedCollectionGroups: Set; + readonly changedDocs: DocumentMap; +} +/** + * Represents a Firestore bundle saved by the SDK in its local storage. + */ +export interface BundleMetadata { + /** + * Id of the bundle. It is used together with `createTime` to determine if a + * bundle has been loaded by the SDK. + */ + readonly id: string; + /** Schema version of the bundle. */ + readonly version: number; + /** + * Set to the snapshot version of the bundle if created by the Server SDKs. + * Otherwise set to SnapshotVersion.MIN. + */ + readonly createTime: SnapshotVersion; +} +/** + * Represents a Query saved by the SDK in its local storage. + */ +export interface NamedQuery { + /** The name of the query. */ + readonly name: string; + /** The underlying query associated with `name`. */ + readonly query: Query; + /** The time at which the results for this query were read. */ + readonly readTime: SnapshotVersion; +} +/** + * Helper to convert objects from bundles to model objects in the SDK. + */ +export interface BundleConverter { + toDocumentKey(name: string): DocumentKey; + /** + * Converts a BundleDocument to a MutableDocument. + */ + toMutableDocument(bundledDoc: BundledDocument): MutableDocument; + toSnapshotVersion(time: ApiTimestamp): SnapshotVersion; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/bundle_impl.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/bundle_impl.d.ts new file mode 100644 index 0000000..55395f2 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/bundle_impl.d.ts @@ -0,0 +1,88 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { LoadBundleTaskProgress } from '@firebase/firestore-types'; +import { LocalStore } from '../local/local_store'; +import { MutableDocument } from '../model/document'; +import { DocumentKey } from '../model/document_key'; +import { BundleMetadata as ProtoBundleMetadata, NamedQuery as ProtoNamedQuery } from '../protos/firestore_bundle_proto'; +import { Timestamp as ApiTimestamp } from '../protos/firestore_proto_api'; +import { JsonProtoSerializer } from '../remote/serializer'; +import { SizedBundleElement } from '../util/bundle_reader'; +import { BundleConverter, BundledDocument, BundledDocuments, BundleLoadResult } from './bundle'; +import { SnapshotVersion } from './snapshot_version'; +/** + * Helper to convert objects from bundles to model objects in the SDK. + */ +export declare class BundleConverterImpl implements BundleConverter { + private readonly serializer; + constructor(serializer: JsonProtoSerializer); + toDocumentKey(name: string): DocumentKey; + /** + * Converts a BundleDocument to a MutableDocument. + */ + toMutableDocument(bundledDoc: BundledDocument): MutableDocument; + toSnapshotVersion(time: ApiTimestamp): SnapshotVersion; +} +/** + * A class to process the elements from a bundle, and optionally load them into local + * storage and provide progress update while loading. + */ +export declare class BundleLoader { + private bundleMetadata; + private serializer; + /** The current progress of loading */ + private progress; + /** Batched queries to be saved into storage */ + private _queries; + /** Batched documents to be saved into storage */ + private _documents; + /** The collection groups affected by this bundle. */ + private collectionGroups; + constructor(bundleMetadata: ProtoBundleMetadata, serializer: JsonProtoSerializer); + /** + * Returns the named queries that have been parsed from the SizeBundleElements added by + * calling {@link adSizedElement}. + */ + get queries(): ProtoNamedQuery[]; + /** + * Returns the BundledDocuments that have been parsed from the SizeBundleElements added by + * calling {@link addSizedElement}. + */ + get documents(): BundledDocuments; + /** + * Adds an element from the bundle to the loader. + * + * Returns a new progress if adding the element leads to a new progress, + * otherwise returns null. + */ + addSizedElement(element: SizedBundleElement): LoadBundleTaskProgress | null; + private getQueryDocumentMapping; + /** + * Update the progress to 'Success' and return the updated progress. + */ + completeAndStoreAsync(localStore: LocalStore): Promise; +} +/** + * Returns a `LoadBundleTaskProgress` representing the initial progress of + * loading a bundle. + */ +export declare function bundleInitialProgress(metadata: ProtoBundleMetadata): LoadBundleTaskProgress; +/** + * Returns a `LoadBundleTaskProgress` representing the progress that the loading + * has succeeded. + */ +export declare function bundleSuccessProgress(metadata: ProtoBundleMetadata): LoadBundleTaskProgress; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/component_provider.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/component_provider.d.ts new file mode 100644 index 0000000..97b6814 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/component_provider.d.ts @@ -0,0 +1,146 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { CredentialsProvider } from '../api/credentials'; +import { User } from '../auth/user'; +import { IndexedDbPersistence } from '../local/indexeddb_persistence'; +import { LocalStore } from '../local/local_store'; +import { Scheduler, Persistence } from '../local/persistence'; +import { ClientId, SharedClientState } from '../local/shared_client_state'; +import { Datastore } from '../remote/datastore'; +import { RemoteStore } from '../remote/remote_store'; +import { JsonProtoSerializer } from '../remote/serializer'; +import { AsyncQueue } from '../util/async_queue'; +import { DatabaseInfo } from './database_info'; +import { EventManager } from './event_manager'; +import { SyncEngine } from './sync_engine'; +type Kind = 'memory' | 'persistent'; +export interface ComponentConfiguration { + asyncQueue: AsyncQueue; + databaseInfo: DatabaseInfo; + authCredentials: CredentialsProvider; + appCheckCredentials: CredentialsProvider; + clientId: ClientId; + initialUser: User; + maxConcurrentLimboResolutions: number; +} +export interface OfflineComponentProviderFactory { + build(onlineComponents: OnlineComponentProvider): OfflineComponentProvider; +} +/** + * Initializes and wires components that are needed to interface with the local + * cache. Implementations override `initialize()` to provide all components. + */ +export interface OfflineComponentProvider { + readonly kind: Kind; + persistence: Persistence; + sharedClientState: SharedClientState; + localStore: LocalStore; + gcScheduler: Scheduler | null; + indexBackfillerScheduler: Scheduler | null; + synchronizeTabs: boolean; + initialize(cfg: ComponentConfiguration): Promise; + terminate(): Promise; +} +/** + * Provides all components needed for Firestore with in-memory persistence. + * Uses EagerGC garbage collection. + */ +export declare class MemoryOfflineComponentProvider implements OfflineComponentProvider { + kind: Kind; + static readonly provider: OfflineComponentProviderFactory; + persistence: Persistence; + sharedClientState: SharedClientState; + localStore: LocalStore; + gcScheduler: Scheduler | null; + indexBackfillerScheduler: Scheduler | null; + synchronizeTabs: boolean; + serializer: JsonProtoSerializer; + initialize(cfg: ComponentConfiguration): Promise; + createGarbageCollectionScheduler(cfg: ComponentConfiguration, localStore: LocalStore): Scheduler | null; + createIndexBackfillerScheduler(cfg: ComponentConfiguration, localStore: LocalStore): Scheduler | null; + createLocalStore(cfg: ComponentConfiguration): LocalStore; + createPersistence(cfg: ComponentConfiguration): Persistence; + createSharedClientState(cfg: ComponentConfiguration): SharedClientState; + terminate(): Promise; +} +export declare class LruGcMemoryOfflineComponentProvider extends MemoryOfflineComponentProvider { + protected readonly cacheSizeBytes: number | undefined; + constructor(cacheSizeBytes: number | undefined); + createGarbageCollectionScheduler(cfg: ComponentConfiguration, localStore: LocalStore): Scheduler | null; + createPersistence(cfg: ComponentConfiguration): Persistence; +} +/** + * Provides all components needed for Firestore with IndexedDB persistence. + */ +export declare class IndexedDbOfflineComponentProvider extends MemoryOfflineComponentProvider { + protected readonly onlineComponentProvider: OnlineComponentProvider; + protected readonly cacheSizeBytes: number | undefined; + protected readonly forceOwnership: boolean | undefined; + kind: Kind; + persistence: IndexedDbPersistence; + sharedClientState: SharedClientState; + localStore: LocalStore; + gcScheduler: Scheduler | null; + indexBackfillerScheduler: Scheduler | null; + synchronizeTabs: boolean; + constructor(onlineComponentProvider: OnlineComponentProvider, cacheSizeBytes: number | undefined, forceOwnership: boolean | undefined); + initialize(cfg: ComponentConfiguration): Promise; + createLocalStore(cfg: ComponentConfiguration): LocalStore; + createGarbageCollectionScheduler(cfg: ComponentConfiguration, localStore: LocalStore): Scheduler | null; + createIndexBackfillerScheduler(cfg: ComponentConfiguration, localStore: LocalStore): Scheduler | null; + createPersistence(cfg: ComponentConfiguration): IndexedDbPersistence; + createSharedClientState(cfg: ComponentConfiguration): SharedClientState; +} +/** + * Provides all components needed for Firestore with multi-tab IndexedDB + * persistence. + * + * In the legacy client, this provider is used to provide both multi-tab and + * non-multi-tab persistence since we cannot tell at build time whether + * `synchronizeTabs` will be enabled. + */ +export declare class MultiTabOfflineComponentProvider extends IndexedDbOfflineComponentProvider { + protected readonly onlineComponentProvider: OnlineComponentProvider; + protected readonly cacheSizeBytes: number | undefined; + synchronizeTabs: boolean; + constructor(onlineComponentProvider: OnlineComponentProvider, cacheSizeBytes: number | undefined); + initialize(cfg: ComponentConfiguration): Promise; + createSharedClientState(cfg: ComponentConfiguration): SharedClientState; +} +export interface OnlineComponentProviderFactory { + build(): OnlineComponentProvider; +} +/** + * Initializes and wires the components that are needed to interface with the + * network. + */ +export declare class OnlineComponentProvider { + static readonly provider: OnlineComponentProviderFactory; + protected localStore: LocalStore; + protected sharedClientState: SharedClientState; + datastore: Datastore; + eventManager: EventManager; + remoteStore: RemoteStore; + syncEngine: SyncEngine; + initialize(offlineComponentProvider: OfflineComponentProvider, cfg: ComponentConfiguration): Promise; + createEventManager(cfg: ComponentConfiguration): EventManager; + createDatastore(cfg: ComponentConfiguration): Datastore; + createRemoteStore(cfg: ComponentConfiguration): RemoteStore; + createSyncEngine(cfg: ComponentConfiguration, startAsPrimary: boolean): SyncEngine; + terminate(): Promise; +} +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/database_info.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/database_info.d.ts new file mode 100644 index 0000000..5429403 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/database_info.d.ts @@ -0,0 +1,64 @@ +import { FirebaseApp } from '@firebase/app'; +import { ExperimentalLongPollingOptions } from '../api/long_polling_options'; +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export declare class DatabaseInfo { + readonly databaseId: DatabaseId; + readonly appId: string; + readonly persistenceKey: string; + readonly host: string; + readonly ssl: boolean; + readonly forceLongPolling: boolean; + readonly autoDetectLongPolling: boolean; + readonly longPollingOptions: ExperimentalLongPollingOptions; + readonly useFetchStreams: boolean; + readonly isUsingEmulator: boolean; + /** + * Constructs a DatabaseInfo using the provided host, databaseId and + * persistenceKey. + * + * @param databaseId - The database to use. + * @param appId - The Firebase App Id. + * @param persistenceKey - A unique identifier for this Firestore's local + * storage (used in conjunction with the databaseId). + * @param host - The Firestore backend host to connect to. + * @param ssl - Whether to use SSL when connecting. + * @param forceLongPolling - Whether to use the forceLongPolling option + * when using WebChannel as the network transport. + * @param autoDetectLongPolling - Whether to use the detectBufferingProxy + * option when using WebChannel as the network transport. + * @param longPollingOptions Options that configure long-polling. + * @param useFetchStreams Whether to use the Fetch API instead of + * XMLHTTPRequest + */ + constructor(databaseId: DatabaseId, appId: string, persistenceKey: string, host: string, ssl: boolean, forceLongPolling: boolean, autoDetectLongPolling: boolean, longPollingOptions: ExperimentalLongPollingOptions, useFetchStreams: boolean, isUsingEmulator: boolean); +} +/** The default database name for a project. */ +export declare const DEFAULT_DATABASE_NAME = "(default)"; +/** + * Represents the database ID a Firestore client is associated with. + * @internal + */ +export declare class DatabaseId { + readonly projectId: string; + readonly database: string; + constructor(projectId: string, database?: string); + static empty(): DatabaseId; + get isDefaultDatabase(): boolean; + isEqual(other: {}): boolean; +} +export declare function databaseIdFromApp(app: FirebaseApp, database?: string): DatabaseId; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/event_manager.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/event_manager.d.ts new file mode 100644 index 0000000..38b980f --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/event_manager.d.ts @@ -0,0 +1,133 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { FirestoreError } from '../util/error'; +import { EventHandler } from '../util/misc'; +import { ObjectMap } from '../util/obj_map'; +import { Query } from './query'; +import { OnlineState } from './types'; +import { ViewSnapshot } from './view_snapshot'; +/** + * Holds the listeners and the last received ViewSnapshot for a query being + * tracked by EventManager. + */ +declare class QueryListenersInfo { + viewSnap: ViewSnapshot | undefined; + listeners: QueryListener[]; + hasRemoteListeners(): boolean; +} +/** + * Interface for handling events from the EventManager. + */ +export interface Observer { + next: EventHandler; + error: EventHandler; +} +/** + * EventManager is responsible for mapping queries to query event emitters. + * It handles "fan-out". -- Identical queries will re-use the same watch on the + * backend. + * + * PORTING NOTE: On Web, EventManager `onListen` and `onUnlisten` need to be + * assigned to SyncEngine's `listen()` and `unlisten()` API before usage. This + * allows users to tree-shake the Watch logic. + */ +export interface EventManager { + onListen?: (query: Query, enableRemoteListen: boolean) => Promise; + onUnlisten?: (query: Query, disableRemoteListen: boolean) => Promise; + onFirstRemoteStoreListen?: (query: Query) => Promise; + onLastRemoteStoreUnlisten?: (query: Query) => Promise; + terminate(): void; +} +export declare function newEventManager(): EventManager; +export declare class EventManagerImpl implements EventManager { + queries: ObjectMap; + onlineState: OnlineState; + snapshotsInSyncListeners: Set>; + /** Callback invoked when a Query is first listen to. */ + onListen?: (query: Query, enableRemoteListen: boolean) => Promise; + /** Callback invoked once all listeners to a Query are removed. */ + onUnlisten?: (query: Query, disableRemoteListen: boolean) => Promise; + /** + * Callback invoked when a Query starts listening to the remote store, while + * already listening to the cache. + */ + onFirstRemoteStoreListen?: (query: Query) => Promise; + /** + * Callback invoked when a Query stops listening to the remote store, while + * still listening to the cache. + */ + onLastRemoteStoreUnlisten?: (query: Query) => Promise; + terminate(): void; +} +export declare function eventManagerListen(eventManager: EventManager, listener: QueryListener): Promise; +export declare function eventManagerUnlisten(eventManager: EventManager, listener: QueryListener): Promise; +export declare function eventManagerOnWatchChange(eventManager: EventManager, viewSnaps: ViewSnapshot[]): void; +export declare function eventManagerOnWatchError(eventManager: EventManager, query: Query, error: FirestoreError): void; +export declare function eventManagerOnOnlineStateChange(eventManager: EventManager, onlineState: OnlineState): void; +export declare function addSnapshotsInSyncListener(eventManager: EventManager, observer: Observer): void; +export declare function removeSnapshotsInSyncListener(eventManager: EventManager, observer: Observer): void; +export declare enum ListenerDataSource { + /** Listen to both cache and server changes */ + Default = "default", + /** Listen to changes in cache only */ + Cache = "cache" +} +export interface ListenOptions { + /** Raise events even when only the metadata changes */ + readonly includeMetadataChanges?: boolean; + /** + * Wait for a sync with the server when online, but still raise events while + * offline. + */ + readonly waitForSyncWhenOnline?: boolean; + /** Set the source events raised from. */ + readonly source?: ListenerDataSource; +} +/** + * QueryListener takes a series of internal view snapshots and determines + * when to raise the event. + * + * It uses an Observer to dispatch events. + */ +export declare class QueryListener { + readonly query: Query; + private queryObserver; + /** + * Initial snapshots (e.g. from cache) may not be propagated to the wrapped + * observer. This flag is set to true once we've actually raised an event. + */ + private raisedInitialEvent; + private options; + private snap; + private onlineState; + constructor(query: Query, queryObserver: Observer, options?: ListenOptions); + /** + * Applies the new ViewSnapshot to this listener, raising a user-facing event + * if applicable (depending on what changed, whether the user has opted into + * metadata-only changes, etc.). Returns true if a user-facing event was + * indeed raised. + */ + onViewSnapshot(snap: ViewSnapshot): boolean; + onError(error: FirestoreError): void; + /** Returns whether a snapshot was raised. */ + applyOnlineStateChange(onlineState: OnlineState): boolean; + private shouldRaiseInitialEvent; + private shouldRaiseEvent; + private raiseInitialEvent; + listensToRemoteStore(): boolean; +} +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/filter.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/filter.d.ts new file mode 100644 index 0000000..ccb871f --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/filter.d.ts @@ -0,0 +1,130 @@ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Document } from '../model/document'; +import { FieldPath } from '../model/path'; +import { Value as ProtoValue } from '../protos/firestore_proto_api'; +export declare const enum Operator { + LESS_THAN = "<", + LESS_THAN_OR_EQUAL = "<=", + EQUAL = "==", + NOT_EQUAL = "!=", + GREATER_THAN = ">", + GREATER_THAN_OR_EQUAL = ">=", + ARRAY_CONTAINS = "array-contains", + IN = "in", + NOT_IN = "not-in", + ARRAY_CONTAINS_ANY = "array-contains-any" +} +export declare const enum CompositeOperator { + OR = "or", + AND = "and" +} +export declare abstract class Filter { + abstract matches(doc: Document): boolean; + abstract getFlattenedFilters(): readonly FieldFilter[]; + abstract getFilters(): Filter[]; +} +export declare class FieldFilter extends Filter { + readonly field: FieldPath; + readonly op: Operator; + readonly value: ProtoValue; + protected constructor(field: FieldPath, op: Operator, value: ProtoValue); + /** + * Creates a filter based on the provided arguments. + */ + static create(field: FieldPath, op: Operator, value: ProtoValue): FieldFilter; + private static createKeyFieldInFilter; + matches(doc: Document): boolean; + protected matchesComparison(comparison: number): boolean; + isInequality(): boolean; + getFlattenedFilters(): readonly FieldFilter[]; + getFilters(): Filter[]; +} +export declare class CompositeFilter extends Filter { + readonly filters: readonly Filter[]; + readonly op: CompositeOperator; + private memoizedFlattenedFilters; + protected constructor(filters: readonly Filter[], op: CompositeOperator); + /** + * Creates a filter based on the provided arguments. + */ + static create(filters: Filter[], op: CompositeOperator): CompositeFilter; + matches(doc: Document): boolean; + getFlattenedFilters(): readonly FieldFilter[]; + getFilters(): Filter[]; +} +export declare function compositeFilterIsConjunction(compositeFilter: CompositeFilter): boolean; +export declare function compositeFilterIsDisjunction(compositeFilter: CompositeFilter): boolean; +/** + * Returns true if this filter is a conjunction of field filters only. Returns false otherwise. + */ +export declare function compositeFilterIsFlatConjunction(compositeFilter: CompositeFilter): boolean; +/** + * Returns true if this filter does not contain any composite filters. Returns false otherwise. + */ +export declare function compositeFilterIsFlat(compositeFilter: CompositeFilter): boolean; +export declare function canonifyFilter(filter: Filter): string; +export declare function filterEquals(f1: Filter, f2: Filter): boolean; +export declare function fieldFilterEquals(f1: FieldFilter, f2: Filter): boolean; +export declare function compositeFilterEquals(f1: CompositeFilter, f2: Filter): boolean; +/** + * Returns a new composite filter that contains all filter from + * `compositeFilter` plus all the given filters in `otherFilters`. + */ +export declare function compositeFilterWithAddedFilters(compositeFilter: CompositeFilter, otherFilters: Filter[]): CompositeFilter; +/** Returns a debug description for `filter`. */ +export declare function stringifyFilter(filter: Filter): string; +export declare function stringifyCompositeFilter(filter: CompositeFilter): string; +export declare function stringifyFieldFilter(filter: FieldFilter): string; +/** Filter that matches on key fields (i.e. '__name__'). */ +export declare class KeyFieldFilter extends FieldFilter { + private readonly key; + constructor(field: FieldPath, op: Operator, value: ProtoValue); + matches(doc: Document): boolean; +} +/** Filter that matches on key fields within an array. */ +export declare class KeyFieldInFilter extends FieldFilter { + private readonly keys; + constructor(field: FieldPath, value: ProtoValue); + matches(doc: Document): boolean; +} +/** Filter that matches on key fields not present within an array. */ +export declare class KeyFieldNotInFilter extends FieldFilter { + private readonly keys; + constructor(field: FieldPath, value: ProtoValue); + matches(doc: Document): boolean; +} +/** A Filter that implements the array-contains operator. */ +export declare class ArrayContainsFilter extends FieldFilter { + constructor(field: FieldPath, value: ProtoValue); + matches(doc: Document): boolean; +} +/** A Filter that implements the IN operator. */ +export declare class InFilter extends FieldFilter { + constructor(field: FieldPath, value: ProtoValue); + matches(doc: Document): boolean; +} +/** A Filter that implements the not-in operator. */ +export declare class NotInFilter extends FieldFilter { + constructor(field: FieldPath, value: ProtoValue); + matches(doc: Document): boolean; +} +/** A Filter that implements the array-contains-any operator. */ +export declare class ArrayContainsAnyFilter extends FieldFilter { + constructor(field: FieldPath, value: ProtoValue); + matches(doc: Document): boolean; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/firestore_client.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/firestore_client.d.ts new file mode 100644 index 0000000..a3a2b24 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/firestore_client.d.ts @@ -0,0 +1,138 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { GetOptions } from '@firebase/firestore-types'; +import { LoadBundleTask } from '../api/bundle'; +import { CredentialsProvider } from '../api/credentials'; +import { User } from '../auth/user'; +import { LocalStore } from '../local/local_store'; +import { Document } from '../model/document'; +import { DocumentKey } from '../model/document_key'; +import { FieldIndex } from '../model/field_index'; +import { Mutation } from '../model/mutation'; +import { ApiClientObjectMap, Value } from '../protos/firestore_proto_api'; +import { JsonProtoSerializer } from '../remote/serializer'; +import { AsyncQueue } from '../util/async_queue'; +import { BundleReaderSync } from '../util/bundle_reader'; +import { FirestoreError } from '../util/error'; +import { Aggregate } from './aggregate'; +import { NamedQuery } from './bundle'; +import { ComponentConfiguration, OfflineComponentProvider, OnlineComponentProvider } from './component_provider'; +import { DatabaseId, DatabaseInfo } from './database_info'; +import { EventManager, ListenOptions, Observer } from './event_manager'; +import { Query } from './query'; +import { SyncEngine } from './sync_engine'; +import { Transaction } from './transaction'; +import { TransactionOptions } from './transaction_options'; +import { ViewSnapshot } from './view_snapshot'; +export declare const MAX_CONCURRENT_LIMBO_RESOLUTIONS = 100; +/** + * FirestoreClient is a top-level class that constructs and owns all of the // + * pieces of the client SDK architecture. It is responsible for creating the // + * async queue that is shared by all of the other components in the system. // + */ +export declare class FirestoreClient { + private authCredentials; + private appCheckCredentials; + /** + * Asynchronous queue responsible for all of our internal processing. When + * we get incoming work from the user (via public API) or the network + * (incoming GRPC messages), we should always schedule onto this queue. + * This ensures all of our work is properly serialized (e.g. we don't + * start processing a new operation while the previous one is waiting for + * an async I/O to complete). + */ + asyncQueue: AsyncQueue; + private databaseInfo; + private user; + private readonly clientId; + private authCredentialListener; + private appCheckCredentialListener; + _uninitializedComponentsProvider?: { + _offline: OfflineComponentProvider; + _online: OnlineComponentProvider; + }; + _offlineComponents?: OfflineComponentProvider; + _onlineComponents?: OnlineComponentProvider; + constructor(authCredentials: CredentialsProvider, appCheckCredentials: CredentialsProvider, + /** + * Asynchronous queue responsible for all of our internal processing. When + * we get incoming work from the user (via public API) or the network + * (incoming GRPC messages), we should always schedule onto this queue. + * This ensures all of our work is properly serialized (e.g. we don't + * start processing a new operation while the previous one is waiting for + * an async I/O to complete). + */ + asyncQueue: AsyncQueue, databaseInfo: DatabaseInfo, componentProvider?: { + _offline: OfflineComponentProvider; + _online: OnlineComponentProvider; + }); + get configuration(): ComponentConfiguration; + setCredentialChangeListener(listener: (user: User) => Promise): void; + setAppCheckTokenChangeListener(listener: (appCheckToken: string, user: User) => Promise): void; + terminate(): Promise; +} +export declare function setOfflineComponentProvider(client: FirestoreClient, offlineComponentProvider: OfflineComponentProvider): Promise; +export declare function setOnlineComponentProvider(client: FirestoreClient, onlineComponentProvider: OnlineComponentProvider): Promise; +/** + * Decides whether the provided error allows us to gracefully disable + * persistence (as opposed to crashing the client). + */ +export declare function canFallbackFromIndexedDbError(error: FirestoreError | DOMException): boolean; +export declare function ensureOnlineComponents(client: FirestoreClient): Promise; +export declare function getLocalStore(client: FirestoreClient): Promise; +export declare function getSyncEngine(client: FirestoreClient): Promise; +export declare function getEventManager(client: FirestoreClient): Promise; +/** Enables the network connection and re-enqueues all pending operations. */ +export declare function firestoreClientEnableNetwork(client: FirestoreClient): Promise; +/** Disables the network connection. Pending operations will not complete. */ +export declare function firestoreClientDisableNetwork(client: FirestoreClient): Promise; +/** + * Returns a Promise that resolves when all writes that were pending at the time + * this method was called received server acknowledgement. An acknowledgement + * can be either acceptance or rejection. + */ +export declare function firestoreClientWaitForPendingWrites(client: FirestoreClient): Promise; +export declare function firestoreClientListen(client: FirestoreClient, query: Query, options: ListenOptions, observer: Partial>): () => void; +export declare function firestoreClientGetDocumentFromLocalCache(client: FirestoreClient, docKey: DocumentKey): Promise; +export declare function firestoreClientGetDocumentViaSnapshotListener(client: FirestoreClient, key: DocumentKey, options?: GetOptions): Promise; +export declare function firestoreClientGetDocumentsFromLocalCache(client: FirestoreClient, query: Query): Promise; +export declare function firestoreClientGetDocumentsViaSnapshotListener(client: FirestoreClient, query: Query, options?: GetOptions): Promise; +export declare function firestoreClientRunAggregateQuery(client: FirestoreClient, query: Query, aggregates: Aggregate[]): Promise>; +export declare function firestoreClientWrite(client: FirestoreClient, mutations: Mutation[]): Promise; +export declare function firestoreClientAddSnapshotsInSyncListener(client: FirestoreClient, observer: Partial>): () => void; +/** + * Takes an updateFunction in which a set of reads and writes can be performed + * atomically. In the updateFunction, the client can read and write values + * using the supplied transaction object. After the updateFunction, all + * changes will be committed. If a retryable error occurs (ex: some other + * client has changed any of the data referenced), then the updateFunction + * will be called again after a backoff. If the updateFunction still fails + * after all retries, then the transaction will be rejected. + * + * The transaction object passed to the updateFunction contains methods for + * accessing documents and collections. Unlike other datastore access, data + * accessed with the transaction will not reflect local changes that have not + * been committed. For this reason, it is required that all reads are + * performed before any writes. Transactions must be performed while online. + */ +export declare function firestoreClientTransaction(client: FirestoreClient, updateFunction: (transaction: Transaction) => Promise, options: TransactionOptions): Promise; +export declare function firestoreClientLoadBundle(client: FirestoreClient, databaseId: DatabaseId, data: ReadableStream | ArrayBuffer | string, resultTask: LoadBundleTask): void; +export declare function firestoreClientGetNamedQuery(client: FirestoreClient, queryName: string): Promise; +export declare function createBundleReaderSync(bundleData: string, serializer: JsonProtoSerializer): BundleReaderSync; +export declare function firestoreClientSetIndexConfiguration(client: FirestoreClient, indexes: FieldIndex[]): Promise; +export declare function firestoreClientSetPersistentCacheIndexAutoCreationEnabled(client: FirestoreClient, isEnabled: boolean): Promise; +export declare function firestoreClientDeleteAllFieldIndexes(client: FirestoreClient): Promise; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/listen_sequence.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/listen_sequence.d.ts new file mode 100644 index 0000000..c824db1 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/listen_sequence.d.ts @@ -0,0 +1,39 @@ +/** + * @license + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { ListenSequenceNumber } from './types'; +/** + * `SequenceNumberSyncer` defines the methods required to keep multiple instances of a + * `ListenSequence` in sync. + */ +export interface SequenceNumberSyncer { + writeSequenceNumber(sequenceNumber: ListenSequenceNumber): void; + sequenceNumberHandler: ((sequenceNumber: ListenSequenceNumber) => void) | null; +} +/** + * `ListenSequence` is a monotonic sequence. It is initialized with a minimum value to + * exceed. All subsequent calls to next will return increasing values. If provided with a + * `SequenceNumberSyncer`, it will additionally bump its next value when told of a new value, as + * well as write out sequence numbers that it produces via `next()`. + */ +export declare class ListenSequence { + private previousValue; + static readonly INVALID: ListenSequenceNumber; + private writeNewSequenceNumber?; + constructor(previousValue: ListenSequenceNumber, sequenceNumberSyncer?: SequenceNumberSyncer); + private setPreviousValue; + next(): ListenSequenceNumber; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/order_by.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/order_by.d.ts new file mode 100644 index 0000000..1d7aa86 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/order_by.d.ts @@ -0,0 +1,35 @@ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { FieldPath } from '../model/path'; +/** + * The direction of sorting in an order by. + */ +export declare const enum Direction { + ASCENDING = "asc", + DESCENDING = "desc" +} +/** + * An ordering on a field, in some Direction. Direction defaults to ASCENDING. + */ +export declare class OrderBy { + readonly field: FieldPath; + readonly dir: Direction; + constructor(field: FieldPath, dir?: Direction); +} +export declare function canonifyOrderBy(orderBy: OrderBy): string; +export declare function stringifyOrderBy(orderBy: OrderBy): string; +export declare function orderByEquals(left: OrderBy, right: OrderBy): boolean; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/query.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/query.d.ts new file mode 100644 index 0000000..d23e0f1 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/query.d.ts @@ -0,0 +1,142 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Document } from '../model/document'; +import { FieldPath, ResourcePath } from '../model/path'; +import { SortedSet } from '../util/sorted_set'; +import { Bound } from './bound'; +import { Filter } from './filter'; +import { OrderBy } from './order_by'; +import { Target } from './target'; +export declare const enum LimitType { + First = "F", + Last = "L" +} +/** + * The Query interface defines all external properties of a query. + * + * QueryImpl implements this interface to provide memoization for `queryNormalizedOrderBy` + * and `queryToTarget`. + */ +export interface Query { + readonly path: ResourcePath; + readonly collectionGroup: string | null; + readonly explicitOrderBy: OrderBy[]; + readonly filters: Filter[]; + readonly limit: number | null; + readonly limitType: LimitType; + readonly startAt: Bound | null; + readonly endAt: Bound | null; +} +/** + * Query encapsulates all the query attributes we support in the SDK. It can + * be run against the LocalStore, as well as be converted to a `Target` to + * query the RemoteStore results. + * + * Visible for testing. + */ +export declare class QueryImpl implements Query { + readonly path: ResourcePath; + readonly collectionGroup: string | null; + readonly explicitOrderBy: OrderBy[]; + readonly filters: Filter[]; + readonly limit: number | null; + readonly limitType: LimitType; + readonly startAt: Bound | null; + readonly endAt: Bound | null; + memoizedNormalizedOrderBy: OrderBy[] | null; + memoizedTarget: Target | null; + memoizedAggregateTarget: Target | null; + /** + * Initializes a Query with a path and optional additional query constraints. + * Path must currently be empty if this is a collection group query. + */ + constructor(path: ResourcePath, collectionGroup?: string | null, explicitOrderBy?: OrderBy[], filters?: Filter[], limit?: number | null, limitType?: LimitType, startAt?: Bound | null, endAt?: Bound | null); +} +/** Creates a new Query instance with the options provided. */ +export declare function newQuery(path: ResourcePath, collectionGroup: string | null, explicitOrderBy: OrderBy[], filters: Filter[], limit: number | null, limitType: LimitType, startAt: Bound | null, endAt: Bound | null): Query; +/** Creates a new Query for a query that matches all documents at `path` */ +export declare function newQueryForPath(path: ResourcePath): Query; +/** + * Helper to convert a collection group query into a collection query at a + * specific path. This is used when executing collection group queries, since + * we have to split the query into a set of collection queries at multiple + * paths. + */ +export declare function asCollectionQueryAtPath(query: Query, path: ResourcePath): Query; +/** + * Returns true if this query does not specify any query constraints that + * could remove results. + */ +export declare function queryMatchesAllDocuments(query: Query): boolean; +export declare function getInequalityFilterFields(query: Query): SortedSet; +/** + * Creates a new Query for a collection group query that matches all documents + * within the provided collection group. + */ +export declare function newQueryForCollectionGroup(collectionId: string): Query; +/** + * Returns whether the query matches a single document by path (rather than a + * collection). + */ +export declare function isDocumentQuery(query: Query): boolean; +/** + * Returns whether the query matches a collection group rather than a specific + * collection. + */ +export declare function isCollectionGroupQuery(query: Query): boolean; +/** + * Returns the normalized order-by constraint that is used to execute the Query, + * which can be different from the order-by constraints the user provided (e.g. + * the SDK and backend always orders by `__name__`). The normalized order-by + * includes implicit order-bys in addition to the explicit user provided + * order-bys. + */ +export declare function queryNormalizedOrderBy(query: Query): OrderBy[]; +/** + * Converts this `Query` instance to its corresponding `Target` representation. + */ +export declare function queryToTarget(query: Query): Target; +/** + * Converts this `Query` instance to its corresponding `Target` representation, + * for use within an aggregate query. Unlike targets for non-aggregate queries, + * aggregate query targets do not contain normalized order-bys, they only + * contain explicit order-bys. + */ +export declare function queryToAggregateTarget(query: Query): Target; +export declare function queryWithAddedFilter(query: Query, filter: Filter): Query; +export declare function queryWithAddedOrderBy(query: Query, orderBy: OrderBy): Query; +export declare function queryWithLimit(query: Query, limit: number | null, limitType: LimitType): Query; +export declare function queryWithStartAt(query: Query, bound: Bound): Query; +export declare function queryWithEndAt(query: Query, bound: Bound): Query; +export declare function queryEquals(left: Query, right: Query): boolean; +export declare function canonifyQuery(query: Query): string; +export declare function stringifyQuery(query: Query): string; +/** Returns whether `doc` matches the constraints of `query`. */ +export declare function queryMatches(query: Query, doc: Document): boolean; +/** + * Returns the collection group that this query targets. + * + * PORTING NOTE: This is only used in the Web SDK to facilitate multi-tab + * synchronization for query results. + */ +export declare function queryCollectionGroup(query: Query): string; +/** + * Returns a new comparator function that can be used to compare two documents + * based on the Query's ordering constraint. + */ +export declare function newQueryComparator(query: Query): (d1: Document, d2: Document) => number; +export declare function compareDocs(orderBy: OrderBy, d1: Document, d2: Document): number; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/snapshot_version.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/snapshot_version.d.ts new file mode 100644 index 0000000..10c508b --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/snapshot_version.d.ts @@ -0,0 +1,34 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Timestamp } from '../lite-api/timestamp'; +/** + * A version of a document in Firestore. This corresponds to the version + * timestamp, such as update_time or read_time. + */ +export declare class SnapshotVersion { + private timestamp; + static fromTimestamp(value: Timestamp): SnapshotVersion; + static min(): SnapshotVersion; + static max(): SnapshotVersion; + private constructor(); + compareTo(other: SnapshotVersion): number; + isEqual(other: SnapshotVersion): boolean; + /** Returns a number representation of the version for use in spec tests. */ + toMicroseconds(): number; + toString(): string; + toTimestamp(): Timestamp; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/sync_engine.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/sync_engine.d.ts new file mode 100644 index 0000000..2c28d31 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/sync_engine.d.ts @@ -0,0 +1,37 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * SyncEngine is the central controller in the client SDK architecture. It is + * the glue code between the EventManager, LocalStore, and RemoteStore. Some of + * SyncEngine's responsibilities include: + * 1. Coordinating client requests and remote events between the EventManager + * and the local and remote data stores. + * 2. Managing a View object for each query, providing the unified view between + * the local and remote data stores. + * 3. Notifying the RemoteStore when the LocalStore has new mutations in its + * queue that need sending to the backend. + * + * The SyncEngine’s methods should only ever be called by methods running in the + * global async queue. + * + * PORTING NOTE: On Web, SyncEngine does not have an explicit subscribe() + * function. Instead, it directly depends on EventManager's tree-shakeable API + * (via `ensureWatchStream()`). + */ +export interface SyncEngine { + isPrimaryClient: boolean; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/sync_engine_impl.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/sync_engine_impl.d.ts new file mode 100644 index 0000000..0d2aef9 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/sync_engine_impl.d.ts @@ -0,0 +1,255 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { LoadBundleTask } from '../api/bundle'; +import { User } from '../auth/user'; +import { LocalStore } from '../local/local_store'; +import { ReferenceSet } from '../local/reference_set'; +import { ClientId, SharedClientState } from '../local/shared_client_state'; +import { QueryTargetState } from '../local/shared_client_state_syncer'; +import { DocumentKeySet, DocumentMap } from '../model/collections'; +import { DocumentKey } from '../model/document_key'; +import { Mutation } from '../model/mutation'; +import { MutationBatchResult } from '../model/mutation_batch'; +import { RemoteEvent } from '../remote/remote_event'; +import { RemoteStore } from '../remote/remote_store'; +import { BundleReader } from '../util/bundle_reader'; +import { FirestoreError } from '../util/error'; +import { ObjectMap } from '../util/obj_map'; +import { Deferred } from '../util/promise'; +import { SortedMap } from '../util/sorted_map'; +import { EventManager } from './event_manager'; +import { Query } from './query'; +import { SyncEngine } from './sync_engine'; +import { TargetIdGenerator } from './target_id_generator'; +import { BatchId, MutationBatchState, OnlineState, OnlineStateSource, TargetId } from './types'; +import { View } from './view'; +import { ViewSnapshot } from './view_snapshot'; +/** + * QueryView contains all of the data that SyncEngine needs to keep track of for + * a particular query. + */ +declare class QueryView { + /** + * The query itself. + */ + query: Query; + /** + * The target number created by the client that is used in the watch + * stream to identify this query. + */ + targetId: TargetId; + /** + * The view is responsible for computing the final merged truth of what + * docs are in the query. It gets notified of local and remote changes, + * and applies the query filters and limits to determine the most correct + * possible results. + */ + view: View; + constructor( + /** + * The query itself. + */ + query: Query, + /** + * The target number created by the client that is used in the watch + * stream to identify this query. + */ + targetId: TargetId, + /** + * The view is responsible for computing the final merged truth of what + * docs are in the query. It gets notified of local and remote changes, + * and applies the query filters and limits to determine the most correct + * possible results. + */ + view: View); +} +/** Tracks a limbo resolution. */ +declare class LimboResolution { + key: DocumentKey; + constructor(key: DocumentKey); + /** + * Set to true once we've received a document. This is used in + * getRemoteKeysForTarget() and ultimately used by WatchChangeAggregator to + * decide whether it needs to manufacture a delete event for the target once + * the target is CURRENT. + */ + receivedDocument: boolean; +} +/** + * A function that updates a QueryView with a set of document changes (and a + * remote event if applicable). + */ +type ApplyDocChangesHandler = (queryView: QueryView, changes: DocumentMap, remoteEvent?: RemoteEvent) => Promise; +/** + * Callbacks implemented by EventManager to handle notifications from + * SyncEngine. + */ +interface SyncEngineListener { + /** Handles new view snapshots. */ + onWatchChange?(snapshots: ViewSnapshot[]): void; + /** Handles the failure of a query. */ + onWatchError?(query: Query, error: FirestoreError): void; +} +/** + * An implementation of `SyncEngine` coordinating with other parts of SDK. + * + * The parts of SyncEngine that act as a callback to RemoteStore need to be + * registered individually. This is done in `syncEngineWrite()` and + * `syncEngineListen()` (as well as `applyPrimaryState()`) as these methods + * serve as entry points to RemoteStore's functionality. + * + * Note: some field defined in this class might have public access level, but + * the class is not exported so they are only accessible from this module. + * This is useful to implement optional features (like bundles) in free + * functions, such that they are tree-shakeable. + */ +declare class SyncEngineImpl implements SyncEngine { + readonly localStore: LocalStore; + readonly remoteStore: RemoteStore; + readonly eventManager: EventManager; + readonly sharedClientState: SharedClientState; + currentUser: User; + readonly maxConcurrentLimboResolutions: number; + syncEngineListener: SyncEngineListener; + /** + * A callback that updates the QueryView based on the provided change. + * + * PORTING NOTE: On other platforms, this logic lives in + * `emitNewSnapshotsAndNotifyLocalStore()`, but on Web it is extracted to + * ensure that all view logic only exists in bundles that include views. + */ + applyDocChanges?: ApplyDocChangesHandler; + queryViewsByQuery: ObjectMap; + queriesByTarget: Map; + /** + * The keys of documents that are in limbo for which we haven't yet started a + * limbo resolution query. The strings in this set are the result of calling + * `key.path.canonicalString()` where `key` is a `DocumentKey` object. + * + * The `Set` type was chosen because it provides efficient lookup and removal + * of arbitrary elements and it also maintains insertion order, providing the + * desired queue-like FIFO semantics. + */ + enqueuedLimboResolutions: Set; + /** + * Keeps track of the target ID for each document that is in limbo with an + * active target. + */ + activeLimboTargetsByKey: SortedMap; + /** + * Keeps track of the information about an active limbo resolution for each + * active target ID that was started for the purpose of limbo resolution. + */ + activeLimboResolutionsByTarget: Map; + limboDocumentRefs: ReferenceSet; + /** Stores user completion handlers, indexed by User and BatchId. */ + mutationUserCallbacks: { + [uidKey: string]: SortedMap>; + }; + /** Stores user callbacks waiting for all pending writes to be acknowledged. */ + pendingWritesCallbacks: Map[]>; + limboTargetIdGenerator: TargetIdGenerator; + onlineState: OnlineState; + _isPrimaryClient: undefined | boolean; + constructor(localStore: LocalStore, remoteStore: RemoteStore, eventManager: EventManager, sharedClientState: SharedClientState, currentUser: User, maxConcurrentLimboResolutions: number); + get isPrimaryClient(): boolean; +} +export declare function newSyncEngine(localStore: LocalStore, remoteStore: RemoteStore, eventManager: EventManager, sharedClientState: SharedClientState, currentUser: User, maxConcurrentLimboResolutions: number, isPrimary: boolean): SyncEngine; +/** + * Initiates the new listen, resolves promise when listen enqueued to the + * server. All the subsequent view snapshots or errors are sent to the + * subscribed handlers. Returns the initial snapshot. + */ +export declare function syncEngineListen(syncEngine: SyncEngine, query: Query, shouldListenToRemote?: boolean): Promise; +/** Query has been listening to the cache, and tries to initiate the remote store listen */ +export declare function triggerRemoteStoreListen(syncEngine: SyncEngine, query: Query): Promise; +/** Stops listening to the query. */ +export declare function syncEngineUnlisten(syncEngine: SyncEngine, query: Query, shouldUnlistenToRemote: boolean): Promise; +/** Unlistens to the remote store while still listening to the cache. */ +export declare function triggerRemoteStoreUnlisten(syncEngine: SyncEngine, query: Query): Promise; +/** + * Initiates the write of local mutation batch which involves adding the + * writes to the mutation queue, notifying the remote store about new + * mutations and raising events for any changes this write caused. + * + * The promise returned by this call is resolved when the above steps + * have completed, *not* when the write was acked by the backend. The + * userCallback is resolved once the write was acked/rejected by the + * backend (or failed locally for any other reason). + */ +export declare function syncEngineWrite(syncEngine: SyncEngine, batch: Mutation[], userCallback: Deferred): Promise; +/** + * Applies one remote event to the sync engine, notifying any views of the + * changes, and releasing any pending mutation batches that would become + * visible because of the snapshot version the remote event contains. + */ +export declare function syncEngineApplyRemoteEvent(syncEngine: SyncEngine, remoteEvent: RemoteEvent): Promise; +/** + * Applies an OnlineState change to the sync engine and notifies any views of + * the change. + */ +export declare function syncEngineApplyOnlineStateChange(syncEngine: SyncEngine, onlineState: OnlineState, source: OnlineStateSource): void; +/** + * Rejects the listen for the given targetID. This can be triggered by the + * backend for any active target. + * + * @param syncEngine - The sync engine implementation. + * @param targetId - The targetID corresponds to one previously initiated by the + * user as part of TargetData passed to listen() on RemoteStore. + * @param err - A description of the condition that has forced the rejection. + * Nearly always this will be an indication that the user is no longer + * authorized to see the data matching the target. + */ +export declare function syncEngineRejectListen(syncEngine: SyncEngine, targetId: TargetId, err: FirestoreError): Promise; +export declare function syncEngineApplySuccessfulWrite(syncEngine: SyncEngine, mutationBatchResult: MutationBatchResult): Promise; +export declare function syncEngineRejectFailedWrite(syncEngine: SyncEngine, batchId: BatchId, error: FirestoreError): Promise; +/** + * Registers a user callback that resolves when all pending mutations at the moment of calling + * are acknowledged . + */ +export declare function syncEngineRegisterPendingWritesCallback(syncEngine: SyncEngine, callback: Deferred): Promise; +export declare function syncEngineGetActiveLimboDocumentResolutions(syncEngine: SyncEngine): SortedMap; +export declare function syncEngineGetEnqueuedLimboDocumentResolutions(syncEngine: SyncEngine): Set; +export declare function syncEngineEmitNewSnapsAndNotifyLocalStore(syncEngine: SyncEngine, changes: DocumentMap, remoteEvent?: RemoteEvent): Promise; +export declare function syncEngineHandleCredentialChange(syncEngine: SyncEngine, user: User): Promise; +export declare function syncEngineGetRemoteKeysForTarget(syncEngine: SyncEngine, targetId: TargetId): DocumentKeySet; +/** + * Retrieves newly changed documents from remote document cache and raises + * snapshots if needed. + */ +export declare function syncEngineSynchronizeWithChangedDocuments(syncEngine: SyncEngine, collectionGroup: string): Promise; +/** Applies a mutation state to an existing batch. */ +export declare function syncEngineApplyBatchState(syncEngine: SyncEngine, batchId: BatchId, batchState: MutationBatchState, error?: FirestoreError): Promise; +/** Applies a query target change from a different tab. */ +export declare function syncEngineApplyPrimaryState(syncEngine: SyncEngine, isPrimary: boolean): Promise; +/** Returns the IDs of the clients that are currently active. */ +export declare function syncEngineGetActiveClients(syncEngine: SyncEngine): Promise; +/** Applies a query target change from a different tab. */ +export declare function syncEngineApplyTargetState(syncEngine: SyncEngine, targetId: TargetId, state: QueryTargetState, error?: FirestoreError): Promise; +/** Adds or removes Watch targets for queries from different tabs. */ +export declare function syncEngineApplyActiveTargetsChange(syncEngine: SyncEngine, added: TargetId[], removed: TargetId[]): Promise; +export declare function syncEngineEnsureWriteCallbacks(syncEngine: SyncEngine): SyncEngineImpl; +/** + * Loads a Firestore bundle into the SDK. The returned promise resolves when + * the bundle finished loading. + * + * @param syncEngine - SyncEngine to use. + * @param bundleReader - Bundle to load into the SDK. + * @param task - LoadBundleTask used to update the loading progress to public API. + */ +export declare function syncEngineLoadBundle(syncEngine: SyncEngine, bundleReader: BundleReader, task: LoadBundleTask): void; +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/target.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/target.d.ts new file mode 100644 index 0000000..fcfed20 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/target.d.ts @@ -0,0 +1,89 @@ +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { FieldIndex } from '../model/field_index'; +import { FieldPath, ResourcePath } from '../model/path'; +import { Value as ProtoValue } from '../protos/firestore_proto_api'; +import { Bound } from './bound'; +import { Filter, FieldFilter } from './filter'; +import { OrderBy } from './order_by'; +/** + * A Target represents the WatchTarget representation of a Query, which is used + * by the LocalStore and the RemoteStore to keep track of and to execute + * backend queries. While a Query can represent multiple Targets, each Targets + * maps to a single WatchTarget in RemoteStore and a single TargetData entry + * in persistence. + */ +export interface Target { + readonly path: ResourcePath; + readonly collectionGroup: string | null; + readonly orderBy: OrderBy[]; + readonly filters: Filter[]; + readonly limit: number | null; + readonly startAt: Bound | null; + readonly endAt: Bound | null; +} +export declare class TargetImpl implements Target { + readonly path: ResourcePath; + readonly collectionGroup: string | null; + readonly orderBy: OrderBy[]; + readonly filters: Filter[]; + readonly limit: number | null; + readonly startAt: Bound | null; + readonly endAt: Bound | null; + memoizedCanonicalId: string | null; + constructor(path: ResourcePath, collectionGroup?: string | null, orderBy?: OrderBy[], filters?: Filter[], limit?: number | null, startAt?: Bound | null, endAt?: Bound | null); +} +/** + * Initializes a Target with a path and optional additional query constraints. + * Path must currently be empty if this is a collection group query. + * + * NOTE: you should always construct `Target` from `Query.toTarget` instead of + * using this factory method, because `Query` provides an implicit `orderBy` + * property. + */ +export declare function newTarget(path: ResourcePath, collectionGroup?: string | null, orderBy?: OrderBy[], filters?: Filter[], limit?: number | null, startAt?: Bound | null, endAt?: Bound | null): Target; +export declare function canonifyTarget(target: Target): string; +export declare function stringifyTarget(target: Target): string; +export declare function targetEquals(left: Target, right: Target): boolean; +export declare function targetIsDocumentTarget(target: Target): boolean; +/** Returns the field filters that target the given field path. */ +export declare function targetGetFieldFiltersForPath(target: Target, path: FieldPath): FieldFilter[]; +/** + * Returns the values that are used in ARRAY_CONTAINS or ARRAY_CONTAINS_ANY + * filters. Returns `null` if there are no such filters. + */ +export declare function targetGetArrayValues(target: Target, fieldIndex: FieldIndex): ProtoValue[] | null; +/** + * Returns the list of values that are used in != or NOT_IN filters. Returns + * `null` if there are no such filters. + */ +export declare function targetGetNotInValues(target: Target, fieldIndex: FieldIndex): ProtoValue[] | null; +/** + * Returns a lower bound of field values that can be used as a starting point to + * scan the index defined by `fieldIndex`. Returns `MIN_VALUE` if no lower bound + * exists. + */ +export declare function targetGetLowerBound(target: Target, fieldIndex: FieldIndex): Bound; +/** + * Returns an upper bound of field values that can be used as an ending point + * when scanning the index defined by `fieldIndex`. Returns `MAX_VALUE` if no + * upper bound exists. + */ +export declare function targetGetUpperBound(target: Target, fieldIndex: FieldIndex): Bound; +/** Returns the number of segments of a perfect index for this target. */ +export declare function targetGetSegmentCount(target: Target): number; +export declare function targetHasLimit(target: Target): boolean; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/target_id_generator.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/target_id_generator.d.ts new file mode 100644 index 0000000..7a00fcd --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/target_id_generator.d.ts @@ -0,0 +1,38 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { TargetId } from './types'; +/** + * Generates monotonically increasing target IDs for sending targets to the + * watch stream. + * + * The client constructs two generators, one for the target cache, and one for + * for the sync engine (to generate limbo documents targets). These + * generators produce non-overlapping IDs (by using even and odd IDs + * respectively). + * + * By separating the target ID space, the query cache can generate target IDs + * that persist across client restarts, while sync engine can independently + * generate in-memory target IDs that are transient and can be reused after a + * restart. + */ +export declare class TargetIdGenerator { + private lastId; + constructor(lastId: number); + next(): TargetId; + static forTargetCache(): TargetIdGenerator; + static forSyncEngine(): TargetIdGenerator; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/transaction.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/transaction.d.ts new file mode 100644 index 0000000..4a982e9 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/transaction.d.ts @@ -0,0 +1,60 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { ParsedSetData, ParsedUpdateData } from '../lite-api/user_data_reader'; +import { Document } from '../model/document'; +import { DocumentKey } from '../model/document_key'; +import { Datastore } from '../remote/datastore'; +/** + * Internal transaction object responsible for accumulating the mutations to + * perform and the base versions for any documents read. + */ +export declare class Transaction { + private datastore; + private readVersions; + private mutations; + private committed; + /** + * A deferred usage error that occurred previously in this transaction that + * will cause the transaction to fail once it actually commits. + */ + private lastTransactionError; + /** + * Set of documents that have been written in the transaction. + * + * When there's more than one write to the same key in a transaction, any + * writes after the first are handled differently. + */ + private writtenDocs; + constructor(datastore: Datastore); + lookup(keys: DocumentKey[]): Promise; + set(key: DocumentKey, data: ParsedSetData): void; + update(key: DocumentKey, data: ParsedUpdateData): void; + delete(key: DocumentKey): void; + commit(): Promise; + private recordVersion; + /** + * Returns the version of this document when it was read in this transaction, + * as a precondition, or no precondition if it was not read. + */ + private precondition; + /** + * Returns the precondition for a document if the operation is an update. + */ + private preconditionForUpdate; + private write; + private ensureCommitNotCalled; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/transaction_options.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/transaction_options.d.ts new file mode 100644 index 0000000..bf52930 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/transaction_options.d.ts @@ -0,0 +1,25 @@ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export declare const DEFAULT_TRANSACTION_OPTIONS: TransactionOptions; +/** + * Options to customize transaction behavior. + */ +export declare interface TransactionOptions { + /** Maximum number of attempts to commit, after which transaction fails. Default is 5. */ + readonly maxAttempts: number; +} +export declare function validateTransactionOptions(options: TransactionOptions): void; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/transaction_runner.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/transaction_runner.d.ts new file mode 100644 index 0000000..794c7d3 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/transaction_runner.d.ts @@ -0,0 +1,41 @@ +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Datastore } from '../remote/datastore'; +import { AsyncQueue } from '../util/async_queue'; +import { Deferred } from '../util/promise'; +import { Transaction } from './transaction'; +import { TransactionOptions } from './transaction_options'; +/** + * TransactionRunner encapsulates the logic needed to run and retry transactions + * with backoff. + */ +export declare class TransactionRunner { + private readonly asyncQueue; + private readonly datastore; + private readonly options; + private readonly updateFunction; + private readonly deferred; + private attemptsRemaining; + private backoff; + constructor(asyncQueue: AsyncQueue, datastore: Datastore, options: TransactionOptions, updateFunction: (transaction: Transaction) => Promise, deferred: Deferred); + /** Runs the transaction and sets the result on deferred. */ + run(): void; + private runWithBackOff; + private tryRunUpdateFunction; + private handleTransactionError; + private isRetryableTransactionError; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/types.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/types.d.ts new file mode 100644 index 0000000..6c3b8ca --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/types.d.ts @@ -0,0 +1,65 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * BatchID is a locally assigned ID for a batch of mutations that have been + * applied. + */ +export type BatchId = number; +/** + * A locally-assigned ID used to refer to a target being watched via the + * Watch service. + */ +export type TargetId = number; +export type ListenSequenceNumber = number; +/** The different states of a mutation batch. */ +export type MutationBatchState = 'pending' | 'acknowledged' | 'rejected'; +/** + * Describes the online state of the Firestore client. Note that this does not + * indicate whether or not the remote store is trying to connect or not. This is + * primarily used by the View / EventManager code to change their behavior while + * offline (e.g. get() calls shouldn't wait for data from the server and + * snapshot events should set metadata.isFromCache=true). + * + * The string values should not be changed since they are persisted in + * WebStorage. + */ +export declare const enum OnlineState { + /** + * The Firestore client is in an unknown online state. This means the client + * is either not actively trying to establish a connection or it is currently + * trying to establish a connection, but it has not succeeded or failed yet. + * Higher-level components should not operate in offline mode. + */ + Unknown = "Unknown", + /** + * The client is connected and the connections are healthy. This state is + * reached after a successful connection and there has been at least one + * successful message received from the backends. + */ + Online = "Online", + /** + * The client is either trying to establish a connection but failing, or it + * has been explicitly marked offline via a call to disableNetwork(). + * Higher-level components should operate in offline mode. + */ + Offline = "Offline" +} +/** The source of an online state event. */ +export declare const enum OnlineStateSource { + RemoteStore = 0, + SharedClientState = 1 +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/version.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/version.d.ts new file mode 100644 index 0000000..9edc565 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/version.d.ts @@ -0,0 +1,18 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export declare let SDK_VERSION: string; +export declare function setSDKVersion(version: string): void; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/view.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/view.d.ts new file mode 100644 index 0000000..57680a5 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/view.d.ts @@ -0,0 +1,152 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { QueryResult } from '../local/local_store_impl'; +import { DocumentKeySet, DocumentMap } from '../model/collections'; +import { DocumentKey } from '../model/document_key'; +import { DocumentSet } from '../model/document_set'; +import { TargetChange } from '../remote/remote_event'; +import { Query } from './query'; +import { OnlineState } from './types'; +import { DocumentChangeSet, ViewSnapshot } from './view_snapshot'; +export type LimboDocumentChange = AddedLimboDocument | RemovedLimboDocument; +export declare class AddedLimboDocument { + key: DocumentKey; + constructor(key: DocumentKey); +} +export declare class RemovedLimboDocument { + key: DocumentKey; + constructor(key: DocumentKey); +} +/** The result of applying a set of doc changes to a view. */ +export interface ViewDocumentChanges { + /** The new set of docs that should be in the view. */ + documentSet: DocumentSet; + /** The diff of these docs with the previous set of docs. */ + changeSet: DocumentChangeSet; + /** + * Whether the set of documents passed in was not sufficient to calculate the + * new state of the view and there needs to be another pass based on the + * local cache. + */ + needsRefill: boolean; + mutatedKeys: DocumentKeySet; +} +export interface ViewChange { + snapshot?: ViewSnapshot; + limboChanges: LimboDocumentChange[]; +} +/** + * View is responsible for computing the final merged truth of what docs are in + * a query. It gets notified of local and remote changes to docs, and applies + * the query filters and limits to determine the most correct possible results. + */ +export declare class View { + private query; + /** Documents included in the remote target */ + private _syncedDocuments; + private syncState; + private hasCachedResults; + /** + * A flag whether the view is current with the backend. A view is considered + * current after it has seen the current flag from the backend and did not + * lose consistency within the watch stream (e.g. because of an existence + * filter mismatch). + */ + private current; + private documentSet; + /** Documents in the view but not in the remote target */ + private limboDocuments; + /** Document Keys that have local changes */ + private mutatedKeys; + /** Query comparator that defines the document order in this view. */ + private docComparator; + constructor(query: Query, + /** Documents included in the remote target */ + _syncedDocuments: DocumentKeySet); + /** + * The set of remote documents that the server has told us belongs to the target associated with + * this view. + */ + get syncedDocuments(): DocumentKeySet; + /** + * Iterates over a set of doc changes, applies the query limit, and computes + * what the new results should be, what the changes were, and whether we may + * need to go back to the local cache for more results. Does not make any + * changes to the view. + * @param docChanges - The doc changes to apply to this view. + * @param previousChanges - If this is being called with a refill, then start + * with this set of docs and changes instead of the current view. + * @returns a new set of docs, changes, and refill flag. + */ + computeDocChanges(docChanges: DocumentMap, previousChanges?: ViewDocumentChanges): ViewDocumentChanges; + private shouldWaitForSyncedDocument; + /** + * Updates the view with the given ViewDocumentChanges and optionally updates + * limbo docs and sync state from the provided target change. + * @param docChanges - The set of changes to make to the view's docs. + * @param limboResolutionEnabled - Whether to update limbo documents based on + * this change. + * @param targetChange - A target change to apply for computing limbo docs and + * sync state. + * @param targetIsPendingReset - Whether the target is pending to reset due to + * existence filter mismatch. If not explicitly specified, it is treated + * equivalently to `false`. + * @returns A new ViewChange with the given docs, changes, and sync state. + */ + applyChanges(docChanges: ViewDocumentChanges, limboResolutionEnabled: boolean, targetChange?: TargetChange, targetIsPendingReset?: boolean): ViewChange; + /** + * Applies an OnlineState change to the view, potentially generating a + * ViewChange if the view's syncState changes as a result. + */ + applyOnlineStateChange(onlineState: OnlineState): ViewChange; + /** + * Returns whether the doc for the given key should be in limbo. + */ + private shouldBeInLimbo; + /** + * Updates syncedDocuments, current, and limbo docs based on the given change. + * Returns the list of changes to which docs are in limbo. + */ + private applyTargetChange; + private updateLimboDocuments; + /** + * Update the in-memory state of the current view with the state read from + * persistence. + * + * We update the query view whenever a client's primary status changes: + * - When a client transitions from primary to secondary, it can miss + * LocalStorage updates and its query views may temporarily not be + * synchronized with the state on disk. + * - For secondary to primary transitions, the client needs to update the list + * of `syncedDocuments` since secondary clients update their query views + * based purely on synthesized RemoteEvents. + * + * @param queryResult.documents - The documents that match the query according + * to the LocalStore. + * @param queryResult.remoteKeys - The keys of the documents that match the + * query according to the backend. + * + * @returns The ViewChange that resulted from this synchronization. + */ + synchronizeWithPersistedState(queryResult: QueryResult): ViewChange; + /** + * Returns a view snapshot as if this query was just listened to. Contains + * a document add for every existing document and the `fromCache` and + * `hasPendingWrites` status of the already established view. + */ + computeInitialSnapshot(): ViewSnapshot; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/view_snapshot.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/view_snapshot.d.ts new file mode 100644 index 0000000..8b284df --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/view_snapshot.d.ts @@ -0,0 +1,59 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { DocumentKeySet } from '../model/collections'; +import { Document } from '../model/document'; +import { DocumentSet } from '../model/document_set'; +import { Query } from './query'; +export declare const enum ChangeType { + Added = 0, + Removed = 1, + Modified = 2, + Metadata = 3 +} +export interface DocumentViewChange { + type: ChangeType; + doc: Document; +} +export declare const enum SyncState { + Local = 0, + Synced = 1 +} +/** + * DocumentChangeSet keeps track of a set of changes to docs in a query, merging + * duplicate events for the same doc. + */ +export declare class DocumentChangeSet { + private changeMap; + track(change: DocumentViewChange): void; + getChanges(): DocumentViewChange[]; +} +export declare class ViewSnapshot { + readonly query: Query; + readonly docs: DocumentSet; + readonly oldDocs: DocumentSet; + readonly docChanges: DocumentViewChange[]; + readonly mutatedKeys: DocumentKeySet; + readonly fromCache: boolean; + readonly syncStateChanged: boolean; + readonly excludesMetadataChanges: boolean; + readonly hasCachedResults: boolean; + constructor(query: Query, docs: DocumentSet, oldDocs: DocumentSet, docChanges: DocumentViewChange[], mutatedKeys: DocumentKeySet, fromCache: boolean, syncStateChanged: boolean, excludesMetadataChanges: boolean, hasCachedResults: boolean); + /** Returns a view snapshot as if all documents in the snapshot were added. */ + static fromInitialDocuments(query: Query, documents: DocumentSet, mutatedKeys: DocumentKeySet, fromCache: boolean, hasCachedResults: boolean): ViewSnapshot; + get hasPendingWrites(): boolean; + isEqual(other: ViewSnapshot): boolean; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/index.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/index.d.ts new file mode 100644 index 0000000..0541f3f --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/index.d.ts @@ -0,0 +1,28 @@ +/** + * Cloud Firestore + * + * @packageDocumentation + */ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Firestore } from './api/database'; +export * from './api'; +declare module '@firebase/component' { + interface NameServiceMapping { + 'firestore': Firestore; + } +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/index.node.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/index.node.d.ts new file mode 100644 index 0000000..952da59 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/index.node.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export * from './api'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/index.rn.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/index.rn.d.ts new file mode 100644 index 0000000..952da59 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/index.rn.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export * from './api'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/index/directional_index_byte_encoder.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/index/directional_index_byte_encoder.d.ts new file mode 100644 index 0000000..0038f37 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/index/directional_index_byte_encoder.d.ts @@ -0,0 +1,24 @@ +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { ByteString } from '../util/byte_string'; +/** An index value encoder. */ +export interface DirectionalIndexByteEncoder { + writeBytes(value: ByteString): void; + writeString(value: string): void; + writeNumber(value: number): void; + writeInfinity(): void; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/index/firestore_index_value_writer.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/index/firestore_index_value_writer.d.ts new file mode 100644 index 0000000..01298c6 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/index/firestore_index_value_writer.d.ts @@ -0,0 +1,34 @@ +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Value } from '../protos/firestore_proto_api'; +import { DirectionalIndexByteEncoder } from './directional_index_byte_encoder'; +/** Firestore index value writer. */ +export declare class FirestoreIndexValueWriter { + static INSTANCE: FirestoreIndexValueWriter; + private constructor(); + /** Writes an index value. */ + writeIndexValue(value: Value, encoder: DirectionalIndexByteEncoder): void; + private writeIndexValueAux; + private writeIndexString; + private writeUnlabeledIndexString; + private writeIndexMap; + private writeIndexVector; + private writeIndexArray; + private writeIndexEntityRef; + private writeValueTypeLabel; + private writeTruncationMarker; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/index/index_byte_encoder.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/index/index_byte_encoder.d.ts new file mode 100644 index 0000000..dce4631 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/index/index_byte_encoder.d.ts @@ -0,0 +1,31 @@ +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { IndexKind } from '../model/field_index'; +import { DirectionalIndexByteEncoder } from './directional_index_byte_encoder'; +/** + * Implements `DirectionalIndexByteEncoder` using `OrderedCodeWriter` for the + * actual encoding. + */ +export declare class IndexByteEncoder { + private orderedCode; + private ascending; + private descending; + seed(encodedBytes: Uint8Array): void; + forKind(kind: IndexKind): DirectionalIndexByteEncoder; + encodedBytes(): Uint8Array; + reset(): void; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/index/index_entry.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/index/index_entry.d.ts new file mode 100644 index 0000000..fe89202 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/index/index_entry.d.ts @@ -0,0 +1,49 @@ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { DbIndexEntry } from '../local/indexeddb_schema'; +import { DbIndexEntryKey, KeySafeBytes } from '../local/indexeddb_sentinels'; +import { DocumentKey } from '../model/document_key'; +/** Represents an index entry saved by the SDK in persisted storage. */ +export declare class IndexEntry { + readonly _indexId: number; + readonly _documentKey: DocumentKey; + readonly _arrayValue: Uint8Array; + readonly _directionalValue: Uint8Array; + constructor(_indexId: number, _documentKey: DocumentKey, _arrayValue: Uint8Array, _directionalValue: Uint8Array); + /** + * Returns an IndexEntry entry that sorts immediately after the current + * directional value. + */ + successor(): IndexEntry; + dbIndexEntry(uid: string, orderedDocumentKey: Uint8Array, documentKey: DocumentKey): DbIndexEntry; + dbIndexEntryKey(uid: string, orderedDocumentKey: Uint8Array, documentKey: DocumentKey): DbIndexEntryKey; +} +export declare function indexEntryComparator(left: IndexEntry, right: IndexEntry): number; +export declare function compareByteArrays(left: Uint8Array, right: Uint8Array): number; +/** + * Workaround for WebKit bug: https://bugs.webkit.org/show_bug.cgi?id=292721 + * Create a key safe representation of Uint8Array values. + * If the browser is detected as Safari or WebKit, then + * the input array will be converted to "sortable byte string". + * Otherwise, the input array will be returned in its original type. + */ +export declare function encodeKeySafeBytes(array: Uint8Array): KeySafeBytes; +/** + * Reverts the key safe representation of Uint8Array (created by + * encodeKeySafeBytes) to a normal Uint8Array. + */ +export declare function decodeKeySafeBytes(input: KeySafeBytes): Uint8Array; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/index/ordered_code_writer.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/index/ordered_code_writer.d.ts new file mode 100644 index 0000000..be345f7 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/index/ordered_code_writer.d.ts @@ -0,0 +1,60 @@ +import { ByteString } from '../util/byte_string'; +/** + * Counts the number of zeros in a byte. + * + * Visible for testing. + */ +export declare function numberOfLeadingZerosInByte(x: number): number; +/** + * OrderedCodeWriter is a minimal-allocation implementation of the writing + * behavior defined by the backend. + * + * The code is ported from its Java counterpart. + */ +export declare class OrderedCodeWriter { + buffer: Uint8Array; + position: number; + writeBytesAscending(value: ByteString): void; + writeBytesDescending(value: ByteString): void; + /** Writes utf8 bytes into this byte sequence, ascending. */ + writeUtf8Ascending(sequence: string): void; + /** Writes utf8 bytes into this byte sequence, descending */ + writeUtf8Descending(sequence: string): void; + writeNumberAscending(val: number): void; + writeNumberDescending(val: number): void; + /** + * Writes the "infinity" byte sequence that sorts after all other byte + * sequences written in ascending order. + */ + writeInfinityAscending(): void; + /** + * Writes the "infinity" byte sequence that sorts before all other byte + * sequences written in descending order. + */ + writeInfinityDescending(): void; + /** + * Resets the buffer such that it is the same as when it was newly + * constructed. + */ + reset(): void; + seed(encodedBytes: Uint8Array): void; + /** Makes a copy of the encoded bytes in this buffer. */ + encodedBytes(): Uint8Array; + /** + * Encodes `val` into an encoding so that the order matches the IEEE 754 + * floating-point comparison results with the following exceptions: + * -0.0 < 0.0 + * all non-NaN < NaN + * NaN = NaN + */ + private toOrderedBits; + /** Writes a single byte ascending to the buffer. */ + private writeByteAscending; + /** Writes a single byte descending to the buffer. */ + private writeByteDescending; + private writeSeparatorAscending; + private writeSeparatorDescending; + private writeEscapedByteAscending; + private writeEscapedByteDescending; + private ensureAvailable; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/aggregate.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/aggregate.d.ts new file mode 100644 index 0000000..3927021 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/aggregate.d.ts @@ -0,0 +1,100 @@ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { AggregateField, AggregateQuerySnapshot, AggregateSpec } from './aggregate_types'; +import { FieldPath } from './field_path'; +import { DocumentData, Query } from './reference'; +/** + * Calculates the number of documents in the result set of the given query + * without actually downloading the documents. + * + * Using this function to count the documents is efficient because only the + * final count, not the documents' data, is downloaded. This function can + * count the documents in cases where the result set is prohibitively large to + * download entirely (thousands of documents). + * + * @param query The query whose result set size is calculated. + * @returns A Promise that will be resolved with the count; the count can be + * retrieved from `snapshot.data().count`, where `snapshot` is the + * `AggregateQuerySnapshot` to which the returned Promise resolves. + */ +export declare function getCount(query: Query): Promise; +}, AppModelType, DbModelType>>; +/** + * Calculates the specified aggregations over the documents in the result + * set of the given query without actually downloading the documents. + * + * Using this function to perform aggregations is efficient because only the + * final aggregation values, not the documents' data, are downloaded. This + * function can perform aggregations of the documents in cases where the result + * set is prohibitively large to download entirely (thousands of documents). + * + * @param query The query whose result set is aggregated over. + * @param aggregateSpec An `AggregateSpec` object that specifies the aggregates + * to perform over the result set. The AggregateSpec specifies aliases for each + * aggregate, which can be used to retrieve the aggregate result. + * @example + * ```typescript + * const aggregateSnapshot = await getAggregate(query, { + * countOfDocs: count(), + * totalHours: sum('hours'), + * averageScore: average('score') + * }); + * + * const countOfDocs: number = aggregateSnapshot.data().countOfDocs; + * const totalHours: number = aggregateSnapshot.data().totalHours; + * const averageScore: number | null = aggregateSnapshot.data().averageScore; + * ``` + */ +export declare function getAggregate(query: Query, aggregateSpec: AggregateSpecType): Promise>; +/** + * Create an AggregateField object that can be used to compute the sum of + * a specified field over a range of documents in the result set of a query. + * @param field Specifies the field to sum across the result set. + */ +export declare function sum(field: string | FieldPath): AggregateField; +/** + * Create an AggregateField object that can be used to compute the average of + * a specified field over a range of documents in the result set of a query. + * @param field Specifies the field to average across the result set. + */ +export declare function average(field: string | FieldPath): AggregateField; +/** + * Create an AggregateField object that can be used to compute the count of + * documents in the result set of a query. + */ +export declare function count(): AggregateField; +/** + * Compares two 'AggregateField` instances for equality. + * + * @param left Compare this AggregateField to the `right`. + * @param right Compare this AggregateField to the `left`. + */ +export declare function aggregateFieldEqual(left: AggregateField, right: AggregateField): boolean; +/** + * Compares two `AggregateQuerySnapshot` instances for equality. + * + * Two `AggregateQuerySnapshot` instances are considered "equal" if they have + * underlying queries that compare equal, and the same data. + * + * @param left - The first `AggregateQuerySnapshot` to compare. + * @param right - The second `AggregateQuerySnapshot` to compare. + * + * @returns `true` if the objects are "equal", as defined above, or `false` + * otherwise. + */ +export declare function aggregateQuerySnapshotEqual(left: AggregateQuerySnapshot, right: AggregateQuerySnapshot): boolean; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/aggregate_types.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/aggregate_types.d.ts new file mode 100644 index 0000000..453dff1 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/aggregate_types.d.ts @@ -0,0 +1,86 @@ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { AggregateType } from '../core/aggregate'; +import { FieldPath as InternalFieldPath } from '../model/path'; +import { ApiClientObjectMap, Value } from '../protos/firestore_proto_api'; +import { average, count, sum } from './aggregate'; +import { DocumentData, Query } from './reference'; +import { AbstractUserDataWriter } from './user_data_writer'; +export { AggregateType }; +/** + * Represents an aggregation that can be performed by Firestore. + */ +export declare class AggregateField { + readonly _internalFieldPath?: InternalFieldPath | undefined; + /** A type string to uniquely identify instances of this class. */ + readonly type = "AggregateField"; + /** Indicates the aggregation operation of this AggregateField. */ + readonly aggregateType: AggregateType; + /** + * Create a new AggregateField + * @param aggregateType Specifies the type of aggregation operation to perform. + * @param _internalFieldPath Optionally specifies the field that is aggregated. + * @internal + */ + constructor(aggregateType?: AggregateType, _internalFieldPath?: InternalFieldPath | undefined); +} +/** + * The union of all `AggregateField` types that are supported by Firestore. + */ +export type AggregateFieldType = ReturnType | ReturnType | ReturnType; +/** + * Specifies a set of aggregations and their aliases. + */ +export interface AggregateSpec { + [field: string]: AggregateFieldType; +} +/** + * A type whose keys are taken from an `AggregateSpec`, and whose values are the + * result of the aggregation performed by the corresponding `AggregateField` + * from the input `AggregateSpec`. + */ +export type AggregateSpecData = { + [P in keyof T]: T[P] extends AggregateField ? U : never; +}; +/** + * The results of executing an aggregation query. + */ +export declare class AggregateQuerySnapshot { + private readonly _userDataWriter; + private readonly _data; + /** A type string to uniquely identify instances of this class. */ + readonly type = "AggregateQuerySnapshot"; + /** + * The underlying query over which the aggregations recorded in this + * `AggregateQuerySnapshot` were performed. + */ + readonly query: Query; + /** @hideconstructor */ + constructor(query: Query, _userDataWriter: AbstractUserDataWriter, _data: ApiClientObjectMap); + /** + * Returns the results of the aggregations performed over the underlying + * query. + * + * The keys of the returned object will be the same as those of the + * `AggregateSpec` object specified to the aggregation method, and the values + * will be the corresponding aggregation result. + * + * @returns The results of the aggregations performed over the underlying + * query. + */ + data(): AggregateSpecData; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/bytes.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/bytes.d.ts new file mode 100644 index 0000000..e4b8e09 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/bytes.d.ts @@ -0,0 +1,83 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { ByteString } from '../util/byte_string'; +import { Property } from '../util/json_validation'; +/** + * An immutable object representing an array of bytes. + */ +export declare class Bytes { + _byteString: ByteString; + /** @hideconstructor */ + constructor(byteString: ByteString); + /** + * Creates a new `Bytes` object from the given Base64 string, converting it to + * bytes. + * + * @param base64 - The Base64 string used to create the `Bytes` object. + */ + static fromBase64String(base64: string): Bytes; + /** + * Creates a new `Bytes` object from the given Uint8Array. + * + * @param array - The Uint8Array used to create the `Bytes` object. + */ + static fromUint8Array(array: Uint8Array): Bytes; + /** + * Returns the underlying bytes as a Base64-encoded string. + * + * @returns The Base64-encoded string created from the `Bytes` object. + */ + toBase64(): string; + /** + * Returns the underlying bytes in a new `Uint8Array`. + * + * @returns The Uint8Array created from the `Bytes` object. + */ + toUint8Array(): Uint8Array; + /** + * Returns a string representation of the `Bytes` object. + * + * @returns A string representation of the `Bytes` object. + */ + toString(): string; + /** + * Returns true if this `Bytes` object is equal to the provided one. + * + * @param other - The `Bytes` object to compare against. + * @returns true if this `Bytes` object is equal to the provided one. + */ + isEqual(other: Bytes): boolean; + static _jsonSchemaVersion: string; + static _jsonSchema: { + type: Property<"string">; + bytes: Property<"string">; + }; + /** + * Returns a JSON-serializable representation of this `Bytes` instance. + * + * @returns a JSON representation of this object. + */ + toJSON(): object; + /** + * Builds a `Bytes` instance from a JSON object created by {@link Bytes.toJSON}. + * + * @param json a JSON object represention of a `Bytes` instance + * @returns an instance of {@link Bytes} if the JSON object could be parsed. Throws a + * {@link FirestoreError} if an error occurs. + */ + static fromJSON(json: object): Bytes; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/components.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/components.d.ts new file mode 100644 index 0000000..a710e68 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/components.d.ts @@ -0,0 +1,49 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { _FirebaseService } from '@firebase/app'; +import { CredentialsProvider } from '../api/credentials'; +import { User } from '../auth/user'; +import { DatabaseId, DatabaseInfo } from '../core/database_info'; +import { Datastore } from '../remote/datastore'; +import { FirestoreSettingsImpl } from './settings'; +export declare const LOG_TAG = "ComponentProvider"; +/** + * An interface implemented by FirebaseFirestore that provides compatibility + * with the usage in this file. + * + * This interface mainly exists to remove a cyclic dependency. + */ +export interface FirestoreService extends _FirebaseService { + _authCredentials: CredentialsProvider; + _appCheckCredentials: CredentialsProvider; + _persistenceKey: string; + _databaseId: DatabaseId; + _terminated: boolean; + _freezeSettings(): FirestoreSettingsImpl; +} +/** + * Returns an initialized and started Datastore for the given Firestore + * instance. Callers must invoke removeComponents() when the Firestore + * instance is terminated. + */ +export declare function getDatastore(firestore: FirestoreService): Datastore; +/** + * Removes all components associated with the provided instance. Must be called + * when the `Firestore` instance is terminated. + */ +export declare function removeComponents(firestore: FirestoreService): void; +export declare function makeDatabaseInfo(databaseId: DatabaseId, appId: string, persistenceKey: string, settings: FirestoreSettingsImpl): DatabaseInfo; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/database.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/database.d.ts new file mode 100644 index 0000000..988a791 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/database.d.ts @@ -0,0 +1,179 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { FirebaseApp } from '@firebase/app'; +import { EmulatorMockTokenOptions } from '@firebase/util'; +import { CredentialsProvider } from '../api/credentials'; +import { User } from '../auth/user'; +import { DatabaseId } from '../core/database_info'; +import { FirestoreService } from './components'; +import { FirestoreSettingsImpl, PrivateSettings, FirestoreSettings } from './settings'; +export { EmulatorMockTokenOptions } from '@firebase/util'; +declare module '@firebase/component' { + interface NameServiceMapping { + 'firestore/lite': Firestore; + } +} +/** + * The Cloud Firestore service interface. + * + * Do not call this constructor directly. Instead, use {@link (getFirestore:1)}. + */ +export declare class Firestore implements FirestoreService { + _authCredentials: CredentialsProvider; + _appCheckCredentials: CredentialsProvider; + readonly _databaseId: DatabaseId; + readonly _app?: FirebaseApp | undefined; + /** + * Whether it's a Firestore or Firestore Lite instance. + */ + type: 'firestore-lite' | 'firestore'; + readonly _persistenceKey: string; + private _settings; + private _settingsFrozen; + private _emulatorOptions; + private _terminateTask; + /** @hideconstructor */ + constructor(_authCredentials: CredentialsProvider, _appCheckCredentials: CredentialsProvider, _databaseId: DatabaseId, _app?: FirebaseApp | undefined); + /** + * The {@link @firebase/app#FirebaseApp} associated with this `Firestore` service + * instance. + */ + get app(): FirebaseApp; + get _initialized(): boolean; + get _terminated(): boolean; + _setSettings(settings: PrivateSettings): void; + _getSettings(): FirestoreSettingsImpl; + _getEmulatorOptions(): { + mockUserToken?: EmulatorMockTokenOptions | string; + }; + _freezeSettings(): FirestoreSettingsImpl; + _delete(): Promise; + _restart(): Promise; + /** Returns a JSON-serializable representation of this `Firestore` instance. */ + toJSON(): object; + /** + * Terminates all components used by this client. Subclasses can override + * this method to clean up their own dependencies, but must also call this + * method. + * + * Only ever called once. + */ + protected _terminate(): Promise; +} +/** + * Initializes a new instance of Cloud Firestore with the provided settings. + * Can only be called before any other functions, including + * {@link (getFirestore:1)}. If the custom settings are empty, this function is + * equivalent to calling {@link (getFirestore:1)}. + * + * @param app - The {@link @firebase/app#FirebaseApp} with which the `Firestore` instance will + * be associated. + * @param settings - A settings object to configure the `Firestore` instance. + * @returns A newly initialized `Firestore` instance. + */ +export declare function initializeFirestore(app: FirebaseApp, settings: FirestoreSettings): Firestore; +/** + * Initializes a new instance of Cloud Firestore with the provided settings. + * Can only be called before any other functions, including + * {@link (getFirestore:1)}. If the custom settings are empty, this function is + * equivalent to calling {@link (getFirestore:1)}. + * + * @param app - The {@link @firebase/app#FirebaseApp} with which the `Firestore` instance will + * be associated. + * @param settings - A settings object to configure the `Firestore` instance. + * @param databaseId - The name of the database. + * @returns A newly initialized `Firestore` instance. + * @beta + */ +export declare function initializeFirestore(app: FirebaseApp, settings: FirestoreSettings, databaseId?: string): Firestore; +/** + * Returns the existing default {@link Firestore} instance that is associated with the + * default {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new + * instance with default settings. + * + * @returns The {@link Firestore} instance of the provided app. + */ +export declare function getFirestore(): Firestore; +/** + * Returns the existing default {@link Firestore} instance that is associated with the + * provided {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new + * instance with default settings. + * + * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned {@link Firestore} + * instance is associated with. + * @returns The {@link Firestore} instance of the provided app. + */ +export declare function getFirestore(app: FirebaseApp): Firestore; +/** + * Returns the existing {@link Firestore} instance that is associated with the + * default {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new + * instance with default settings. + * + * @param databaseId - The name of the database. + * @returns The {@link Firestore} instance of the provided app. + * @beta + */ +export declare function getFirestore(databaseId: string): Firestore; +/** + * Returns the existing {@link Firestore} instance that is associated with the + * provided {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new + * instance with default settings. + * + * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned {@link Firestore} + * instance is associated with. + * @param databaseId - The name of the database. + * @returns The {@link Firestore} instance of the provided app. + * @beta + */ +export declare function getFirestore(app: FirebaseApp, databaseId: string): Firestore; +/** + * Modify this instance to communicate with the Cloud Firestore emulator. + * + * Note: This must be called before this instance has been used to do any + * operations. + * + * @param firestore - The `Firestore` instance to configure to connect to the + * emulator. + * @param host - the emulator host (ex: localhost). + * @param port - the emulator port (ex: 9000). + * @param options.mockUserToken - the mock auth token to use for unit testing + * Security Rules. + */ +export declare function connectFirestoreEmulator(firestore: Firestore, host: string, port: number, options?: { + mockUserToken?: EmulatorMockTokenOptions | string; +}): void; +/** + * Terminates the provided `Firestore` instance. + * + * After calling `terminate()` only the `clearIndexedDbPersistence()` functions + * may be used. Any other function will throw a `FirestoreError`. Termination + * does not cancel any pending writes, and any promises that are awaiting a + * response from the server will not be resolved. + * + * To restart after termination, create a new instance of `Firestore` with + * {@link (getFirestore:1)}. + * + * Note: Under normal circumstances, calling `terminate()` is not required. This + * function is useful only when you want to force this instance to release all of + * its resources or in combination with {@link clearIndexedDbPersistence} to + * ensure that all local state is destroyed between test runs. + * + * @param firestore - The `Firestore` instance to terminate. + * @returns A `Promise` that is resolved when the instance has been successfully + * terminated. + */ +export declare function terminate(firestore: Firestore): Promise; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/field_path.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/field_path.d.ts new file mode 100644 index 0000000..38faa8f --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/field_path.d.ts @@ -0,0 +1,48 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { FieldPath as InternalFieldPath } from '../model/path'; +/** + * A `FieldPath` refers to a field in a document. The path may consist of a + * single field name (referring to a top-level field in the document), or a + * list of field names (referring to a nested field in the document). + * + * Create a `FieldPath` by providing field names. If more than one field + * name is provided, the path will point to a nested field in a document. + */ +export declare class FieldPath { + /** Internal representation of a Firestore field path. */ + readonly _internalPath: InternalFieldPath; + /** + * Creates a `FieldPath` from the provided field names. If more than one field + * name is provided, the path will point to a nested field in a document. + * + * @param fieldNames - A list of field names. + */ + constructor(...fieldNames: string[]); + /** + * Returns true if this `FieldPath` is equal to the provided one. + * + * @param other - The `FieldPath` to compare against. + * @returns true if this `FieldPath` is equal to the provided one. + */ + isEqual(other: FieldPath): boolean; +} +/** + * Returns a special sentinel `FieldPath` to refer to the ID of a document. + * It can be used in queries to sort or filter by the document ID. + */ +export declare function documentId(): FieldPath; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/field_value.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/field_value.d.ts new file mode 100644 index 0000000..5e44c8e --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/field_value.d.ts @@ -0,0 +1,33 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { ParseContext } from '../api/parse_context'; +import { FieldTransform } from '../model/mutation'; +/** + * Sentinel values that can be used when writing document fields with `set()` + * or `update()`. + */ +export declare abstract class FieldValue { + _methodName: string; + /** + * @param _methodName - The public API endpoint that returns this class. + * @hideconstructor + */ + constructor(_methodName: string); + /** Compares `FieldValue`s for equality. */ + abstract isEqual(other: FieldValue): boolean; + abstract _toFieldTransform(context: ParseContext): FieldTransform | null; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/field_value_impl.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/field_value_impl.d.ts new file mode 100644 index 0000000..019e460 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/field_value_impl.d.ts @@ -0,0 +1,81 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { FieldValue } from './field_value'; +import { VectorValue } from './vector_value'; +/** + * Returns a sentinel for use with {@link @firebase/firestore/lite#(updateDoc:1)} or + * {@link @firebase/firestore/lite#(setDoc:1)} with `{merge: true}` to mark a field for deletion. + */ +export declare function deleteField(): FieldValue; +/** + * Returns a sentinel used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link @firebase/firestore/lite#(updateDoc:1)} to + * include a server-generated timestamp in the written data. + */ +export declare function serverTimestamp(): FieldValue; +/** + * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link + * @firebase/firestore/lite#(updateDoc:1)} that tells the server to union the given elements with any array + * value that already exists on the server. Each specified element that doesn't + * already exist in the array will be added to the end. If the field being + * modified is not already an array it will be overwritten with an array + * containing exactly the specified elements. + * + * @param elements - The elements to union into the array. + * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or + * `updateDoc()`. + */ +export declare function arrayUnion(...elements: unknown[]): FieldValue; +/** + * Returns a special value that can be used with {@link (setDoc:1)} or {@link + * updateDoc:1} that tells the server to remove the given elements from any + * array value that already exists on the server. All instances of each element + * specified will be removed from the array. If the field being modified is not + * already an array it will be overwritten with an empty array. + * + * @param elements - The elements to remove from the array. + * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or + * `updateDoc()` + */ +export declare function arrayRemove(...elements: unknown[]): FieldValue; +/** + * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link + * @firebase/firestore/lite#(updateDoc:1)} that tells the server to increment the field's current value by + * the given value. + * + * If either the operand or the current field value uses floating point + * precision, all arithmetic follows IEEE 754 semantics. If both values are + * integers, values outside of JavaScript's safe number range + * (`Number.MIN_SAFE_INTEGER` to `Number.MAX_SAFE_INTEGER`) are also subject to + * precision loss. Furthermore, once processed by the Firestore backend, all + * integer operations are capped between -2^63 and 2^63-1. + * + * If the current field value is not of type `number`, or if the field does not + * yet exist, the transformation sets the field to the given value. + * + * @param n - The value to increment by. + * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or + * `updateDoc()` + */ +export declare function increment(n: number): FieldValue; +/** + * Creates a new `VectorValue` constructed with a copy of the given array of numbers. + * + * @param values - Create a `VectorValue` instance with a copy of this array of numbers. + * + * @returns A new `VectorValue` constructed with a copy of the given array of numbers. + */ +export declare function vector(values?: number[]): VectorValue; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/geo_point.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/geo_point.d.ts new file mode 100644 index 0000000..bfe8cd5 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/geo_point.d.ts @@ -0,0 +1,79 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Property } from '../util/json_validation'; +/** + * An immutable object representing a geographic location in Firestore. The + * location is represented as latitude/longitude pair. + * + * Latitude values are in the range of [-90, 90]. + * Longitude values are in the range of [-180, 180]. + */ +export declare class GeoPoint { + private _lat; + private _long; + /** + * Creates a new immutable `GeoPoint` object with the provided latitude and + * longitude values. + * @param latitude - The latitude as number between -90 and 90. + * @param longitude - The longitude as number between -180 and 180. + */ + constructor(latitude: number, longitude: number); + /** + * The latitude of this `GeoPoint` instance. + */ + get latitude(): number; + /** + * The longitude of this `GeoPoint` instance. + */ + get longitude(): number; + /** + * Returns true if this `GeoPoint` is equal to the provided one. + * + * @param other - The `GeoPoint` to compare against. + * @returns true if this `GeoPoint` is equal to the provided one. + */ + isEqual(other: GeoPoint): boolean; + /** + * Actually private to JS consumers of our API, so this function is prefixed + * with an underscore. + */ + _compareTo(other: GeoPoint): number; + static _jsonSchemaVersion: string; + static _jsonSchema: { + type: Property<"string">; + latitude: Property<"number">; + longitude: Property<"number">; + }; + /** + * Returns a JSON-serializable representation of this `GeoPoint` instance. + * + * @returns a JSON representation of this object. + */ + toJSON(): { + latitude: number; + longitude: number; + type: string; + }; + /** + * Builds a `GeoPoint` instance from a JSON object created by {@link GeoPoint.toJSON}. + * + * @param json a JSON object represention of a `GeoPoint` instance + * @returns an instance of {@link GeoPoint} if the JSON object could be parsed. Throws a + * {@link FirestoreError} if an error occurs. + */ + static fromJSON(json: object): GeoPoint; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/query.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/query.d.ts new file mode 100644 index 0000000..9053d9d --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/query.d.ts @@ -0,0 +1,404 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Bound } from '../core/bound'; +import { DatabaseId } from '../core/database_info'; +import { CompositeOperator, FieldFilter, Filter, Operator } from '../core/filter'; +import { Direction, OrderBy } from '../core/order_by'; +import { LimitType, Query as InternalQuery } from '../core/query'; +import { Document } from '../model/document'; +import { FieldPath as InternalFieldPath } from '../model/path'; +import { FieldPath } from './field_path'; +import { DocumentData, Query } from './reference'; +import { DocumentSnapshot } from './snapshot'; +import { UserDataReader } from './user_data_reader'; +export declare function validateHasExplicitOrderByForLimitToLast(query: InternalQuery): void; +/** Describes the different query constraints available in this SDK. */ +export type QueryConstraintType = 'where' | 'orderBy' | 'limit' | 'limitToLast' | 'startAt' | 'startAfter' | 'endAt' | 'endBefore'; +/** + * An `AppliableConstraint` is an abstraction of a constraint that can be applied + * to a Firestore query. + */ +export declare abstract class AppliableConstraint { + /** + * Takes the provided {@link Query} and returns a copy of the {@link Query} with this + * {@link AppliableConstraint} applied. + */ + abstract _apply(query: Query): Query; +} +/** + * A `QueryConstraint` is used to narrow the set of documents returned by a + * Firestore query. `QueryConstraint`s are created by invoking {@link where}, + * {@link orderBy}, {@link (startAt:1)}, {@link (startAfter:1)}, {@link + * (endBefore:1)}, {@link (endAt:1)}, {@link limit}, {@link limitToLast} and + * can then be passed to {@link (query:1)} to create a new query instance that + * also contains this `QueryConstraint`. + */ +export declare abstract class QueryConstraint extends AppliableConstraint { + /** The type of this query constraint */ + abstract readonly type: QueryConstraintType; + /** + * Takes the provided {@link Query} and returns a copy of the {@link Query} with this + * {@link AppliableConstraint} applied. + */ + abstract _apply(query: Query): Query; +} +/** + * Creates a new immutable instance of {@link Query} that is extended to also + * include additional query constraints. + * + * @param query - The {@link Query} instance to use as a base for the new + * constraints. + * @param compositeFilter - The {@link QueryCompositeFilterConstraint} to + * apply. Create {@link QueryCompositeFilterConstraint} using {@link and} or + * {@link or}. + * @param queryConstraints - Additional {@link QueryNonFilterConstraint}s to + * apply (e.g. {@link orderBy}, {@link limit}). + * @throws if any of the provided query constraints cannot be combined with the + * existing or new constraints. + */ +export declare function query(query: Query, compositeFilter: QueryCompositeFilterConstraint, ...queryConstraints: QueryNonFilterConstraint[]): Query; +/** + * Creates a new immutable instance of {@link Query} that is extended to also + * include additional query constraints. + * + * @param query - The {@link Query} instance to use as a base for the new + * constraints. + * @param queryConstraints - The list of {@link QueryConstraint}s to apply. + * @throws if any of the provided query constraints cannot be combined with the + * existing or new constraints. + */ +export declare function query(query: Query, ...queryConstraints: QueryConstraint[]): Query; +/** + * A `QueryFieldFilterConstraint` is used to narrow the set of documents returned by + * a Firestore query by filtering on one or more document fields. + * `QueryFieldFilterConstraint`s are created by invoking {@link where} and can then + * be passed to {@link (query:1)} to create a new query instance that also contains + * this `QueryFieldFilterConstraint`. + */ +export declare class QueryFieldFilterConstraint extends QueryConstraint { + private readonly _field; + private _op; + private _value; + /** The type of this query constraint */ + readonly type = "where"; + /** + * @internal + */ + protected constructor(_field: InternalFieldPath, _op: Operator, _value: unknown); + static _create(_field: InternalFieldPath, _op: Operator, _value: unknown): QueryFieldFilterConstraint; + _apply(query: Query): Query; + _parse(query: Query): FieldFilter; +} +/** + * Filter conditions in a {@link where} clause are specified using the + * strings '<', '<=', '==', '!=', '>=', '>', 'array-contains', 'in', + * 'array-contains-any', and 'not-in'. + */ +export type WhereFilterOp = '<' | '<=' | '==' | '!=' | '>=' | '>' | 'array-contains' | 'in' | 'array-contains-any' | 'not-in'; +/** + * Creates a {@link QueryFieldFilterConstraint} that enforces that documents + * must contain the specified field and that the value should satisfy the + * relation constraint provided. + * + * @param fieldPath - The path to compare + * @param opStr - The operation string (e.g "<", "<=", "==", "<", + * "<=", "!="). + * @param value - The value for comparison + * @returns The created {@link QueryFieldFilterConstraint}. + */ +export declare function where(fieldPath: string | FieldPath, opStr: WhereFilterOp, value: unknown): QueryFieldFilterConstraint; +/** + * A `QueryCompositeFilterConstraint` is used to narrow the set of documents + * returned by a Firestore query by performing the logical OR or AND of multiple + * {@link QueryFieldFilterConstraint}s or {@link QueryCompositeFilterConstraint}s. + * `QueryCompositeFilterConstraint`s are created by invoking {@link or} or + * {@link and} and can then be passed to {@link (query:1)} to create a new query + * instance that also contains the `QueryCompositeFilterConstraint`. + */ +export declare class QueryCompositeFilterConstraint extends AppliableConstraint { + /** The type of this query constraint */ + readonly type: 'or' | 'and'; + private readonly _queryConstraints; + /** + * @internal + */ + protected constructor( + /** The type of this query constraint */ + type: 'or' | 'and', _queryConstraints: QueryFilterConstraint[]); + static _create(type: 'or' | 'and', _queryConstraints: QueryFilterConstraint[]): QueryCompositeFilterConstraint; + _parse(query: Query): Filter; + _apply(query: Query): Query; + _getQueryConstraints(): readonly AppliableConstraint[]; + _getOperator(): CompositeOperator; +} +/** + * `QueryNonFilterConstraint` is a helper union type that represents + * QueryConstraints which are used to narrow or order the set of documents, + * but that do not explicitly filter on a document field. + * `QueryNonFilterConstraint`s are created by invoking {@link orderBy}, + * {@link (startAt:1)}, {@link (startAfter:1)}, {@link (endBefore:1)}, {@link (endAt:1)}, + * {@link limit} or {@link limitToLast} and can then be passed to {@link (query:1)} + * to create a new query instance that also contains the `QueryConstraint`. + */ +export type QueryNonFilterConstraint = QueryOrderByConstraint | QueryLimitConstraint | QueryStartAtConstraint | QueryEndAtConstraint; +/** + * `QueryFilterConstraint` is a helper union type that represents + * {@link QueryFieldFilterConstraint} and {@link QueryCompositeFilterConstraint}. + */ +export type QueryFilterConstraint = QueryFieldFilterConstraint | QueryCompositeFilterConstraint; +/** + * Creates a new {@link QueryCompositeFilterConstraint} that is a disjunction of + * the given filter constraints. A disjunction filter includes a document if it + * satisfies any of the given filters. + * + * @param queryConstraints - Optional. The list of + * {@link QueryFilterConstraint}s to perform a disjunction for. These must be + * created with calls to {@link where}, {@link or}, or {@link and}. + * @returns The newly created {@link QueryCompositeFilterConstraint}. + */ +export declare function or(...queryConstraints: QueryFilterConstraint[]): QueryCompositeFilterConstraint; +/** + * Creates a new {@link QueryCompositeFilterConstraint} that is a conjunction of + * the given filter constraints. A conjunction filter includes a document if it + * satisfies all of the given filters. + * + * @param queryConstraints - Optional. The list of + * {@link QueryFilterConstraint}s to perform a conjunction for. These must be + * created with calls to {@link where}, {@link or}, or {@link and}. + * @returns The newly created {@link QueryCompositeFilterConstraint}. + */ +export declare function and(...queryConstraints: QueryFilterConstraint[]): QueryCompositeFilterConstraint; +/** + * A `QueryOrderByConstraint` is used to sort the set of documents returned by a + * Firestore query. `QueryOrderByConstraint`s are created by invoking + * {@link orderBy} and can then be passed to {@link (query:1)} to create a new query + * instance that also contains this `QueryOrderByConstraint`. + * + * Note: Documents that do not contain the orderBy field will not be present in + * the query result. + */ +export declare class QueryOrderByConstraint extends QueryConstraint { + private readonly _field; + private _direction; + /** The type of this query constraint */ + readonly type = "orderBy"; + /** + * @internal + */ + protected constructor(_field: InternalFieldPath, _direction: Direction); + static _create(_field: InternalFieldPath, _direction: Direction): QueryOrderByConstraint; + _apply(query: Query): Query; +} +/** + * The direction of a {@link orderBy} clause is specified as 'desc' or 'asc' + * (descending or ascending). + */ +export type OrderByDirection = 'desc' | 'asc'; +/** + * Creates a {@link QueryOrderByConstraint} that sorts the query result by the + * specified field, optionally in descending order instead of ascending. + * + * Note: Documents that do not contain the specified field will not be present + * in the query result. + * + * @param fieldPath - The field to sort by. + * @param directionStr - Optional direction to sort by ('asc' or 'desc'). If + * not specified, order will be ascending. + * @returns The created {@link QueryOrderByConstraint}. + */ +export declare function orderBy(fieldPath: string | FieldPath, directionStr?: OrderByDirection): QueryOrderByConstraint; +/** + * A `QueryLimitConstraint` is used to limit the number of documents returned by + * a Firestore query. + * `QueryLimitConstraint`s are created by invoking {@link limit} or + * {@link limitToLast} and can then be passed to {@link (query:1)} to create a new + * query instance that also contains this `QueryLimitConstraint`. + */ +export declare class QueryLimitConstraint extends QueryConstraint { + /** The type of this query constraint */ + readonly type: 'limit' | 'limitToLast'; + private readonly _limit; + private readonly _limitType; + /** + * @internal + */ + protected constructor( + /** The type of this query constraint */ + type: 'limit' | 'limitToLast', _limit: number, _limitType: LimitType); + static _create(type: 'limit' | 'limitToLast', _limit: number, _limitType: LimitType): QueryLimitConstraint; + _apply(query: Query): Query; +} +/** + * Creates a {@link QueryLimitConstraint} that only returns the first matching + * documents. + * + * @param limit - The maximum number of items to return. + * @returns The created {@link QueryLimitConstraint}. + */ +export declare function limit(limit: number): QueryLimitConstraint; +/** + * Creates a {@link QueryLimitConstraint} that only returns the last matching + * documents. + * + * You must specify at least one `orderBy` clause for `limitToLast` queries, + * otherwise an exception will be thrown during execution. + * + * @param limit - The maximum number of items to return. + * @returns The created {@link QueryLimitConstraint}. + */ +export declare function limitToLast(limit: number): QueryLimitConstraint; +/** + * A `QueryStartAtConstraint` is used to exclude documents from the start of a + * result set returned by a Firestore query. + * `QueryStartAtConstraint`s are created by invoking {@link (startAt:1)} or + * {@link (startAfter:1)} and can then be passed to {@link (query:1)} to create a + * new query instance that also contains this `QueryStartAtConstraint`. + */ +export declare class QueryStartAtConstraint extends QueryConstraint { + /** The type of this query constraint */ + readonly type: 'startAt' | 'startAfter'; + private readonly _docOrFields; + private readonly _inclusive; + /** + * @internal + */ + protected constructor( + /** The type of this query constraint */ + type: 'startAt' | 'startAfter', _docOrFields: Array>, _inclusive: boolean); + static _create(type: 'startAt' | 'startAfter', _docOrFields: Array>, _inclusive: boolean): QueryStartAtConstraint; + _apply(query: Query): Query; +} +/** + * Creates a {@link QueryStartAtConstraint} that modifies the result set to + * start at the provided document (inclusive). The starting position is relative + * to the order of the query. The document must contain all of the fields + * provided in the `orderBy` of this query. + * + * @param snapshot - The snapshot of the document to start at. + * @returns A {@link QueryStartAtConstraint} to pass to `query()`. + */ +export declare function startAt(snapshot: DocumentSnapshot): QueryStartAtConstraint; +/** + * Creates a {@link QueryStartAtConstraint} that modifies the result set to + * start at the provided fields relative to the order of the query. The order of + * the field values must match the order of the order by clauses of the query. + * + * @param fieldValues - The field values to start this query at, in order + * of the query's order by. + * @returns A {@link QueryStartAtConstraint} to pass to `query()`. + */ +export declare function startAt(...fieldValues: unknown[]): QueryStartAtConstraint; +/** + * Creates a {@link QueryStartAtConstraint} that modifies the result set to + * start after the provided document (exclusive). The starting position is + * relative to the order of the query. The document must contain all of the + * fields provided in the orderBy of the query. + * + * @param snapshot - The snapshot of the document to start after. + * @returns A {@link QueryStartAtConstraint} to pass to `query()` + */ +export declare function startAfter(snapshot: DocumentSnapshot): QueryStartAtConstraint; +/** + * Creates a {@link QueryStartAtConstraint} that modifies the result set to + * start after the provided fields relative to the order of the query. The order + * of the field values must match the order of the order by clauses of the query. + * + * @param fieldValues - The field values to start this query after, in order + * of the query's order by. + * @returns A {@link QueryStartAtConstraint} to pass to `query()` + */ +export declare function startAfter(...fieldValues: unknown[]): QueryStartAtConstraint; +/** + * A `QueryEndAtConstraint` is used to exclude documents from the end of a + * result set returned by a Firestore query. + * `QueryEndAtConstraint`s are created by invoking {@link (endAt:1)} or + * {@link (endBefore:1)} and can then be passed to {@link (query:1)} to create a new + * query instance that also contains this `QueryEndAtConstraint`. + */ +export declare class QueryEndAtConstraint extends QueryConstraint { + /** The type of this query constraint */ + readonly type: 'endBefore' | 'endAt'; + private readonly _docOrFields; + private readonly _inclusive; + /** + * @internal + */ + protected constructor( + /** The type of this query constraint */ + type: 'endBefore' | 'endAt', _docOrFields: Array>, _inclusive: boolean); + static _create(type: 'endBefore' | 'endAt', _docOrFields: Array>, _inclusive: boolean): QueryEndAtConstraint; + _apply(query: Query): Query; +} +/** + * Creates a {@link QueryEndAtConstraint} that modifies the result set to end + * before the provided document (exclusive). The end position is relative to the + * order of the query. The document must contain all of the fields provided in + * the orderBy of the query. + * + * @param snapshot - The snapshot of the document to end before. + * @returns A {@link QueryEndAtConstraint} to pass to `query()` + */ +export declare function endBefore(snapshot: DocumentSnapshot): QueryEndAtConstraint; +/** + * Creates a {@link QueryEndAtConstraint} that modifies the result set to end + * before the provided fields relative to the order of the query. The order of + * the field values must match the order of the order by clauses of the query. + * + * @param fieldValues - The field values to end this query before, in order + * of the query's order by. + * @returns A {@link QueryEndAtConstraint} to pass to `query()` + */ +export declare function endBefore(...fieldValues: unknown[]): QueryEndAtConstraint; +/** + * Creates a {@link QueryEndAtConstraint} that modifies the result set to end at + * the provided document (inclusive). The end position is relative to the order + * of the query. The document must contain all of the fields provided in the + * orderBy of the query. + * + * @param snapshot - The snapshot of the document to end at. + * @returns A {@link QueryEndAtConstraint} to pass to `query()` + */ +export declare function endAt(snapshot: DocumentSnapshot): QueryEndAtConstraint; +/** + * Creates a {@link QueryEndAtConstraint} that modifies the result set to end at + * the provided fields relative to the order of the query. The order of the field + * values must match the order of the order by clauses of the query. + * + * @param fieldValues - The field values to end this query at, in order + * of the query's order by. + * @returns A {@link QueryEndAtConstraint} to pass to `query()` + */ +export declare function endAt(...fieldValues: unknown[]): QueryEndAtConstraint; +export declare function newQueryFilter(query: InternalQuery, methodName: string, dataReader: UserDataReader, databaseId: DatabaseId, fieldPath: InternalFieldPath, op: Operator, value: unknown): FieldFilter; +export declare function newQueryOrderBy(query: InternalQuery, fieldPath: InternalFieldPath, direction: Direction): OrderBy; +/** + * Create a `Bound` from a query and a document. + * + * Note that the `Bound` will always include the key of the document + * and so only the provided document will compare equal to the returned + * position. + * + * Will throw if the document does not contain all fields of the order by + * of the query or if any of the fields in the order by are an uncommitted + * server timestamp. + */ +export declare function newQueryBoundFromDocument(query: InternalQuery, databaseId: DatabaseId, methodName: string, doc: Document | null, inclusive: boolean): Bound; +/** + * Converts a list of field values to a `Bound` for the given query. + */ +export declare function newQueryBoundFromFields(query: InternalQuery, databaseId: DatabaseId, dataReader: UserDataReader, methodName: string, values: unknown[], inclusive: boolean): Bound; +export declare function validateQueryFilterConstraint(functionName: string, queryConstraint: AppliableConstraint): void; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/reference.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/reference.d.ts new file mode 100644 index 0000000..fd89e5a --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/reference.d.ts @@ -0,0 +1,362 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Query as InternalQuery } from '../core/query'; +import { DocumentKey } from '../model/document_key'; +import { ResourcePath } from '../model/path'; +import { Property } from '../util/json_validation'; +import { Firestore } from './database'; +import { FieldPath } from './field_path'; +import { FieldValue } from './field_value'; +import { FirestoreDataConverter } from './snapshot'; +import { NestedUpdateFields, Primitive } from './types'; +/** + * Document data (for use with {@link @firebase/firestore/lite#(setDoc:1)}) consists of fields mapped to + * values. + */ +export interface DocumentData { + /** A mapping between a field and its value. */ + [field: string]: any; +} +/** + * Similar to TypeScript's `Partial`, but allows nested fields to be + * omitted and FieldValues to be passed in as property values. + */ +export type PartialWithFieldValue = Partial | (T extends Primitive ? T : T extends {} ? { + [K in keyof T]?: PartialWithFieldValue | FieldValue; +} : never); +/** + * Allows FieldValues to be passed in as a property value while maintaining + * type safety. + */ +export type WithFieldValue = T | (T extends Primitive ? T : T extends {} ? { + [K in keyof T]: WithFieldValue | FieldValue; +} : never); +/** + * Update data (for use with {@link (updateDoc:1)}) that consists of field paths + * (e.g. 'foo' or 'foo.baz') mapped to values. Fields that contain dots + * reference nested fields within the document. FieldValues can be passed in + * as property values. + */ +export type UpdateData = T extends Primitive ? T : T extends {} ? { + [K in keyof T]?: UpdateData | FieldValue; +} & NestedUpdateFields : Partial; +/** + * An options object that configures the behavior of {@link @firebase/firestore/lite#(setDoc:1)}, {@link + * @firebase/firestore/lite#(WriteBatch.set:1)} and {@link @firebase/firestore/lite#(Transaction.set:1)} calls. These calls can be + * configured to perform granular merges instead of overwriting the target + * documents in their entirety by providing a `SetOptions` with `merge: true`. + * + * @param merge - Changes the behavior of a `setDoc()` call to only replace the + * values specified in its data argument. Fields omitted from the `setDoc()` + * call remain untouched. If your input sets any field to an empty map, all + * nested fields are overwritten. + * @param mergeFields - Changes the behavior of `setDoc()` calls to only replace + * the specified field paths. Any field path that is not specified is ignored + * and remains untouched. If your input sets any field to an empty map, all + * nested fields are overwritten. + */ +export type SetOptions = { + readonly merge?: boolean; +} | { + readonly mergeFields?: Array; +}; +/** + * A `Query` refers to a query which you can read or listen to. You can also + * construct refined `Query` objects by adding filters and ordering. + */ +export declare class Query { + /** + * If provided, the `FirestoreDataConverter` associated with this instance. + */ + readonly converter: FirestoreDataConverter | null; + readonly _query: InternalQuery; + /** The type of this Firestore reference. */ + readonly type: 'query' | 'collection'; + /** + * The `Firestore` instance for the Firestore database (useful for performing + * transactions, etc.). + */ + readonly firestore: Firestore; + /** @hideconstructor protected */ + constructor(firestore: Firestore, + /** + * If provided, the `FirestoreDataConverter` associated with this instance. + */ + converter: FirestoreDataConverter | null, _query: InternalQuery); + /** + * Removes the current converter. + * + * @param converter - `null` removes the current converter. + * @returns A `Query` that does not use a + * converter. + */ + withConverter(converter: null): Query; + /** + * Applies a custom data converter to this query, allowing you to use your own + * custom model objects with Firestore. When you call {@link getDocs} with + * the returned query, the provided converter will convert between Firestore + * data of type `NewDbModelType` and your custom type `NewAppModelType`. + * + * @param converter - Converts objects to and from Firestore. + * @returns A `Query` that uses the provided converter. + */ + withConverter(converter: FirestoreDataConverter): Query; +} +/** + * A `DocumentReference` refers to a document location in a Firestore database + * and can be used to write, read, or listen to the location. The document at + * the referenced location may or may not exist. + */ +export declare class DocumentReference { + /** + * If provided, the `FirestoreDataConverter` associated with this instance. + */ + readonly converter: FirestoreDataConverter | null; + readonly _key: DocumentKey; + /** The type of this Firestore reference. */ + readonly type = "document"; + /** + * The {@link Firestore} instance the document is in. + * This is useful for performing transactions, for example. + */ + readonly firestore: Firestore; + /** @hideconstructor */ + constructor(firestore: Firestore, + /** + * If provided, the `FirestoreDataConverter` associated with this instance. + */ + converter: FirestoreDataConverter | null, _key: DocumentKey); + get _path(): ResourcePath; + /** + * The document's identifier within its collection. + */ + get id(): string; + /** + * A string representing the path of the referenced document (relative + * to the root of the database). + */ + get path(): string; + /** + * The collection this `DocumentReference` belongs to. + */ + get parent(): CollectionReference; + /** + * Applies a custom data converter to this `DocumentReference`, allowing you + * to use your own custom model objects with Firestore. When you call {@link + * @firebase/firestore/lite#(setDoc:1)}, {@link @firebase/firestore/lite#getDoc}, etc. with the returned `DocumentReference` + * instance, the provided converter will convert between Firestore data of + * type `NewDbModelType` and your custom type `NewAppModelType`. + * + * @param converter - Converts objects to and from Firestore. + * @returns A `DocumentReference` that uses the provided converter. + */ + withConverter(converter: FirestoreDataConverter): DocumentReference; + /** + * Removes the current converter. + * + * @param converter - `null` removes the current converter. + * @returns A `DocumentReference` that does not + * use a converter. + */ + withConverter(converter: null): DocumentReference; + static _jsonSchemaVersion: string; + static _jsonSchema: { + type: Property<"string">; + referencePath: Property<"string">; + }; + /** + * Returns a JSON-serializable representation of this `DocumentReference` instance. + * + * @returns a JSON representation of this object. + */ + toJSON(): object; + /** + * Builds a `DocumentReference` instance from a JSON object created by + * {@link DocumentReference.toJSON}. + * + * @param firestore - The {@link Firestore} instance the snapshot should be loaded for. + * @param json a JSON object represention of a `DocumentReference` instance + * @returns an instance of {@link DocumentReference} if the JSON object could be parsed. Throws a + * {@link FirestoreError} if an error occurs. + */ + static fromJSON(firestore: Firestore, json: object): DocumentReference; + /** + * Builds a `DocumentReference` instance from a JSON object created by + * {@link DocumentReference.toJSON}. + * + * @param firestore - The {@link Firestore} instance the snapshot should be loaded for. + * @param json a JSON object represention of a `DocumentReference` instance + * @param converter - Converts objects to and from Firestore. + * @returns an instance of {@link DocumentReference} if the JSON object could be parsed. Throws a + * {@link FirestoreError} if an error occurs. + */ + static fromJSON(firestore: Firestore, json: object, converter: FirestoreDataConverter): DocumentReference; +} +/** + * A `CollectionReference` object can be used for adding documents, getting + * document references, and querying for documents (using {@link (query:1)}). + */ +export declare class CollectionReference extends Query { + readonly _path: ResourcePath; + /** The type of this Firestore reference. */ + readonly type = "collection"; + /** @hideconstructor */ + constructor(firestore: Firestore, converter: FirestoreDataConverter | null, _path: ResourcePath); + /** The collection's identifier. */ + get id(): string; + /** + * A string representing the path of the referenced collection (relative + * to the root of the database). + */ + get path(): string; + /** + * A reference to the containing `DocumentReference` if this is a + * subcollection. If this isn't a subcollection, the reference is null. + */ + get parent(): DocumentReference | null; + /** + * Applies a custom data converter to this `CollectionReference`, allowing you + * to use your own custom model objects with Firestore. When you call {@link + * addDoc} with the returned `CollectionReference` instance, the provided + * converter will convert between Firestore data of type `NewDbModelType` and + * your custom type `NewAppModelType`. + * + * @param converter - Converts objects to and from Firestore. + * @returns A `CollectionReference` that uses the provided converter. + */ + withConverter(converter: FirestoreDataConverter): CollectionReference; + /** + * Removes the current converter. + * + * @param converter - `null` removes the current converter. + * @returns A `CollectionReference` that does not + * use a converter. + */ + withConverter(converter: null): CollectionReference; +} +/** + * Gets a `CollectionReference` instance that refers to the collection at + * the specified absolute path. + * + * @param firestore - A reference to the root `Firestore` instance. + * @param path - A slash-separated path to a collection. + * @param pathSegments - Additional path segments to apply relative to the first + * argument. + * @throws If the final path has an even number of segments and does not point + * to a collection. + * @returns The `CollectionReference` instance. + */ +export declare function collection(firestore: Firestore, path: string, ...pathSegments: string[]): CollectionReference; +/** + * Gets a `CollectionReference` instance that refers to a subcollection of + * `reference` at the specified relative path. + * + * @param reference - A reference to a collection. + * @param path - A slash-separated path to a collection. + * @param pathSegments - Additional path segments to apply relative to the first + * argument. + * @throws If the final path has an even number of segments and does not point + * to a collection. + * @returns The `CollectionReference` instance. + */ +export declare function collection(reference: CollectionReference, path: string, ...pathSegments: string[]): CollectionReference; +/** + * Gets a `CollectionReference` instance that refers to a subcollection of + * `reference` at the specified relative path. + * + * @param reference - A reference to a Firestore document. + * @param path - A slash-separated path to a collection. + * @param pathSegments - Additional path segments that will be applied relative + * to the first argument. + * @throws If the final path has an even number of segments and does not point + * to a collection. + * @returns The `CollectionReference` instance. + */ +export declare function collection(reference: DocumentReference, path: string, ...pathSegments: string[]): CollectionReference; +/** + * Creates and returns a new `Query` instance that includes all documents in the + * database that are contained in a collection or subcollection with the + * given `collectionId`. + * + * @param firestore - A reference to the root `Firestore` instance. + * @param collectionId - Identifies the collections to query over. Every + * collection or subcollection with this ID as the last segment of its path + * will be included. Cannot contain a slash. + * @returns The created `Query`. + */ +export declare function collectionGroup(firestore: Firestore, collectionId: string): Query; +/** + * Gets a `DocumentReference` instance that refers to the document at the + * specified absolute path. + * + * @param firestore - A reference to the root `Firestore` instance. + * @param path - A slash-separated path to a document. + * @param pathSegments - Additional path segments that will be applied relative + * to the first argument. + * @throws If the final path has an odd number of segments and does not point to + * a document. + * @returns The `DocumentReference` instance. + */ +export declare function doc(firestore: Firestore, path: string, ...pathSegments: string[]): DocumentReference; +/** + * Gets a `DocumentReference` instance that refers to a document within + * `reference` at the specified relative path. If no path is specified, an + * automatically-generated unique ID will be used for the returned + * `DocumentReference`. + * + * @param reference - A reference to a collection. + * @param path - A slash-separated path to a document. Has to be omitted to use + * auto-generated IDs. + * @param pathSegments - Additional path segments that will be applied relative + * to the first argument. + * @throws If the final path has an odd number of segments and does not point to + * a document. + * @returns The `DocumentReference` instance. + */ +export declare function doc(reference: CollectionReference, path?: string, ...pathSegments: string[]): DocumentReference; +/** + * Gets a `DocumentReference` instance that refers to a document within + * `reference` at the specified relative path. + * + * @param reference - A reference to a Firestore document. + * @param path - A slash-separated path to a document. + * @param pathSegments - Additional path segments that will be applied relative + * to the first argument. + * @throws If the final path has an odd number of segments and does not point to + * a document. + * @returns The `DocumentReference` instance. + */ +export declare function doc(reference: DocumentReference, path: string, ...pathSegments: string[]): DocumentReference; +/** + * Returns true if the provided references are equal. + * + * @param left - A reference to compare. + * @param right - A reference to compare. + * @returns true if the references point to the same location in the same + * Firestore database. + */ +export declare function refEqual(left: DocumentReference | CollectionReference, right: DocumentReference | CollectionReference): boolean; +/** + * Returns true if the provided queries point to the same collection and apply + * the same constraints. + * + * @param left - A `Query` to compare. + * @param right - A `Query` to compare. + * @returns true if the references point to the same location in the same + * Firestore database. + */ +export declare function queryEqual(left: Query, right: Query): boolean; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/reference_impl.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/reference_impl.d.ts new file mode 100644 index 0000000..724ae99 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/reference_impl.d.ts @@ -0,0 +1,172 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { DocumentData as PublicDocumentData, SetOptions as PublicSetOptions } from '@firebase/firestore-types'; +import { ByteString } from '../util/byte_string'; +import { Bytes } from './bytes'; +import { Firestore } from './database'; +import { FieldPath } from './field_path'; +import { CollectionReference, DocumentData, DocumentReference, PartialWithFieldValue, Query, SetOptions, UpdateData, WithFieldValue } from './reference'; +import { DocumentSnapshot, QuerySnapshot } from './snapshot'; +import { UntypedFirestoreDataConverter } from './user_data_reader'; +import { AbstractUserDataWriter } from './user_data_writer'; +/** + * Converts custom model object of type T into `DocumentData` by applying the + * converter if it exists. + * + * This function is used when converting user objects to `DocumentData` + * because we want to provide the user with a more specific error message if + * their `set()` or fails due to invalid data originating from a `toFirestore()` + * call. + */ +export declare function applyFirestoreDataConverter(converter: UntypedFirestoreDataConverter | null, value: WithFieldValue | PartialWithFieldValue, options?: PublicSetOptions): PublicDocumentData; +export declare class LiteUserDataWriter extends AbstractUserDataWriter { + protected firestore: Firestore; + constructor(firestore: Firestore); + protected convertBytes(bytes: ByteString): Bytes; + protected convertReference(name: string): DocumentReference; +} +/** + * Reads the document referred to by the specified document reference. + * + * All documents are directly fetched from the server, even if the document was + * previously read or modified. Recent modifications are only reflected in the + * retrieved `DocumentSnapshot` if they have already been applied by the + * backend. If the client is offline, the read fails. If you like to use + * caching or see local modifications, please use the full Firestore SDK. + * + * @param reference - The reference of the document to fetch. + * @returns A Promise resolved with a `DocumentSnapshot` containing the current + * document contents. + */ +export declare function getDoc(reference: DocumentReference): Promise>; +/** + * Executes the query and returns the results as a {@link QuerySnapshot}. + * + * All queries are executed directly by the server, even if the query was + * previously executed. Recent modifications are only reflected in the retrieved + * results if they have already been applied by the backend. If the client is + * offline, the operation fails. To see previously cached result and local + * modifications, use the full Firestore SDK. + * + * @param query - The `Query` to execute. + * @returns A Promise that will be resolved with the results of the query. + */ +export declare function getDocs(query: Query): Promise>; +/** + * Writes to the document referred to by the specified `DocumentReference`. If + * the document does not yet exist, it will be created. + * + * The result of this write will only be reflected in document reads that occur + * after the returned promise resolves. If the client is offline, the + * write fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @param reference - A reference to the document to write. + * @param data - A map of the fields and values for the document. + * @throws Error - If the provided input is not a valid Firestore document. + * @returns A `Promise` resolved once the data has been successfully written + * to the backend. + */ +export declare function setDoc(reference: DocumentReference, data: WithFieldValue): Promise; +/** + * Writes to the document referred to by the specified `DocumentReference`. If + * the document does not yet exist, it will be created. If you provide `merge` + * or `mergeFields`, the provided data can be merged into an existing document. + * + * The result of this write will only be reflected in document reads that occur + * after the returned promise resolves. If the client is offline, the + * write fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @param reference - A reference to the document to write. + * @param data - A map of the fields and values for the document. + * @param options - An object to configure the set behavior. + * @throws Error - If the provided input is not a valid Firestore document. + * @returns A `Promise` resolved once the data has been successfully written + * to the backend. + */ +export declare function setDoc(reference: DocumentReference, data: PartialWithFieldValue, options: SetOptions): Promise; +/** + * Updates fields in the document referred to by the specified + * `DocumentReference`. The update will fail if applied to a document that does + * not exist. + * + * The result of this update will only be reflected in document reads that occur + * after the returned promise resolves. If the client is offline, the + * update fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @param reference - A reference to the document to update. + * @param data - An object containing the fields and values with which to + * update the document. Fields can contain dots to reference nested fields + * within the document. + * @throws Error - If the provided input is not valid Firestore data. + * @returns A `Promise` resolved once the data has been successfully written + * to the backend. + */ +export declare function updateDoc(reference: DocumentReference, data: UpdateData): Promise; +/** + * Updates fields in the document referred to by the specified + * `DocumentReference` The update will fail if applied to a document that does + * not exist. + * + * Nested fields can be updated by providing dot-separated field path + * strings or by providing `FieldPath` objects. + * + * The result of this update will only be reflected in document reads that occur + * after the returned promise resolves. If the client is offline, the + * update fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @param reference - A reference to the document to update. + * @param field - The first field to update. + * @param value - The first value. + * @param moreFieldsAndValues - Additional key value pairs. + * @throws Error - If the provided input is not valid Firestore data. + * @returns A `Promise` resolved once the data has been successfully written + * to the backend. + */ +export declare function updateDoc(reference: DocumentReference, field: string | FieldPath, value: unknown, ...moreFieldsAndValues: unknown[]): Promise; +/** + * Deletes the document referred to by the specified `DocumentReference`. + * + * The deletion will only be reflected in document reads that occur after the + * returned promise resolves. If the client is offline, the + * delete fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @param reference - A reference to the document to delete. + * @returns A `Promise` resolved once the document has been successfully + * deleted from the backend. + */ +export declare function deleteDoc(reference: DocumentReference): Promise; +/** + * Add a new document to specified `CollectionReference` with the given data, + * assigning it a document ID automatically. + * + * The result of this write will only be reflected in document reads that occur + * after the returned promise resolves. If the client is offline, the + * write fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @param reference - A reference to the collection to add this document to. + * @param data - An Object containing the data for the new document. + * @throws Error - If the provided input is not a valid Firestore document. + * @returns A `Promise` resolved with a `DocumentReference` pointing to the + * newly created document after it has been written to the backend. + */ +export declare function addDoc(reference: CollectionReference, data: WithFieldValue): Promise>; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/settings.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/settings.d.ts new file mode 100644 index 0000000..e86bdbe --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/settings.d.ts @@ -0,0 +1,77 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { EmulatorMockTokenOptions } from '@firebase/util'; +import { FirestoreLocalCache } from '../api/cache_config'; +import { CredentialsSettings } from '../api/credentials'; +import { ExperimentalLongPollingOptions } from '../api/long_polling_options'; +export declare const DEFAULT_HOST = "firestore.googleapis.com"; +export declare const DEFAULT_SSL = true; +/** + * Specifies custom configurations for your Cloud Firestore instance. + * You must set these before invoking any other methods. + */ +export interface FirestoreSettings { + /** The hostname to connect to. */ + host?: string; + /** Whether to use SSL when connecting. */ + ssl?: boolean; + /** + * Whether to skip nested properties that are set to `undefined` during + * object serialization. If set to `true`, these properties are skipped + * and not written to Firestore. If set to `false` or omitted, the SDK + * throws an exception when it encounters properties of type `undefined`. + */ + ignoreUndefinedProperties?: boolean; +} +/** + * @internal + * Undocumented, private additional settings not exposed in our public API. + */ +export interface PrivateSettings extends FirestoreSettings { + credentials?: CredentialsSettings; + cacheSizeBytes?: number; + experimentalForceLongPolling?: boolean; + experimentalAutoDetectLongPolling?: boolean; + experimentalLongPollingOptions?: ExperimentalLongPollingOptions; + useFetchStreams?: boolean; + emulatorOptions?: { + mockUserToken?: EmulatorMockTokenOptions | string; + }; + localCache?: FirestoreLocalCache; +} +/** + * A concrete type describing all the values that can be applied via a + * user-supplied `FirestoreSettings` object. This is a separate type so that + * defaults can be supplied and the value can be checked for equality. + */ +export declare class FirestoreSettingsImpl { + /** The hostname to connect to. */ + readonly host: string; + /** Whether to use SSL when connecting. */ + readonly ssl: boolean; + readonly cacheSizeBytes: number; + readonly experimentalForceLongPolling: boolean; + readonly experimentalAutoDetectLongPolling: boolean; + readonly experimentalLongPollingOptions: ExperimentalLongPollingOptions; + readonly ignoreUndefinedProperties: boolean; + readonly useFetchStreams: boolean; + readonly localCache?: FirestoreLocalCache; + readonly isUsingEmulator: boolean; + credentials?: any; + constructor(settings: PrivateSettings); + isEqual(other: FirestoreSettingsImpl): boolean; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/snapshot.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/snapshot.d.ts new file mode 100644 index 0000000..312e3f3 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/snapshot.d.ts @@ -0,0 +1,367 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Compat } from '@firebase/util'; +import { Document } from '../model/document'; +import { DocumentKey } from '../model/document_key'; +import { FieldPath as InternalFieldPath } from '../model/path'; +import { Firestore } from './database'; +import { FieldPath } from './field_path'; +import { DocumentData, DocumentReference, PartialWithFieldValue, Query, SetOptions, WithFieldValue } from './reference'; +import { UntypedFirestoreDataConverter } from './user_data_reader'; +import { AbstractUserDataWriter } from './user_data_writer'; +/** + * Converter used by `withConverter()` to transform user objects of type + * `AppModelType` into Firestore data of type `DbModelType`. + * + * Using the converter allows you to specify generic type arguments when + * storing and retrieving objects from Firestore. + * + * In this context, an "AppModel" is a class that is used in an application to + * package together related information and functionality. Such a class could, + * for example, have properties with complex, nested data types, properties used + * for memoization, properties of types not supported by Firestore (such as + * `symbol` and `bigint`), and helper functions that perform compound + * operations. Such classes are not suitable and/or possible to store into a + * Firestore database. Instead, instances of such classes need to be converted + * to "plain old JavaScript objects" (POJOs) with exclusively primitive + * properties, potentially nested inside other POJOs or arrays of POJOs. In this + * context, this type is referred to as the "DbModel" and would be an object + * suitable for persisting into Firestore. For convenience, applications can + * implement `FirestoreDataConverter` and register the converter with Firestore + * objects, such as `DocumentReference` or `Query`, to automatically convert + * `AppModel` to `DbModel` when storing into Firestore, and convert `DbModel` + * to `AppModel` when retrieving from Firestore. + * + * @example + * + * Simple Example + * + * ```typescript + * const numberConverter = { + * toFirestore(value: WithFieldValue) { + * return { value }; + * }, + * fromFirestore(snapshot: QueryDocumentSnapshot, options: SnapshotOptions) { + * return snapshot.data(options).value as number; + * } + * }; + * + * async function simpleDemo(db: Firestore): Promise { + * const documentRef = doc(db, 'values/value123').withConverter(numberConverter); + * + * // converters are used with `setDoc`, `addDoc`, and `getDoc` + * await setDoc(documentRef, 42); + * const snapshot1 = await getDoc(documentRef); + * assertEqual(snapshot1.data(), 42); + * + * // converters are not used when writing data with `updateDoc` + * await updateDoc(documentRef, { value: 999 }); + * const snapshot2 = await getDoc(documentRef); + * assertEqual(snapshot2.data(), 999); + * } + * ``` + * + * Advanced Example + * + * ```typescript + * // The Post class is a model that is used by our application. + * // This class may have properties and methods that are specific + * // to our application execution, which do not need to be persisted + * // to Firestore. + * class Post { + * constructor( + * readonly title: string, + * readonly author: string, + * readonly lastUpdatedMillis: number + * ) {} + * toString(): string { + * return `${this.title} by ${this.author}`; + * } + * } + * + * // The PostDbModel represents how we want our posts to be stored + * // in Firestore. This DbModel has different properties (`ttl`, + * // `aut`, and `lut`) from the Post class we use in our application. + * interface PostDbModel { + * ttl: string; + * aut: { firstName: string; lastName: string }; + * lut: Timestamp; + * } + * + * // The `PostConverter` implements `FirestoreDataConverter` and specifies + * // how the Firestore SDK can convert `Post` objects to `PostDbModel` + * // objects and vice versa. + * class PostConverter implements FirestoreDataConverter { + * toFirestore(post: WithFieldValue): WithFieldValue { + * return { + * ttl: post.title, + * aut: this._autFromAuthor(post.author), + * lut: this._lutFromLastUpdatedMillis(post.lastUpdatedMillis) + * }; + * } + * + * fromFirestore(snapshot: QueryDocumentSnapshot, options: SnapshotOptions): Post { + * const data = snapshot.data(options) as PostDbModel; + * const author = `${data.aut.firstName} ${data.aut.lastName}`; + * return new Post(data.ttl, author, data.lut.toMillis()); + * } + * + * _autFromAuthor( + * author: string | FieldValue + * ): { firstName: string; lastName: string } | FieldValue { + * if (typeof author !== 'string') { + * // `author` is a FieldValue, so just return it. + * return author; + * } + * const [firstName, lastName] = author.split(' '); + * return {firstName, lastName}; + * } + * + * _lutFromLastUpdatedMillis( + * lastUpdatedMillis: number | FieldValue + * ): Timestamp | FieldValue { + * if (typeof lastUpdatedMillis !== 'number') { + * // `lastUpdatedMillis` must be a FieldValue, so just return it. + * return lastUpdatedMillis; + * } + * return Timestamp.fromMillis(lastUpdatedMillis); + * } + * } + * + * async function advancedDemo(db: Firestore): Promise { + * // Create a `DocumentReference` with a `FirestoreDataConverter`. + * const documentRef = doc(db, 'posts/post123').withConverter(new PostConverter()); + * + * // The `data` argument specified to `setDoc()` is type checked by the + * // TypeScript compiler to be compatible with `Post`. Since the `data` + * // argument is typed as `WithFieldValue` rather than just `Post`, + * // this allows properties of the `data` argument to also be special + * // Firestore values that perform server-side mutations, such as + * // `arrayRemove()`, `deleteField()`, and `serverTimestamp()`. + * await setDoc(documentRef, { + * title: 'My Life', + * author: 'Foo Bar', + * lastUpdatedMillis: serverTimestamp() + * }); + * + * // The TypeScript compiler will fail to compile if the `data` argument to + * // `setDoc()` is _not_ compatible with `WithFieldValue`. This + * // type checking prevents the caller from specifying objects with incorrect + * // properties or property values. + * // @ts-expect-error "Argument of type { ttl: string; } is not assignable + * // to parameter of type WithFieldValue" + * await setDoc(documentRef, { ttl: 'The Title' }); + * + * // When retrieving a document with `getDoc()` the `DocumentSnapshot` + * // object's `data()` method returns a `Post`, rather than a generic object, + * // which would have been returned if the `DocumentReference` did _not_ have a + * // `FirestoreDataConverter` attached to it. + * const snapshot1: DocumentSnapshot = await getDoc(documentRef); + * const post1: Post = snapshot1.data()!; + * if (post1) { + * assertEqual(post1.title, 'My Life'); + * assertEqual(post1.author, 'Foo Bar'); + * } + * + * // The `data` argument specified to `updateDoc()` is type checked by the + * // TypeScript compiler to be compatible with `PostDbModel`. Note that + * // unlike `setDoc()`, whose `data` argument must be compatible with `Post`, + * // the `data` argument to `updateDoc()` must be compatible with + * // `PostDbModel`. Similar to `setDoc()`, since the `data` argument is typed + * // as `WithFieldValue` rather than just `PostDbModel`, this + * // allows properties of the `data` argument to also be those special + * // Firestore values, like `arrayRemove()`, `deleteField()`, and + * // `serverTimestamp()`. + * await updateDoc(documentRef, { + * 'aut.firstName': 'NewFirstName', + * lut: serverTimestamp() + * }); + * + * // The TypeScript compiler will fail to compile if the `data` argument to + * // `updateDoc()` is _not_ compatible with `WithFieldValue`. + * // This type checking prevents the caller from specifying objects with + * // incorrect properties or property values. + * // @ts-expect-error "Argument of type { title: string; } is not assignable + * // to parameter of type WithFieldValue" + * await updateDoc(documentRef, { title: 'New Title' }); + * const snapshot2: DocumentSnapshot = await getDoc(documentRef); + * const post2: Post = snapshot2.data()!; + * if (post2) { + * assertEqual(post2.title, 'My Life'); + * assertEqual(post2.author, 'NewFirstName Bar'); + * } + * } + * ``` + */ +export interface FirestoreDataConverter { + /** + * Called by the Firestore SDK to convert a custom model object of type + * `AppModelType` into a plain JavaScript object (suitable for writing + * directly to the Firestore database) of type `DbModelType`. Used with + * {@link @firebase/firestore/lite#(setDoc:1)}, + * {@link @firebase/firestore/lite#(WriteBatch.set:1)} and + * {@link @firebase/firestore/lite#(Transaction.set:1)}. + * + * The `WithFieldValue` type extends `T` to also allow FieldValues such as + * {@link (deleteField:1)} to be used as property values. + */ + toFirestore(modelObject: WithFieldValue): WithFieldValue; + /** + * Called by the Firestore SDK to convert a custom model object of type + * `AppModelType` into a plain JavaScript object (suitable for writing + * directly to the Firestore database) of type `DbModelType`. Used with + * {@link @firebase/firestore/lite#(setDoc:1)}, + * {@link @firebase/firestore/lite#(WriteBatch.set:1)} and + * {@link @firebase/firestore/lite#(Transaction.set:1)} with `merge:true` + * or `mergeFields`. + * + * The `PartialWithFieldValue` type extends `Partial` to allow + * FieldValues such as {@link (arrayUnion:1)} to be used as property values. + * It also supports nested `Partial` by allowing nested fields to be + * omitted. + */ + toFirestore(modelObject: PartialWithFieldValue, options: SetOptions): PartialWithFieldValue; + /** + * Called by the Firestore SDK to convert Firestore data into an object of + * type `AppModelType`. You can access your data by calling: + * `snapshot.data()`. + * + * + * Generally, the data returned from `snapshot.data()` can be cast to + * `DbModelType`; however, this is not guaranteed because Firestore does not + * enforce a schema on the database. For example, writes from a previous + * version of the application or writes from another client that did not use a + * type converter could have written data with different properties and/or + * property types. The implementation will need to choose whether to + * gracefully recover from non-conforming data or throw an error. + * + * @param snapshot - A `QueryDocumentSnapshot` containing your data and + * metadata. + */ + fromFirestore(snapshot: QueryDocumentSnapshot): AppModelType; +} +/** + * A `DocumentSnapshot` contains data read from a document in your Firestore + * database. The data can be extracted with `.data()` or `.get()` to + * get a specific field. + * + * For a `DocumentSnapshot` that points to a non-existing document, any data + * access will return 'undefined'. You can use the `exists()` method to + * explicitly verify a document's existence. + */ +export declare class DocumentSnapshot { + _firestore: Firestore; + _userDataWriter: AbstractUserDataWriter; + _key: DocumentKey; + _document: Document | null; + _converter: UntypedFirestoreDataConverter | null; + /** @hideconstructor protected */ + constructor(_firestore: Firestore, _userDataWriter: AbstractUserDataWriter, _key: DocumentKey, _document: Document | null, _converter: UntypedFirestoreDataConverter | null); + /** Property of the `DocumentSnapshot` that provides the document's ID. */ + get id(): string; + /** + * The `DocumentReference` for the document included in the `DocumentSnapshot`. + */ + get ref(): DocumentReference; + /** + * Signals whether or not the document at the snapshot's location exists. + * + * @returns true if the document exists. + */ + exists(): this is QueryDocumentSnapshot; + /** + * Retrieves all fields in the document as an `Object`. Returns `undefined` if + * the document doesn't exist. + * + * @returns An `Object` containing all fields in the document or `undefined` + * if the document doesn't exist. + */ + data(): AppModelType | undefined; + /** + * Retrieves the field specified by `fieldPath`. Returns `undefined` if the + * document or field doesn't exist. + * + * @param fieldPath - The path (for example 'foo' or 'foo.bar') to a specific + * field. + * @returns The data at the specified field location or undefined if no such + * field exists in the document. + */ + get(fieldPath: string | FieldPath): any; +} +/** + * A `QueryDocumentSnapshot` contains data read from a document in your + * Firestore database as part of a query. The document is guaranteed to exist + * and its data can be extracted with `.data()` or `.get()` to get a + * specific field. + * + * A `QueryDocumentSnapshot` offers the same API surface as a + * `DocumentSnapshot`. Since query results contain only existing documents, the + * `exists` property will always be true and `data()` will never return + * 'undefined'. + */ +export declare class QueryDocumentSnapshot extends DocumentSnapshot { + /** + * Retrieves all fields in the document as an `Object`. + * + * @override + * @returns An `Object` containing all fields in the document. + */ + data(): AppModelType; +} +/** + * A `QuerySnapshot` contains zero or more `DocumentSnapshot` objects + * representing the results of a query. The documents can be accessed as an + * array via the `docs` property or enumerated using the `forEach` method. The + * number of documents can be determined via the `empty` and `size` + * properties. + */ +export declare class QuerySnapshot { + readonly _docs: Array>; + /** + * The query on which you called {@link getDocs} in order to get this + * `QuerySnapshot`. + */ + readonly query: Query; + /** @hideconstructor */ + constructor(_query: Query, _docs: Array>); + /** An array of all the documents in the `QuerySnapshot`. */ + get docs(): Array>; + /** The number of documents in the `QuerySnapshot`. */ + get size(): number; + /** True if there are no documents in the `QuerySnapshot`. */ + get empty(): boolean; + /** + * Enumerates all of the documents in the `QuerySnapshot`. + * + * @param callback - A callback to be called with a `QueryDocumentSnapshot` for + * each document in the snapshot. + * @param thisArg - The `this` binding for the callback. + */ + forEach(callback: (result: QueryDocumentSnapshot) => void, thisArg?: unknown): void; +} +/** + * Returns true if the provided snapshots are equal. + * + * @param left - A snapshot to compare. + * @param right - A snapshot to compare. + * @returns true if the snapshots are equal. + */ +export declare function snapshotEqual(left: DocumentSnapshot | QuerySnapshot, right: DocumentSnapshot | QuerySnapshot): boolean; +/** + * Helper that calls `fromDotSeparatedString()` but wraps any error thrown. + */ +export declare function fieldPathFromArgument(methodName: string, arg: string | FieldPath | Compat): InternalFieldPath; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/timestamp.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/timestamp.d.ts new file mode 100644 index 0000000..6d14f82 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/timestamp.d.ts @@ -0,0 +1,134 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Property } from '../util/json_validation'; +/** + * A `Timestamp` represents a point in time independent of any time zone or + * calendar, represented as seconds and fractions of seconds at nanosecond + * resolution in UTC Epoch time. + * + * It is encoded using the Proleptic Gregorian Calendar which extends the + * Gregorian calendar backwards to year one. It is encoded assuming all minutes + * are 60 seconds long, i.e. leap seconds are "smeared" so that no leap second + * table is needed for interpretation. Range is from 0001-01-01T00:00:00Z to + * 9999-12-31T23:59:59.999999999Z. + * + * For examples and further specifications, refer to the + * {@link https://github.com/google/protobuf/blob/master/src/google/protobuf/timestamp.proto | Timestamp definition}. + */ +export declare class Timestamp { + /** + * The number of seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z. + */ + readonly seconds: number; + /** + * The fractions of a second at nanosecond resolution.* + */ + readonly nanoseconds: number; + /** + * Creates a new timestamp with the current date, with millisecond precision. + * + * @returns a new timestamp representing the current date. + */ + static now(): Timestamp; + /** + * Creates a new timestamp from the given date. + * + * @param date - The date to initialize the `Timestamp` from. + * @returns A new `Timestamp` representing the same point in time as the given + * date. + */ + static fromDate(date: Date): Timestamp; + /** + * Creates a new timestamp from the given number of milliseconds. + * + * @param milliseconds - Number of milliseconds since Unix epoch + * 1970-01-01T00:00:00Z. + * @returns A new `Timestamp` representing the same point in time as the given + * number of milliseconds. + */ + static fromMillis(milliseconds: number): Timestamp; + /** + * Creates a new timestamp. + * + * @param seconds - The number of seconds of UTC time since Unix epoch + * 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to + * 9999-12-31T23:59:59Z inclusive. + * @param nanoseconds - The non-negative fractions of a second at nanosecond + * resolution. Negative second values with fractions must still have + * non-negative nanoseconds values that count forward in time. Must be + * from 0 to 999,999,999 inclusive. + */ + constructor( + /** + * The number of seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z. + */ + seconds: number, + /** + * The fractions of a second at nanosecond resolution.* + */ + nanoseconds: number); + /** + * Converts a `Timestamp` to a JavaScript `Date` object. This conversion + * causes a loss of precision since `Date` objects only support millisecond + * precision. + * + * @returns JavaScript `Date` object representing the same point in time as + * this `Timestamp`, with millisecond precision. + */ + toDate(): Date; + /** + * Converts a `Timestamp` to a numeric timestamp (in milliseconds since + * epoch). This operation causes a loss of precision. + * + * @returns The point in time corresponding to this timestamp, represented as + * the number of milliseconds since Unix epoch 1970-01-01T00:00:00Z. + */ + toMillis(): number; + _compareTo(other: Timestamp): number; + /** + * Returns true if this `Timestamp` is equal to the provided one. + * + * @param other - The `Timestamp` to compare against. + * @returns true if this `Timestamp` is equal to the provided one. + */ + isEqual(other: Timestamp): boolean; + /** Returns a textual representation of this `Timestamp`. */ + toString(): string; + static _jsonSchemaVersion: string; + static _jsonSchema: { + type: Property<"string">; + seconds: Property<"number">; + nanoseconds: Property<"number">; + }; + /** + * Returns a JSON-serializable representation of this `Timestamp`. + */ + toJSON(): { + seconds: number; + nanoseconds: number; + type: string; + }; + /** + * Builds a `Timestamp` instance from a JSON object created by {@link Timestamp.toJSON}. + */ + static fromJSON(json: object): Timestamp; + /** + * Converts this object to a primitive string, which allows `Timestamp` objects + * to be compared using the `>`, `<=`, `>=` and `>` operators. + */ + valueOf(): string; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/transaction.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/transaction.d.ts new file mode 100644 index 0000000..eee3374 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/transaction.d.ts @@ -0,0 +1,122 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Transaction as InternalTransaction } from '../core/transaction'; +import { Firestore } from './database'; +import { FieldPath } from './field_path'; +import { DocumentData, DocumentReference, PartialWithFieldValue, SetOptions, UpdateData, WithFieldValue } from './reference'; +import { DocumentSnapshot } from './snapshot'; +import { TransactionOptions } from './transaction_options'; +/** + * A reference to a transaction. + * + * The `Transaction` object passed to a transaction's `updateFunction` provides + * the methods to read and write data within the transaction context. See + * {@link runTransaction}. + */ +export declare class Transaction { + protected readonly _firestore: Firestore; + private readonly _transaction; + private readonly _dataReader; + /** @hideconstructor */ + constructor(_firestore: Firestore, _transaction: InternalTransaction); + /** + * Reads the document referenced by the provided {@link DocumentReference}. + * + * @param documentRef - A reference to the document to be read. + * @returns A `DocumentSnapshot` with the read data. + */ + get(documentRef: DocumentReference): Promise>; + /** + * Writes to the document referred to by the provided {@link + * DocumentReference}. If the document does not exist yet, it will be created. + * + * @param documentRef - A reference to the document to be set. + * @param data - An object of the fields and values for the document. + * @throws Error - If the provided input is not a valid Firestore document. + * @returns This `Transaction` instance. Used for chaining method calls. + */ + set(documentRef: DocumentReference, data: WithFieldValue): this; + /** + * Writes to the document referred to by the provided {@link + * DocumentReference}. If the document does not exist yet, it will be created. + * If you provide `merge` or `mergeFields`, the provided data can be merged + * into an existing document. + * + * @param documentRef - A reference to the document to be set. + * @param data - An object of the fields and values for the document. + * @param options - An object to configure the set behavior. + * @throws Error - If the provided input is not a valid Firestore document. + * @returns This `Transaction` instance. Used for chaining method calls. + */ + set(documentRef: DocumentReference, data: PartialWithFieldValue, options: SetOptions): this; + /** + * Updates fields in the document referred to by the provided {@link + * DocumentReference}. The update will fail if applied to a document that does + * not exist. + * + * @param documentRef - A reference to the document to be updated. + * @param data - An object containing the fields and values with which to + * update the document. Fields can contain dots to reference nested fields + * within the document. + * @throws Error - If the provided input is not valid Firestore data. + * @returns This `Transaction` instance. Used for chaining method calls. + */ + update(documentRef: DocumentReference, data: UpdateData): this; + /** + * Updates fields in the document referred to by the provided {@link + * DocumentReference}. The update will fail if applied to a document that does + * not exist. + * + * Nested fields can be updated by providing dot-separated field path + * strings or by providing `FieldPath` objects. + * + * @param documentRef - A reference to the document to be updated. + * @param field - The first field to update. + * @param value - The first value. + * @param moreFieldsAndValues - Additional key/value pairs. + * @throws Error - If the provided input is not valid Firestore data. + * @returns This `Transaction` instance. Used for chaining method calls. + */ + update(documentRef: DocumentReference, field: string | FieldPath, value: unknown, ...moreFieldsAndValues: unknown[]): this; + /** + * Deletes the document referred to by the provided {@link DocumentReference}. + * + * @param documentRef - A reference to the document to be deleted. + * @returns This `Transaction` instance. Used for chaining method calls. + */ + delete(documentRef: DocumentReference): this; +} +/** + * Executes the given `updateFunction` and then attempts to commit the changes + * applied within the transaction. If any document read within the transaction + * has changed, Cloud Firestore retries the `updateFunction`. If it fails to + * commit after 5 attempts, the transaction fails. + * + * The maximum number of writes allowed in a single transaction is 500. + * + * @param firestore - A reference to the Firestore database to run this + * transaction against. + * @param updateFunction - The function to execute within the transaction + * context. + * @param options - An options object to configure maximum number of attempts to + * commit. + * @returns If the transaction completed successfully or was explicitly aborted + * (the `updateFunction` returned a failed promise), the promise returned by the + * `updateFunction `is returned here. Otherwise, if the transaction failed, a + * rejected promise with the corresponding failure error is returned. + */ +export declare function runTransaction(firestore: Firestore, updateFunction: (transaction: Transaction) => Promise, options?: TransactionOptions): Promise; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/transaction_options.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/transaction_options.d.ts new file mode 100644 index 0000000..113fb49 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/transaction_options.d.ts @@ -0,0 +1,23 @@ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Options to customize transaction behavior. + */ +export declare interface TransactionOptions { + /** Maximum number of attempts to commit, after which transaction fails. Default is 5. */ + readonly maxAttempts?: number; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/types.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/types.d.ts new file mode 100644 index 0000000..5c56c2d --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/types.d.ts @@ -0,0 +1,61 @@ +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { UpdateData } from './reference'; +/** + * These types primarily exist to support the `UpdateData`, + * `WithFieldValue`, and `PartialWithFieldValue` types and are not consumed + * directly by the end developer. + */ +/** Primitive types. */ +export type Primitive = string | number | boolean | undefined | null; +/** + * For each field (e.g. 'bar'), find all nested keys (e.g. {'bar.baz': T1, + * 'bar.qux': T2}). Intersect them together to make a single map containing + * all possible keys that are all marked as optional + */ +export type NestedUpdateFields> = UnionToIntersection<{ + [K in keyof T & string]: ChildUpdateFields; +}[keyof T & string]>; +/** + * Helper for calculating the nested fields for a given type T1. This is needed + * to distribute union types such as `undefined | {...}` (happens for optional + * props) or `{a: A} | {b: B}`. + * + * In this use case, `V` is used to distribute the union types of `T[K]` on + * `Record`, since `T[K]` is evaluated as an expression and not distributed. + * + * See https://www.typescriptlang.org/docs/handbook/advanced-types.html#distributive-conditional-types + */ +export type ChildUpdateFields = V extends Record ? AddPrefixToKeys> : never; +/** + * Returns a new map where every key is prefixed with the outer key appended + * to a dot. + */ +export type AddPrefixToKeys> = { + [K in keyof T & string as `${Prefix}.${K}`]+?: string extends K ? any : T[K]; +}; +/** + * Given a union type `U = T1 | T2 | ...`, returns an intersected type + * `(T1 & T2 & ...)`. + * + * Uses distributive conditional types and inference from conditional types. + * This works because multiple candidates for the same type variable in + * contra-variant positions causes an intersection type to be inferred. + * https://www.typescriptlang.org/docs/handbook/advanced-types.html#type-inference-in-conditional-types + * https://stackoverflow.com/questions/50374908/transform-union-type-to-intersection-type + */ +export type UnionToIntersection = (U extends unknown ? (k: U) => void : never) extends (k: infer I) => void ? I : never; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/user_data_reader.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/user_data_reader.d.ts new file mode 100644 index 0000000..821bb46 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/user_data_reader.d.ts @@ -0,0 +1,224 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { DocumentData, FieldPath as PublicFieldPath, SetOptions } from '@firebase/firestore-types'; +import { Compat } from '@firebase/util'; +import { ParseContext } from '../api/parse_context'; +import { DatabaseId } from '../core/database_info'; +import { DocumentKey } from '../model/document_key'; +import { FieldMask } from '../model/field_mask'; +import { FieldTransform, Mutation, Precondition } from '../model/mutation'; +import { ObjectValue } from '../model/object_value'; +import { FieldPath as InternalFieldPath } from '../model/path'; +import { MapValue as ProtoMapValue, Value as ProtoValue } from '../protos/firestore_proto_api'; +import { JsonProtoSerializer } from '../remote/serializer'; +import { FirestoreError } from '../util/error'; +import { Dict } from '../util/obj'; +import { Firestore } from './database'; +import { FieldValue } from './field_value'; +import { PartialWithFieldValue, WithFieldValue } from './reference'; +import { VectorValue } from './vector_value'; +/** + * An untyped Firestore Data Converter interface that is shared between the + * lite, firestore-exp and classic SDK. + */ +export interface UntypedFirestoreDataConverter { + toFirestore(modelObject: WithFieldValue): WithFieldValue; + toFirestore(modelObject: PartialWithFieldValue, options: SetOptions): PartialWithFieldValue; + fromFirestore(snapshot: unknown, options?: unknown): AppModelType; +} +/** The result of parsing document data (e.g. for a setData call). */ +export declare class ParsedSetData { + readonly data: ObjectValue; + readonly fieldMask: FieldMask | null; + readonly fieldTransforms: FieldTransform[]; + constructor(data: ObjectValue, fieldMask: FieldMask | null, fieldTransforms: FieldTransform[]); + toMutation(key: DocumentKey, precondition: Precondition): Mutation; +} +/** The result of parsing "update" data (i.e. for an updateData call). */ +export declare class ParsedUpdateData { + readonly data: ObjectValue; + readonly fieldMask: FieldMask; + readonly fieldTransforms: FieldTransform[]; + constructor(data: ObjectValue, fieldMask: FieldMask, fieldTransforms: FieldTransform[]); + toMutation(key: DocumentKey, precondition: Precondition): Mutation; +} +export declare const enum UserDataSource { + Set = 0, + Update = 1, + MergeSet = 2, + /** + * Indicates the source is a where clause, cursor bound, arrayUnion() + * element, etc. Of note, isWrite(source) will return false. + */ + Argument = 3, + /** + * Indicates that the source is an Argument that may directly contain nested + * arrays (e.g. the operand of an `in` query). + */ + ArrayArgument = 4 +} +/** Contains the settings that are mutated as we parse user data. */ +interface ContextSettings { + /** Indicates what kind of API method this data came from. */ + readonly dataSource: UserDataSource; + /** The name of the method the user called to create the ParseContext. */ + readonly methodName: string; + /** The document the user is attempting to modify, if that applies. */ + readonly targetDoc?: DocumentKey; + /** + * A path within the object being parsed. This could be an empty path (in + * which case the context represents the root of the data being parsed), or a + * nonempty path (indicating the context represents a nested location within + * the data). + */ + readonly path?: InternalFieldPath; + /** + * Whether or not this context corresponds to an element of an array. + * If not set, elements are treated as if they were outside of arrays. + */ + readonly arrayElement?: boolean; + /** + * Whether or not a converter was specified in this context. If true, error + * messages will reference the converter when invalid data is provided. + */ + readonly hasConverter?: boolean; +} +/** A "context" object passed around while parsing user data. */ +declare class ParseContextImpl implements ParseContext { + readonly settings: ContextSettings; + readonly databaseId: DatabaseId; + readonly serializer: JsonProtoSerializer; + readonly ignoreUndefinedProperties: boolean; + readonly fieldTransforms: FieldTransform[]; + readonly fieldMask: InternalFieldPath[]; + /** + * Initializes a ParseContext with the given source and path. + * + * @param settings - The settings for the parser. + * @param databaseId - The database ID of the Firestore instance. + * @param serializer - The serializer to use to generate the Value proto. + * @param ignoreUndefinedProperties - Whether to ignore undefined properties + * rather than throw. + * @param fieldTransforms - A mutable list of field transforms encountered + * while parsing the data. + * @param fieldMask - A mutable list of field paths encountered while parsing + * the data. + * + * TODO(b/34871131): We don't support array paths right now, so path can be + * null to indicate the context represents any location within an array (in + * which case certain features will not work and errors will be somewhat + * compromised). + */ + constructor(settings: ContextSettings, databaseId: DatabaseId, serializer: JsonProtoSerializer, ignoreUndefinedProperties: boolean, fieldTransforms?: FieldTransform[], fieldMask?: InternalFieldPath[]); + get path(): InternalFieldPath | undefined; + get dataSource(): UserDataSource; + /** Returns a new context with the specified settings overwritten. */ + contextWith(configuration: Partial): ParseContextImpl; + childContextForField(field: string): ParseContextImpl; + childContextForFieldPath(field: InternalFieldPath): ParseContextImpl; + childContextForArray(index: number): ParseContextImpl; + createError(reason: string): FirestoreError; + /** Returns 'true' if 'fieldPath' was traversed when creating this context. */ + contains(fieldPath: InternalFieldPath): boolean; + private validatePath; + private validatePathSegment; +} +/** + * Helper for parsing raw user input (provided via the API) into internal model + * classes. + */ +export declare class UserDataReader { + private readonly databaseId; + private readonly ignoreUndefinedProperties; + private readonly serializer; + constructor(databaseId: DatabaseId, ignoreUndefinedProperties: boolean, serializer?: JsonProtoSerializer); + /** Creates a new top-level parse context. */ + createContext(dataSource: UserDataSource, methodName: string, targetDoc?: DocumentKey, hasConverter?: boolean): ParseContextImpl; +} +export declare function newUserDataReader(firestore: Firestore): UserDataReader; +/** Parse document data from a set() call. */ +export declare function parseSetData(userDataReader: UserDataReader, methodName: string, targetDoc: DocumentKey, input: unknown, hasConverter: boolean, options?: SetOptions): ParsedSetData; +export declare class DeleteFieldValueImpl extends FieldValue { + _toFieldTransform(context: ParseContextImpl): null; + isEqual(other: FieldValue): boolean; +} +export declare class ServerTimestampFieldValueImpl extends FieldValue { + _toFieldTransform(context: ParseContextImpl): FieldTransform; + isEqual(other: FieldValue): boolean; +} +export declare class ArrayUnionFieldValueImpl extends FieldValue { + private readonly _elements; + constructor(methodName: string, _elements: unknown[]); + _toFieldTransform(context: ParseContextImpl): FieldTransform; + isEqual(other: FieldValue): boolean; +} +export declare class ArrayRemoveFieldValueImpl extends FieldValue { + private readonly _elements; + constructor(methodName: string, _elements: unknown[]); + _toFieldTransform(context: ParseContextImpl): FieldTransform; + isEqual(other: FieldValue): boolean; +} +export declare class NumericIncrementFieldValueImpl extends FieldValue { + private readonly _operand; + constructor(methodName: string, _operand: number); + _toFieldTransform(context: ParseContextImpl): FieldTransform; + isEqual(other: FieldValue): boolean; +} +/** Parse update data from an update() call. */ +export declare function parseUpdateData(userDataReader: UserDataReader, methodName: string, targetDoc: DocumentKey, input: unknown): ParsedUpdateData; +/** Parse update data from a list of field/value arguments. */ +export declare function parseUpdateVarargs(userDataReader: UserDataReader, methodName: string, targetDoc: DocumentKey, field: string | PublicFieldPath | Compat, value: unknown, moreFieldsAndValues: unknown[]): ParsedUpdateData; +/** + * Parse a "query value" (e.g. value in a where filter or a value in a cursor + * bound). + * + * @param allowArrays - Whether the query value is an array that may directly + * contain additional arrays (e.g. the operand of an `in` query). + */ +export declare function parseQueryValue(userDataReader: UserDataReader, methodName: string, input: unknown, allowArrays?: boolean): ProtoValue; +/** + * Parses user data to Protobuf Values. + * + * @param input - Data to be parsed. + * @param context - A context object representing the current path being parsed, + * the source of the data being parsed, etc. + * @returns The parsed value, or null if the value was a FieldValue sentinel + * that should not be included in the resulting parsed data. + */ +export declare function parseData(input: unknown, context: ParseContextImpl): ProtoValue | null; +export declare function parseObject(obj: Dict, context: ParseContextImpl): { + mapValue: ProtoMapValue; +}; +/** + * Creates a new VectorValue proto value (using the internal format). + */ +export declare function parseVectorValue(value: VectorValue, context: ParseContextImpl): ProtoValue; +/** + * Helper that calls fromDotSeparatedString() but wraps any error thrown. + */ +export declare function fieldPathFromArgument(methodName: string, path: string | PublicFieldPath | Compat, targetDoc?: DocumentKey): InternalFieldPath; +/** + * Wraps fromDotSeparatedString with an error message about the method that + * was thrown. + * @param methodName - The publicly visible method name + * @param path - The dot-separated string form of a field path which will be + * split on dots. + * @param targetDoc - The document against which the field path will be + * evaluated. + */ +export declare function fieldPathFromDotSeparatedString(methodName: string, path: string, targetDoc?: DocumentKey): InternalFieldPath; +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/user_data_writer.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/user_data_writer.d.ts new file mode 100644 index 0000000..391593a --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/user_data_writer.d.ts @@ -0,0 +1,48 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { DocumentData } from '@firebase/firestore-types'; +import { DatabaseId } from '../core/database_info'; +import { DocumentKey } from '../model/document_key'; +import { ApiClientObjectMap, MapValue as ProtoMapValue, Value, Value as ProtoValue } from '../protos/firestore_proto_api'; +import { ByteString } from '../util/byte_string'; +import { VectorValue } from './vector_value'; +export type ServerTimestampBehavior = 'estimate' | 'previous' | 'none'; +/** + * Converts Firestore's internal types to the JavaScript types that we expose + * to the user. + * + * @internal + */ +export declare abstract class AbstractUserDataWriter { + convertValue(value: ProtoValue, serverTimestampBehavior?: ServerTimestampBehavior): unknown; + private convertObject; + /** + * @internal + */ + convertObjectMap(fields: ApiClientObjectMap | undefined, serverTimestampBehavior?: ServerTimestampBehavior): DocumentData; + /** + * @internal + */ + convertVectorValue(mapValue: ProtoMapValue): VectorValue; + private convertGeoPoint; + private convertArray; + private convertServerTimestamp; + private convertTimestamp; + protected convertDocumentKey(name: string, expectedDatabaseId: DatabaseId): DocumentKey; + protected abstract convertReference(name: string): unknown; + protected abstract convertBytes(bytes: ByteString): unknown; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/vector_value.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/vector_value.d.ts new file mode 100644 index 0000000..b4808e0 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/vector_value.d.ts @@ -0,0 +1,58 @@ +/** + * @license + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Property } from '../util/json_validation'; +/** + * Represents a vector type in Firestore documents. + * Create an instance with {@link vector}. + * + * @class VectorValue + */ +export declare class VectorValue { + private readonly _values; + /** + * @private + * @internal + */ + constructor(values: number[] | undefined); + /** + * Returns a copy of the raw number array form of the vector. + */ + toArray(): number[]; + /** + * Returns `true` if the two `VectorValue` values have the same raw number arrays, returns `false` otherwise. + */ + isEqual(other: VectorValue): boolean; + static _jsonSchemaVersion: string; + static _jsonSchema: { + type: Property<"string">; + vectorValues: Property<"object">; + }; + /** + * Returns a JSON-serializable representation of this `VectorValue` instance. + * + * @returns a JSON representation of this object. + */ + toJSON(): object; + /** + * Builds a `VectorValue` instance from a JSON object created by {@link VectorValue.toJSON}. + * + * @param json a JSON object represention of a `VectorValue` instance. + * @returns an instance of {@link VectorValue} if the JSON object could be parsed. Throws a + * {@link FirestoreError} if an error occurs. + */ + static fromJSON(json: object): VectorValue; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/write_batch.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/write_batch.d.ts new file mode 100644 index 0000000..4835feb --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/write_batch.d.ts @@ -0,0 +1,125 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Compat } from '@firebase/util'; +import { Mutation } from '../model/mutation'; +import { Firestore } from './database'; +import { FieldPath } from './field_path'; +import { DocumentData, DocumentReference, PartialWithFieldValue, SetOptions, UpdateData, WithFieldValue } from './reference'; +/** + * A write batch, used to perform multiple writes as a single atomic unit. + * + * A `WriteBatch` object can be acquired by calling {@link writeBatch}. It + * provides methods for adding writes to the write batch. None of the writes + * will be committed (or visible locally) until {@link WriteBatch.commit} is + * called. + */ +export declare class WriteBatch { + private readonly _firestore; + private readonly _commitHandler; + private readonly _dataReader; + private _mutations; + private _committed; + /** @hideconstructor */ + constructor(_firestore: Firestore, _commitHandler: (m: Mutation[]) => Promise); + /** + * Writes to the document referred to by the provided {@link + * DocumentReference}. If the document does not exist yet, it will be created. + * + * @param documentRef - A reference to the document to be set. + * @param data - An object of the fields and values for the document. + * @returns This `WriteBatch` instance. Used for chaining method calls. + */ + set(documentRef: DocumentReference, data: WithFieldValue): WriteBatch; + /** + * Writes to the document referred to by the provided {@link + * DocumentReference}. If the document does not exist yet, it will be created. + * If you provide `merge` or `mergeFields`, the provided data can be merged + * into an existing document. + * + * @param documentRef - A reference to the document to be set. + * @param data - An object of the fields and values for the document. + * @param options - An object to configure the set behavior. + * @throws Error - If the provided input is not a valid Firestore document. + * @returns This `WriteBatch` instance. Used for chaining method calls. + */ + set(documentRef: DocumentReference, data: PartialWithFieldValue, options: SetOptions): WriteBatch; + /** + * Updates fields in the document referred to by the provided {@link + * DocumentReference}. The update will fail if applied to a document that does + * not exist. + * + * @param documentRef - A reference to the document to be updated. + * @param data - An object containing the fields and values with which to + * update the document. Fields can contain dots to reference nested fields + * within the document. + * @throws Error - If the provided input is not valid Firestore data. + * @returns This `WriteBatch` instance. Used for chaining method calls. + */ + update(documentRef: DocumentReference, data: UpdateData): WriteBatch; + /** + * Updates fields in the document referred to by this {@link + * DocumentReference}. The update will fail if applied to a document that does + * not exist. + * + * Nested fields can be update by providing dot-separated field path strings + * or by providing `FieldPath` objects. + * + * @param documentRef - A reference to the document to be updated. + * @param field - The first field to update. + * @param value - The first value. + * @param moreFieldsAndValues - Additional key value pairs. + * @throws Error - If the provided input is not valid Firestore data. + * @returns This `WriteBatch` instance. Used for chaining method calls. + */ + update(documentRef: DocumentReference, field: string | FieldPath, value: unknown, ...moreFieldsAndValues: unknown[]): WriteBatch; + /** + * Deletes the document referred to by the provided {@link DocumentReference}. + * + * @param documentRef - A reference to the document to be deleted. + * @returns This `WriteBatch` instance. Used for chaining method calls. + */ + delete(documentRef: DocumentReference): WriteBatch; + /** + * Commits all of the writes in this write batch as a single atomic unit. + * + * The result of these writes will only be reflected in document reads that + * occur after the returned promise resolves. If the client is offline, the + * write fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @returns A `Promise` resolved once all of the writes in the batch have been + * successfully written to the backend as an atomic unit (note that it won't + * resolve while you're offline). + */ + commit(): Promise; + private _verifyNotCommitted; +} +export declare function validateReference(documentRef: DocumentReference | Compat>, firestore: Firestore): DocumentReference; +/** + * Creates a write batch, used for performing multiple writes as a single + * atomic operation. The maximum number of writes allowed in a single WriteBatch + * is 500. + * + * The result of these writes will only be reflected in document reads that + * occur after the returned promise resolves. If the client is offline, the + * write fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @returns A `WriteBatch` that can be used to atomically execute multiple + * writes. + */ +export declare function writeBatch(firestore: Firestore): WriteBatch; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/bundle_cache.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/bundle_cache.d.ts new file mode 100644 index 0000000..2949e55 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/bundle_cache.d.ts @@ -0,0 +1,44 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { BundleMetadata, NamedQuery } from '../core/bundle'; +import { NamedQuery as ProtoNamedQuery, BundleMetadata as ProtoBundleMetadata } from '../protos/firestore_bundle_proto'; +import { PersistencePromise } from './persistence_promise'; +import { PersistenceTransaction } from './persistence_transaction'; +/** + * Provides interfaces to save and read Firestore bundles. + */ +export interface BundleCache { + /** + * Gets the saved `BundleMetadata` for a given `bundleId`, returns undefined + * if no bundle metadata is found under the given id. + */ + getBundleMetadata(transaction: PersistenceTransaction, bundleId: string): PersistencePromise; + /** + * Saves a `BundleMetadata` from a bundle into local storage, using its id as + * the persistent key. + */ + saveBundleMetadata(transaction: PersistenceTransaction, metadata: ProtoBundleMetadata): PersistencePromise; + /** + * Gets a saved `NamedQuery` for the given query name. Returns undefined if + * no queries are found under the given name. + */ + getNamedQuery(transaction: PersistenceTransaction, queryName: string): PersistencePromise; + /** + * Saves a `NamedQuery` from a bundle, using its name as the persistent key. + */ + saveNamedQuery(transaction: PersistenceTransaction, query: ProtoNamedQuery): PersistencePromise; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/document_overlay_cache.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/document_overlay_cache.d.ts new file mode 100644 index 0000000..e1f1f2a --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/document_overlay_cache.d.ts @@ -0,0 +1,76 @@ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { DocumentKeySet, MutationMap, OverlayMap } from '../model/collections'; +import { DocumentKey } from '../model/document_key'; +import { Overlay } from '../model/overlay'; +import { ResourcePath } from '../model/path'; +import { PersistencePromise } from './persistence_promise'; +import { PersistenceTransaction } from './persistence_transaction'; +/** + * Provides methods to read and write document overlays. + * + * An overlay is a saved mutation, that gives a local view of a document when + * applied to the remote version of the document. + * + * Each overlay stores the largest batch ID that is included in the overlay, + * which allows us to remove the overlay once all batches leading up to it have + * been acknowledged. + */ +export interface DocumentOverlayCache { + /** + * Gets the saved overlay mutation for the given document key. + * Returns null if there is no overlay for that key. + */ + getOverlay(transaction: PersistenceTransaction, key: DocumentKey): PersistencePromise; + /** + * Gets the saved overlay mutation for the given document keys. Skips keys for + * which there are no overlays. + */ + getOverlays(transaction: PersistenceTransaction, keys: DocumentKey[]): PersistencePromise; + /** + * Saves the given document mutation map to persistence as overlays. + * All overlays will have their largest batch id set to `largestBatchId`. + */ + saveOverlays(transaction: PersistenceTransaction, largestBatchId: number, overlays: MutationMap): PersistencePromise; + /** Removes overlays for the given document keys and batch ID. */ + removeOverlaysForBatchId(transaction: PersistenceTransaction, documentKeys: DocumentKeySet, batchId: number): PersistencePromise; + /** + * Returns all saved overlays for the given collection. + * + * @param transaction - The persistence transaction to use for this operation. + * @param collection - The collection path to get the overlays for. + * @param sinceBatchId - The minimum batch ID to filter by (exclusive). + * Only overlays that contain a change past `sinceBatchId` are returned. + * @returns Mapping of each document key in the collection to its overlay. + */ + getOverlaysForCollection(transaction: PersistenceTransaction, collection: ResourcePath, sinceBatchId: number): PersistencePromise; + /** + * Returns `count` overlays with a batch ID higher than `sinceBatchId` for the + * provided collection group, processed by ascending batch ID. The method + * always returns all overlays for a batch even if the last batch contains + * more documents than the remaining limit. + * + * @param transaction - The persistence transaction used for this operation. + * @param collectionGroup - The collection group to get the overlays for. + * @param sinceBatchId - The minimum batch ID to filter by (exclusive). + * Only overlays that contain a change past `sinceBatchId` are returned. + * @param count - The number of overlays to return. Can be exceeded if the last + * batch contains more entries. + * @return Mapping of each document key in the collection group to its overlay. + */ + getOverlaysForCollectionGroup(transaction: PersistenceTransaction, collectionGroup: string, sinceBatchId: number, count: number): PersistencePromise; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/encoded_resource_path.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/encoded_resource_path.d.ts new file mode 100644 index 0000000..73353db --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/encoded_resource_path.d.ts @@ -0,0 +1,73 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { ResourcePath } from '../model/path'; +/** + * Helpers for dealing with resource paths stored in IndexedDB. + * + * Resource paths in their canonical string form do not sort as the server + * sorts them. Specifically the server splits paths into segments first and then + * sorts, putting end-of-segment before any character. In a UTF-8 string + * encoding the slash ('/') that denotes the end-of-segment naturally comes + * after other characters so the intent here is to encode the path delimiters in + * such a way that the resulting strings sort naturally. + * + * Resource paths are also used for prefix scans so it's important to + * distinguish whole segments from any longer segments of which they might be a + * prefix. For example, it's important to make it possible to scan documents in + * a collection "foo" without encountering documents in a collection "foobar". + * + * Separate from the concerns about resource path ordering and separation, + * On Android, SQLite imposes additional restrictions since it does not handle + * keys with embedded NUL bytes particularly well. Rather than change the + * implementation we keep the encoding identical to keep the ports similar. + * + * Taken together this means resource paths when encoded for storage in + * IndexedDB have the following characteristics: + * + * * Segment separators ("/") sort before everything else. + * * All paths have a trailing separator. + * * NUL bytes do not exist in the output, since IndexedDB doesn't treat them + * well. + * + * Therefore resource paths are encoded into string form using the following + * rules: + * + * * '\x01' is used as an escape character. + * * Path separators are encoded as "\x01\x01" + * * NUL bytes are encoded as "\x01\x10" + * * '\x01' is encoded as "\x01\x11" + * + * This encoding leaves some room between path separators and the NUL byte + * just in case we decide to support integer document ids after all. + * + * Note that characters treated specially by the backend ('.', '/', and '~') + * are not treated specially here. This class assumes that any unescaping of + * resource path strings into actual ResourcePath objects will handle these + * characters there. + */ +export type EncodedResourcePath = string; +/** + * Encodes a resource path into a IndexedDb-compatible string form. + */ +export declare function encodeResourcePath(path: ResourcePath): EncodedResourcePath; +/** + * Decodes the given IndexedDb-compatible string form of a resource path into + * a ResourcePath instance. Note that this method is not suitable for use with + * decoding resource names from the server; those are One Platform format + * strings. + */ +export declare function decodeResourcePath(path: EncodedResourcePath): ResourcePath; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/globals_cache.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/globals_cache.d.ts new file mode 100644 index 0000000..a2a7ff6 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/globals_cache.d.ts @@ -0,0 +1,39 @@ +/** + * @license + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { ByteString } from '../util/byte_string'; +import { PersistencePromise } from './persistence_promise'; +import { PersistenceTransaction } from './persistence_transaction'; +/** + * General purpose cache for global values. + * + * Global state that cuts across components should be saved here. Following are contained herein: + * + * `sessionToken` tracks server interaction across Listen and Write streams. This facilitates cache + * synchronization and invalidation. + */ +export interface GlobalsCache { + /** + * Gets session token. + */ + getSessionToken(transaction: PersistenceTransaction): PersistencePromise; + /** + * Sets session token. + * + * @param sessionToken - The new session token. + */ + setSessionToken(transaction: PersistenceTransaction, sessionToken: ByteString): PersistencePromise; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/index_backfiller.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/index_backfiller.d.ts new file mode 100644 index 0000000..2abeb5f --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/index_backfiller.d.ts @@ -0,0 +1,44 @@ +import { AsyncQueue } from '../util/async_queue'; +import { LocalStore } from './local_store'; +import { Persistence, Scheduler } from './persistence'; +/** This class is responsible for the scheduling of Index Backfiller. */ +export declare class IndexBackfillerScheduler implements Scheduler { + private readonly asyncQueue; + private readonly backfiller; + private task; + constructor(asyncQueue: AsyncQueue, backfiller: IndexBackfiller); + start(): void; + stop(): void; + get started(): boolean; + private schedule; +} +/** Implements the steps for backfilling indexes. */ +export declare class IndexBackfiller { + /** + * LocalStore provides access to IndexManager and LocalDocumentView. + * These properties will update when the user changes. Consequently, + * making a local copy of IndexManager and LocalDocumentView will require + * updates over time. The simpler solution is to rely on LocalStore to have + * an up-to-date references to IndexManager and LocalDocumentStore. + */ + private readonly localStore; + private readonly persistence; + constructor( + /** + * LocalStore provides access to IndexManager and LocalDocumentView. + * These properties will update when the user changes. Consequently, + * making a local copy of IndexManager and LocalDocumentView will require + * updates over time. The simpler solution is to rely on LocalStore to have + * an up-to-date references to IndexManager and LocalDocumentStore. + */ + localStore: LocalStore, persistence: Persistence); + backfill(maxDocumentsToProcess?: number): Promise; + /** Writes index entries until the cap is reached. Returns the number of documents processed. */ + private writeIndexEntries; + /** + * Writes entries for the provided collection group. Returns the number of documents processed. + */ + private writeEntriesForCollectionGroup; + /** Returns the next offset based on the provided documents. */ + private getNewOffset; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/index_manager.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/index_manager.d.ts new file mode 100644 index 0000000..6a02ffc --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/index_manager.d.ts @@ -0,0 +1,124 @@ +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Target } from '../core/target'; +import { DocumentMap } from '../model/collections'; +import { DocumentKey } from '../model/document_key'; +import { FieldIndex, IndexOffset } from '../model/field_index'; +import { ResourcePath } from '../model/path'; +import { PersistencePromise } from './persistence_promise'; +import { PersistenceTransaction } from './persistence_transaction'; +/** Represents the index state as it relates to a particular target. */ +export declare const enum IndexType { + /** Indicates that no index could be found for serving the target. */ + NONE = 0, + /** + * Indicates that only a "partial index" could be found for serving the + * target. A partial index is one which does not have a segment for every + * filter/orderBy in the target. + */ + PARTIAL = 1, + /** + * Indicates that a "full index" could be found for serving the target. A full + * index is one which has a segment for every filter/orderBy in the target. + */ + FULL = 2 +} +export declare function displayNameForIndexType(indexType: IndexType): string; +/** + * Represents a set of indexes that are used to execute queries efficiently. + * + * Currently the only index is a [collection id] => [parent path] index, used + * to execute Collection Group queries. + */ +export interface IndexManager { + /** + * Creates an index entry mapping the collectionId (last segment of the path) + * to the parent path (either the containing document location or the empty + * path for root-level collections). Index entries can be retrieved via + * getCollectionParents(). + * + * NOTE: Currently we don't remove index entries. If this ends up being an + * issue we can devise some sort of GC strategy. + */ + addToCollectionParentIndex(transaction: PersistenceTransaction, collectionPath: ResourcePath): PersistencePromise; + /** + * Retrieves all parent locations containing the given collectionId, as a + * list of paths (each path being either a document location or the empty + * path for a root-level collection). + */ + getCollectionParents(transaction: PersistenceTransaction, collectionId: string): PersistencePromise; + /** + * Adds a field path index. + * + * Values for this index are persisted via the index backfill, which runs + * asynchronously in the background. Once the first values are written, + * an index can be used to serve partial results for any matching queries. + * Any unindexed portion of the database will continue to be served via + * collection scons. + */ + addFieldIndex(transaction: PersistenceTransaction, index: FieldIndex): PersistencePromise; + /** Removes the given field index and deletes all index values. */ + deleteFieldIndex(transaction: PersistenceTransaction, index: FieldIndex): PersistencePromise; + /** Removes all field indexes and deletes all index values. */ + deleteAllFieldIndexes(transaction: PersistenceTransaction): PersistencePromise; + /** Creates a full matched field index which serves the given target. */ + createTargetIndexes(transaction: PersistenceTransaction, target: Target): PersistencePromise; + /** + * Returns a list of field indexes that correspond to the specified collection + * group. + * + * @param collectionGroup The collection group to get matching field indexes + * for. + * @return A collection of field indexes for the specified collection group. + */ + getFieldIndexes(transaction: PersistenceTransaction, collectionGroup: string): PersistencePromise; + /** Returns all configured field indexes. */ + getFieldIndexes(transaction: PersistenceTransaction): PersistencePromise; + /** + * Returns the type of index (if any) that can be used to serve the given + * target. + */ + getIndexType(transaction: PersistenceTransaction, target: Target): PersistencePromise; + /** + * Returns the documents that match the given target based on the provided + * index or `null` if the target does not have a matching index. + */ + getDocumentsMatchingTarget(transaction: PersistenceTransaction, target: Target): PersistencePromise; + /** + * Returns the next collection group to update. Returns `null` if no group + * exists. + */ + getNextCollectionGroupToUpdate(transaction: PersistenceTransaction): PersistencePromise; + /** + * Sets the collection group's latest read time. + * + * This method updates the index offset for all field indices for the + * collection group and increments their sequence number. Subsequent calls to + * `getNextCollectionGroupToUpdate()` will return a different collection group + * (unless only one collection group is configured). + */ + updateCollectionGroup(transaction: PersistenceTransaction, collectionGroup: string, offset: IndexOffset): PersistencePromise; + /** Updates the index entries for the provided documents. */ + updateIndexEntries(transaction: PersistenceTransaction, documents: DocumentMap): PersistencePromise; + /** + * Iterates over all field indexes that are used to serve the given target, + * and returns the minimum offset of them all. + */ + getMinOffset(transaction: PersistenceTransaction, target: Target): PersistencePromise; + /** Returns the minimum offset for the given collection group. */ + getMinOffsetFromCollectionGroup(transaction: PersistenceTransaction, collectionGroup: string): PersistencePromise; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_bundle_cache.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_bundle_cache.d.ts new file mode 100644 index 0000000..60f49fc --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_bundle_cache.d.ts @@ -0,0 +1,27 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { BundleMetadata, NamedQuery } from '../core/bundle'; +import { BundleMetadata as ProtoBundleMetadata, NamedQuery as ProtoNamedQuery } from '../protos/firestore_bundle_proto'; +import { BundleCache } from './bundle_cache'; +import { PersistencePromise } from './persistence_promise'; +import { PersistenceTransaction } from './persistence_transaction'; +export declare class IndexedDbBundleCache implements BundleCache { + getBundleMetadata(transaction: PersistenceTransaction, bundleId: string): PersistencePromise; + saveBundleMetadata(transaction: PersistenceTransaction, bundleMetadata: ProtoBundleMetadata): PersistencePromise; + getNamedQuery(transaction: PersistenceTransaction, queryName: string): PersistencePromise; + saveNamedQuery(transaction: PersistenceTransaction, query: ProtoNamedQuery): PersistencePromise; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_document_overlay_cache.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_document_overlay_cache.d.ts new file mode 100644 index 0000000..eda11b2 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_document_overlay_cache.d.ts @@ -0,0 +1,45 @@ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { User } from '../auth/user'; +import { DocumentKeySet, MutationMap, OverlayMap } from '../model/collections'; +import { DocumentKey } from '../model/document_key'; +import { Overlay } from '../model/overlay'; +import { ResourcePath } from '../model/path'; +import { DocumentOverlayCache } from './document_overlay_cache'; +import { LocalSerializer } from './local_serializer'; +import { PersistencePromise } from './persistence_promise'; +import { PersistenceTransaction } from './persistence_transaction'; +/** + * Implementation of DocumentOverlayCache using IndexedDb. + */ +export declare class IndexedDbDocumentOverlayCache implements DocumentOverlayCache { + private readonly serializer; + private readonly userId; + /** + * @param serializer - The document serializer. + * @param userId - The userId for which we are accessing overlays. + */ + constructor(serializer: LocalSerializer, userId: string); + static forUser(serializer: LocalSerializer, user: User): IndexedDbDocumentOverlayCache; + getOverlay(transaction: PersistenceTransaction, key: DocumentKey): PersistencePromise; + getOverlays(transaction: PersistenceTransaction, keys: DocumentKey[]): PersistencePromise; + saveOverlays(transaction: PersistenceTransaction, largestBatchId: number, overlays: MutationMap): PersistencePromise; + removeOverlaysForBatchId(transaction: PersistenceTransaction, documentKeys: DocumentKeySet, batchId: number): PersistencePromise; + getOverlaysForCollection(transaction: PersistenceTransaction, collection: ResourcePath, sinceBatchId: number): PersistencePromise; + getOverlaysForCollectionGroup(transaction: PersistenceTransaction, collectionGroup: string, sinceBatchId: number, count: number): PersistencePromise; + private saveOverlay; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_globals_cache.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_globals_cache.d.ts new file mode 100644 index 0000000..2f550f5 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_globals_cache.d.ts @@ -0,0 +1,25 @@ +/** + * @license + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { ByteString } from '../util/byte_string'; +import { GlobalsCache } from './globals_cache'; +import { PersistencePromise } from './persistence_promise'; +import { PersistenceTransaction } from './persistence_transaction'; +export declare class IndexedDbGlobalsCache implements GlobalsCache { + private globalsStore; + getSessionToken(txn: PersistenceTransaction): PersistencePromise; + setSessionToken(txn: PersistenceTransaction, sessionToken: ByteString): PersistencePromise; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_index_manager.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_index_manager.d.ts new file mode 100644 index 0000000..8078d1c --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_index_manager.d.ts @@ -0,0 +1,136 @@ +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { User } from '../auth/user'; +import { DatabaseId } from '../core/database_info'; +import { Target } from '../core/target'; +import { IndexEntry } from '../index/index_entry'; +import { DocumentMap } from '../model/collections'; +import { DocumentKey } from '../model/document_key'; +import { FieldIndex, IndexOffset } from '../model/field_index'; +import { ResourcePath } from '../model/path'; +import { IndexManager, IndexType } from './index_manager'; +import { PersistencePromise } from './persistence_promise'; +import { PersistenceTransaction } from './persistence_transaction'; +/** + * A persisted implementation of IndexManager. + * + * PORTING NOTE: Unlike iOS and Android, the Web SDK does not memoize index + * data as it supports multi-tab access. + */ +export declare class IndexedDbIndexManager implements IndexManager { + private readonly databaseId; + /** + * An in-memory copy of the index entries we've already written since the SDK + * launched. Used to avoid re-writing the same entry repeatedly. + * + * This is *NOT* a complete cache of what's in persistence and so can never be + * used to satisfy reads. + */ + private collectionParentsCache; + private readonly uid; + /** + * Maps from a target to its equivalent list of sub-targets. Each sub-target + * contains only one term from the target's disjunctive normal form (DNF). + */ + private targetToDnfSubTargets; + constructor(user: User, databaseId: DatabaseId); + /** + * Adds a new entry to the collection parent index. + * + * Repeated calls for the same collectionPath should be avoided within a + * transaction as IndexedDbIndexManager only caches writes once a transaction + * has been committed. + */ + addToCollectionParentIndex(transaction: PersistenceTransaction, collectionPath: ResourcePath): PersistencePromise; + getCollectionParents(transaction: PersistenceTransaction, collectionId: string): PersistencePromise; + addFieldIndex(transaction: PersistenceTransaction, index: FieldIndex): PersistencePromise; + deleteFieldIndex(transaction: PersistenceTransaction, index: FieldIndex): PersistencePromise; + deleteAllFieldIndexes(transaction: PersistenceTransaction): PersistencePromise; + createTargetIndexes(transaction: PersistenceTransaction, target: Target): PersistencePromise; + getDocumentsMatchingTarget(transaction: PersistenceTransaction, target: Target): PersistencePromise; + private getSubTargets; + /** + * Constructs a key range query on `DbIndexEntryStore` that unions all + * bounds. + */ + private generateIndexRanges; + /** Generates the lower bound for `arrayValue` and `directionalValue`. */ + private generateLowerBound; + /** Generates the upper bound for `arrayValue` and `directionalValue`. */ + private generateUpperBound; + private getFieldIndex; + getIndexType(transaction: PersistenceTransaction, target: Target): PersistencePromise; + /** + * Returns the byte encoded form of the directional values in the field index. + * Returns `null` if the document does not have all fields specified in the + * index. + */ + private encodeDirectionalElements; + /** Encodes a single value to the ascending index format. */ + private encodeSingleElement; + /** + * Returns an encoded form of the document key that sorts based on the key + * ordering of the field index. + */ + private encodeDirectionalKey; + /** + * Encodes the given field values according to the specification in `target`. + * For IN queries, a list of possible values is returned. + */ + private encodeValues; + /** + * Encodes the given bounds according to the specification in `target`. For IN + * queries, a list of possible values is returned. + */ + private encodeBound; + /** Returns the byte representation for the provided encoders. */ + private getEncodedBytes; + /** + * Creates a separate encoder for each element of an array. + * + * The method appends each value to all existing encoders (e.g. filter("a", + * "==", "a1").filter("b", "in", ["b1", "b2"]) becomes ["a1,b1", "a1,b2"]). A + * list of new encoders is returned. + */ + private expandIndexValues; + private isInFilter; + getFieldIndexes(transaction: PersistenceTransaction, collectionGroup?: string): PersistencePromise; + getNextCollectionGroupToUpdate(transaction: PersistenceTransaction): PersistencePromise; + updateCollectionGroup(transaction: PersistenceTransaction, collectionGroup: string, offset: IndexOffset): PersistencePromise; + updateIndexEntries(transaction: PersistenceTransaction, documents: DocumentMap): PersistencePromise; + private addIndexEntry; + private deleteIndexEntry; + private getExistingIndexEntries; + /** Creates the index entries for the given document. */ + private computeIndexEntries; + /** + * Updates the index entries for the provided document by deleting entries + * that are no longer referenced in `newEntries` and adding all newly added + * entries. + */ + private updateEntries; + private getNextSequenceNumber; + /** + * Returns a new set of IDB ranges that splits the existing range and excludes + * any values that match the `notInValue` from these ranges. As an example, + * '[foo > 2 && foo != 3]` becomes `[foo > 2 && < 3, foo > 3]`. + */ + private createRange; + isRangeMatchable(lowerBound: IndexEntry, upperBound: IndexEntry): boolean; + getMinOffsetFromCollectionGroup(transaction: PersistenceTransaction, collectionGroup: string): PersistencePromise; + getMinOffset(transaction: PersistenceTransaction, target: Target): PersistencePromise; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_lru_delegate.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_lru_delegate.d.ts new file mode 100644 index 0000000..fea8087 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_lru_delegate.d.ts @@ -0,0 +1,22 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { LruDelegate, LruGarbageCollector } from './lru_garbage_collector'; +import { ReferenceDelegate } from './persistence'; +/** Provides LRU functionality for IndexedDB persistence. */ +export interface IndexedDbLruDelegate extends ReferenceDelegate, LruDelegate { + readonly garbageCollector: LruGarbageCollector; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_lru_delegate_impl.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_lru_delegate_impl.d.ts new file mode 100644 index 0000000..56e5e6b --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_lru_delegate_impl.d.ts @@ -0,0 +1,56 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { ListenSequenceNumber, TargetId } from '../core/types'; +import { DocumentKey } from '../model/document_key'; +import { IndexedDbLruDelegate } from './indexeddb_lru_delegate'; +import { ActiveTargets, LruGarbageCollector, LruParams } from './lru_garbage_collector'; +import { Persistence } from './persistence'; +import { PersistencePromise } from './persistence_promise'; +import { PersistenceTransaction } from './persistence_transaction'; +import { TargetData } from './target_data'; +/** Provides LRU functionality for IndexedDB persistence. */ +export declare class IndexedDbLruDelegateImpl implements IndexedDbLruDelegate { + private readonly db; + readonly garbageCollector: LruGarbageCollector; + constructor(db: Persistence, params: LruParams); + getSequenceNumberCount(txn: PersistenceTransaction): PersistencePromise; + private orphanedDocumentCount; + forEachTarget(txn: PersistenceTransaction, f: (q: TargetData) => void): PersistencePromise; + forEachOrphanedDocumentSequenceNumber(txn: PersistenceTransaction, f: (sequenceNumber: ListenSequenceNumber) => void): PersistencePromise; + addReference(txn: PersistenceTransaction, targetId: TargetId, key: DocumentKey): PersistencePromise; + removeReference(txn: PersistenceTransaction, targetId: TargetId, key: DocumentKey): PersistencePromise; + removeTargets(txn: PersistenceTransaction, upperBound: ListenSequenceNumber, activeTargetIds: ActiveTargets): PersistencePromise; + markPotentiallyOrphaned(txn: PersistenceTransaction, key: DocumentKey): PersistencePromise; + /** + * Returns true if anything would prevent this document from being garbage + * collected, given that the document in question is not present in any + * targets and has a sequence number less than or equal to the upper bound for + * the collection run. + */ + private isPinned; + removeOrphanedDocuments(txn: PersistenceTransaction, upperBound: ListenSequenceNumber): PersistencePromise; + removeTarget(txn: PersistenceTransaction, targetData: TargetData): PersistencePromise; + updateLimboDocument(txn: PersistenceTransaction, key: DocumentKey): PersistencePromise; + /** + * Call provided function for each document in the cache that is 'orphaned'. Orphaned + * means not a part of any target, so the only entry in the target-document index for + * that document will be the sentinel row (targetId 0), which will also have the sequence + * number for the last time the document was accessed. + */ + private forEachOrphanedDocument; + getCacheSize(txn: PersistenceTransaction): PersistencePromise; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_mutation_batch_impl.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_mutation_batch_impl.d.ts new file mode 100644 index 0000000..b4f0ac4 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_mutation_batch_impl.d.ts @@ -0,0 +1,35 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { DocumentKey } from '../model/document_key'; +import { DbRemoteDocument } from './indexeddb_schema'; +import { DbRemoteDocument as DbRemoteDocumentLegacy } from './indexeddb_schema_legacy'; +import { PersistencePromise } from './persistence_promise'; +import { SimpleDbTransaction } from './simple_db'; +/** + * Delete a mutation batch and the associated document mutations. + * @returns A PersistencePromise of the document mutations that were removed. + */ +export declare function removeMutationBatch(txn: SimpleDbTransaction, userId: string, batch: { + batchId: number; + mutations: Array<{ + key: DocumentKey; + }>; +}): PersistencePromise; +/** + * Returns an approximate size for the given document. + */ +export declare function dbDocumentSize(doc: DbRemoteDocument | DbRemoteDocumentLegacy | null): number; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_mutation_queue.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_mutation_queue.d.ts new file mode 100644 index 0000000..ad62a1d --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_mutation_queue.d.ts @@ -0,0 +1,99 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { User } from '../auth/user'; +import { Query } from '../core/query'; +import { BatchId } from '../core/types'; +import { Timestamp } from '../lite-api/timestamp'; +import { DocumentKeySet } from '../model/collections'; +import { DocumentKey } from '../model/document_key'; +import { Mutation } from '../model/mutation'; +import { MutationBatch } from '../model/mutation_batch'; +import { SortedMap } from '../util/sorted_map'; +import { IndexManager } from './index_manager'; +import { LocalSerializer } from './local_serializer'; +import { MutationQueue } from './mutation_queue'; +import { ReferenceDelegate } from './persistence'; +import { PersistencePromise } from './persistence_promise'; +import { PersistenceTransaction } from './persistence_transaction'; +/** A mutation queue for a specific user, backed by IndexedDB. */ +export declare class IndexedDbMutationQueue implements MutationQueue { + /** + * The normalized userId (e.g. null UID => "" userId) used to store / + * retrieve mutations. + */ + private userId; + private readonly serializer; + private readonly indexManager; + private readonly referenceDelegate; + /** + * Caches the document keys for pending mutation batches. If the mutation + * has been removed from IndexedDb, the cached value may continue to + * be used to retrieve the batch's document keys. To remove a cached value + * locally, `removeCachedMutationKeys()` should be invoked either directly + * or through `removeMutationBatches()`. + * + * With multi-tab, when the primary client acknowledges or rejects a mutation, + * this cache is used by secondary clients to invalidate the local + * view of the documents that were previously affected by the mutation. + */ + private documentKeysByBatchId; + constructor( + /** + * The normalized userId (e.g. null UID => "" userId) used to store / + * retrieve mutations. + */ + userId: string, serializer: LocalSerializer, indexManager: IndexManager, referenceDelegate: ReferenceDelegate); + /** + * Creates a new mutation queue for the given user. + * @param user - The user for which to create a mutation queue. + * @param serializer - The serializer to use when persisting to IndexedDb. + */ + static forUser(user: User, serializer: LocalSerializer, indexManager: IndexManager, referenceDelegate: ReferenceDelegate): IndexedDbMutationQueue; + checkEmpty(transaction: PersistenceTransaction): PersistencePromise; + addMutationBatch(transaction: PersistenceTransaction, localWriteTime: Timestamp, baseMutations: Mutation[], mutations: Mutation[]): PersistencePromise; + lookupMutationBatch(transaction: PersistenceTransaction, batchId: BatchId): PersistencePromise; + /** + * Returns the document keys for the mutation batch with the given batchId. + * For primary clients, this method returns `null` after + * `removeMutationBatches()` has been called. Secondary clients return a + * cached result until `removeCachedMutationKeys()` is invoked. + */ + lookupMutationKeys(transaction: PersistenceTransaction, batchId: BatchId): PersistencePromise; + getNextMutationBatchAfterBatchId(transaction: PersistenceTransaction, batchId: BatchId): PersistencePromise; + getHighestUnacknowledgedBatchId(transaction: PersistenceTransaction): PersistencePromise; + getAllMutationBatches(transaction: PersistenceTransaction): PersistencePromise; + getAllMutationBatchesAffectingDocumentKey(transaction: PersistenceTransaction, documentKey: DocumentKey): PersistencePromise; + getAllMutationBatchesAffectingDocumentKeys(transaction: PersistenceTransaction, documentKeys: SortedMap): PersistencePromise; + getAllMutationBatchesAffectingQuery(transaction: PersistenceTransaction, query: Query): PersistencePromise; + private lookupMutationBatches; + removeMutationBatch(transaction: PersistenceTransaction, batch: MutationBatch): PersistencePromise; + /** + * Clears the cached keys for a mutation batch. This method should be + * called by secondary clients after they process mutation updates. + * + * Note that this method does not have to be called from primary clients as + * the corresponding cache entries are cleared when an acknowledged or + * rejected batch is removed from the mutation queue. + */ + removeCachedMutationKeys(batchId: BatchId): void; + performConsistencyCheck(txn: PersistenceTransaction): PersistencePromise; + containsKey(txn: PersistenceTransaction, key: DocumentKey): PersistencePromise; + /** Returns the mutation queue's metadata from IndexedDb. */ + private getMutationQueueMetadata; +} +/** Returns true if any mutation queue contains the given document. */ +export declare function mutationQueuesContainKey(txn: PersistenceTransaction, docKey: DocumentKey): PersistencePromise; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_persistence.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_persistence.d.ts new file mode 100644 index 0000000..f4cf7d8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_persistence.d.ts @@ -0,0 +1,270 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { User } from '../auth/user'; +import { DatabaseId } from '../core/database_info'; +import { SequenceNumberSyncer } from '../core/listen_sequence'; +import { JsonProtoSerializer } from '../remote/serializer'; +import { AsyncQueue } from '../util/async_queue'; +import { DocumentLike, WindowLike } from '../util/types'; +import { BundleCache } from './bundle_cache'; +import { DocumentOverlayCache } from './document_overlay_cache'; +import { GlobalsCache } from './globals_cache'; +import { IndexManager } from './index_manager'; +import { IndexedDbLruDelegateImpl } from './indexeddb_lru_delegate_impl'; +import { IndexedDbMutationQueue } from './indexeddb_mutation_queue'; +import { IndexedDbRemoteDocumentCache } from './indexeddb_remote_document_cache'; +import { IndexedDbTargetCache } from './indexeddb_target_cache'; +import { LruParams } from './lru_garbage_collector'; +import { Persistence, PrimaryStateListener } from './persistence'; +import { PersistencePromise } from './persistence_promise'; +import { PersistenceTransaction, PersistenceTransactionMode } from './persistence_transaction'; +import { ClientId } from './shared_client_state'; +/** + * The name of the main (and currently only) IndexedDB database. This name is + * appended to the prefix provided to the IndexedDbPersistence constructor. + */ +export declare const MAIN_DATABASE = "main"; +/** + * An IndexedDB-backed instance of Persistence. Data is stored persistently + * across sessions. + * + * On Web only, the Firestore SDKs support shared access to its persistence + * layer. This allows multiple browser tabs to read and write to IndexedDb and + * to synchronize state even without network connectivity. Shared access is + * currently optional and not enabled unless all clients invoke + * `enablePersistence()` with `{synchronizeTabs:true}`. + * + * In multi-tab mode, if multiple clients are active at the same time, the SDK + * will designate one client as the "primary client". An effort is made to pick + * a visible, network-connected and active client, and this client is + * responsible for letting other clients know about its presence. The primary + * client writes a unique client-generated identifier (the client ID) to + * IndexedDb’s "owner" store every 4 seconds. If the primary client fails to + * update this entry, another client can acquire the lease and take over as + * primary. + * + * Some persistence operations in the SDK are designated as primary-client only + * operations. This includes the acknowledgment of mutations and all updates of + * remote documents. The effects of these operations are written to persistence + * and then broadcast to other tabs via LocalStorage (see + * `WebStorageSharedClientState`), which then refresh their state from + * persistence. + * + * Similarly, the primary client listens to notifications sent by secondary + * clients to discover persistence changes written by secondary clients, such as + * the addition of new mutations and query targets. + * + * If multi-tab is not enabled and another tab already obtained the primary + * lease, IndexedDbPersistence enters a failed state and all subsequent + * operations will automatically fail. + * + * Additionally, there is an optimization so that when a tab is closed, the + * primary lease is released immediately (this is especially important to make + * sure that a refreshed tab is able to immediately re-acquire the primary + * lease). Unfortunately, IndexedDB cannot be reliably used in window.unload + * since it is an asynchronous API. So in addition to attempting to give up the + * lease, the leaseholder writes its client ID to a "zombiedClient" entry in + * LocalStorage which acts as an indicator that another tab should go ahead and + * take the primary lease immediately regardless of the current lease timestamp. + * + * TODO(b/114226234): Remove `synchronizeTabs` section when multi-tab is no + * longer optional. + */ +export declare class IndexedDbPersistence implements Persistence { + /** + * Whether to synchronize the in-memory state of multiple tabs and share + * access to local persistence. + */ + private readonly allowTabSynchronization; + private readonly persistenceKey; + private readonly clientId; + private readonly queue; + private readonly window; + private readonly document; + private readonly sequenceNumberSyncer; + /** + * If set to true, forcefully obtains database access. Existing tabs will + * no longer be able to access IndexedDB. + */ + private readonly forceOwningTab; + private readonly schemaVersion; + private simpleDb; + private listenSequence; + private _started; + private isPrimary; + private networkEnabled; + private dbName; + /** Our window.unload handler, if registered. */ + private windowUnloadHandler; + private inForeground; + private serializer; + /** Our 'visibilitychange' listener if registered. */ + private documentVisibilityHandler; + /** The client metadata refresh task. */ + private clientMetadataRefresher; + /** The last time we garbage collected the client metadata object store. */ + private lastGarbageCollectionTime; + /** A listener to notify on primary state changes. */ + private primaryStateListener; + private readonly globalsCache; + private readonly targetCache; + private readonly remoteDocumentCache; + private readonly bundleCache; + private readonly webStorage; + readonly referenceDelegate: IndexedDbLruDelegateImpl; + constructor( + /** + * Whether to synchronize the in-memory state of multiple tabs and share + * access to local persistence. + */ + allowTabSynchronization: boolean, persistenceKey: string, clientId: ClientId, lruParams: LruParams, queue: AsyncQueue, window: WindowLike | null, document: DocumentLike | null, serializer: JsonProtoSerializer, sequenceNumberSyncer: SequenceNumberSyncer, + /** + * If set to true, forcefully obtains database access. Existing tabs will + * no longer be able to access IndexedDB. + */ + forceOwningTab: boolean, schemaVersion?: number); + /** + * Attempt to start IndexedDb persistence. + * + * @returns Whether persistence was enabled. + */ + start(): Promise; + /** + * Registers a listener that gets called when the primary state of the + * instance changes. Upon registering, this listener is invoked immediately + * with the current primary state. + * + * PORTING NOTE: This is only used for Web multi-tab. + */ + setPrimaryStateListener(primaryStateListener: PrimaryStateListener): Promise; + /** + * Registers a listener that gets called when the database receives a + * version change event indicating that it has deleted. + * + * PORTING NOTE: This is only used for Web multi-tab. + */ + setDatabaseDeletedListener(databaseDeletedListener: () => Promise): void; + /** + * Adjusts the current network state in the client's metadata, potentially + * affecting the primary lease. + * + * PORTING NOTE: This is only used for Web multi-tab. + */ + setNetworkEnabled(networkEnabled: boolean): void; + /** + * Updates the client metadata in IndexedDb and attempts to either obtain or + * extend the primary lease for the local client. Asynchronously notifies the + * primary state listener if the client either newly obtained or released its + * primary lease. + */ + private updateClientMetadataAndTryBecomePrimary; + private verifyPrimaryLease; + private removeClientMetadata; + /** + * If the garbage collection threshold has passed, prunes the + * RemoteDocumentChanges and the ClientMetadata store based on the last update + * time of all clients. + */ + private maybeGarbageCollectMultiClientState; + /** + * Schedules a recurring timer to update the client metadata and to either + * extend or acquire the primary lease if the client is eligible. + */ + private scheduleClientMetadataAndPrimaryLeaseRefreshes; + /** Checks whether `client` is the local client. */ + private isLocalClient; + /** + * Evaluate the state of all active clients and determine whether the local + * client is or can act as the holder of the primary lease. Returns whether + * the client is eligible for the lease, but does not actually acquire it. + * May return 'false' even if there is no active leaseholder and another + * (foreground) client should become leaseholder instead. + */ + private canActAsPrimary; + shutdown(): Promise; + /** + * Returns clients that are not zombied and have an updateTime within the + * provided threshold. + */ + private filterActiveClients; + /** + * Returns the IDs of the clients that are currently active. If multi-tab + * is not supported, returns an array that only contains the local client's + * ID. + * + * PORTING NOTE: This is only used for Web multi-tab. + */ + getActiveClients(): Promise; + get started(): boolean; + getGlobalsCache(): GlobalsCache; + getMutationQueue(user: User, indexManager: IndexManager): IndexedDbMutationQueue; + getTargetCache(): IndexedDbTargetCache; + getRemoteDocumentCache(): IndexedDbRemoteDocumentCache; + getIndexManager(user: User): IndexManager; + getDocumentOverlayCache(user: User): DocumentOverlayCache; + getBundleCache(): BundleCache; + runTransaction(action: string, mode: PersistenceTransactionMode, transactionOperation: (transaction: PersistenceTransaction) => PersistencePromise): Promise; + /** + * Verifies that the current tab is the primary leaseholder or alternatively + * that the leaseholder has opted into multi-tab synchronization. + */ + private verifyAllowTabSynchronization; + /** + * Obtains or extends the new primary lease for the local client. This + * method does not verify that the client is eligible for this lease. + */ + private acquireOrExtendPrimaryLease; + static isAvailable(): boolean; + /** Checks the primary lease and removes it if we are the current primary. */ + private releasePrimaryLeaseIfHeld; + /** Verifies that `updateTimeMs` is within `maxAgeMs`. */ + private isWithinAge; + private attachVisibilityHandler; + private detachVisibilityHandler; + /** + * Attaches a window.unload handler that will synchronously write our + * clientId to a "zombie client id" location in LocalStorage. This can be used + * by tabs trying to acquire the primary lease to determine that the lease + * is no longer valid even if the timestamp is recent. This is particularly + * important for the refresh case (so the tab correctly re-acquires the + * primary lease). LocalStorage is used for this rather than IndexedDb because + * it is a synchronous API and so can be used reliably from an unload + * handler. + */ + private attachWindowUnloadHook; + private detachWindowUnloadHook; + /** + * Returns whether a client is "zombied" based on its LocalStorage entry. + * Clients become zombied when their tab closes without running all of the + * cleanup logic in `shutdown()`. + */ + private isClientZombied; + /** + * Record client as zombied (a client that had its tab closed). Zombied + * clients are ignored during primary tab selection. + */ + private markClientZombied; + /** Removes the zombied client entry if it exists. */ + private removeClientZombiedEntry; + private zombiedClientLocalStorageKey; +} +/** + * Generates a string used as a prefix when storing data in IndexedDB and + * LocalStorage. + */ +export declare function indexedDbStoragePrefix(databaseId: DatabaseId, persistenceKey: string): string; +export declare function indexedDbClearPersistence(persistenceKey: string): Promise; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_remote_document_cache.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_remote_document_cache.d.ts new file mode 100644 index 0000000..14532c1 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_remote_document_cache.d.ts @@ -0,0 +1,36 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { MutableDocument } from '../model/document'; +import { DocumentKey } from '../model/document_key'; +import { LocalSerializer } from './local_serializer'; +import { RemoteDocumentCache } from './remote_document_cache'; +export interface DocumentSizeEntry { + document: MutableDocument; + size: number; +} +export interface IndexedDbRemoteDocumentCache extends RemoteDocumentCache { +} +/** Creates a new IndexedDbRemoteDocumentCache. */ +export declare function newIndexedDbRemoteDocumentCache(serializer: LocalSerializer): IndexedDbRemoteDocumentCache; +/** + * Comparator that compares document keys according to the primary key sorting + * used by the `DbRemoteDocumentDocument` store (by prefix path, collection id + * and then document ID). + * + * Visible for testing. + */ +export declare function dbKeyComparator(l: DocumentKey, r: DocumentKey): number; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_schema.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_schema.d.ts new file mode 100644 index 0000000..a88f237 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_schema.d.ts @@ -0,0 +1,509 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { BatchId, ListenSequenceNumber, TargetId } from '../core/types'; +import { IndexKind } from '../model/field_index'; +import { BundledQuery } from '../protos/firestore_bundle_proto'; +import { Document as ProtoDocument, DocumentsTarget as ProtoDocumentsTarget, QueryTarget as ProtoQueryTarget, Write as ProtoWrite } from '../protos/firestore_proto_api'; +import { EncodedResourcePath } from './encoded_resource_path'; +import { DbTimestampKey, KeySafeBytes } from './indexeddb_sentinels'; +/** + * Schema Version for the Web client: + * 1. Initial version including Mutation Queue, Query Cache, and Remote + * Document Cache + * 2. Used to ensure a targetGlobal object exists and add targetCount to it. No + * longer required because migration 3 unconditionally clears it. + * 3. Dropped and re-created Query Cache to deal with cache corruption related + * to limbo resolution. Addresses + * https://github.com/firebase/firebase-ios-sdk/issues/1548 + * 4. Multi-Tab Support. + * 5. Removal of held write acks. + * 6. Create document global for tracking document cache size. + * 7. Ensure every cached document has a sentinel row with a sequence number. + * 8. Add collection-parent index for Collection Group queries. + * 9. Change RemoteDocumentChanges store to be keyed by readTime rather than + * an auto-incrementing ID. This is required for Index-Free queries. + * 10. Rewrite the canonical IDs to the explicit Protobuf-based format. + * 11. Add bundles and named_queries for bundle support. + * 12. Add document overlays. + * 13. Rewrite the keys of the remote document cache to allow for efficient + * document lookup via `getAll()`. + * 14. Add overlays. + * 15. Add indexing support. + * 16. Parse timestamp strings before creating index entries. + * 17. TODO(tomandersen) + * 18. Encode key safe representations of IndexEntry in DbIndexEntryStore. + */ +export declare const SCHEMA_VERSION = 18; +/** + * Wrapper class to store timestamps (seconds and nanos) in IndexedDb objects. + */ +export interface DbTimestamp { + seconds: number; + nanoseconds: number; +} +/** + * A singleton object to be stored in the 'owner' store in IndexedDb. + * + * A given database can have a single primary tab assigned at a given time. That + * tab must validate that it is still holding the primary lease before every + * operation that requires locked access. The primary tab should regularly + * write an updated timestamp to this lease to prevent other tabs from + * "stealing" the primary lease + */ +export interface DbPrimaryClient { + ownerId: string; + /** Whether to allow shared access from multiple tabs. */ + allowTabSynchronization: boolean; + leaseTimestampMs: number; +} +/** + * An object to be stored in the 'mutationQueues' store in IndexedDb. + * + * Each user gets a single queue of MutationBatches to apply to the server. + * DbMutationQueue tracks the metadata about the queue. + */ +export interface DbMutationQueue { + /** + * The normalized user ID to which this queue belongs. + */ + userId: string; + /** + * An identifier for the highest numbered batch that has been acknowledged + * by the server. All MutationBatches in this queue with batchIds less + * than or equal to this value are considered to have been acknowledged by + * the server. + * + * NOTE: this is deprecated and no longer used by the code. + */ + lastAcknowledgedBatchId: number; + /** + * A stream token that was previously sent by the server. + * + * See StreamingWriteRequest in datastore.proto for more details about + * usage. + * + * After sending this token, earlier tokens may not be used anymore so + * only a single stream token is retained. + * + * NOTE: this is deprecated and no longer used by the code. + */ + lastStreamToken: string; +} +/** + * An object to be stored in the 'mutations' store in IndexedDb. + * + * Represents a batch of user-level mutations intended to be sent to the server + * in a single write. Each user-level batch gets a separate DbMutationBatch + * with a new batchId. + */ +export interface DbMutationBatch { + /** + * The normalized user ID to which this batch belongs. + */ + userId: string; + /** + * An identifier for this batch, allocated using an auto-generated key. + */ + batchId: BatchId; + /** + * The local write time of the batch, stored as milliseconds since the + * epoch. + */ + localWriteTimeMs: number; + /** + * A list of "mutations" that represent a partial base state from when this + * write batch was initially created. During local application of the write + * batch, these baseMutations are applied prior to the real writes in order + * to override certain document fields from the remote document cache. This + * is necessary in the case of non-idempotent writes (e.g. `increment()` + * transforms) to make sure that the local view of the modified documents + * doesn't flicker if the remote document cache receives the result of the + * non-idempotent write before the write is removed from the queue. + * + * These mutations are never sent to the backend. + */ + baseMutations?: ProtoWrite[]; + /** + * A list of mutations to apply. All mutations will be applied atomically. + * + * Mutations are serialized via toMutation(). + */ + mutations: ProtoWrite[]; +} +/** + * An object to be stored in the 'documentMutations' store in IndexedDb. + * + * A manually maintained index of all the mutation batches that affect a given + * document key. The rows in this table are references based on the contents of + * DbMutationBatch.mutations. + */ +export interface DbDocumentMutation { +} +/** + * Represents the known absence of a document at a particular version. + * Stored in IndexedDb as part of a DbRemoteDocument object. + */ +export interface DbNoDocument { + path: string[]; + readTime: DbTimestamp; +} +/** + * Represents a document that is known to exist but whose data is unknown. + * Stored in IndexedDb as part of a DbRemoteDocument object. + */ +export interface DbUnknownDocument { + path: string[]; + version: DbTimestamp; +} +/** + * An object to be stored in the 'remoteDocuments' store in IndexedDb. + * It represents either: + * + * - A complete document. + * - A "no document" representing a document that is known not to exist (at + * some version). + * - An "unknown document" representing a document that is known to exist (at + * some version) but whose contents are unknown. + * + * The document key is split up across `prefixPath`, `collectionGroup` and + * `documentId`. + * + * Note: This is the persisted equivalent of a MaybeDocument and could perhaps + * be made more general if necessary. + */ +export interface DbRemoteDocument { + /** The path to the document's collection (excluding). */ + prefixPath: string[]; + /** The collection ID the document is directly nested under. */ + collectionGroup: string; + /** The document ID. */ + documentId: string; + /** When the document was read from the backend. */ + readTime: DbTimestampKey; + /** + * Set to an instance of DbUnknownDocument if the data for a document is + * not known, but it is known that a document exists at the specified + * version (e.g. it had a successful update applied to it) + */ + unknownDocument?: DbUnknownDocument; + /** + * Set to an instance of a DbNoDocument if it is known that no document + * exists. + */ + noDocument?: DbNoDocument; + /** + * Set to an instance of a Document if there's a cached version of the + * document. + */ + document?: ProtoDocument; + /** + * Documents that were written to the remote document store based on + * a write acknowledgment are marked with `hasCommittedMutations`. These + * documents are potentially inconsistent with the backend's copy and use + * the write's commit version as their document version. + */ + hasCommittedMutations: boolean; +} +/** + * Contains a single entry that has metadata about the remote document cache. + */ +export interface DbRemoteDocumentGlobal { + /** + * Approximately the total size in bytes of all the + * documents in the document cache. + */ + byteSize: number; +} +/** + * The persisted type for a query nested with in the 'targets' store in + * IndexedDb. We use the proto definitions for these two kinds of queries in + * order to avoid writing extra serialization logic. + */ +export type DbQuery = ProtoQueryTarget | ProtoDocumentsTarget; +/** + * An object to be stored in the 'targets' store in IndexedDb. + * + * This is based on and should be kept in sync with the proto used in the iOS + * client. + * + * Each query the client listens to against the server is tracked on disk so + * that the query can be efficiently resumed on restart. + */ +export interface DbTarget { + /** + * An auto-generated sequential numeric identifier for the query. + * + * Queries are stored using their canonicalId as the key, but these + * canonicalIds can be quite long so we additionally assign a unique + * queryId which can be used by referenced data structures (e.g. + * indexes) to minimize the on-disk cost. + */ + targetId: TargetId; + /** + * The canonical string representing this query. This is not unique. + */ + canonicalId: string; + /** + * The last readTime received from the Watch Service for this query. + * + * This is the same value as TargetChange.read_time in the protos. + */ + readTime: DbTimestamp; + /** + * An opaque, server-assigned token that allows watching a query to be + * resumed after disconnecting without retransmitting all the data + * that matches the query. The resume token essentially identifies a + * point in time from which the server should resume sending results. + * + * This is related to the snapshotVersion in that the resumeToken + * effectively also encodes that value, but the resumeToken is opaque + * and sometimes encodes additional information. + * + * A consequence of this is that the resumeToken should be used when + * asking the server to reason about where this client is in the watch + * stream, but the client should use the snapshotVersion for its own + * purposes. + * + * This is the same value as TargetChange.resume_token in the protos. + */ + resumeToken: string; + /** + * A sequence number representing the last time this query was + * listened to, used for garbage collection purposes. + * + * Conventionally this would be a timestamp value, but device-local + * clocks are unreliable and they must be able to create new listens + * even while disconnected. Instead this should be a monotonically + * increasing number that's incremented on each listen call. + * + * This is different from the queryId since the queryId is an + * immutable identifier assigned to the Query on first use while + * lastListenSequenceNumber is updated every time the query is + * listened to. + */ + lastListenSequenceNumber: number; + /** + * Denotes the maximum snapshot version at which the associated query view + * contained no limbo documents. Undefined for data written prior to + * schema version 9. + */ + lastLimboFreeSnapshotVersion?: DbTimestamp; + /** + * The query for this target. + * + * Because canonical ids are not unique we must store the actual query. We + * use the proto to have an object we can persist without having to + * duplicate translation logic to and from a `Query` object. + */ + query: DbQuery; +} +/** + * An object representing an association between a target and a document, or a + * sentinel row marking the last sequence number at which a document was used. + * Each document cached must have a corresponding sentinel row before lru + * garbage collection is enabled. + * + * The target associations and sentinel rows are co-located so that orphaned + * documents and their sequence numbers can be identified efficiently via a scan + * of this store. + */ +export interface DbTargetDocument { + /** + * The targetId identifying a target or 0 for a sentinel row. + */ + targetId: TargetId; + /** + * The path to the document, as encoded in the key. + */ + path: EncodedResourcePath; + /** + * If this is a sentinel row, this should be the sequence number of the last + * time the document specified by `path` was used. Otherwise, it should be + * `undefined`. + */ + sequenceNumber?: ListenSequenceNumber; +} +/** + * A record of global state tracked across all Targets, tracked separately + * to avoid the need for extra indexes. + * + * This should be kept in-sync with the proto used in the iOS client. + */ +export interface DbTargetGlobal { + /** + * The highest numbered target id across all targets. + * + * See DbTarget.targetId. + */ + highestTargetId: TargetId; + /** + * The highest numbered lastListenSequenceNumber across all targets. + * + * See DbTarget.lastListenSequenceNumber. + */ + highestListenSequenceNumber: number; + /** + * A global snapshot version representing the last consistent snapshot we + * received from the backend. This is monotonically increasing and any + * snapshots received from the backend prior to this version (e.g. for + * targets resumed with a resumeToken) should be suppressed (buffered) + * until the backend has caught up to this snapshot version again. This + * prevents our cache from ever going backwards in time. + */ + lastRemoteSnapshotVersion: DbTimestamp; + /** + * The number of targets persisted. + */ + targetCount: number; +} +/** + * An object representing an association between a Collection id (e.g. 'messages') + * to a parent path (e.g. '/chats/123') that contains it as a (sub)collection. + * This is used to efficiently find all collections to query when performing + * a Collection Group query. + */ +export interface DbCollectionParent { + /** + * The collectionId (e.g. 'messages') + */ + collectionId: string; + /** + * The path to the parent (either a document location or an empty path for + * a root-level collection). + */ + parent: EncodedResourcePath; +} +/** + * A record of the metadata state of each client. + * + * PORTING NOTE: This is used to synchronize multi-tab state and does not need + * to be ported to iOS or Android. + */ +export interface DbClientMetadata { + /** The auto-generated client id assigned at client startup. */ + clientId: string; + /** The last time this state was updated. */ + updateTimeMs: number; + /** Whether the client's network connection is enabled. */ + networkEnabled: boolean; + /** Whether this client is running in a foreground tab. */ + inForeground: boolean; +} +/** An object representing a bundle loaded by the SDK. */ +export interface DbBundle { + /** The ID of the loaded bundle. */ + bundleId: string; + /** The create time of the loaded bundle. */ + createTime: DbTimestamp; + /** The schema version of the loaded bundle. */ + version: number; +} +/** An object representing a named query loaded by the SDK via a bundle. */ +export interface DbNamedQuery { + /** The name of the query. */ + name: string; + /** The read time of the results saved in the bundle from the named query. */ + readTime: DbTimestamp; + /** The query saved in the bundle. */ + bundledQuery: BundledQuery; +} +/** An object representing the global configuration for a field index. */ +export interface DbIndexConfiguration { + /** + * The index id for this entry. Undefined for indexes that are not yet + * persisted. + */ + indexId?: number; + /** The collection group this index belongs to. */ + collectionGroup: string; + /** The fields to index for this index. */ + fields: Array<[name: string, kind: IndexKind]>; +} +/** + * An object describing how up-to-date the index backfill is for each user and + * index. + */ +export interface DbIndexState { + /** The index id for this entry. */ + indexId: number; + /** The user id for this entry. */ + uid: string; + /** + * A number that indicates when the index was last updated (relative to + * other indexes). + */ + sequenceNumber: number; + /** + * The latest read time that has been indexed by Firestore for this field + * index. Set to `{seconds: 0, nanos: 0}` if no documents have been indexed. + */ + readTime: DbTimestamp; + /** + * The last document that has been indexed for this field index. Empty if + * no documents have been indexed. + */ + documentKey: EncodedResourcePath; + /** + * The largest mutation batch id that has been processed for this index. -1 + * if no mutations have been indexed. + */ + largestBatchId: number; +} +/** An object that stores the encoded entries for all documents and fields. */ +export interface DbIndexEntry { + /** The index id for this entry. */ + indexId: number; + /** The user id for this entry. */ + uid: string; + /** The encoded array index value for this entry. */ + arrayValue: KeySafeBytes; + /** The encoded directional value for equality and inequality filters. */ + directionalValue: KeySafeBytes; + /** + * The document key this entry points to. This entry is encoded by an ordered + * encoder to match the key order of the index. + */ + orderedDocumentKey: KeySafeBytes; + /** The segments of the document key this entry points to. */ + documentKey: string[]; +} +/** + * An object representing a document overlay. + */ +export interface DbDocumentOverlay { + /** The user ID to whom this overlay belongs. */ + userId: string; + /** The path to the collection that contains the document. */ + collectionPath: string; + /** The ID (key) of the document within the collection. */ + documentId: string; + /** The collection group to which the document belongs. */ + collectionGroup: string; + /** The largest batch ID that's been applied for this overlay. */ + largestBatchId: number; + /** The overlay mutation. */ + overlayMutation: ProtoWrite; +} +/** + * An object containing global name/value pair. + */ +export interface DbGlobals { + /** Name is a globally unique identifier for a value. */ + name: string; + /** Value is a general purpose storage for global data. */ + value: Uint8Array; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_schema_converter.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_schema_converter.d.ts new file mode 100644 index 0000000..0daedc5 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_schema_converter.d.ts @@ -0,0 +1,43 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { LocalSerializer } from './local_serializer'; +import { PersistencePromise } from './persistence_promise'; +import { SimpleDbSchemaConverter } from './simple_db'; +/** Performs database creation and schema upgrades. */ +export declare class SchemaConverter implements SimpleDbSchemaConverter { + private readonly serializer; + constructor(serializer: LocalSerializer); + /** + * Performs database creation and schema upgrades. + * + * Note that in production, this method is only ever used to upgrade the schema + * to SCHEMA_VERSION. Different values of toVersion are only used for testing + * and local feature development. + */ + createOrUpgrade(db: IDBDatabase, txn: IDBTransaction, fromVersion: number, toVersion: number): PersistencePromise; + private addDocumentGlobal; + private removeAcknowledgedMutations; + /** + * Ensures that every document in the remote document cache has a corresponding sentinel row + * with a sequence number. Missing rows are given the most recently used sequence number. + */ + private ensureSequenceNumbers; + private createCollectionParentIndex; + private rewriteCanonicalIds; + private rewriteRemoteDocumentCache; + private runOverlayMigration; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_schema_legacy.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_schema_legacy.d.ts new file mode 100644 index 0000000..51716a6 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_schema_legacy.d.ts @@ -0,0 +1,29 @@ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Document as ProtoDocument } from '../protos/firestore_proto_api'; +import { DbNoDocument, DbUnknownDocument } from './indexeddb_schema'; +import { DbTimestampKey } from './indexeddb_sentinels'; +export interface DbRemoteDocument { + unknownDocument?: DbUnknownDocument; + noDocument?: DbNoDocument; + document?: ProtoDocument; + hasCommittedMutations?: boolean; + readTime?: DbTimestampKey; + parentPath?: string[]; +} +export type DbRemoteDocumentKey = string[]; +export declare const DbRemoteDocumentStore = "remoteDocuments"; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_sentinels.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_sentinels.d.ts new file mode 100644 index 0000000..acd9785 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_sentinels.d.ts @@ -0,0 +1,267 @@ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { BatchId, TargetId } from '../core/types'; +import { ResourcePath } from '../model/path'; +import { EncodedResourcePath } from './encoded_resource_path'; +import { DbDocumentMutation } from './indexeddb_schema'; +/** A timestamp type that can be used in IndexedDb keys. */ +export type DbTimestampKey = [/* seconds */ number, /* nanos */ number]; +export type DbPrimaryClientKey = typeof DbPrimaryClientKey; +/** + * Name of the IndexedDb object store. + * + * Note that the name 'owner' is chosen to ensure backwards compatibility with + * older clients that only supported single locked access to the persistence + * layer. + */ +export declare const DbPrimaryClientStore = "owner"; +/** + * The key string used for the single object that exists in the + * DbPrimaryClient store. + */ +export declare const DbPrimaryClientKey = "owner"; +/** Object keys in the 'mutationQueues' store are userId strings. */ +export type DbMutationQueueKey = string; +/** Name of the IndexedDb object store. */ +export declare const DbMutationQueueStore = "mutationQueues"; +/** Keys are automatically assigned via the userId property. */ +export declare const DbMutationQueueKeyPath = "userId"; +/** The 'mutations' store is keyed by batch ID. */ +export type DbMutationBatchKey = BatchId; +/** Name of the IndexedDb object store. */ +export declare const DbMutationBatchStore = "mutations"; +/** Keys are automatically assigned via the userId, batchId properties. */ +export declare const DbMutationBatchKeyPath = "batchId"; +/** The index name for lookup of mutations by user. */ +export declare const DbMutationBatchUserMutationsIndex = "userMutationsIndex"; +/** The user mutations index is keyed by [userId, batchId] pairs. */ +export declare const DbMutationBatchUserMutationsKeyPath: string[]; +/** + * The key for a db document mutation, which is made up of a userID, path, and + * batchId. Note that the path must be serialized into a form that indexedDB can + * sort. + */ +export type DbDocumentMutationKey = [string, EncodedResourcePath, BatchId]; +/** + * Creates a [userId] key for use in the DbDocumentMutations index to iterate + * over all of a user's document mutations. + */ +export declare function newDbDocumentMutationPrefixForUser(userId: string): [string]; +/** + * Creates a [userId, encodedPath] key for use in the DbDocumentMutations + * index to iterate over all at document mutations for a given path or lower. + */ +export declare function newDbDocumentMutationPrefixForPath(userId: string, path: ResourcePath): [string, EncodedResourcePath]; +/** + * Creates a full index key of [userId, encodedPath, batchId] for inserting + * and deleting into the DbDocumentMutations index. + */ +export declare function newDbDocumentMutationKey(userId: string, path: ResourcePath, batchId: BatchId): DbDocumentMutationKey; +/** + * Because we store all the useful information for this store in the key, + * there is no useful information to store as the value. The raw (unencoded) + * path cannot be stored because IndexedDb doesn't store prototype + * information. + */ +export declare const DbDocumentMutationPlaceholder: DbDocumentMutation; +export declare const DbDocumentMutationStore = "documentMutations"; +export declare const DbRemoteDocumentStore = "remoteDocumentsV14"; +/** + * A key in the 'remoteDocumentsV14' object store is an array containing the + * collection path, the collection group, the read time and the document id. + */ +export type DbRemoteDocumentKey = [ + /** path to collection */ string[], + /** collection group */ string, + /** read time */ DbTimestampKey, + /** document ID */ string +]; +/** + * The primary key of the remote documents store, which allows for efficient + * access by collection path and read time. + */ +export declare const DbRemoteDocumentKeyPath: string[]; +/** An index that provides access to documents by key. */ +export declare const DbRemoteDocumentDocumentKeyIndex = "documentKeyIndex"; +export declare const DbRemoteDocumentDocumentKeyIndexPath: string[]; +/** + * An index that provides access to documents by collection group and read + * time. + * + * This index is used by the index backfiller. + */ +export declare const DbRemoteDocumentCollectionGroupIndex = "collectionGroupIndex"; +export declare const DbRemoteDocumentCollectionGroupIndexPath: string[]; +export declare const DbRemoteDocumentGlobalStore = "remoteDocumentGlobal"; +export declare const DbRemoteDocumentGlobalKey = "remoteDocumentGlobalKey"; +export type DbRemoteDocumentGlobalKey = typeof DbRemoteDocumentGlobalKey; +/** + * A key in the 'targets' object store is a targetId of the query. + */ +export type DbTargetKey = TargetId; +export declare const DbTargetStore = "targets"; +/** Keys are automatically assigned via the targetId property. */ +export declare const DbTargetKeyPath = "targetId"; +/** The name of the queryTargets index. */ +export declare const DbTargetQueryTargetsIndexName = "queryTargetsIndex"; +/** + * The index of all canonicalIds to the targets that they match. This is not + * a unique mapping because canonicalId does not promise a unique name for all + * possible queries, so we append the targetId to make the mapping unique. + */ +export declare const DbTargetQueryTargetsKeyPath: string[]; +/** + * The key for a DbTargetDocument, containing a targetId and an encoded resource + * path. + */ +export type DbTargetDocumentKey = [TargetId, EncodedResourcePath]; +/** Name of the IndexedDb object store. */ +export declare const DbTargetDocumentStore = "targetDocuments"; +/** Keys are automatically assigned via the targetId, path properties. */ +export declare const DbTargetDocumentKeyPath: string[]; +/** The index name for the reverse index. */ +export declare const DbTargetDocumentDocumentTargetsIndex = "documentTargetsIndex"; +/** We also need to create the reverse index for these properties. */ +export declare const DbTargetDocumentDocumentTargetsKeyPath: string[]; +/** + * The type to represent the single allowed key for the DbTargetGlobal store. + */ +export type DbTargetGlobalKey = typeof DbTargetGlobalKey; +/** + * The key string used for the single object that exists in the + * DbTargetGlobal store. + */ +export declare const DbTargetGlobalKey = "targetGlobalKey"; +export declare const DbTargetGlobalStore = "targetGlobal"; +/** + * The key for a DbCollectionParent entry, containing the collection ID + * and the parent path that contains it. Note that the parent path will be an + * empty path in the case of root-level collections. + */ +export type DbCollectionParentKey = [string, EncodedResourcePath]; +/** Name of the IndexedDb object store. */ +export declare const DbCollectionParentStore = "collectionParents"; +/** Keys are automatically assigned via the collectionId, parent properties. */ +export declare const DbCollectionParentKeyPath: string[]; +/** Name of the IndexedDb object store. */ +export declare const DbClientMetadataStore = "clientMetadata"; +/** Keys are automatically assigned via the clientId properties. */ +export declare const DbClientMetadataKeyPath = "clientId"; +/** Object keys in the 'clientMetadata' store are clientId strings. */ +export type DbClientMetadataKey = string; +export type DbBundlesKey = string; +/** Name of the IndexedDb object store. */ +export declare const DbBundleStore = "bundles"; +export declare const DbBundleKeyPath = "bundleId"; +export type DbNamedQueriesKey = string; +/** Name of the IndexedDb object store. */ +export declare const DbNamedQueryStore = "namedQueries"; +export declare const DbNamedQueryKeyPath = "name"; +/** The key for each index consisting of just the index id. */ +export type DbIndexConfigurationKey = number; +/** Name of the IndexedDb object store. */ +export declare const DbIndexConfigurationStore = "indexConfiguration"; +export declare const DbIndexConfigurationKeyPath = "indexId"; +/** + * An index that provides access to the index configurations by collection + * group. + * + * PORTING NOTE: iOS and Android maintain this index in-memory, but this is + * not possible here as the Web client supports concurrent access to + * persistence via multi-tab. + */ +export declare const DbIndexConfigurationCollectionGroupIndex = "collectionGroupIndex"; +export declare const DbIndexConfigurationCollectionGroupIndexPath = "collectionGroup"; +/** The key for each index state consisting of the index id and its user id. */ +export type DbIndexStateKey = [number, string]; +/** Name of the IndexedDb object store. */ +export declare const DbIndexStateStore = "indexState"; +export declare const DbIndexStateKeyPath: string[]; +/** + * An index that provides access to documents in a collection sorted by last + * update time. Used by the backfiller. + * + * PORTING NOTE: iOS and Android maintain this index in-memory, but this is + * not possible here as the Web client supports concurrent access to + * persistence via multi-tab. + */ +export declare const DbIndexStateSequenceNumberIndex = "sequenceNumberIndex"; +export declare const DbIndexStateSequenceNumberIndexPath: string[]; +/** + * Representation of a byte array that is safe for + * use in an IndexedDb key. The value is either + * a "sortable byte string", which is key safe in + * Safari/WebKit, or the value is a Uint8Array, + * which is key safe in other browsers. + */ +export type KeySafeBytes = Uint8Array | string; +/** + * The key for each index entry consists of the index id and its user id, + * the encoded array and directional value for the indexed fields as well as + * an ordered and an encoded document path for the indexed document. + */ +export type DbIndexEntryKey = [ + number, + string, + KeySafeBytes, + KeySafeBytes, + KeySafeBytes, + string[] +]; +/** Name of the IndexedDb object store. */ +export declare const DbIndexEntryStore = "indexEntries"; +export declare const DbIndexEntryKeyPath: string[]; +export declare const DbIndexEntryDocumentKeyIndex = "documentKeyIndex"; +export declare const DbIndexEntryDocumentKeyIndexPath: string[]; +export type DbDocumentOverlayKey = [ + string, + string, + string +]; +/** Name of the IndexedDb object store. */ +export declare const DbDocumentOverlayStore = "documentOverlays"; +export declare const DbDocumentOverlayKeyPath: string[]; +export declare const DbDocumentOverlayCollectionPathOverlayIndex = "collectionPathOverlayIndex"; +export declare const DbDocumentOverlayCollectionPathOverlayIndexPath: string[]; +export declare const DbDocumentOverlayCollectionGroupOverlayIndex = "collectionGroupOverlayIndex"; +export declare const DbDocumentOverlayCollectionGroupOverlayIndexPath: string[]; +/** Name of the IndexedDb object store. */ +export declare const DbGlobalsStore = "globals"; +export declare const DbGlobalsKeyPath = "name"; +/** Names of global values */ +export type DbGlobalsKey = 'sessionToken'; +export declare const V1_STORES: string[]; +export declare const V3_STORES: string[]; +export declare const V4_STORES: string[]; +export declare const V6_STORES: string[]; +export declare const V8_STORES: string[]; +export declare const V11_STORES: string[]; +export declare const V12_STORES: string[]; +export declare const V13_STORES: string[]; +export declare const V14_STORES: string[]; +export declare const V15_STORES: string[]; +export declare const V16_STORES: string[]; +export declare const V17_STORES: string[]; +export declare const V18_STORES: string[]; +/** + * The list of all default IndexedDB stores used throughout the SDK. This is + * used when creating transactions so that access across all stores is done + * atomically. + */ +export declare const ALL_STORES: string[]; +/** Returns the object stores for the provided schema. */ +export declare function getObjectStores(schemaVersion: number): string[]; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_target_cache.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_target_cache.d.ts new file mode 100644 index 0000000..74654fe --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_target_cache.d.ts @@ -0,0 +1,81 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { SnapshotVersion } from '../core/snapshot_version'; +import { Target } from '../core/target'; +import { ListenSequenceNumber, TargetId } from '../core/types'; +import { DocumentKeySet } from '../model/collections'; +import { DocumentKey } from '../model/document_key'; +import { IndexedDbLruDelegate } from './indexeddb_lru_delegate'; +import { DbTargetDocument } from './indexeddb_schema'; +import { DbTargetDocumentKey } from './indexeddb_sentinels'; +import { LocalSerializer } from './local_serializer'; +import { ActiveTargets } from './lru_garbage_collector'; +import { PersistencePromise } from './persistence_promise'; +import { PersistenceTransaction } from './persistence_transaction'; +import { SimpleDbStore } from './simple_db'; +import { TargetCache } from './target_cache'; +import { TargetData } from './target_data'; +export declare class IndexedDbTargetCache implements TargetCache { + private readonly referenceDelegate; + private serializer; + constructor(referenceDelegate: IndexedDbLruDelegate, serializer: LocalSerializer); + allocateTargetId(transaction: PersistenceTransaction): PersistencePromise; + getLastRemoteSnapshotVersion(transaction: PersistenceTransaction): PersistencePromise; + getHighestSequenceNumber(transaction: PersistenceTransaction): PersistencePromise; + setTargetsMetadata(transaction: PersistenceTransaction, highestListenSequenceNumber: number, lastRemoteSnapshotVersion?: SnapshotVersion): PersistencePromise; + addTargetData(transaction: PersistenceTransaction, targetData: TargetData): PersistencePromise; + updateTargetData(transaction: PersistenceTransaction, targetData: TargetData): PersistencePromise; + removeTargetData(transaction: PersistenceTransaction, targetData: TargetData): PersistencePromise; + /** + * Drops any targets with sequence number less than or equal to the upper bound, excepting those + * present in `activeTargetIds`. Document associations for the removed targets are also removed. + * Returns the number of targets removed. + */ + removeTargets(txn: PersistenceTransaction, upperBound: ListenSequenceNumber, activeTargetIds: ActiveTargets): PersistencePromise; + /** + * Call provided function with each `TargetData` that we have cached. + */ + forEachTarget(txn: PersistenceTransaction, f: (q: TargetData) => void): PersistencePromise; + private retrieveMetadata; + private saveMetadata; + private saveTargetData; + /** + * In-place updates the provided metadata to account for values in the given + * TargetData. Saving is done separately. Returns true if there were any + * changes to the metadata. + */ + private updateMetadataFromTargetData; + getTargetCount(transaction: PersistenceTransaction): PersistencePromise; + getTargetData(transaction: PersistenceTransaction, target: Target): PersistencePromise; + addMatchingKeys(txn: PersistenceTransaction, keys: DocumentKeySet, targetId: TargetId): PersistencePromise; + removeMatchingKeys(txn: PersistenceTransaction, keys: DocumentKeySet, targetId: TargetId): PersistencePromise; + removeMatchingKeysForTargetId(txn: PersistenceTransaction, targetId: TargetId): PersistencePromise; + getMatchingKeysForTargetId(txn: PersistenceTransaction, targetId: TargetId): PersistencePromise; + containsKey(txn: PersistenceTransaction, key: DocumentKey): PersistencePromise; + /** + * Looks up a TargetData entry by target ID. + * + * @param targetId - The target ID of the TargetData entry to look up. + * @returns The cached TargetData entry, or null if the cache has no entry for + * the target. + */ + getTargetDataForTarget(transaction: PersistenceTransaction, targetId: TargetId): PersistencePromise; +} +/** + * Helper to get a typed SimpleDbStore for the document target object store. + */ +export declare function documentTargetStore(txn: PersistenceTransaction): SimpleDbStore; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_transaction.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_transaction.d.ts new file mode 100644 index 0000000..4d1fc92 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_transaction.d.ts @@ -0,0 +1,25 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { ListenSequenceNumber } from '../core/types'; +import { PersistenceTransaction } from './persistence_transaction'; +import { SimpleDbStore, SimpleDbTransaction } from './simple_db'; +export declare class IndexedDbTransaction extends PersistenceTransaction { + readonly simpleDbTransaction: SimpleDbTransaction; + readonly currentSequenceNumber: ListenSequenceNumber; + constructor(simpleDbTransaction: SimpleDbTransaction, currentSequenceNumber: ListenSequenceNumber); +} +export declare function getStore(txn: PersistenceTransaction, store: string): SimpleDbStore; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/local_documents_view.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/local_documents_view.d.ts new file mode 100644 index 0000000..8d276c3 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/local_documents_view.d.ts @@ -0,0 +1,127 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Query } from '../core/query'; +import { DocumentKeySet, OverlayMap, DocumentMap, MutableDocumentMap, DocumentKeyMap, OverlayedDocumentMap } from '../model/collections'; +import { Document } from '../model/document'; +import { DocumentKey } from '../model/document_key'; +import { IndexOffset } from '../model/field_index'; +import { FieldMask } from '../model/field_mask'; +import { DocumentOverlayCache } from './document_overlay_cache'; +import { IndexManager } from './index_manager'; +import { LocalWriteResult } from './local_store_impl'; +import { MutationQueue } from './mutation_queue'; +import { PersistencePromise } from './persistence_promise'; +import { PersistenceTransaction } from './persistence_transaction'; +import { QueryContext } from './query_context'; +import { RemoteDocumentCache } from './remote_document_cache'; +/** + * A readonly view of the local state of all documents we're tracking (i.e. we + * have a cached version in remoteDocumentCache or local mutations for the + * document). The view is computed by applying the mutations in the + * MutationQueue to the RemoteDocumentCache. + */ +export declare class LocalDocumentsView { + readonly remoteDocumentCache: RemoteDocumentCache; + readonly mutationQueue: MutationQueue; + readonly documentOverlayCache: DocumentOverlayCache; + readonly indexManager: IndexManager; + constructor(remoteDocumentCache: RemoteDocumentCache, mutationQueue: MutationQueue, documentOverlayCache: DocumentOverlayCache, indexManager: IndexManager); + /** + * Get the local view of the document identified by `key`. + * + * @returns Local view of the document or null if we don't have any cached + * state for it. + */ + getDocument(transaction: PersistenceTransaction, key: DocumentKey): PersistencePromise; + /** + * Gets the local view of the documents identified by `keys`. + * + * If we don't have cached state for a document in `keys`, a NoDocument will + * be stored for that key in the resulting set. + */ + getDocuments(transaction: PersistenceTransaction, keys: DocumentKeySet): PersistencePromise; + /** + * Similar to `getDocuments`, but creates the local view from the given + * `baseDocs` without retrieving documents from the local store. + * + * @param transaction - The transaction this operation is scoped to. + * @param docs - The documents to apply local mutations to get the local views. + * @param existenceStateChanged - The set of document keys whose existence state + * is changed. This is useful to determine if some documents overlay needs + * to be recalculated. + */ + getLocalViewOfDocuments(transaction: PersistenceTransaction, docs: MutableDocumentMap, existenceStateChanged?: DocumentKeySet): PersistencePromise; + /** + * Gets the overlayed documents for the given document map, which will include + * the local view of those documents and a `FieldMask` indicating which fields + * are mutated locally, `null` if overlay is a Set or Delete mutation. + */ + getOverlayedDocuments(transaction: PersistenceTransaction, docs: MutableDocumentMap): PersistencePromise; + /** + * Fetches the overlays for {@code docs} and adds them to provided overlay map + * if the map does not already contain an entry for the given document key. + */ + private populateOverlays; + /** + * Computes the local view for the given documents. + * + * @param docs - The documents to compute views for. It also has the base + * version of the documents. + * @param overlays - The overlays that need to be applied to the given base + * version of the documents. + * @param existenceStateChanged - A set of documents whose existence states + * might have changed. This is used to determine if we need to re-calculate + * overlays from mutation queues. + * @return A map represents the local documents view. + */ + computeViews(transaction: PersistenceTransaction, docs: MutableDocumentMap, overlays: OverlayMap, existenceStateChanged: DocumentKeySet): PersistencePromise; + private recalculateAndSaveOverlays; + /** + * Recalculates overlays by reading the documents from remote document cache + * first, and saves them after they are calculated. + */ + recalculateAndSaveOverlaysForDocumentKeys(transaction: PersistenceTransaction, documentKeys: DocumentKeySet): PersistencePromise>; + /** + * Performs a query against the local view of all documents. + * + * @param transaction - The persistence transaction. + * @param query - The query to match documents against. + * @param offset - Read time and key to start scanning by (exclusive). + * @param context - A optional tracker to keep a record of important details + * during database local query execution. + */ + getDocumentsMatchingQuery(transaction: PersistenceTransaction, query: Query, offset: IndexOffset, context?: QueryContext): PersistencePromise; + /** + * Given a collection group, returns the next documents that follow the provided offset, along + * with an updated batch ID. + * + *

The documents returned by this method are ordered by remote version from the provided + * offset. If there are no more remote documents after the provided offset, documents with + * mutations in order of batch id from the offset are returned. Since all documents in a batch are + * returned together, the total number of documents returned can exceed {@code count}. + * + * @param transaction + * @param collectionGroup The collection group for the documents. + * @param offset The offset to index into. + * @param count The number of documents to return + * @return A LocalWriteResult with the documents that follow the provided offset and the last processed batch id. + */ + getNextDocuments(transaction: PersistenceTransaction, collectionGroup: string, offset: IndexOffset, count: number): PersistencePromise; + private getDocumentsMatchingDocumentQuery; + private getDocumentsMatchingCollectionGroupQuery; + private getDocumentsMatchingCollectionQuery; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/local_serializer.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/local_serializer.d.ts new file mode 100644 index 0000000..88599b4 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/local_serializer.d.ts @@ -0,0 +1,80 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { BundleMetadata, NamedQuery } from '../core/bundle'; +import { Query } from '../core/query'; +import { SnapshotVersion } from '../core/snapshot_version'; +import { MutableDocument } from '../model/document'; +import { DocumentKey } from '../model/document_key'; +import { FieldIndex, IndexOffset } from '../model/field_index'; +import { MutationBatch } from '../model/mutation_batch'; +import { Overlay } from '../model/overlay'; +import { BundledQuery as ProtoBundledQuery, BundleMetadata as ProtoBundleMetadata, NamedQuery as ProtoNamedQuery } from '../protos/firestore_bundle_proto'; +import { JsonProtoSerializer } from '../remote/serializer'; +import { DbBundle, DbDocumentOverlay, DbIndexConfiguration, DbIndexState, DbMutationBatch, DbNamedQuery, DbRemoteDocument, DbTarget, DbTimestamp } from './indexeddb_schema'; +import { DbDocumentOverlayKey, DbTimestampKey } from './indexeddb_sentinels'; +import { TargetData } from './target_data'; +/** Serializer for values stored in the LocalStore. */ +export declare class LocalSerializer { + readonly remoteSerializer: JsonProtoSerializer; + constructor(remoteSerializer: JsonProtoSerializer); +} +/** Decodes a remote document from storage locally to a Document. */ +export declare function fromDbRemoteDocument(localSerializer: LocalSerializer, remoteDoc: DbRemoteDocument): MutableDocument; +/** Encodes a document for storage locally. */ +export declare function toDbRemoteDocument(localSerializer: LocalSerializer, document: MutableDocument): DbRemoteDocument; +export declare function toDbTimestampKey(snapshotVersion: SnapshotVersion): DbTimestampKey; +export declare function fromDbTimestampKey(dbTimestampKey: DbTimestampKey): SnapshotVersion; +export declare function toDbTimestamp(snapshotVersion: SnapshotVersion): DbTimestamp; +/** Encodes a batch of mutations into a DbMutationBatch for local storage. */ +export declare function toDbMutationBatch(localSerializer: LocalSerializer, userId: string, batch: MutationBatch): DbMutationBatch; +/** Decodes a DbMutationBatch into a MutationBatch */ +export declare function fromDbMutationBatch(localSerializer: LocalSerializer, dbBatch: DbMutationBatch): MutationBatch; +/** Decodes a DbTarget into TargetData */ +export declare function fromDbTarget(dbTarget: DbTarget): TargetData; +/** Encodes TargetData into a DbTarget for storage locally. */ +export declare function toDbTarget(localSerializer: LocalSerializer, targetData: TargetData): DbTarget; +/** Encodes a DbBundle to a BundleMetadata object. */ +export declare function fromDbBundle(dbBundle: DbBundle): BundleMetadata; +/** Encodes a BundleMetadata to a DbBundle. */ +export declare function toDbBundle(metadata: ProtoBundleMetadata): DbBundle; +/** Encodes a DbNamedQuery to a NamedQuery. */ +export declare function fromDbNamedQuery(dbNamedQuery: DbNamedQuery): NamedQuery; +/** Encodes a NamedQuery from a bundle proto to a DbNamedQuery. */ +export declare function toDbNamedQuery(query: ProtoNamedQuery): DbNamedQuery; +/** + * Encodes a `BundledQuery` from bundle proto to a Query object. + * + * This reconstructs the original query used to build the bundle being loaded, + * including features exists only in SDKs (for example: limit-to-last). + */ +export declare function fromBundledQuery(bundledQuery: ProtoBundledQuery): Query; +/** Encodes a NamedQuery proto object to a NamedQuery model object. */ +export declare function fromProtoNamedQuery(namedQuery: ProtoNamedQuery): NamedQuery; +/** Decodes a BundleMetadata proto into a BundleMetadata object. */ +export declare function fromBundleMetadata(metadata: ProtoBundleMetadata): BundleMetadata; +/** Encodes a DbDocumentOverlay object to an Overlay model object. */ +export declare function fromDbDocumentOverlay(localSerializer: LocalSerializer, dbDocumentOverlay: DbDocumentOverlay): Overlay; +/** Decodes an Overlay model object into a DbDocumentOverlay object. */ +export declare function toDbDocumentOverlay(localSerializer: LocalSerializer, userId: string, overlay: Overlay): DbDocumentOverlay; +/** + * Returns the DbDocumentOverlayKey corresponding to the given user and + * document key. + */ +export declare function toDbDocumentOverlayKey(userId: string, docKey: DocumentKey): DbDocumentOverlayKey; +export declare function toDbIndexConfiguration(index: FieldIndex): DbIndexConfiguration; +export declare function fromDbIndexConfiguration(index: DbIndexConfiguration, state: DbIndexState | null): FieldIndex; +export declare function toDbIndexState(indexId: number, uid: string, sequenceNumber: number, offset: IndexOffset): DbIndexState; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/local_store.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/local_store.d.ts new file mode 100644 index 0000000..2284d7d --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/local_store.d.ts @@ -0,0 +1,41 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { FirestoreError } from '../util/error'; +import { IndexManager } from './index_manager'; +import { LocalDocumentsView } from './local_documents_view'; +import { LruGarbageCollector, LruResults } from './lru_garbage_collector'; +export interface LocalStore { + collectGarbage(garbageCollector: LruGarbageCollector): Promise; + /** Manages the list of active field and collection indices. */ + indexManager: IndexManager; + /** + * The "local" view of all documents (layering mutationQueue on top of + * remoteDocumentCache). + */ + localDocuments: LocalDocumentsView; +} +/** + * Verifies the error thrown by a LocalStore operation. If a LocalStore + * operation fails because the primary lease has been taken by another client, + * we ignore the error (the persistence layer will immediately call + * `applyPrimaryLease` to propagate the primary state change). All other errors + * are re-thrown. + * + * @param err - An error returned by a LocalStore operation. + * @returns A Promise that resolves after we recovered, or the original error. + */ +export declare function ignoreIfPrimaryLeaseLoss(err: FirestoreError): Promise; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/local_store_impl.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/local_store_impl.d.ts new file mode 100644 index 0000000..1b86e0d --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/local_store_impl.d.ts @@ -0,0 +1,208 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { User } from '../auth/user'; +import { BundleConverter, BundledDocuments, NamedQuery } from '../core/bundle'; +import { Query } from '../core/query'; +import { SnapshotVersion } from '../core/snapshot_version'; +import { Target } from '../core/target'; +import { BatchId, TargetId } from '../core/types'; +import { DocumentKeySet, DocumentMap } from '../model/collections'; +import { Document } from '../model/document'; +import { DocumentKey } from '../model/document_key'; +import { FieldIndex } from '../model/field_index'; +import { Mutation } from '../model/mutation'; +import { MutationBatch, MutationBatchResult } from '../model/mutation_batch'; +import { BundleMetadata, NamedQuery as ProtoNamedQuery } from '../protos/firestore_bundle_proto'; +import { RemoteEvent } from '../remote/remote_event'; +import { JsonProtoSerializer } from '../remote/serializer'; +import { LocalStore } from './local_store'; +import { LocalViewChanges } from './local_view_changes'; +import { Persistence } from './persistence'; +import { PersistencePromise } from './persistence_promise'; +import { PersistenceTransaction } from './persistence_transaction'; +import { QueryEngine } from './query_engine'; +import { ClientId } from './shared_client_state'; +import { TargetData } from './target_data'; +export declare const LOG_TAG = "LocalStore"; +/** The result of a write to the local store. */ +export interface LocalWriteResult { + batchId: BatchId; + changes: DocumentMap; +} +/** The result of a user-change operation in the local store. */ +export interface UserChangeResult { + readonly affectedDocuments: DocumentMap; + readonly removedBatchIds: BatchId[]; + readonly addedBatchIds: BatchId[]; +} +/** The result of executing a query against the local store. */ +export interface QueryResult { + readonly documents: DocumentMap; + readonly remoteKeys: DocumentKeySet; +} +export declare function newLocalStore( +/** Manages our in-memory or durable persistence. */ +persistence: Persistence, queryEngine: QueryEngine, initialUser: User, serializer: JsonProtoSerializer): LocalStore; +/** + * Tells the LocalStore that the currently authenticated user has changed. + * + * In response the local store switches the mutation queue to the new user and + * returns any resulting document changes. + */ +export declare function localStoreHandleUserChange(localStore: LocalStore, user: User): Promise; +export declare function localStoreWriteLocally(localStore: LocalStore, mutations: Mutation[]): Promise; +/** + * Acknowledges the given batch. + * + * On the happy path when a batch is acknowledged, the local store will + * + * + remove the batch from the mutation queue; + * + apply the changes to the remote document cache; + * + recalculate the latency compensated view implied by those changes (there + * may be mutations in the queue that affect the documents but haven't been + * acknowledged yet); and + * + give the changed documents back the sync engine + * + * @returns The resulting (modified) documents. + */ +export declare function localStoreAcknowledgeBatch(localStore: LocalStore, batchResult: MutationBatchResult): Promise; +/** + * Removes mutations from the MutationQueue for the specified batch; + * LocalDocuments will be recalculated. + * + * @returns The resulting modified documents. + */ +export declare function localStoreRejectBatch(localStore: LocalStore, batchId: BatchId): Promise; +/** + * Returns the largest (latest) batch id in mutation queue that is pending + * server response. + * + * Returns `BATCHID_UNKNOWN` if the queue is empty. + */ +export declare function localStoreGetHighestUnacknowledgedBatchId(localStore: LocalStore): Promise; +/** + * Returns the last consistent snapshot processed (used by the RemoteStore to + * determine whether to buffer incoming snapshots from the backend). + */ +export declare function localStoreGetLastRemoteSnapshotVersion(localStore: LocalStore): Promise; +/** + * Updates the "ground-state" (remote) documents. We assume that the remote + * event reflects any write batches that have been acknowledged or rejected + * (i.e. we do not re-apply local mutations to updates from this event). + * + * LocalDocuments are re-calculated if there are remaining mutations in the + * queue. + */ +export declare function localStoreApplyRemoteEventToLocalCache(localStore: LocalStore, remoteEvent: RemoteEvent): Promise; +/** + * Notifies local store of the changed views to locally pin documents. + */ +export declare function localStoreNotifyLocalViewChanges(localStore: LocalStore, viewChanges: LocalViewChanges[]): Promise; +/** + * Gets the mutation batch after the passed in batchId in the mutation queue + * or null if empty. + * @param afterBatchId - If provided, the batch to search after. + * @returns The next mutation or null if there wasn't one. + */ +export declare function localStoreGetNextMutationBatch(localStore: LocalStore, afterBatchId?: BatchId): Promise; +/** + * Reads the current value of a Document with a given key or null if not + * found - used for testing. + */ +export declare function localStoreReadDocument(localStore: LocalStore, key: DocumentKey): Promise; +/** + * Assigns the given target an internal ID so that its results can be pinned so + * they don't get GC'd. A target must be allocated in the local store before + * the store can be used to manage its view. + * + * Allocating an already allocated `Target` will return the existing `TargetData` + * for that `Target`. + */ +export declare function localStoreAllocateTarget(localStore: LocalStore, target: Target): Promise; +/** + * Returns the TargetData as seen by the LocalStore, including updates that may + * have not yet been persisted to the TargetCache. + */ +export declare function localStoreGetTargetData(localStore: LocalStore, transaction: PersistenceTransaction, target: Target): PersistencePromise; +/** + * Unpins all the documents associated with the given target. If + * `keepPersistedTargetData` is set to false and Eager GC enabled, the method + * directly removes the associated target data from the target cache. + * + * Releasing a non-existing `Target` is a no-op. + */ +export declare function localStoreReleaseTarget(localStore: LocalStore, targetId: number, keepPersistedTargetData: boolean): Promise; +/** + * Runs the specified query against the local store and returns the results, + * potentially taking advantage of query data from previous executions (such + * as the set of remote keys). + * + * @param usePreviousResults - Whether results from previous executions can + * be used to optimize this query execution. + */ +export declare function localStoreExecuteQuery(localStore: LocalStore, query: Query, usePreviousResults: boolean): Promise; +/** Returns the local view of the documents affected by a mutation batch. */ +export declare function localStoreLookupMutationDocuments(localStore: LocalStore, batchId: BatchId): Promise; +export declare function localStoreRemoveCachedMutationBatchMetadata(localStore: LocalStore, batchId: BatchId): void; +export declare function localStoreGetActiveClients(localStore: LocalStore): Promise; +export declare function localStoreGetCachedTarget(localStore: LocalStore, targetId: TargetId): Promise; +/** + * Returns the set of documents that have been updated since the last call. + * If this is the first call, returns the set of changes since client + * initialization. Further invocations will return document that have changed + * since the prior call. + */ +export declare function localStoreGetNewDocumentChanges(localStore: LocalStore, collectionGroup: string): Promise; +/** + * Applies the documents from a bundle to the "ground-state" (remote) + * documents. + * + * LocalDocuments are re-calculated if there are remaining mutations in the + * queue. + */ +export declare function localStoreApplyBundledDocuments(localStore: LocalStore, bundleConverter: BundleConverter, documents: BundledDocuments, bundleName: string): Promise; +/** + * Returns a promise of a boolean to indicate if the given bundle has already + * been loaded and the create time is newer than the current loading bundle. + */ +export declare function localStoreHasNewerBundle(localStore: LocalStore, bundleMetadata: BundleMetadata): Promise; +/** + * Saves the given `BundleMetadata` to local persistence. + */ +export declare function localStoreSaveBundle(localStore: LocalStore, bundleMetadata: BundleMetadata): Promise; +/** + * Returns a promise of a `NamedQuery` associated with given query name. Promise + * resolves to undefined if no persisted data can be found. + */ +export declare function localStoreGetNamedQuery(localStore: LocalStore, queryName: string): Promise; +/** + * Saves the given `NamedQuery` to local persistence. + */ +export declare function localStoreSaveNamedQuery(localStore: LocalStore, query: ProtoNamedQuery, documents?: DocumentKeySet): Promise; +export declare function localStoreConfigureFieldIndexes(localStore: LocalStore, newFieldIndexes: FieldIndex[]): Promise; +export declare function localStoreSetIndexAutoCreationEnabled(localStore: LocalStore, isEnabled: boolean): void; +export declare function localStoreDeleteAllFieldIndexes(localStore: LocalStore): Promise; +/** + * Test-only hooks into the SDK for use exclusively by tests. + */ +export declare class TestingHooks { + private constructor(); + static setIndexAutoCreationSettings(localStore: LocalStore, settings: { + indexAutoCreationMinCollectionSize?: number; + relativeIndexReadCostPerDocument?: number; + }): void; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/local_view_changes.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/local_view_changes.d.ts new file mode 100644 index 0000000..0448fb1 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/local_view_changes.d.ts @@ -0,0 +1,32 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { TargetId } from '../core/types'; +import { ViewSnapshot } from '../core/view_snapshot'; +import { DocumentKeySet } from '../model/collections'; +/** + * A set of changes to what documents are currently in view and out of view for + * a given query. These changes are sent to the LocalStore by the View (via + * the SyncEngine) and are used to pin / unpin documents as appropriate. + */ +export declare class LocalViewChanges { + readonly targetId: TargetId; + readonly fromCache: boolean; + readonly addedKeys: DocumentKeySet; + readonly removedKeys: DocumentKeySet; + constructor(targetId: TargetId, fromCache: boolean, addedKeys: DocumentKeySet, removedKeys: DocumentKeySet); + static fromSnapshot(targetId: TargetId, viewSnapshot: ViewSnapshot): LocalViewChanges; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/lru_garbage_collector.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/lru_garbage_collector.d.ts new file mode 100644 index 0000000..9ba755c --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/lru_garbage_collector.d.ts @@ -0,0 +1,102 @@ +/** + * @license + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { ListenSequenceNumber, TargetId } from '../core/types'; +import { SortedMap } from '../util/sorted_map'; +import { PersistencePromise } from './persistence_promise'; +import { PersistenceTransaction } from './persistence_transaction'; +import { TargetData } from './target_data'; +/** + * Describes a map whose keys are active target ids. We do not care about the type of the + * values. + */ +export type ActiveTargets = SortedMap; +export declare const GC_DID_NOT_RUN: LruResults; +export declare const LRU_COLLECTION_DISABLED = -1; +export declare const LRU_DEFAULT_CACHE_SIZE_BYTES: number; +export declare class LruParams { + readonly cacheSizeCollectionThreshold: number; + readonly percentileToCollect: number; + readonly maximumSequenceNumbersToCollect: number; + private static readonly DEFAULT_COLLECTION_PERCENTILE; + private static readonly DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT; + static withCacheSize(cacheSize: number): LruParams; + static readonly DEFAULT: LruParams; + static readonly DISABLED: LruParams; + constructor(cacheSizeCollectionThreshold: number, percentileToCollect: number, maximumSequenceNumbersToCollect: number); +} +export interface LruGarbageCollector { + readonly params: LruParams; + collect(txn: PersistenceTransaction, activeTargetIds: ActiveTargets): PersistencePromise; + /** Given a percentile of target to collect, returns the number of targets to collect. */ + calculateTargetCount(txn: PersistenceTransaction, percentile: number): PersistencePromise; + /** Returns the nth sequence number, counting in order from the smallest. */ + nthSequenceNumber(txn: PersistenceTransaction, n: number): PersistencePromise; + /** + * Removes documents that have a sequence number equal to or less than the + * upper bound and are not otherwise pinned. + */ + removeOrphanedDocuments(txn: PersistenceTransaction, upperBound: ListenSequenceNumber): PersistencePromise; + getCacheSize(txn: PersistenceTransaction): PersistencePromise; + /** + * Removes targets with a sequence number equal to or less than the given + * upper bound, and removes document associations with those targets. + */ + removeTargets(txn: PersistenceTransaction, upperBound: ListenSequenceNumber, activeTargetIds: ActiveTargets): PersistencePromise; +} +/** + * Describes the results of a garbage collection run. `didRun` will be set to + * `false` if collection was skipped (either it is disabled or the cache size + * has not hit the threshold). If collection ran, the other fields will be + * filled in with the details of the results. + */ +export interface LruResults { + readonly didRun: boolean; + readonly sequenceNumbersCollected: number; + readonly targetsRemoved: number; + readonly documentsRemoved: number; +} +/** + * Persistence layers intending to use LRU Garbage collection should have + * reference delegates that implement this interface. This interface defines the + * operations that the LRU garbage collector needs from the persistence layer. + */ +export interface LruDelegate { + readonly garbageCollector: LruGarbageCollector; + /** Enumerates all the targets in the TargetCache. */ + forEachTarget(txn: PersistenceTransaction, f: (target: TargetData) => void): PersistencePromise; + getSequenceNumberCount(txn: PersistenceTransaction): PersistencePromise; + /** + * Enumerates sequence numbers for documents not associated with a target. + * Note that this may include duplicate sequence numbers. + */ + forEachOrphanedDocumentSequenceNumber(txn: PersistenceTransaction, f: (sequenceNumber: ListenSequenceNumber) => void): PersistencePromise; + /** + * Removes all targets that have a sequence number less than or equal to + * `upperBound`, and are not present in the `activeTargetIds` set. + * + * @returns the number of targets removed. + */ + removeTargets(txn: PersistenceTransaction, upperBound: ListenSequenceNumber, activeTargetIds: ActiveTargets): PersistencePromise; + /** + * Removes all unreferenced documents from the cache that have a sequence + * number less than or equal to the given `upperBound`. + * + * @returns the number of documents removed. + */ + removeOrphanedDocuments(txn: PersistenceTransaction, upperBound: ListenSequenceNumber): PersistencePromise; + getCacheSize(txn: PersistenceTransaction): PersistencePromise; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/lru_garbage_collector_impl.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/lru_garbage_collector_impl.d.ts new file mode 100644 index 0000000..f4ab1a5 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/lru_garbage_collector_impl.d.ts @@ -0,0 +1,37 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { AsyncQueue } from '../util/async_queue'; +import { LocalStore } from './local_store'; +import { LruDelegate, LruGarbageCollector, LruParams } from './lru_garbage_collector'; +import { Scheduler } from './persistence'; +export declare const LRU_MINIMUM_CACHE_SIZE_BYTES: number; +/** + * This class is responsible for the scheduling of LRU garbage collection. It handles checking + * whether or not GC is enabled, as well as which delay to use before the next run. + */ +export declare class LruScheduler implements Scheduler { + private readonly garbageCollector; + private readonly asyncQueue; + private readonly localStore; + private gcTask; + constructor(garbageCollector: LruGarbageCollector, asyncQueue: AsyncQueue, localStore: LocalStore); + start(): void; + stop(): void; + get started(): boolean; + private scheduleGC; +} +export declare function newLruGarbageCollector(delegate: LruDelegate, params: LruParams): LruGarbageCollector; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/memory_bundle_cache.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/memory_bundle_cache.d.ts new file mode 100644 index 0000000..972d4fc --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/memory_bundle_cache.d.ts @@ -0,0 +1,32 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { BundleMetadata, NamedQuery } from '../core/bundle'; +import { NamedQuery as ProtoNamedQuery, BundleMetadata as ProtoBundleMetadata } from '../protos/firestore_bundle_proto'; +import { BundleCache } from './bundle_cache'; +import { LocalSerializer } from './local_serializer'; +import { PersistencePromise } from './persistence_promise'; +import { PersistenceTransaction } from './persistence_transaction'; +export declare class MemoryBundleCache implements BundleCache { + private serializer; + private bundles; + private namedQueries; + constructor(serializer: LocalSerializer); + getBundleMetadata(transaction: PersistenceTransaction, bundleId: string): PersistencePromise; + saveBundleMetadata(transaction: PersistenceTransaction, bundleMetadata: ProtoBundleMetadata): PersistencePromise; + getNamedQuery(transaction: PersistenceTransaction, queryName: string): PersistencePromise; + saveNamedQuery(transaction: PersistenceTransaction, query: ProtoNamedQuery): PersistencePromise; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/memory_document_overlay_cache.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/memory_document_overlay_cache.d.ts new file mode 100644 index 0000000..b6ee945 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/memory_document_overlay_cache.d.ts @@ -0,0 +1,37 @@ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { DocumentKeySet, MutationMap, OverlayMap } from '../model/collections'; +import { DocumentKey } from '../model/document_key'; +import { Overlay } from '../model/overlay'; +import { ResourcePath } from '../model/path'; +import { DocumentOverlayCache } from './document_overlay_cache'; +import { PersistencePromise } from './persistence_promise'; +import { PersistenceTransaction } from './persistence_transaction'; +/** + * An in-memory implementation of DocumentOverlayCache. + */ +export declare class MemoryDocumentOverlayCache implements DocumentOverlayCache { + private overlays; + private overlayByBatchId; + getOverlay(transaction: PersistenceTransaction, key: DocumentKey): PersistencePromise; + getOverlays(transaction: PersistenceTransaction, keys: DocumentKey[]): PersistencePromise; + saveOverlays(transaction: PersistenceTransaction, largestBatchId: number, overlays: MutationMap): PersistencePromise; + removeOverlaysForBatchId(transaction: PersistenceTransaction, documentKeys: DocumentKeySet, batchId: number): PersistencePromise; + getOverlaysForCollection(transaction: PersistenceTransaction, collection: ResourcePath, sinceBatchId: number): PersistencePromise; + getOverlaysForCollectionGroup(transaction: PersistenceTransaction, collectionGroup: string, sinceBatchId: number, count: number): PersistencePromise; + private saveOverlay; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/memory_globals_cache.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/memory_globals_cache.d.ts new file mode 100644 index 0000000..9877c67 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/memory_globals_cache.d.ts @@ -0,0 +1,25 @@ +/** + * @license + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { ByteString } from '../util/byte_string'; +import { GlobalsCache } from './globals_cache'; +import { PersistencePromise } from './persistence_promise'; +import { PersistenceTransaction } from './persistence_transaction'; +export declare class MemoryGlobalsCache implements GlobalsCache { + private sessionToken; + getSessionToken(transaction: PersistenceTransaction): PersistencePromise; + setSessionToken(transaction: PersistenceTransaction, sessionToken: ByteString): PersistencePromise; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/memory_index_manager.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/memory_index_manager.d.ts new file mode 100644 index 0000000..14ffd3d --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/memory_index_manager.d.ts @@ -0,0 +1,55 @@ +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Target } from '../core/target'; +import { DocumentMap } from '../model/collections'; +import { DocumentKey } from '../model/document_key'; +import { FieldIndex, IndexOffset } from '../model/field_index'; +import { ResourcePath } from '../model/path'; +import { IndexManager, IndexType } from './index_manager'; +import { PersistencePromise } from './persistence_promise'; +import { PersistenceTransaction } from './persistence_transaction'; +/** + * An in-memory implementation of IndexManager. + */ +export declare class MemoryIndexManager implements IndexManager { + private collectionParentIndex; + addToCollectionParentIndex(transaction: PersistenceTransaction, collectionPath: ResourcePath): PersistencePromise; + getCollectionParents(transaction: PersistenceTransaction, collectionId: string): PersistencePromise; + addFieldIndex(transaction: PersistenceTransaction, index: FieldIndex): PersistencePromise; + deleteFieldIndex(transaction: PersistenceTransaction, index: FieldIndex): PersistencePromise; + deleteAllFieldIndexes(transaction: PersistenceTransaction): PersistencePromise; + createTargetIndexes(transaction: PersistenceTransaction, target: Target): PersistencePromise; + getDocumentsMatchingTarget(transaction: PersistenceTransaction, target: Target): PersistencePromise; + getIndexType(transaction: PersistenceTransaction, target: Target): PersistencePromise; + getFieldIndexes(transaction: PersistenceTransaction, collectionGroup?: string): PersistencePromise; + getNextCollectionGroupToUpdate(transaction: PersistenceTransaction): PersistencePromise; + getMinOffset(transaction: PersistenceTransaction, target: Target): PersistencePromise; + getMinOffsetFromCollectionGroup(transaction: PersistenceTransaction, collectionGroup: string): PersistencePromise; + updateCollectionGroup(transaction: PersistenceTransaction, collectionGroup: string, offset: IndexOffset): PersistencePromise; + updateIndexEntries(transaction: PersistenceTransaction, documents: DocumentMap): PersistencePromise; +} +/** + * Internal implementation of the collection-parent index exposed by MemoryIndexManager. + * Also used for in-memory caching by IndexedDbIndexManager and initial index population + * in indexeddb_schema.ts + */ +export declare class MemoryCollectionParentIndex { + private index; + add(collectionPath: ResourcePath): boolean; + has(collectionPath: ResourcePath): boolean; + getEntries(collectionId: string): ResourcePath[]; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/memory_mutation_queue.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/memory_mutation_queue.d.ts new file mode 100644 index 0000000..ad685f9 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/memory_mutation_queue.d.ts @@ -0,0 +1,80 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Query } from '../core/query'; +import { BatchId } from '../core/types'; +import { Timestamp } from '../lite-api/timestamp'; +import { DocumentKey } from '../model/document_key'; +import { Mutation } from '../model/mutation'; +import { MutationBatch } from '../model/mutation_batch'; +import { SortedMap } from '../util/sorted_map'; +import { IndexManager } from './index_manager'; +import { MutationQueue } from './mutation_queue'; +import { ReferenceDelegate } from './persistence'; +import { PersistencePromise } from './persistence_promise'; +import { PersistenceTransaction } from './persistence_transaction'; +export declare class MemoryMutationQueue implements MutationQueue { + private readonly indexManager; + private readonly referenceDelegate; + /** + * The set of all mutations that have been sent but not yet been applied to + * the backend. + */ + private mutationQueue; + /** Next value to use when assigning sequential IDs to each mutation batch. */ + private nextBatchId; + /** An ordered mapping between documents and the mutations batch IDs. */ + private batchesByDocumentKey; + constructor(indexManager: IndexManager, referenceDelegate: ReferenceDelegate); + checkEmpty(transaction: PersistenceTransaction): PersistencePromise; + addMutationBatch(transaction: PersistenceTransaction, localWriteTime: Timestamp, baseMutations: Mutation[], mutations: Mutation[]): PersistencePromise; + lookupMutationBatch(transaction: PersistenceTransaction, batchId: BatchId): PersistencePromise; + getNextMutationBatchAfterBatchId(transaction: PersistenceTransaction, batchId: BatchId): PersistencePromise; + getHighestUnacknowledgedBatchId(): PersistencePromise; + getAllMutationBatches(transaction: PersistenceTransaction): PersistencePromise; + getAllMutationBatchesAffectingDocumentKey(transaction: PersistenceTransaction, documentKey: DocumentKey): PersistencePromise; + getAllMutationBatchesAffectingDocumentKeys(transaction: PersistenceTransaction, documentKeys: SortedMap): PersistencePromise; + getAllMutationBatchesAffectingQuery(transaction: PersistenceTransaction, query: Query): PersistencePromise; + private findMutationBatches; + removeMutationBatch(transaction: PersistenceTransaction, batch: MutationBatch): PersistencePromise; + removeCachedMutationKeys(batchId: BatchId): void; + containsKey(txn: PersistenceTransaction, key: DocumentKey): PersistencePromise; + performConsistencyCheck(txn: PersistenceTransaction): PersistencePromise; + /** + * Finds the index of the given batchId in the mutation queue and asserts that + * the resulting index is within the bounds of the queue. + * + * @param batchId - The batchId to search for + * @param action - A description of what the caller is doing, phrased in passive + * form (e.g. "acknowledged" in a routine that acknowledges batches). + */ + private indexOfExistingBatchId; + /** + * Finds the index of the given batchId in the mutation queue. This operation + * is O(1). + * + * @returns The computed index of the batch with the given batchId, based on + * the state of the queue. Note this index can be negative if the requested + * batchId has already been removed from the queue or past the end of the + * queue if the batchId is larger than the last added batch. + */ + private indexOfBatchId; + /** + * A version of lookupMutationBatch that doesn't return a promise, this makes + * other functions that uses this code easier to read and more efficient. + */ + private findMutationBatch; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/memory_persistence.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/memory_persistence.d.ts new file mode 100644 index 0000000..051c94b --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/memory_persistence.d.ts @@ -0,0 +1,134 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { User } from '../auth/user'; +import { ListenSequenceNumber, TargetId } from '../core/types'; +import { Document } from '../model/document'; +import { DocumentKey } from '../model/document_key'; +import { JsonProtoSerializer } from '../remote/serializer'; +import { DocumentOverlayCache } from './document_overlay_cache'; +import { GlobalsCache } from './globals_cache'; +import { IndexManager } from './index_manager'; +import { ActiveTargets, LruDelegate, LruGarbageCollector, LruParams } from './lru_garbage_collector'; +import { MemoryBundleCache } from './memory_bundle_cache'; +import { MemoryIndexManager } from './memory_index_manager'; +import { MemoryRemoteDocumentCache } from './memory_remote_document_cache'; +import { MemoryTargetCache } from './memory_target_cache'; +import { MutationQueue } from './mutation_queue'; +import { Persistence, ReferenceDelegate } from './persistence'; +import { PersistencePromise } from './persistence_promise'; +import { PersistenceTransaction, PersistenceTransactionMode } from './persistence_transaction'; +import { TargetData } from './target_data'; +/** + * A memory-backed instance of Persistence. Data is stored only in RAM and + * not persisted across sessions. + */ +export declare class MemoryPersistence implements Persistence { + /** + * Note that these are retained here to make it easier to write tests + * affecting both the in-memory and IndexedDB-backed persistence layers. Tests + * can create a new LocalStore wrapping this Persistence instance and this + * will make the in-memory persistence layer behave as if it were actually + * persisting values. + */ + private readonly indexManager; + private readonly globalsCache; + private mutationQueues; + private overlays; + private readonly remoteDocumentCache; + private readonly targetCache; + private readonly bundleCache; + private readonly listenSequence; + private serializer; + private _started; + readonly referenceDelegate: MemoryReferenceDelegate; + /** + * The constructor accepts a factory for creating a reference delegate. This + * allows both the delegate and this instance to have strong references to + * each other without having nullable fields that would then need to be + * checked or asserted on every access. + */ + constructor(referenceDelegateFactory: (p: MemoryPersistence) => MemoryReferenceDelegate, serializer: JsonProtoSerializer); + start(): Promise; + shutdown(): Promise; + get started(): boolean; + setDatabaseDeletedListener(): void; + setNetworkEnabled(): void; + getIndexManager(user: User): MemoryIndexManager; + getDocumentOverlayCache(user: User): DocumentOverlayCache; + getMutationQueue(user: User, indexManager: IndexManager): MutationQueue; + getGlobalsCache(): GlobalsCache; + getTargetCache(): MemoryTargetCache; + getRemoteDocumentCache(): MemoryRemoteDocumentCache; + getBundleCache(): MemoryBundleCache; + runTransaction(action: string, mode: PersistenceTransactionMode, transactionOperation: (transaction: PersistenceTransaction) => PersistencePromise): Promise; + mutationQueuesContainKey(transaction: PersistenceTransaction, key: DocumentKey): PersistencePromise; +} +/** + * Memory persistence is not actually transactional, but future implementations + * may have transaction-scoped state. + */ +export declare class MemoryTransaction extends PersistenceTransaction { + readonly currentSequenceNumber: ListenSequenceNumber; + constructor(currentSequenceNumber: ListenSequenceNumber); +} +export interface MemoryReferenceDelegate extends ReferenceDelegate { + documentSize(doc: Document): number; + onTransactionStarted(): void; + onTransactionCommitted(txn: PersistenceTransaction): PersistencePromise; +} +export declare class MemoryEagerDelegate implements MemoryReferenceDelegate { + private readonly persistence; + /** Tracks all documents that are active in Query views. */ + private localViewReferences; + /** The list of documents that are potentially GCed after each transaction. */ + private _orphanedDocuments; + private constructor(); + static factory(persistence: MemoryPersistence): MemoryEagerDelegate; + private get orphanedDocuments(); + addReference(txn: PersistenceTransaction, targetId: TargetId, key: DocumentKey): PersistencePromise; + removeReference(txn: PersistenceTransaction, targetId: TargetId, key: DocumentKey): PersistencePromise; + markPotentiallyOrphaned(txn: PersistenceTransaction, key: DocumentKey): PersistencePromise; + removeTarget(txn: PersistenceTransaction, targetData: TargetData): PersistencePromise; + onTransactionStarted(): void; + onTransactionCommitted(txn: PersistenceTransaction): PersistencePromise; + updateLimboDocument(txn: PersistenceTransaction, key: DocumentKey): PersistencePromise; + documentSize(doc: Document): number; + private isReferenced; +} +export declare class MemoryLruDelegate implements ReferenceDelegate, LruDelegate { + private readonly persistence; + private orphanedSequenceNumbers; + readonly garbageCollector: LruGarbageCollector; + constructor(persistence: MemoryPersistence, lruParams: LruParams); + static factory(persistence: MemoryPersistence, lruParams: LruParams): MemoryLruDelegate; + onTransactionStarted(): void; + onTransactionCommitted(txn: PersistenceTransaction): PersistencePromise; + forEachTarget(txn: PersistenceTransaction, f: (q: TargetData) => void): PersistencePromise; + getSequenceNumberCount(txn: PersistenceTransaction): PersistencePromise; + private orphanedDocumentCount; + forEachOrphanedDocumentSequenceNumber(txn: PersistenceTransaction, f: (sequenceNumber: ListenSequenceNumber) => void): PersistencePromise; + removeTargets(txn: PersistenceTransaction, upperBound: ListenSequenceNumber, activeTargetIds: ActiveTargets): PersistencePromise; + removeOrphanedDocuments(txn: PersistenceTransaction, upperBound: ListenSequenceNumber): PersistencePromise; + markPotentiallyOrphaned(txn: PersistenceTransaction, key: DocumentKey): PersistencePromise; + removeTarget(txn: PersistenceTransaction, targetData: TargetData): PersistencePromise; + addReference(txn: PersistenceTransaction, targetId: TargetId, key: DocumentKey): PersistencePromise; + removeReference(txn: PersistenceTransaction, targetId: TargetId, key: DocumentKey): PersistencePromise; + updateLimboDocument(txn: PersistenceTransaction, key: DocumentKey): PersistencePromise; + documentSize(document: Document): number; + private isPinned; + getCacheSize(txn: PersistenceTransaction): PersistencePromise; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/memory_remote_document_cache.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/memory_remote_document_cache.d.ts new file mode 100644 index 0000000..7752914 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/memory_remote_document_cache.d.ts @@ -0,0 +1,33 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Document } from '../model/document'; +import { DocumentKey } from '../model/document_key'; +import { PersistencePromise } from './persistence_promise'; +import { PersistenceTransaction } from './persistence_transaction'; +import { RemoteDocumentCache } from './remote_document_cache'; +export type DocumentSizer = (doc: Document) => number; +export interface MemoryRemoteDocumentCache extends RemoteDocumentCache { + forEachDocumentKey(transaction: PersistenceTransaction, f: (key: DocumentKey) => PersistencePromise): PersistencePromise; +} +/** + * Creates a new memory-only RemoteDocumentCache. + * + * @param sizer - Used to assess the size of a document. For eager GC, this is + * expected to just return 0 to avoid unnecessarily doing the work of + * calculating the size. + */ +export declare function newMemoryRemoteDocumentCache(sizer: DocumentSizer): MemoryRemoteDocumentCache; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/memory_target_cache.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/memory_target_cache.d.ts new file mode 100644 index 0000000..4539d62 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/memory_target_cache.d.ts @@ -0,0 +1,65 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { SnapshotVersion } from '../core/snapshot_version'; +import { Target } from '../core/target'; +import { ListenSequenceNumber, TargetId } from '../core/types'; +import { DocumentKeySet } from '../model/collections'; +import { DocumentKey } from '../model/document_key'; +import { ActiveTargets } from './lru_garbage_collector'; +import { Persistence } from './persistence'; +import { PersistencePromise } from './persistence_promise'; +import { PersistenceTransaction } from './persistence_transaction'; +import { TargetCache } from './target_cache'; +import { TargetData } from './target_data'; +export declare class MemoryTargetCache implements TargetCache { + private readonly persistence; + /** + * Maps a target to the data about that target + */ + private targets; + /** The last received snapshot version. */ + private lastRemoteSnapshotVersion; + /** The highest numbered target ID encountered. */ + private highestTargetId; + /** The highest sequence number encountered. */ + private highestSequenceNumber; + /** + * A ordered bidirectional mapping between documents and the remote target + * IDs. + */ + private references; + private targetCount; + private targetIdGenerator; + constructor(persistence: Persistence); + forEachTarget(txn: PersistenceTransaction, f: (q: TargetData) => void): PersistencePromise; + getLastRemoteSnapshotVersion(transaction: PersistenceTransaction): PersistencePromise; + getHighestSequenceNumber(transaction: PersistenceTransaction): PersistencePromise; + allocateTargetId(transaction: PersistenceTransaction): PersistencePromise; + setTargetsMetadata(transaction: PersistenceTransaction, highestListenSequenceNumber: number, lastRemoteSnapshotVersion?: SnapshotVersion): PersistencePromise; + private saveTargetData; + addTargetData(transaction: PersistenceTransaction, targetData: TargetData): PersistencePromise; + updateTargetData(transaction: PersistenceTransaction, targetData: TargetData): PersistencePromise; + removeTargetData(transaction: PersistenceTransaction, targetData: TargetData): PersistencePromise; + removeTargets(transaction: PersistenceTransaction, upperBound: ListenSequenceNumber, activeTargetIds: ActiveTargets): PersistencePromise; + getTargetCount(transaction: PersistenceTransaction): PersistencePromise; + getTargetData(transaction: PersistenceTransaction, target: Target): PersistencePromise; + addMatchingKeys(txn: PersistenceTransaction, keys: DocumentKeySet, targetId: TargetId): PersistencePromise; + removeMatchingKeys(txn: PersistenceTransaction, keys: DocumentKeySet, targetId: TargetId): PersistencePromise; + removeMatchingKeysForTargetId(txn: PersistenceTransaction, targetId: TargetId): PersistencePromise; + getMatchingKeysForTargetId(txn: PersistenceTransaction, targetId: TargetId): PersistencePromise; + containsKey(txn: PersistenceTransaction, key: DocumentKey): PersistencePromise; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/mutation_queue.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/mutation_queue.d.ts new file mode 100644 index 0000000..2f7b2dd --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/mutation_queue.d.ts @@ -0,0 +1,123 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Query } from '../core/query'; +import { BatchId } from '../core/types'; +import { Timestamp } from '../lite-api/timestamp'; +import { DocumentKey } from '../model/document_key'; +import { Mutation } from '../model/mutation'; +import { MutationBatch } from '../model/mutation_batch'; +import { SortedMap } from '../util/sorted_map'; +import { PersistencePromise } from './persistence_promise'; +import { PersistenceTransaction } from './persistence_transaction'; +/** A queue of mutations to apply to the remote store. */ +export interface MutationQueue { + /** Returns true if this queue contains no mutation batches. */ + checkEmpty(transaction: PersistenceTransaction): PersistencePromise; + /** + * Creates a new mutation batch and adds it to this mutation queue. + * + * @param transaction - The transaction this operation is scoped to. + * @param localWriteTime - The original write time of this mutation. + * @param baseMutations - Mutations that are used to populate the base values + * when this mutation is applied locally. These mutations are used to locally + * overwrite values that are persisted in the remote document cache. + * @param mutations - The user-provided mutations in this mutation batch. + */ + addMutationBatch(transaction: PersistenceTransaction, localWriteTime: Timestamp, baseMutations: Mutation[], mutations: Mutation[]): PersistencePromise; + /** + * Loads the mutation batch with the given batchId. + */ + lookupMutationBatch(transaction: PersistenceTransaction, batchId: BatchId): PersistencePromise; + /** + * Gets the first unacknowledged mutation batch after the passed in batchId + * in the mutation queue or null if empty. + * + * @param batchId - The batch to search after, or BATCHID_UNKNOWN for the + * first mutation in the queue. + * + * @returns the next mutation or null if there wasn't one. + */ + getNextMutationBatchAfterBatchId(transaction: PersistenceTransaction, batchId: BatchId): PersistencePromise; + /** + * Gets the largest (latest) batch id in mutation queue for the current user + * that is pending server response, returns `BATCHID_UNKNOWN` if the queue is + * empty. + * + * @returns the largest batch id in the mutation queue that is not + * acknowledged. + */ + getHighestUnacknowledgedBatchId(transaction: PersistenceTransaction): PersistencePromise; + /** Gets all mutation batches in the mutation queue. */ + getAllMutationBatches(transaction: PersistenceTransaction): PersistencePromise; + /** + * Finds all mutation batches that could possibly affect the given + * document key. Not all mutations in a batch will necessarily affect the + * document key, so when looping through the batch you'll need to check that + * the mutation itself matches the key. + * + * Batches are guaranteed to be in sorted order. + * + * Note that because of this requirement implementations are free to return + * mutation batches that don't contain the document key at all if it's + * convenient. + */ + getAllMutationBatchesAffectingDocumentKey(transaction: PersistenceTransaction, documentKey: DocumentKey): PersistencePromise; + /** + * Finds all mutation batches that could possibly affect the given set of + * document keys. Not all mutations in a batch will necessarily affect each + * key, so when looping through the batch you'll need to check that the + * mutation itself matches the key. + * + * Batches are guaranteed to be in sorted order. + * + * Note that because of this requirement implementations are free to return + * mutation batches that don't contain any of the document keys at all if it's + * convenient. + */ + getAllMutationBatchesAffectingDocumentKeys(transaction: PersistenceTransaction, documentKeys: SortedMap): PersistencePromise; + /** + * Finds all mutation batches that could affect the results for the given + * query. Not all mutations in a batch will necessarily affect the query, so + * when looping through the batch you'll need to check that the mutation + * itself matches the query. + * + * Batches are guaranteed to be in sorted order. + * + * Note that because of this requirement implementations are free to return + * mutation batches that don't match the query at all if it's convenient. + * + * NOTE: A PatchMutation does not need to include all fields in the query + * filter criteria in order to be a match (but any fields it does contain do + * need to match). + */ + getAllMutationBatchesAffectingQuery(transaction: PersistenceTransaction, query: Query): PersistencePromise; + /** + * Removes the given mutation batch from the queue. This is useful in two + * circumstances: + * + * + Removing an applied mutation from the head of the queue + * + Removing a rejected mutation from anywhere in the queue + * + * Multi-Tab Note: This operation should only be called by the primary client. + */ + removeMutationBatch(transaction: PersistenceTransaction, batch: MutationBatch): PersistencePromise; + /** + * Performs a consistency check, examining the mutation queue for any + * leaks, if possible. + */ + performConsistencyCheck(transaction: PersistenceTransaction): PersistencePromise; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/overlayed_document.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/overlayed_document.d.ts new file mode 100644 index 0000000..56a3286 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/overlayed_document.d.ts @@ -0,0 +1,40 @@ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Document } from '../model/document'; +import { FieldMask } from '../model/field_mask'; +/** + * Represents a local view (overlay) of a document, and the fields that are + * locally mutated. + */ +export declare class OverlayedDocument { + readonly overlayedDocument: Document; + /** + * The fields that are locally mutated by patch mutations. + * + * If the overlayed document is from set or delete mutations, this is `null`. + * If there is no overlay (mutation) for the document, this is an empty `FieldMask`. + */ + readonly mutatedFields: FieldMask | null; + constructor(overlayedDocument: Document, + /** + * The fields that are locally mutated by patch mutations. + * + * If the overlayed document is from set or delete mutations, this is `null`. + * If there is no overlay (mutation) for the document, this is an empty `FieldMask`. + */ + mutatedFields: FieldMask | null); +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/persistence.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/persistence.d.ts new file mode 100644 index 0000000..0360173 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/persistence.d.ts @@ -0,0 +1,217 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { User } from '../auth/user'; +import { TargetId } from '../core/types'; +import { DocumentKey } from '../model/document_key'; +import { BundleCache } from './bundle_cache'; +import { DocumentOverlayCache } from './document_overlay_cache'; +import { GlobalsCache } from './globals_cache'; +import { IndexManager } from './index_manager'; +import { MutationQueue } from './mutation_queue'; +import { PersistencePromise } from './persistence_promise'; +import { PersistenceTransaction, PersistenceTransactionMode } from './persistence_transaction'; +import { RemoteDocumentCache } from './remote_document_cache'; +import { TargetCache } from './target_cache'; +import { TargetData } from './target_data'; +/** + * Callback type for primary state notifications. This callback can be + * registered with the persistence layer to get notified when we transition from + * primary to secondary state and vice versa. + * + * Note: Instances can only toggle between Primary and Secondary state if + * IndexedDB persistence is enabled and multiple clients are active. If this + * listener is registered with MemoryPersistence, the callback will be called + * exactly once marking the current instance as Primary. + */ +export type PrimaryStateListener = (isPrimary: boolean) => Promise; +/** + * A ReferenceDelegate instance handles all of the hooks into the document-reference lifecycle. This + * includes being added to a target, being removed from a target, being subject to mutation, and + * being mutated by the user. + * + * Different implementations may do different things with each of these events. Not every + * implementation needs to do something with every lifecycle hook. + * + * PORTING NOTE: since sequence numbers are attached to transactions in this + * client, the ReferenceDelegate does not need to deal in transactional + * semantics (onTransactionStarted/Committed()), nor does it need to track and + * generate sequence numbers (getCurrentSequenceNumber()). + */ +export interface ReferenceDelegate { + /** Notify the delegate that the given document was added to a target. */ + addReference(txn: PersistenceTransaction, targetId: TargetId, doc: DocumentKey): PersistencePromise; + /** Notify the delegate that the given document was removed from a target. */ + removeReference(txn: PersistenceTransaction, targetId: TargetId, doc: DocumentKey): PersistencePromise; + /** + * Notify the delegate that a target was removed. The delegate may, but is not obligated to, + * actually delete the target and associated data. + */ + removeTarget(txn: PersistenceTransaction, targetData: TargetData): PersistencePromise; + /** + * Notify the delegate that a document may no longer be part of any views or + * have any mutations associated. + */ + markPotentiallyOrphaned(txn: PersistenceTransaction, doc: DocumentKey): PersistencePromise; + /** Notify the delegate that a limbo document was updated. */ + updateLimboDocument(txn: PersistenceTransaction, doc: DocumentKey): PersistencePromise; +} +/** + * Persistence is the lowest-level shared interface to persistent storage in + * Firestore. + * + * Persistence is used to create MutationQueue and RemoteDocumentCache + * instances backed by persistence (which might be in-memory or LevelDB). + * + * Persistence also exposes an API to create and run PersistenceTransactions + * against persistence. All read / write operations must be wrapped in a + * transaction. Implementations of PersistenceTransaction / Persistence only + * need to guarantee that writes made against the transaction are not made to + * durable storage until the transaction resolves its PersistencePromise. + * Since memory-only storage components do not alter durable storage, they are + * free to ignore the transaction. + * + * This contract is enough to allow the LocalStore be be written + * independently of whether or not the stored state actually is durably + * persisted. If persistent storage is enabled, writes are grouped together to + * avoid inconsistent state that could cause crashes. + * + * Concretely, when persistent storage is enabled, the persistent versions of + * MutationQueue, RemoteDocumentCache, and others (the mutators) will + * defer their writes into a transaction. Once the local store has completed + * one logical operation, it commits the transaction. + * + * When persistent storage is disabled, the non-persistent versions of the + * mutators ignore the transaction. This short-cut is allowed because + * memory-only storage leaves no state so it cannot be inconsistent. + * + * This simplifies the implementations of the mutators and allows memory-only + * implementations to supplement the persistent ones without requiring any + * special dual-store implementation of Persistence. The cost is that the + * LocalStore needs to be slightly careful about the order of its reads and + * writes in order to avoid relying on being able to read back uncommitted + * writes. + */ +export interface Persistence { + /** + * Whether or not this persistence instance has been started. + */ + readonly started: boolean; + readonly referenceDelegate: ReferenceDelegate; + /** Starts persistence. */ + start(): Promise; + /** + * Releases any resources held during eager shutdown. + */ + shutdown(): Promise; + /** + * Registers a listener that gets called when the database receives a + * version change event indicating that it has deleted. + * + * PORTING NOTE: This is only used for Web multi-tab. + */ + setDatabaseDeletedListener(databaseDeletedListener: () => Promise): void; + /** + * Adjusts the current network state in the client's metadata, potentially + * affecting the primary lease. + * + * PORTING NOTE: This is only used for Web multi-tab. + */ + setNetworkEnabled(networkEnabled: boolean): void; + /** + * Returns GlobalCache representing a general purpose cache for global values. + */ + getGlobalsCache(): GlobalsCache; + /** + * Returns a MutationQueue representing the persisted mutations for the + * given user. + * + * Note: The implementation is free to return the same instance every time + * this is called for a given user. In particular, the memory-backed + * implementation does this to emulate the persisted implementation to the + * extent possible (e.g. in the case of uid switching from + * sally=>jack=>sally, sally's mutation queue will be preserved). + */ + getMutationQueue(user: User, indexManager: IndexManager): MutationQueue; + /** + * Returns a TargetCache representing the persisted cache of targets. + * + * Note: The implementation is free to return the same instance every time + * this is called. In particular, the memory-backed implementation does this + * to emulate the persisted implementation to the extent possible. + */ + getTargetCache(): TargetCache; + /** + * Returns a RemoteDocumentCache representing the persisted cache of remote + * documents. + * + * Note: The implementation is free to return the same instance every time + * this is called. In particular, the memory-backed implementation does this + * to emulate the persisted implementation to the extent possible. + */ + getRemoteDocumentCache(): RemoteDocumentCache; + /** + * Returns a BundleCache representing the persisted cache of loaded bundles. + * + * Note: The implementation is free to return the same instance every time + * this is called. In particular, the memory-backed implementation does this + * to emulate the persisted implementation to the extent possible. + */ + getBundleCache(): BundleCache; + /** + * Returns an IndexManager instance that manages our persisted query indexes. + * + * Note: The implementation is free to return the same instance every time + * this is called. In particular, the memory-backed implementation does this + * to emulate the persisted implementation to the extent possible. + */ + getIndexManager(user: User): IndexManager; + /** + * Returns a DocumentOverlayCache representing the documents that are mutated + * locally. + */ + getDocumentOverlayCache(user: User): DocumentOverlayCache; + /** + * Performs an operation inside a persistence transaction. Any reads or writes + * against persistence must be performed within a transaction. Writes will be + * committed atomically once the transaction completes. + * + * Persistence operations are asynchronous and therefore the provided + * transactionOperation must return a PersistencePromise. When it is resolved, + * the transaction will be committed and the Promise returned by this method + * will resolve. + * + * @param action - A description of the action performed by this transaction, + * used for logging. + * @param mode - The underlying mode of the IndexedDb transaction. Can be + * 'readonly', 'readwrite' or 'readwrite-primary'. Transactions marked + * 'readwrite-primary' can only be executed by the primary client. In this + * mode, the transactionOperation will not be run if the primary lease cannot + * be acquired and the returned promise will be rejected with a + * FAILED_PRECONDITION error. + * @param transactionOperation - The operation to run inside a transaction. + * @returns A `Promise` that is resolved once the transaction completes. + */ + runTransaction(action: string, mode: PersistenceTransactionMode, transactionOperation: (transaction: PersistenceTransaction) => PersistencePromise): Promise; +} +/** + * Interface to schedule periodic tasks within SDK. + */ +export interface Scheduler { + readonly started: boolean; + start(): void; + stop(): void; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/persistence_promise.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/persistence_promise.d.ts new file mode 100644 index 0000000..3803123 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/persistence_promise.d.ts @@ -0,0 +1,83 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export type FulfilledHandler = ((result: T) => R | PersistencePromise) | null; +export type RejectedHandler = ((reason: Error) => R | PersistencePromise) | null; +export type Resolver = (value?: T) => void; +export type Rejector = (error: Error) => void; +/** + * PersistencePromise is essentially a re-implementation of Promise except + * it has a .next() method instead of .then() and .next() and .catch() callbacks + * are executed synchronously when a PersistencePromise resolves rather than + * asynchronously (Promise implementations use setImmediate() or similar). + * + * This is necessary to interoperate with IndexedDB which will automatically + * commit transactions if control is returned to the event loop without + * synchronously initiating another operation on the transaction. + * + * NOTE: .then() and .catch() only allow a single consumer, unlike normal + * Promises. + */ +export declare class PersistencePromise { + private nextCallback; + private catchCallback; + private result; + private error; + private isDone; + private callbackAttached; + constructor(callback: (resolve: Resolver, reject: Rejector) => void); + catch(fn: (error: Error) => R | PersistencePromise): PersistencePromise; + next(nextFn?: FulfilledHandler, catchFn?: RejectedHandler): PersistencePromise; + toPromise(): Promise; + private wrapUserFunction; + private wrapSuccess; + private wrapFailure; + static resolve(): PersistencePromise; + static resolve(result: R): PersistencePromise; + static reject(error: Error): PersistencePromise; + static waitFor(all: { + forEach: (cb: (el: PersistencePromise) => void) => void; + }): PersistencePromise; + /** + * Given an array of predicate functions that asynchronously evaluate to a + * boolean, implements a short-circuiting `or` between the results. Predicates + * will be evaluated until one of them returns `true`, then stop. The final + * result will be whether any of them returned `true`. + */ + static or(predicates: Array<() => PersistencePromise>): PersistencePromise; + /** + * Given an iterable, call the given function on each element in the + * collection and wait for all of the resulting concurrent PersistencePromises + * to resolve. + */ + static forEach(collection: { + forEach: (cb: (r: R, s: S) => void) => void; + }, f: ((r: R, s: S) => PersistencePromise) | ((r: R) => PersistencePromise)): PersistencePromise; + static forEach(collection: { + forEach: (cb: (r: R) => void) => void; + }, f: (r: R) => PersistencePromise): PersistencePromise; + /** + * Concurrently map all array elements through asynchronous function. + */ + static mapArray(array: T[], f: (t: T) => PersistencePromise): PersistencePromise; + /** + * An alternative to recursive PersistencePromise calls, that avoids + * potential memory problems from unbounded chains of promises. + * + * The `action` will be called repeatedly while `condition` is true. + */ + static doWhile(condition: () => boolean, action: () => PersistencePromise): PersistencePromise; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/persistence_transaction.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/persistence_transaction.d.ts new file mode 100644 index 0000000..d4da8b6 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/persistence_transaction.d.ts @@ -0,0 +1,34 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { ListenSequenceNumber } from '../core/types'; +export declare const PRIMARY_LEASE_LOST_ERROR_MSG: string; +/** The different modes supported by `Persistence.runTransaction()`. */ +export type PersistenceTransactionMode = 'readonly' | 'readwrite' | 'readwrite-primary'; +/** + * A base class representing a persistence transaction, encapsulating both the + * transaction's sequence numbers as well as a list of onCommitted listeners. + * + * When you call Persistence.runTransaction(), it will create a transaction and + * pass it to your callback. You then pass it to any method that operates + * on persistence. + */ +export declare abstract class PersistenceTransaction { + private readonly onCommittedListeners; + abstract readonly currentSequenceNumber: ListenSequenceNumber; + addOnCommittedListener(listener: () => void): void; + raiseOnCommittedEvent(): void; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/query_context.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/query_context.d.ts new file mode 100644 index 0000000..aeff2fa --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/query_context.d.ts @@ -0,0 +1,28 @@ +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A tracker to keep a record of important details during database local query + * execution. + */ +export declare class QueryContext { + /** + * Counts the number of documents passed through during local query execution. + */ + private _documentReadCount; + get documentReadCount(): number; + incrementDocumentReadCount(amount: number): void; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/query_engine.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/query_engine.d.ts new file mode 100644 index 0000000..58148f1 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/query_engine.d.ts @@ -0,0 +1,110 @@ +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Query } from '../core/query'; +import { SnapshotVersion } from '../core/snapshot_version'; +import { DocumentKeySet, DocumentMap } from '../model/collections'; +import { IndexManager } from './index_manager'; +import { LocalDocumentsView } from './local_documents_view'; +import { PersistencePromise } from './persistence_promise'; +import { PersistenceTransaction } from './persistence_transaction'; +import { QueryContext } from './query_context'; +/** + * The Firestore query engine. + * + * Firestore queries can be executed in three modes. The Query Engine determines + * what mode to use based on what data is persisted. The mode only determines + * the runtime complexity of the query - the result set is equivalent across all + * implementations. + * + * The Query engine will use indexed-based execution if a user has configured + * any index that can be used to execute query (via `setIndexConfiguration()`). + * Otherwise, the engine will try to optimize the query by re-using a previously + * persisted query result. If that is not possible, the query will be executed + * via a full collection scan. + * + * Index-based execution is the default when available. The query engine + * supports partial indexed execution and merges the result from the index + * lookup with documents that have not yet been indexed. The index evaluation + * matches the backend's format and as such, the SDK can use indexing for all + * queries that the backend supports. + * + * If no index exists, the query engine tries to take advantage of the target + * document mapping in the TargetCache. These mappings exists for all queries + * that have been synced with the backend at least once and allow the query + * engine to only read documents that previously matched a query plus any + * documents that were edited after the query was last listened to. + * + * There are some cases when this optimization is not guaranteed to produce + * the same results as full collection scans. In these cases, query + * processing falls back to full scans. These cases are: + * + * - Limit queries where a document that matched the query previously no longer + * matches the query. + * + * - Limit queries where a document edit may cause the document to sort below + * another document that is in the local cache. + * + * - Queries that have never been CURRENT or free of limbo documents. + */ +export declare class QueryEngine { + private localDocumentsView; + private indexManager; + private initialized; + indexAutoCreationEnabled: boolean; + /** + * SDK only decides whether it should create index when collection size is + * larger than this. + */ + indexAutoCreationMinCollectionSize: number; + relativeIndexReadCostPerDocument: number; + /** Sets the document view to query against. */ + initialize(localDocuments: LocalDocumentsView, indexManager: IndexManager): void; + /** Returns all local documents matching the specified query. */ + getDocumentsMatchingQuery(transaction: PersistenceTransaction, query: Query, lastLimboFreeSnapshotVersion: SnapshotVersion, remoteKeys: DocumentKeySet): PersistencePromise; + createCacheIndexes(transaction: PersistenceTransaction, query: Query, context: QueryContext, resultSize: number): PersistencePromise; + /** + * Performs an indexed query that evaluates the query based on a collection's + * persisted index values. Returns `null` if an index is not available. + */ + private performQueryUsingIndex; + /** + * Performs a query based on the target's persisted query mapping. Returns + * `null` if the mapping is not available or cannot be used. + */ + private performQueryUsingRemoteKeys; + /** Applies the query filter and sorting to the provided documents. */ + private applyQuery; + /** + * Determines if a limit query needs to be refilled from cache, making it + * ineligible for index-free execution. + * + * @param query - The query. + * @param sortedPreviousResults - The documents that matched the query when it + * was last synchronized, sorted by the query's comparator. + * @param remoteKeys - The document keys that matched the query at the last + * snapshot. + * @param limboFreeSnapshotVersion - The version of the snapshot when the + * query was last synchronized. + */ + private needsRefill; + private executeFullCollectionScan; + /** + * Combines the results from an indexed execution with the remaining documents + * that have not yet been indexed. + */ + private appendRemainingResults; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/reference_set.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/reference_set.d.ts new file mode 100644 index 0000000..5ff71dc --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/reference_set.d.ts @@ -0,0 +1,68 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { BatchId, TargetId } from '../core/types'; +import { DocumentKeySet } from '../model/collections'; +import { DocumentKey } from '../model/document_key'; +/** + * A collection of references to a document from some kind of numbered entity + * (either a target ID or batch ID). As references are added to or removed from + * the set corresponding events are emitted to a registered garbage collector. + * + * Each reference is represented by a DocumentReference object. Each of them + * contains enough information to uniquely identify the reference. They are all + * stored primarily in a set sorted by key. A document is considered garbage if + * there's no references in that set (this can be efficiently checked thanks to + * sorting by key). + * + * ReferenceSet also keeps a secondary set that contains references sorted by + * IDs. This one is used to efficiently implement removal of all references by + * some target ID. + */ +export declare class ReferenceSet { + private refsByKey; + private refsByTarget; + /** Returns true if the reference set contains no references. */ + isEmpty(): boolean; + /** Adds a reference to the given document key for the given ID. */ + addReference(key: DocumentKey, id: TargetId | BatchId): void; + /** Add references to the given document keys for the given ID. */ + addReferences(keys: DocumentKeySet, id: TargetId | BatchId): void; + /** + * Removes a reference to the given document key for the given + * ID. + */ + removeReference(key: DocumentKey, id: TargetId | BatchId): void; + removeReferences(keys: DocumentKeySet, id: TargetId | BatchId): void; + /** + * Clears all references with a given ID. Calls removeRef() for each key + * removed. + */ + removeReferencesForId(id: TargetId | BatchId): DocumentKey[]; + removeAllReferences(): void; + private removeRef; + referencesForId(id: TargetId | BatchId): DocumentKeySet; + containsKey(key: DocumentKey): boolean; +} +export declare class DocReference { + key: DocumentKey; + targetOrBatchId: TargetId | BatchId; + constructor(key: DocumentKey, targetOrBatchId: TargetId | BatchId); + /** Compare by key then by ID */ + static compareByKey(left: DocReference, right: DocReference): number; + /** Compare by ID then by key */ + static compareByTargetId(left: DocReference, right: DocReference): number; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/remote_document_cache.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/remote_document_cache.d.ts new file mode 100644 index 0000000..abb9f3b --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/remote_document_cache.d.ts @@ -0,0 +1,91 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Query } from '../core/query'; +import { DocumentKeySet, MutableDocumentMap, OverlayMap } from '../model/collections'; +import { MutableDocument } from '../model/document'; +import { DocumentKey } from '../model/document_key'; +import { IndexOffset } from '../model/field_index'; +import { IndexManager } from './index_manager'; +import { PersistencePromise } from './persistence_promise'; +import { PersistenceTransaction } from './persistence_transaction'; +import { QueryContext } from './query_context'; +import { RemoteDocumentChangeBuffer } from './remote_document_change_buffer'; +/** + * Represents cached documents received from the remote backend. + * + * The cache is keyed by DocumentKey and entries in the cache are + * MutableDocuments, meaning we can cache both actual documents as well as + * documents that are known to not exist. + */ +export interface RemoteDocumentCache { + /** Sets the index manager to use for managing the collectionGroup index. */ + setIndexManager(indexManager: IndexManager): void; + /** + * Looks up an entry in the cache. + * + * @param documentKey - The key of the entry to look up.* + * @returns The cached document entry. Returns an invalid document if the + * document is not cached. + */ + getEntry(transaction: PersistenceTransaction, documentKey: DocumentKey): PersistencePromise; + /** + * Looks up a set of entries in the cache. + * + * @param documentKeys - The keys of the entries to look up. + * @returns The cached document entries indexed by key. If an entry is not + * cached, the corresponding key will be mapped to an invalid document. + */ + getEntries(transaction: PersistenceTransaction, documentKeys: DocumentKeySet): PersistencePromise; + /** + * Returns the documents matching the given query + * + * @param query - The query to match documents against. + * @param offset - The offset to start the scan at (exclusive). + * @param context - A optional tracker to keep a record of important details + * during database local query execution. + * @returns The set of matching documents. + */ + getDocumentsMatchingQuery(transaction: PersistenceTransaction, query: Query, offset: IndexOffset, mutatedDocs: OverlayMap, context?: QueryContext): PersistencePromise; + /** + * Looks up the next `limit` documents for a collection group based on the + * provided offset. The ordering is based on the document's read time and key. + * + * @param collectionGroup - The collection group to scan. + * @param offset - The offset to start the scan at (exclusive). + * @param limit - The maximum number of results to return. + * @returns The set of matching documents. + */ + getAllFromCollectionGroup(transaction: PersistenceTransaction, collectionGroup: string, offset: IndexOffset, limit: number): PersistencePromise; + /** + * Provides access to add or update the contents of the cache. The buffer + * handles proper size accounting for the change. + * + * Multi-Tab Note: This should only be called by the primary client. + * + * @param options - Specify `trackRemovals` to create sentinel entries for + * removed documents, which allows removals to be tracked by + * `getNewDocumentChanges()`. + */ + newChangeBuffer(options?: { + trackRemovals: boolean; + }): RemoteDocumentChangeBuffer; + /** + * Get an estimate of the size of the document cache. Note that for eager + * garbage collection, we don't track sizes so this will return 0. + */ + getSize(transaction: PersistenceTransaction): PersistencePromise; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/remote_document_change_buffer.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/remote_document_change_buffer.d.ts new file mode 100644 index 0000000..3b8a1fa --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/remote_document_change_buffer.d.ts @@ -0,0 +1,88 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { SnapshotVersion } from '../core/snapshot_version'; +import { DocumentKeySet, MutableDocumentMap } from '../model/collections'; +import { MutableDocument } from '../model/document'; +import { DocumentKey } from '../model/document_key'; +import { ObjectMap } from '../util/obj_map'; +import { PersistencePromise } from './persistence_promise'; +import { PersistenceTransaction } from './persistence_transaction'; +/** + * An in-memory buffer of entries to be written to a RemoteDocumentCache. + * It can be used to batch up a set of changes to be written to the cache, but + * additionally supports reading entries back with the `getEntry()` method, + * falling back to the underlying RemoteDocumentCache if no entry is + * buffered. + * + * Entries added to the cache *must* be read first. This is to facilitate + * calculating the size delta of the pending changes. + * + * PORTING NOTE: This class was implemented then removed from other platforms. + * If byte-counting ends up being needed on the other platforms, consider + * porting this class as part of that implementation work. + */ +export declare abstract class RemoteDocumentChangeBuffer { + protected changes: ObjectMap; + private changesApplied; + protected abstract getFromCache(transaction: PersistenceTransaction, documentKey: DocumentKey): PersistencePromise; + protected abstract getAllFromCache(transaction: PersistenceTransaction, documentKeys: DocumentKeySet): PersistencePromise; + protected abstract applyChanges(transaction: PersistenceTransaction): PersistencePromise; + /** + * Buffers a `RemoteDocumentCache.addEntry()` call. + * + * You can only modify documents that have already been retrieved via + * `getEntry()/getEntries()` (enforced via IndexedDbs `apply()`). + */ + addEntry(document: MutableDocument): void; + /** + * Buffers a `RemoteDocumentCache.removeEntry()` call. + * + * You can only remove documents that have already been retrieved via + * `getEntry()/getEntries()` (enforced via IndexedDbs `apply()`). + */ + removeEntry(key: DocumentKey, readTime: SnapshotVersion): void; + /** + * Looks up an entry in the cache. The buffered changes will first be checked, + * and if no buffered change applies, this will forward to + * `RemoteDocumentCache.getEntry()`. + * + * @param transaction - The transaction in which to perform any persistence + * operations. + * @param documentKey - The key of the entry to look up. + * @returns The cached document or an invalid document if we have nothing + * cached. + */ + getEntry(transaction: PersistenceTransaction, documentKey: DocumentKey): PersistencePromise; + /** + * Looks up several entries in the cache, forwarding to + * `RemoteDocumentCache.getEntry()`. + * + * @param transaction - The transaction in which to perform any persistence + * operations. + * @param documentKeys - The keys of the entries to look up. + * @returns A map of cached documents, indexed by key. If an entry cannot be + * found, the corresponding key will be mapped to an invalid document. + */ + getEntries(transaction: PersistenceTransaction, documentKeys: DocumentKeySet): PersistencePromise; + /** + * Applies buffered changes to the underlying RemoteDocumentCache, using + * the provided transaction. + */ + apply(transaction: PersistenceTransaction): PersistencePromise; + /** Helper to assert this.changes is not null */ + protected assertNotApplied(): void; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/shared_client_state.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/shared_client_state.d.ts new file mode 100644 index 0000000..98efa94 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/shared_client_state.d.ts @@ -0,0 +1,312 @@ +/** + * @license + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { User } from '../auth/user'; +import { BatchId, ListenSequenceNumber, MutationBatchState, OnlineState, TargetId } from '../core/types'; +import { TargetIdSet } from '../model/collections'; +import { AsyncQueue } from '../util/async_queue'; +import { FirestoreError } from '../util/error'; +import { SortedSet } from '../util/sorted_set'; +import { WindowLike } from '../util/types'; +import { QueryTargetState, SharedClientStateSyncer } from './shared_client_state_syncer'; +/** + * A randomly-generated key assigned to each Firestore instance at startup. + */ +export type ClientId = string; +/** + * A `SharedClientState` keeps track of the global state of the mutations + * and query targets for all active clients with the same persistence key (i.e. + * project ID and FirebaseApp name). It relays local changes to other clients + * and updates its local state as new state is observed. + * + * `SharedClientState` is primarily used for synchronization in Multi-Tab + * environments. Each tab is responsible for registering its active query + * targets and mutations. `SharedClientState` will then notify the listener + * assigned to `.syncEngine` for updates to mutations and queries that + * originated in other clients. + * + * To receive notifications, `.syncEngine` and `.onlineStateHandler` has to be + * assigned before calling `start()`. + */ +export interface SharedClientState { + onlineStateHandler: ((onlineState: OnlineState) => void) | null; + sequenceNumberHandler: ((sequenceNumber: ListenSequenceNumber) => void) | null; + /** Registers the Mutation Batch ID of a newly pending mutation. */ + addPendingMutation(batchId: BatchId): void; + /** + * Records that a pending mutation has been acknowledged or rejected. + * Called by the primary client to notify secondary clients of mutation + * results as they come back from the backend. + */ + updateMutationState(batchId: BatchId, state: 'acknowledged' | 'rejected', error?: FirestoreError): void; + /** + * Associates a new Query Target ID with the local Firestore client. Returns + * the new query state for the query (which can be 'current' if the query is + * already associated with another tab). + * + * If the target id is already associated with local client, the method simply + * returns its `QueryTargetState`. + */ + addLocalQueryTarget(targetId: TargetId, addToActiveTargetIds?: boolean): QueryTargetState; + /** Removes the Query Target ID association from the local client. */ + removeLocalQueryTarget(targetId: TargetId): void; + /** Checks whether the target is associated with the local client. */ + isLocalQueryTarget(targetId: TargetId): boolean; + /** + * Processes an update to a query target. + * + * Called by the primary client to notify secondary clients of document + * changes or state transitions that affect the provided query target. + */ + updateQueryState(targetId: TargetId, state: QueryTargetState, error?: FirestoreError): void; + /** + * Removes the target's metadata entry. + * + * Called by the primary client when all clients stopped listening to a query + * target. + */ + clearQueryState(targetId: TargetId): void; + /** + * Gets the active Query Targets IDs for all active clients. + * + * The implementation for this may require O(n) runtime, where 'n' is the size + * of the result set. + */ + getAllActiveQueryTargets(): SortedSet; + /** + * Checks whether the provided target ID is currently being listened to by + * any of the active clients. + * + * The implementation may require O(n*log m) runtime, where 'n' is the number + * of clients and 'm' the number of targets. + */ + isActiveQueryTarget(targetId: TargetId): boolean; + /** + * Starts the SharedClientState, reads existing client data and registers + * listeners for updates to new and existing clients. + */ + start(): Promise; + /** Shuts down the `SharedClientState` and its listeners. */ + shutdown(): void; + /** + * Changes the active user and removes all existing user-specific data. The + * user change does not call back into SyncEngine (for example, no mutations + * will be marked as removed). + */ + handleUserChange(user: User, removedBatchIds: BatchId[], addedBatchIds: BatchId[]): void; + /** Changes the shared online state of all clients. */ + setOnlineState(onlineState: OnlineState): void; + writeSequenceNumber(sequenceNumber: ListenSequenceNumber): void; + /** + * Notifies other clients when remote documents have changed due to loading + * a bundle. + * + * @param collectionGroups The collection groups affected by this bundle. + */ + notifyBundleLoaded(collectionGroups: Set): void; +} +/** + * Holds the state of a mutation batch, including its user ID, batch ID and + * whether the batch is 'pending', 'acknowledged' or 'rejected'. + */ +export declare class MutationMetadata { + readonly user: User; + readonly batchId: BatchId; + readonly state: MutationBatchState; + readonly error?: FirestoreError | undefined; + constructor(user: User, batchId: BatchId, state: MutationBatchState, error?: FirestoreError | undefined); + /** + * Parses a MutationMetadata from its JSON representation in WebStorage. + * Logs a warning and returns null if the format of the data is not valid. + */ + static fromWebStorageEntry(user: User, batchId: BatchId, value: string): MutationMetadata | null; + toWebStorageJSON(): string; +} +/** + * Holds the state of a query target, including its target ID and whether the + * target is 'not-current', 'current' or 'rejected'. + */ +export declare class QueryTargetMetadata { + readonly targetId: TargetId; + readonly state: QueryTargetState; + readonly error?: FirestoreError | undefined; + constructor(targetId: TargetId, state: QueryTargetState, error?: FirestoreError | undefined); + /** + * Parses a QueryTargetMetadata from its JSON representation in WebStorage. + * Logs a warning and returns null if the format of the data is not valid. + */ + static fromWebStorageEntry(targetId: TargetId, value: string): QueryTargetMetadata | null; + toWebStorageJSON(): string; +} +/** + * Metadata state of a single client denoting the query targets it is actively + * listening to the watch. + */ +export interface ClientState { + readonly activeTargetIds: TargetIdSet; +} +/** + * This class represents the online state for all clients participating in + * multi-tab. The online state is only written to by the primary client, and + * used in secondary clients to update their query views. + */ +export declare class SharedOnlineState { + readonly clientId: string; + readonly onlineState: OnlineState; + constructor(clientId: string, onlineState: OnlineState); + /** + * Parses a SharedOnlineState from its JSON representation in WebStorage. + * Logs a warning and returns null if the format of the data is not valid. + */ + static fromWebStorageEntry(value: string): SharedOnlineState | null; +} +/** + * Metadata state of the local client. Unlike `RemoteClientState`, this class is + * mutable and keeps track of all pending mutations, which allows us to + * update the range of pending mutation batch IDs as new mutations are added or + * removed. + * + * The data in `LocalClientState` is not read from WebStorage and instead + * updated via its instance methods. The updated state can be serialized via + * `toWebStorageJSON()`. + */ +export declare class LocalClientState implements ClientState { + activeTargetIds: SortedSet; + addQueryTarget(targetId: TargetId): void; + removeQueryTarget(targetId: TargetId): void; + /** + * Converts this entry into a JSON-encoded format we can use for WebStorage. + * Does not encode `clientId` as it is part of the key in WebStorage. + */ + toWebStorageJSON(): string; +} +/** + * `WebStorageSharedClientState` uses WebStorage (window.localStorage) as the + * backing store for the SharedClientState. It keeps track of all active + * clients and supports modifications of the local client's data. + */ +export declare class WebStorageSharedClientState implements SharedClientState { + private readonly window; + private readonly queue; + private readonly persistenceKey; + private readonly localClientId; + syncEngine: SharedClientStateSyncer | null; + onlineStateHandler: ((onlineState: OnlineState) => void) | null; + sequenceNumberHandler: ((sequenceNumber: ListenSequenceNumber) => void) | null; + private readonly storage; + private readonly localClientStorageKey; + private readonly sequenceNumberKey; + private readonly storageListener; + private readonly onlineStateKey; + private readonly bundleLoadedKey; + private readonly clientStateKeyRe; + private readonly mutationBatchKeyRe; + private readonly queryTargetKeyRe; + private activeClients; + private started; + private currentUser; + /** + * Captures WebStorage events that occur before `start()` is called. These + * events are replayed once `WebStorageSharedClientState` is started. + */ + private earlyEvents; + constructor(window: WindowLike, queue: AsyncQueue, persistenceKey: string, localClientId: ClientId, initialUser: User); + /** Returns 'true' if WebStorage is available in the current environment. */ + static isAvailable(window: WindowLike | null): window is WindowLike; + start(): Promise; + writeSequenceNumber(sequenceNumber: ListenSequenceNumber): void; + getAllActiveQueryTargets(): TargetIdSet; + isActiveQueryTarget(targetId: TargetId): boolean; + addPendingMutation(batchId: BatchId): void; + updateMutationState(batchId: BatchId, state: 'acknowledged' | 'rejected', error?: FirestoreError): void; + addLocalQueryTarget(targetId: TargetId, addToActiveTargetIds?: boolean): QueryTargetState; + removeLocalQueryTarget(targetId: TargetId): void; + isLocalQueryTarget(targetId: TargetId): boolean; + clearQueryState(targetId: TargetId): void; + updateQueryState(targetId: TargetId, state: QueryTargetState, error?: FirestoreError): void; + handleUserChange(user: User, removedBatchIds: BatchId[], addedBatchIds: BatchId[]): void; + setOnlineState(onlineState: OnlineState): void; + notifyBundleLoaded(collectionGroups: Set): void; + shutdown(): void; + private getItem; + private setItem; + private removeItem; + private handleWebStorageEvent; + private get localClientState(); + private persistClientState; + private persistMutationState; + private removeMutationState; + private persistOnlineState; + private persistQueryTargetState; + private persistBundleLoadedState; + /** + * Parses a client state key in WebStorage. Returns null if the key does not + * match the expected key format. + */ + private fromWebStorageClientStateKey; + /** + * Parses a client state in WebStorage. Returns 'null' if the value could not + * be parsed. + */ + private fromWebStorageClientState; + /** + * Parses a mutation batch state in WebStorage. Returns 'null' if the value + * could not be parsed. + */ + private fromWebStorageMutationMetadata; + /** + * Parses a query target state from WebStorage. Returns 'null' if the value + * could not be parsed. + */ + private fromWebStorageQueryTargetMetadata; + /** + * Parses an online state from WebStorage. Returns 'null' if the value + * could not be parsed. + */ + private fromWebStorageOnlineState; + private fromWebStoreBundleLoadedState; + private handleMutationBatchEvent; + private handleQueryTargetEvent; + private handleClientStateEvent; + private handleOnlineStateEvent; + private extractActiveQueryTargets; +} +/** + * `MemorySharedClientState` is a simple implementation of SharedClientState for + * clients using memory persistence. The state in this class remains fully + * isolated and no synchronization is performed. + */ +export declare class MemorySharedClientState implements SharedClientState { + private localState; + private queryState; + onlineStateHandler: ((onlineState: OnlineState) => void) | null; + sequenceNumberHandler: ((sequenceNumber: ListenSequenceNumber) => void) | null; + addPendingMutation(batchId: BatchId): void; + updateMutationState(batchId: BatchId, state: 'acknowledged' | 'rejected', error?: FirestoreError): void; + addLocalQueryTarget(targetId: TargetId, addToActiveTargetIds?: boolean): QueryTargetState; + updateQueryState(targetId: TargetId, state: QueryTargetState, error?: FirestoreError): void; + removeLocalQueryTarget(targetId: TargetId): void; + isLocalQueryTarget(targetId: TargetId): boolean; + clearQueryState(targetId: TargetId): void; + getAllActiveQueryTargets(): TargetIdSet; + isActiveQueryTarget(targetId: TargetId): boolean; + start(): Promise; + handleUserChange(user: User, removedBatchIds: BatchId[], addedBatchIds: BatchId[]): void; + setOnlineState(onlineState: OnlineState): void; + shutdown(): void; + writeSequenceNumber(sequenceNumber: ListenSequenceNumber): void; + notifyBundleLoaded(collectionGroups: Set): void; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/shared_client_state_schema.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/shared_client_state_schema.d.ts new file mode 100644 index 0000000..b856116 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/shared_client_state_schema.d.ts @@ -0,0 +1,84 @@ +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { User } from '../auth/user'; +import { BatchId, MutationBatchState, TargetId } from '../core/types'; +import { ClientId } from './shared_client_state'; +import { QueryTargetState } from './shared_client_state_syncer'; +export declare const CLIENT_STATE_KEY_PREFIX = "firestore_clients"; +/** Assembles the key for a client state in WebStorage */ +export declare function createWebStorageClientStateKey(persistenceKey: string, clientId: ClientId): string; +/** + * The JSON representation of a clients's metadata as used during WebStorage + * serialization. The ClientId is omitted here as it is encoded as part of the + * key. + */ +export interface ClientStateSchema { + activeTargetIds: number[]; + updateTimeMs: number; +} +export declare const MUTATION_BATCH_KEY_PREFIX = "firestore_mutations"; +/** Assembles the key for a mutation batch in WebStorage */ +export declare function createWebStorageMutationBatchKey(persistenceKey: string, user: User, batchId: BatchId): string; +/** + * The JSON representation of a mutation batch's metadata as used during + * WebStorage serialization. The UserId and BatchId is omitted as it is + * encoded as part of the key. + */ +export interface MutationMetadataSchema { + state: MutationBatchState; + error?: { + code: string; + message: string; + }; + updateTimeMs: number; +} +export declare const QUERY_TARGET_KEY_PREFIX = "firestore_targets"; +/** Assembles the key for a query state in WebStorage */ +export declare function createWebStorageQueryTargetMetadataKey(persistenceKey: string, targetId: TargetId): string; +/** + * The JSON representation of a query target's state as used during WebStorage + * serialization. The TargetId is omitted as it is encoded as part of the key. + */ +export interface QueryTargetStateSchema { + state: QueryTargetState; + error?: { + code: string; + message: string; + }; + updateTimeMs: number; +} +export declare const ONLINE_STATE_KEY_PREFIX = "firestore_online_state"; +/** Assembles the key for the online state of the primary tab. */ +export declare function createWebStorageOnlineStateKey(persistenceKey: string): string; +export declare const BUNDLE_LOADED_KEY_PREFIX = "firestore_bundle_loaded_v2"; +export declare function createBundleLoadedKey(persistenceKey: string): string; +/** + * The JSON representation of the system's online state, as written by the + * primary client. + */ +export interface SharedOnlineStateSchema { + /** + * The clientId of the client that wrote this onlineState value. Tracked so + * that on startup, clients can check if this client is still active when + * determining whether to apply this value or not. + */ + readonly clientId: string; + readonly onlineState: string; +} +export declare const SEQUENCE_NUMBER_KEY_PREFIX = "firestore_sequence_number"; +/** Assembles the key for the current sequence number. */ +export declare function createWebStorageSequenceNumberKey(persistenceKey: string): string; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/shared_client_state_syncer.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/shared_client_state_syncer.d.ts new file mode 100644 index 0000000..edc4a1b --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/shared_client_state_syncer.d.ts @@ -0,0 +1,40 @@ +/** + * @license + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { BatchId, MutationBatchState, TargetId } from '../core/types'; +import { FirestoreError } from '../util/error'; +import { ClientId } from './shared_client_state'; +/** The different states of a watch target. */ +export type QueryTargetState = 'not-current' | 'current' | 'rejected'; +/** + * An interface that describes the actions the SharedClientState class needs to + * perform on a cooperating synchronization engine. + */ +export interface SharedClientStateSyncer { + /** Applies a mutation state to an existing batch. */ + applyBatchState(batchId: BatchId, state: MutationBatchState, error?: FirestoreError): Promise; + /** Applies a query target change from a different tab. */ + applyTargetState(targetId: TargetId, state: QueryTargetState, error?: FirestoreError): Promise; + /** Adds or removes Watch targets for queries from different tabs. */ + applyActiveTargetsChange(added: TargetId[], removed: TargetId[]): Promise; + /** Returns the IDs of the clients that are currently active. */ + getActiveClients(): Promise; + /** + * Retrieves newly changed documents from remote document cache and raises + * snapshots if needed. + */ + synchronizeWithChangedDocuments(collectionGroup: string): Promise; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/simple_db.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/simple_db.d.ts new file mode 100644 index 0000000..edaef3b --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/simple_db.d.ts @@ -0,0 +1,233 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { FirestoreError } from '../util/error'; +import { PersistencePromise } from './persistence_promise'; +type SimpleDbTransactionMode = 'readonly' | 'readwrite'; +export interface SimpleDbSchemaConverter { + createOrUpgrade(db: IDBDatabase, txn: IDBTransaction, fromVersion: number, toVersion: number): PersistencePromise; +} +/** + * Wraps an IDBTransaction and exposes a store() method to get a handle to a + * specific object store. + */ +export declare class SimpleDbTransaction { + private readonly action; + private readonly transaction; + private aborted; + /** + * A `Promise` that resolves with the result of the IndexedDb transaction. + */ + private readonly completionDeferred; + static open(db: IDBDatabase, action: string, mode: IDBTransactionMode, objectStoreNames: string[]): SimpleDbTransaction; + constructor(action: string, transaction: IDBTransaction); + get completionPromise(): Promise; + abort(error?: Error): void; + maybeCommit(): void; + /** + * Returns a SimpleDbStore for the specified store. All + * operations performed on the SimpleDbStore happen within the context of this + * transaction and it cannot be used anymore once the transaction is + * completed. + * + * Note that we can't actually enforce that the KeyType and ValueType are + * correct, but they allow type safety through the rest of the consuming code. + */ + store(storeName: string): SimpleDbStore; +} +/** + * Provides a wrapper around IndexedDb with a simplified interface that uses + * Promise-like return values to chain operations. Real promises cannot be used + * since .then() continuations are executed asynchronously (e.g. via + * .setImmediate), which would cause IndexedDB to end the transaction. + * See PersistencePromise for more details. + */ +export declare class SimpleDb { + private readonly name; + private readonly version; + private readonly schemaConverter; + private db?; + private lastClosedDbVersion; + private versionchangelistener?; + /** Deletes the specified database. */ + static delete(name: string): Promise; + /** Returns true if IndexedDB is available in the current environment. */ + static isAvailable(): boolean; + /** + * Returns true if the backing IndexedDB store is the Node IndexedDBShim + * (see https://github.com/axemclion/IndexedDBShim). + */ + static isMockPersistence(): boolean; + /** Helper to get a typed SimpleDbStore from a transaction. */ + static getStore(txn: SimpleDbTransaction, store: string): SimpleDbStore; + /** Parse User Agent to determine iOS version. Returns -1 if not found. */ + static getIOSVersion(ua: string): number; + constructor(name: string, version: number, schemaConverter: SimpleDbSchemaConverter); + /** + * Opens the specified database, creating or upgrading it if necessary. + */ + ensureDb(action: string): Promise; + setVersionChangeListener(versionChangeListener: (event: IDBVersionChangeEvent) => void): void; + runTransaction(action: string, mode: SimpleDbTransactionMode, objectStores: string[], transactionFn: (transaction: SimpleDbTransaction) => PersistencePromise): Promise; + close(): void; +} +/** Parse User Agent to determine Android version. Returns -1 if not found. */ +export declare function getAndroidVersion(ua: string): number; +/** + * A controller for iterating over a key range or index. It allows an iterate + * callback to delete the currently-referenced object, or jump to a new key + * within the key range or index. + */ +export declare class IterationController { + private dbCursor; + private shouldStop; + private nextKey; + constructor(dbCursor: IDBCursorWithValue); + get isDone(): boolean; + get skipToKey(): IDBValidKey | null; + set cursor(value: IDBCursorWithValue); + /** + * This function can be called to stop iteration at any point. + */ + done(): void; + /** + * This function can be called to skip to that next key, which could be + * an index or a primary key. + */ + skip(key: IDBValidKey): void; + /** + * Delete the current cursor value from the object store. + * + * NOTE: You CANNOT do this with a keysOnly query. + */ + delete(): PersistencePromise; +} +/** + * Callback used with iterate() method. + */ +export type IterateCallback = (key: KeyType, value: ValueType, control: IterationController) => void | PersistencePromise; +/** Options available to the iterate() method. */ +export interface IterateOptions { + /** Index to iterate over (else primary keys will be iterated) */ + index?: string; + /** IndexedDB Range to iterate over (else entire store will be iterated) */ + range?: IDBKeyRange; + /** If true, values aren't read while iterating. */ + keysOnly?: boolean; + /** If true, iterate over the store in reverse. */ + reverse?: boolean; +} +/** An error that wraps exceptions that thrown during IndexedDB execution. */ +export declare class IndexedDbTransactionError extends FirestoreError { + name: string; + constructor(actionName: string, cause: Error | string); +} +/** Verifies whether `e` is an IndexedDbTransactionError. */ +export declare function isIndexedDbTransactionError(e: Error): boolean; +/** + * A wrapper around an IDBObjectStore providing an API that: + * + * 1) Has generic KeyType / ValueType parameters to provide strongly-typed + * methods for acting against the object store. + * 2) Deals with IndexedDB's onsuccess / onerror event callbacks, making every + * method return a PersistencePromise instead. + * 3) Provides a higher-level API to avoid needing to do excessive wrapping of + * intermediate IndexedDB types (IDBCursorWithValue, etc.) + */ +export declare class SimpleDbStore { + private store; + constructor(store: IDBObjectStore); + /** + * Writes a value into the Object Store. + * + * @param key - Optional explicit key to use when writing the object, else the + * key will be auto-assigned (e.g. via the defined keyPath for the store). + * @param value - The object to write. + */ + put(value: ValueType): PersistencePromise; + put(key: KeyType, value: ValueType): PersistencePromise; + /** + * Adds a new value into an Object Store and returns the new key. Similar to + * IndexedDb's `add()`, this method will fail on primary key collisions. + * + * @param value - The object to write. + * @returns The key of the value to add. + */ + add(value: ValueType): PersistencePromise; + /** + * Gets the object with the specified key from the specified store, or null + * if no object exists with the specified key. + * + * @key The key of the object to get. + * @returns The object with the specified key or null if no object exists. + */ + get(key: KeyType): PersistencePromise; + delete(key: KeyType | IDBKeyRange): PersistencePromise; + /** + * If we ever need more of the count variants, we can add overloads. For now, + * all we need is to count everything in a store. + * + * Returns the number of rows in the store. + */ + count(): PersistencePromise; + /** Loads all elements from the object store. */ + loadAll(): PersistencePromise; + /** Loads all elements for the index range from the object store. */ + loadAll(range: IDBKeyRange): PersistencePromise; + /** Loads all elements ordered by the given index. */ + loadAll(index: string): PersistencePromise; + /** + * Loads all elements from the object store that fall into the provided in the + * index range for the given index. + */ + loadAll(index: string, range: IDBKeyRange): PersistencePromise; + /** + * Loads the first `count` elements from the provided index range. Loads all + * elements if no limit is provided. + */ + loadFirst(range: IDBKeyRange, count: number | null): PersistencePromise; + deleteAll(): PersistencePromise; + deleteAll(range: IDBKeyRange): PersistencePromise; + deleteAll(index: string, range: IDBKeyRange): PersistencePromise; + /** + * Iterates over keys and values in an object store. + * + * @param options - Options specifying how to iterate the objects in the + * store. + * @param callback - will be called for each iterated object. Iteration can be + * canceled at any point by calling the doneFn passed to the callback. + * The callback can return a PersistencePromise if it performs async + * operations but note that iteration will continue without waiting for them + * to complete. + * @returns A PersistencePromise that resolves once all PersistencePromises + * returned by callbacks resolve. + */ + iterate(callback: IterateCallback): PersistencePromise; + iterate(options: IterateOptions, callback: IterateCallback): PersistencePromise; + /** + * Iterates over a store, but waits for the given callback to complete for + * each entry before iterating the next entry. This allows the callback to do + * asynchronous work to determine if this iteration should continue. + * + * The provided callback should return `true` to continue iteration, and + * `false` otherwise. + */ + iterateSerial(callback: (k: KeyType, v: ValueType) => PersistencePromise): PersistencePromise; + private iterateCursor; + private options; + private cursor; +} +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/target_cache.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/target_cache.d.ts new file mode 100644 index 0000000..218c805 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/target_cache.d.ts @@ -0,0 +1,130 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { SnapshotVersion } from '../core/snapshot_version'; +import { Target } from '../core/target'; +import { ListenSequenceNumber, TargetId } from '../core/types'; +import { DocumentKeySet } from '../model/collections'; +import { DocumentKey } from '../model/document_key'; +import { PersistencePromise } from './persistence_promise'; +import { PersistenceTransaction } from './persistence_transaction'; +import { TargetData } from './target_data'; +/** + * Represents cached targets received from the remote backend. + * + * The cache is keyed by `Target` and entries in the cache are `TargetData` + * instances. + */ +export interface TargetCache { + /** + * A global snapshot version representing the last consistent snapshot we + * received from the backend. This is monotonically increasing and any + * snapshots received from the backend prior to this version (e.g. for targets + * resumed with a resume_token) should be suppressed (buffered) until the + * backend has caught up to this snapshot version again. This prevents our + * cache from ever going backwards in time. + * + * This is updated whenever our we get a TargetChange with a read_time and + * empty target_ids. + */ + getLastRemoteSnapshotVersion(transaction: PersistenceTransaction): PersistencePromise; + /** + * @returns The highest sequence number observed, including any that might be + * persisted on-disk. + */ + getHighestSequenceNumber(transaction: PersistenceTransaction): PersistencePromise; + /** + * Call provided function with each `TargetData` that we have cached. + */ + forEachTarget(txn: PersistenceTransaction, f: (q: TargetData) => void): PersistencePromise; + /** + * Set the highest listen sequence number and optionally updates the + * snapshot version of the last consistent snapshot received from the backend + * (see getLastRemoteSnapshotVersion() for more details). + * + * @param highestListenSequenceNumber - The new maximum listen sequence number. + * @param lastRemoteSnapshotVersion - The new snapshot version. Optional. + */ + setTargetsMetadata(transaction: PersistenceTransaction, highestListenSequenceNumber: number, lastRemoteSnapshotVersion?: SnapshotVersion): PersistencePromise; + /** + * Adds an entry in the cache. + * + * The cache key is extracted from `targetData.target`. The key must not already + * exist in the cache. + * + * @param targetData - A TargetData instance to put in the cache. + */ + addTargetData(transaction: PersistenceTransaction, targetData: TargetData): PersistencePromise; + /** + * Updates an entry in the cache. + * + * The cache key is extracted from `targetData.target`. The entry must already + * exist in the cache, and it will be replaced. + * @param targetData - The TargetData to be replaced into the cache. + */ + updateTargetData(transaction: PersistenceTransaction, targetData: TargetData): PersistencePromise; + /** + * Removes the cached entry for the given target data. It is an error to remove + * a target data that does not exist. + * + * Multi-Tab Note: This operation should only be called by the primary client. + */ + removeTargetData(transaction: PersistenceTransaction, targetData: TargetData): PersistencePromise; + /** + * The number of targets currently in the cache. + */ + getTargetCount(transaction: PersistenceTransaction): PersistencePromise; + /** + * Looks up a TargetData entry by target. + * + * @param target - The query target corresponding to the entry to look up. + * @returns The cached TargetData entry, or null if the cache has no entry for + * the target. + */ + getTargetData(transaction: PersistenceTransaction, target: Target): PersistencePromise; + /** + * Adds the given document keys to cached query results of the given target + * ID. + * + * Multi-Tab Note: This operation should only be called by the primary client. + */ + addMatchingKeys(transaction: PersistenceTransaction, keys: DocumentKeySet, targetId: TargetId): PersistencePromise; + /** + * Removes the given document keys from the cached query results of the + * given target ID. + * + * Multi-Tab Note: This operation should only be called by the primary client. + */ + removeMatchingKeys(transaction: PersistenceTransaction, keys: DocumentKeySet, targetId: TargetId): PersistencePromise; + /** + * Removes all the keys in the query results of the given target ID. + * + * Multi-Tab Note: This operation should only be called by the primary client. + */ + removeMatchingKeysForTargetId(transaction: PersistenceTransaction, targetId: TargetId): PersistencePromise; + /** + * Returns the document keys that match the provided target ID. + */ + getMatchingKeysForTargetId(transaction: PersistenceTransaction, targetId: TargetId): PersistencePromise; + /** + * Returns a new target ID that is higher than any query in the cache. If + * there are no queries in the cache, returns the first valid target ID. + * Allocated target IDs are persisted and `allocateTargetId()` will never + * return the same ID twice. + */ + allocateTargetId(transaction: PersistenceTransaction): PersistencePromise; + containsKey(transaction: PersistenceTransaction, key: DocumentKey): PersistencePromise; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/target_data.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/target_data.d.ts new file mode 100644 index 0000000..595a334 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/target_data.d.ts @@ -0,0 +1,127 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { SnapshotVersion } from '../core/snapshot_version'; +import { Target } from '../core/target'; +import { ListenSequenceNumber, TargetId } from '../core/types'; +import { ByteString } from '../util/byte_string'; +/** An enumeration of the different purposes we have for targets. */ +export declare const enum TargetPurpose { + /** A regular, normal query target. */ + Listen = "TargetPurposeListen", + /** + * The query target was used to refill a query after an existence filter + * mismatch. + */ + ExistenceFilterMismatch = "TargetPurposeExistenceFilterMismatch", + /** + * The query target was used if the query is the result of a false positive in + * the bloom filter. + */ + ExistenceFilterMismatchBloom = "TargetPurposeExistenceFilterMismatchBloom", + /** The query target was used to resolve a limbo document. */ + LimboResolution = "TargetPurposeLimboResolution" +} +/** + * An immutable set of metadata that the local store tracks for each target. + */ +export declare class TargetData { + /** The target being listened to. */ + readonly target: Target; + /** + * The target ID to which the target corresponds; Assigned by the + * LocalStore for user listens and by the SyncEngine for limbo watches. + */ + readonly targetId: TargetId; + /** The purpose of the target. */ + readonly purpose: TargetPurpose; + /** + * The sequence number of the last transaction during which this target data + * was modified. + */ + readonly sequenceNumber: ListenSequenceNumber; + /** The latest snapshot version seen for this target. */ + readonly snapshotVersion: SnapshotVersion; + /** + * The maximum snapshot version at which the associated view + * contained no limbo documents. + */ + readonly lastLimboFreeSnapshotVersion: SnapshotVersion; + /** + * An opaque, server-assigned token that allows watching a target to be + * resumed after disconnecting without retransmitting all the data that + * matches the target. The resume token essentially identifies a point in + * time from which the server should resume sending results. + */ + readonly resumeToken: ByteString; + /** + * The number of documents that last matched the query at the resume token or + * read time. Documents are counted only when making a listen request with + * resume token or read time, otherwise, keep it null. + */ + readonly expectedCount: number | null; + constructor( + /** The target being listened to. */ + target: Target, + /** + * The target ID to which the target corresponds; Assigned by the + * LocalStore for user listens and by the SyncEngine for limbo watches. + */ + targetId: TargetId, + /** The purpose of the target. */ + purpose: TargetPurpose, + /** + * The sequence number of the last transaction during which this target data + * was modified. + */ + sequenceNumber: ListenSequenceNumber, + /** The latest snapshot version seen for this target. */ + snapshotVersion?: SnapshotVersion, + /** + * The maximum snapshot version at which the associated view + * contained no limbo documents. + */ + lastLimboFreeSnapshotVersion?: SnapshotVersion, + /** + * An opaque, server-assigned token that allows watching a target to be + * resumed after disconnecting without retransmitting all the data that + * matches the target. The resume token essentially identifies a point in + * time from which the server should resume sending results. + */ + resumeToken?: ByteString, + /** + * The number of documents that last matched the query at the resume token or + * read time. Documents are counted only when making a listen request with + * resume token or read time, otherwise, keep it null. + */ + expectedCount?: number | null); + /** Creates a new target data instance with an updated sequence number. */ + withSequenceNumber(sequenceNumber: number): TargetData; + /** + * Creates a new target data instance with an updated resume token and + * snapshot version. + */ + withResumeToken(resumeToken: ByteString, snapshotVersion: SnapshotVersion): TargetData; + /** + * Creates a new target data instance with an updated expected count. + */ + withExpectedCount(expectedCount: number): TargetData; + /** + * Creates a new target data instance with an updated last limbo free + * snapshot version number. + */ + withLastLimboFreeSnapshotVersion(lastLimboFreeSnapshotVersion: SnapshotVersion): TargetData; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/collections.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/collections.d.ts new file mode 100644 index 0000000..999c4ea --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/collections.d.ts @@ -0,0 +1,50 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { SnapshotVersion } from '../core/snapshot_version'; +import { TargetId } from '../core/types'; +import { OverlayedDocument } from '../local/overlayed_document'; +import { ObjectMap } from '../util/obj_map'; +import { SortedMap } from '../util/sorted_map'; +import { SortedSet } from '../util/sorted_set'; +import { Document, MutableDocument } from './document'; +import { DocumentKey } from './document_key'; +import { Mutation } from './mutation'; +import { Overlay } from './overlay'; +/** Miscellaneous collection types / constants. */ +export type MutableDocumentMap = SortedMap; +export declare function mutableDocumentMap(): MutableDocumentMap; +export interface DocumentSizeEntries { + documents: MutableDocumentMap; + sizeMap: SortedMap; +} +export type DocumentMap = SortedMap; +export declare function documentMap(...docs: Document[]): DocumentMap; +export type OverlayedDocumentMap = DocumentKeyMap; +export declare function newOverlayedDocumentMap(): OverlayedDocumentMap; +export declare function convertOverlayedDocumentMapToDocumentMap(collection: OverlayedDocumentMap): DocumentMap; +export type OverlayMap = DocumentKeyMap; +export declare function newOverlayMap(): OverlayMap; +export type MutationMap = DocumentKeyMap; +export declare function newMutationMap(): MutationMap; +export type DocumentKeyMap = ObjectMap; +export declare function newDocumentKeyMap(): DocumentKeyMap; +export type DocumentVersionMap = SortedMap; +export declare function documentVersionMap(): DocumentVersionMap; +export type DocumentKeySet = SortedSet; +export declare function documentKeySet(...keys: DocumentKey[]): DocumentKeySet; +export type TargetIdSet = SortedSet; +export declare function targetIdSet(): SortedSet; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/document.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/document.d.ts new file mode 100644 index 0000000..66ba3f3 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/document.d.ts @@ -0,0 +1,150 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { SnapshotVersion } from '../core/snapshot_version'; +import { DocumentKey } from './document_key'; +import { ObjectValue } from './object_value'; +import { FieldPath } from './path'; +/** + * Represents a document in Firestore with a key, version, data and whether the + * data has local mutations applied to it. + */ +export interface Document { + /** The key for this document */ + readonly key: DocumentKey; + /** + * The version of this document if it exists or a version at which this + * document was guaranteed to not exist. + */ + readonly version: SnapshotVersion; + /** + * The timestamp at which this document was read from the remote server. Uses + * `SnapshotVersion.min()` for documents created by the user. + */ + readonly readTime: SnapshotVersion; + /** + * The timestamp at which the document was created. This value increases + * monotonically when a document is deleted then recreated. It can also be + * compared to `createTime` of other documents and the `readTime` of a query. + */ + readonly createTime: SnapshotVersion; + /** The underlying data of this document or an empty value if no data exists. */ + readonly data: ObjectValue; + /** Returns whether local mutations were applied via the mutation queue. */ + readonly hasLocalMutations: boolean; + /** Returns whether mutations were applied based on a write acknowledgment. */ + readonly hasCommittedMutations: boolean; + /** + * Whether this document had a local mutation applied that has not yet been + * acknowledged by Watch. + */ + readonly hasPendingWrites: boolean; + /** + * Returns whether this document is valid (i.e. it is an entry in the + * RemoteDocumentCache, was created by a mutation or read from the backend). + */ + isValidDocument(): boolean; + /** + * Returns whether the document exists and its data is known at the current + * version. + */ + isFoundDocument(): boolean; + /** + * Returns whether the document is known to not exist at the current version. + */ + isNoDocument(): boolean; + /** + * Returns whether the document exists and its data is unknown at the current + * version. + */ + isUnknownDocument(): boolean; + isEqual(other: Document | null | undefined): boolean; + /** Creates a mutable copy of this document. */ + mutableCopy(): MutableDocument; + toString(): string; +} +/** + * Represents a document in Firestore with a key, version, data and whether it + * has local mutations applied to it. + * + * Documents can transition between states via `convertToFoundDocument()`, + * `convertToNoDocument()` and `convertToUnknownDocument()`. If a document does + * not transition to one of these states even after all mutations have been + * applied, `isValidDocument()` returns false and the document should be removed + * from all views. + */ +export declare class MutableDocument implements Document { + readonly key: DocumentKey; + private documentType; + version: SnapshotVersion; + readTime: SnapshotVersion; + createTime: SnapshotVersion; + data: ObjectValue; + private documentState; + private constructor(); + /** + * Creates a document with no known version or data, but which can serve as + * base document for mutations. + */ + static newInvalidDocument(documentKey: DocumentKey): MutableDocument; + /** + * Creates a new document that is known to exist with the given data at the + * given version. + */ + static newFoundDocument(documentKey: DocumentKey, version: SnapshotVersion, createTime: SnapshotVersion, value: ObjectValue): MutableDocument; + /** Creates a new document that is known to not exist at the given version. */ + static newNoDocument(documentKey: DocumentKey, version: SnapshotVersion): MutableDocument; + /** + * Creates a new document that is known to exist at the given version but + * whose data is not known (e.g. a document that was updated without a known + * base document). + */ + static newUnknownDocument(documentKey: DocumentKey, version: SnapshotVersion): MutableDocument; + /** + * Changes the document type to indicate that it exists and that its version + * and data are known. + */ + convertToFoundDocument(version: SnapshotVersion, value: ObjectValue): MutableDocument; + /** + * Changes the document type to indicate that it doesn't exist at the given + * version. + */ + convertToNoDocument(version: SnapshotVersion): MutableDocument; + /** + * Changes the document type to indicate that it exists at a given version but + * that its data is not known (e.g. a document that was updated without a known + * base document). + */ + convertToUnknownDocument(version: SnapshotVersion): MutableDocument; + setHasCommittedMutations(): MutableDocument; + setHasLocalMutations(): MutableDocument; + setReadTime(readTime: SnapshotVersion): MutableDocument; + get hasLocalMutations(): boolean; + get hasCommittedMutations(): boolean; + get hasPendingWrites(): boolean; + isValidDocument(): boolean; + isFoundDocument(): boolean; + isNoDocument(): boolean; + isUnknownDocument(): boolean; + isEqual(other: Document | null | undefined): boolean; + mutableCopy(): MutableDocument; + toString(): string; +} +/** + * Compares the value for field `field` in the provided documents. Throws if + * the field does not exist in both documents. + */ +export declare function compareDocumentsByField(field: FieldPath, d1: Document, d2: Document): number; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/document_comparator.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/document_comparator.d.ts new file mode 100644 index 0000000..100ed19 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/document_comparator.d.ts @@ -0,0 +1,19 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Document } from './document'; +export type DocumentComparator = (doc1: Document, doc2: Document) => number; +export declare function compareByKey(doc1: Document, doc2: Document): number; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/document_key.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/document_key.d.ts new file mode 100644 index 0000000..4c95b57 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/document_key.d.ts @@ -0,0 +1,45 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { ResourcePath } from './path'; +/** + * @internal + */ +export declare class DocumentKey { + readonly path: ResourcePath; + constructor(path: ResourcePath); + static fromPath(path: string): DocumentKey; + static fromName(name: string): DocumentKey; + static empty(): DocumentKey; + get collectionGroup(): string; + /** Returns true if the document is in the specified collectionId. */ + hasCollectionId(collectionId: string): boolean; + /** Returns the collection group (i.e. the name of the parent collection) for this key. */ + getCollectionGroup(): string; + /** Returns the fully qualified path to the parent collection. */ + getCollectionPath(): ResourcePath; + isEqual(other: DocumentKey | null): boolean; + toString(): string; + static comparator(k1: DocumentKey, k2: DocumentKey): number; + static isDocumentKey(path: ResourcePath): boolean; + /** + * Creates and returns a new document key with the given segments. + * + * @param segments - The segments of the path to the document + * @returns A new instance of DocumentKey + */ + static fromSegments(segments: string[]): DocumentKey; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/document_set.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/document_set.d.ts new file mode 100644 index 0000000..5dc7ebd --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/document_set.d.ts @@ -0,0 +1,57 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Document } from './document'; +import { DocumentComparator } from './document_comparator'; +import { DocumentKey } from './document_key'; +/** + * DocumentSet is an immutable (copy-on-write) collection that holds documents + * in order specified by the provided comparator. We always add a document key + * comparator on top of what is provided to guarantee document equality based on + * the key. + */ +export declare class DocumentSet { + /** + * Returns an empty copy of the existing DocumentSet, using the same + * comparator. + */ + static emptySet(oldSet: DocumentSet): DocumentSet; + private comparator; + private keyedMap; + private sortedSet; + /** The default ordering is by key if the comparator is omitted */ + constructor(comp?: DocumentComparator); + has(key: DocumentKey): boolean; + get(key: DocumentKey): Document | null; + first(): Document | null; + last(): Document | null; + isEmpty(): boolean; + /** + * Returns the index of the provided key in the document set, or -1 if the + * document key is not present in the set; + */ + indexOf(key: DocumentKey): number; + get size(): number; + /** Iterates documents in order defined by "comparator" */ + forEach(cb: (doc: Document) => void): void; + /** Inserts or updates a document with the same key */ + add(doc: Document): DocumentSet; + /** Deletes a document with a given key */ + delete(key: DocumentKey): DocumentSet; + isEqual(other: DocumentSet | null | undefined): boolean; + toString(): string; + private copy; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/field_index.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/field_index.d.ts new file mode 100644 index 0000000..1f4ccb0 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/field_index.d.ts @@ -0,0 +1,171 @@ +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { SnapshotVersion } from '../core/snapshot_version'; +import { Document } from './document'; +import { DocumentKey } from './document_key'; +import { FieldPath } from './path'; +/** + * The initial mutation batch id for each index. Gets updated during index + * backfill. + */ +export declare const INITIAL_LARGEST_BATCH_ID = -1; +/** + * The initial sequence number for each index. Gets updated during index + * backfill. + */ +export declare const INITIAL_SEQUENCE_NUMBER = 0; +/** + * An index definition for field indexes in Firestore. + * + * Every index is associated with a collection. The definition contains a list + * of fields and their index kind (which can be `ASCENDING`, `DESCENDING` or + * `CONTAINS` for ArrayContains/ArrayContainsAny queries). + * + * Unlike the backend, the SDK does not differentiate between collection or + * collection group-scoped indices. Every index can be used for both single + * collection and collection group queries. + */ +export declare class FieldIndex { + /** + * The index ID. Returns -1 if the index ID is not available (e.g. the index + * has not yet been persisted). + */ + readonly indexId: number; + /** The collection ID this index applies to. */ + readonly collectionGroup: string; + /** The field segments for this index. */ + readonly fields: IndexSegment[]; + /** Shows how up-to-date the index is for the current user. */ + readonly indexState: IndexState; + /** An ID for an index that has not yet been added to persistence. */ + static UNKNOWN_ID: number; + constructor( + /** + * The index ID. Returns -1 if the index ID is not available (e.g. the index + * has not yet been persisted). + */ + indexId: number, + /** The collection ID this index applies to. */ + collectionGroup: string, + /** The field segments for this index. */ + fields: IndexSegment[], + /** Shows how up-to-date the index is for the current user. */ + indexState: IndexState); +} +/** Returns the ArrayContains/ArrayContainsAny segment for this index. */ +export declare function fieldIndexGetArraySegment(fieldIndex: FieldIndex): IndexSegment | undefined; +/** Returns all directional (ascending/descending) segments for this index. */ +export declare function fieldIndexGetDirectionalSegments(fieldIndex: FieldIndex): IndexSegment[]; +/** + * Returns the order of the document key component for the given index. + * + * PORTING NOTE: This is only used in the Web IndexedDb implementation. + */ +export declare function fieldIndexGetKeyOrder(fieldIndex: FieldIndex): IndexKind; +/** + * Compares indexes by collection group and segments. Ignores update time and + * index ID. + */ +export declare function fieldIndexSemanticComparator(left: FieldIndex, right: FieldIndex): number; +/** Returns a debug representation of the field index */ +export declare function fieldIndexToString(fieldIndex: FieldIndex): string; +/** The type of the index, e.g. for which type of query it can be used. */ +export declare const enum IndexKind { + /** + * Ordered index. Can be used for <, <=, ==, >=, >, !=, IN and NOT IN queries. + */ + ASCENDING = 0, + /** + * Ordered index. Can be used for <, <=, ==, >=, >, !=, IN and NOT IN queries. + */ + DESCENDING = 1, + /** Contains index. Can be used for ArrayContains and ArrayContainsAny. */ + CONTAINS = 2 +} +/** An index component consisting of field path and index type. */ +export declare class IndexSegment { + /** The field path of the component. */ + readonly fieldPath: FieldPath; + /** The fields sorting order. */ + readonly kind: IndexKind; + constructor( + /** The field path of the component. */ + fieldPath: FieldPath, + /** The fields sorting order. */ + kind: IndexKind); +} +/** + * Stores the "high water mark" that indicates how updated the Index is for the + * current user. + */ +export declare class IndexState { + /** + * Indicates when the index was last updated (relative to other indexes). + */ + readonly sequenceNumber: number; + /** The the latest indexed read time, document and batch id. */ + readonly offset: IndexOffset; + constructor( + /** + * Indicates when the index was last updated (relative to other indexes). + */ + sequenceNumber: number, + /** The the latest indexed read time, document and batch id. */ + offset: IndexOffset); + /** The state of an index that has not yet been backfilled. */ + static empty(): IndexState; +} +/** + * Creates an offset that matches all documents with a read time higher than + * `readTime`. + */ +export declare function newIndexOffsetSuccessorFromReadTime(readTime: SnapshotVersion, largestBatchId: number): IndexOffset; +/** Creates a new offset based on the provided document. */ +export declare function newIndexOffsetFromDocument(document: Document): IndexOffset; +/** + * Stores the latest read time, document and batch ID that were processed for an + * index. + */ +export declare class IndexOffset { + /** + * The latest read time version that has been indexed by Firestore for this + * field index. + */ + readonly readTime: SnapshotVersion; + /** + * The key of the last document that was indexed for this query. Use + * `DocumentKey.empty()` if no document has been indexed. + */ + readonly documentKey: DocumentKey; + readonly largestBatchId: number; + constructor( + /** + * The latest read time version that has been indexed by Firestore for this + * field index. + */ + readTime: SnapshotVersion, + /** + * The key of the last document that was indexed for this query. Use + * `DocumentKey.empty()` if no document has been indexed. + */ + documentKey: DocumentKey, largestBatchId: number); + /** Returns an offset that sorts before all regular offsets. */ + static min(): IndexOffset; + /** Returns an offset that sorts after all regular offsets. */ + static max(): IndexOffset; +} +export declare function indexOffsetComparator(left: IndexOffset, right: IndexOffset): number; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/field_mask.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/field_mask.d.ts new file mode 100644 index 0000000..555ea0d --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/field_mask.d.ts @@ -0,0 +1,45 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { FieldPath } from './path'; +/** + * Provides a set of fields that can be used to partially patch a document. + * FieldMask is used in conjunction with ObjectValue. + * Examples: + * foo - Overwrites foo entirely with the provided value. If foo is not + * present in the companion ObjectValue, the field is deleted. + * foo.bar - Overwrites only the field bar of the object foo. + * If foo is not an object, foo is replaced with an object + * containing foo + */ +export declare class FieldMask { + readonly fields: FieldPath[]; + constructor(fields: FieldPath[]); + static empty(): FieldMask; + /** + * Returns a new FieldMask object that is the result of adding all the given + * fields paths to this field mask. + */ + unionWith(extraFields: FieldPath[]): FieldMask; + /** + * Verifies that `fieldPath` is included by at least one field in this field + * mask. + * + * This is an O(n) operation, where `n` is the size of the field mask. + */ + covers(fieldPath: FieldPath): boolean; + isEqual(other: FieldMask): boolean; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/mutation.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/mutation.d.ts new file mode 100644 index 0000000..9dd68b9 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/mutation.d.ts @@ -0,0 +1,270 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { SnapshotVersion } from '../core/snapshot_version'; +import { Timestamp } from '../lite-api/timestamp'; +import { Value as ProtoValue } from '../protos/firestore_proto_api'; +import { Document, MutableDocument } from './document'; +import { DocumentKey } from './document_key'; +import { FieldMask } from './field_mask'; +import { ObjectValue } from './object_value'; +import { FieldPath } from './path'; +import { TransformOperation } from './transform_operation'; +/** A field path and the TransformOperation to perform upon it. */ +export declare class FieldTransform { + readonly field: FieldPath; + readonly transform: TransformOperation; + constructor(field: FieldPath, transform: TransformOperation); +} +export declare function fieldTransformEquals(left: FieldTransform, right: FieldTransform): boolean; +export declare function fieldTransformsAreEqual(left?: FieldTransform[], right?: FieldTransform[]): boolean; +/** The result of successfully applying a mutation to the backend. */ +export declare class MutationResult { + /** + * The version at which the mutation was committed: + * + * - For most operations, this is the updateTime in the WriteResult. + * - For deletes, the commitTime of the WriteResponse (because deletes are + * not stored and have no updateTime). + * + * Note that these versions can be different: No-op writes will not change + * the updateTime even though the commitTime advances. + */ + readonly version: SnapshotVersion; + /** + * The resulting fields returned from the backend after a mutation + * containing field transforms has been committed. Contains one FieldValue + * for each FieldTransform that was in the mutation. + * + * Will be empty if the mutation did not contain any field transforms. + */ + readonly transformResults: Array; + constructor( + /** + * The version at which the mutation was committed: + * + * - For most operations, this is the updateTime in the WriteResult. + * - For deletes, the commitTime of the WriteResponse (because deletes are + * not stored and have no updateTime). + * + * Note that these versions can be different: No-op writes will not change + * the updateTime even though the commitTime advances. + */ + version: SnapshotVersion, + /** + * The resulting fields returned from the backend after a mutation + * containing field transforms has been committed. Contains one FieldValue + * for each FieldTransform that was in the mutation. + * + * Will be empty if the mutation did not contain any field transforms. + */ + transformResults: Array); +} +export declare const enum MutationType { + Set = 0, + Patch = 1, + Delete = 2, + Verify = 3 +} +/** + * Encodes a precondition for a mutation. This follows the model that the + * backend accepts with the special case of an explicit "empty" precondition + * (meaning no precondition). + */ +export declare class Precondition { + readonly updateTime?: SnapshotVersion | undefined; + readonly exists?: boolean | undefined; + private constructor(); + /** Creates a new empty Precondition. */ + static none(): Precondition; + /** Creates a new Precondition with an exists flag. */ + static exists(exists: boolean): Precondition; + /** Creates a new Precondition based on a version a document exists at. */ + static updateTime(version: SnapshotVersion): Precondition; + /** Returns whether this Precondition is empty. */ + get isNone(): boolean; + isEqual(other: Precondition): boolean; +} +/** Returns true if the preconditions is valid for the given document. */ +export declare function preconditionIsValidForDocument(precondition: Precondition, document: MutableDocument): boolean; +/** + * A mutation describes a self-contained change to a document. Mutations can + * create, replace, delete, and update subsets of documents. + * + * Mutations not only act on the value of the document but also its version. + * + * For local mutations (mutations that haven't been committed yet), we preserve + * the existing version for Set and Patch mutations. For Delete mutations, we + * reset the version to 0. + * + * Here's the expected transition table. + * + * MUTATION APPLIED TO RESULTS IN + * + * SetMutation Document(v3) Document(v3) + * SetMutation NoDocument(v3) Document(v0) + * SetMutation InvalidDocument(v0) Document(v0) + * PatchMutation Document(v3) Document(v3) + * PatchMutation NoDocument(v3) NoDocument(v3) + * PatchMutation InvalidDocument(v0) UnknownDocument(v3) + * DeleteMutation Document(v3) NoDocument(v0) + * DeleteMutation NoDocument(v3) NoDocument(v0) + * DeleteMutation InvalidDocument(v0) NoDocument(v0) + * + * For acknowledged mutations, we use the updateTime of the WriteResponse as + * the resulting version for Set and Patch mutations. As deletes have no + * explicit update time, we use the commitTime of the WriteResponse for + * Delete mutations. + * + * If a mutation is acknowledged by the backend but fails the precondition check + * locally, we transition to an `UnknownDocument` and rely on Watch to send us + * the updated version. + * + * Field transforms are used only with Patch and Set Mutations. We use the + * `updateTransforms` message to store transforms, rather than the `transforms`s + * messages. + * + * ## Subclassing Notes + * + * Every type of mutation needs to implement its own applyToRemoteDocument() and + * applyToLocalView() to implement the actual behavior of applying the mutation + * to some source document (see `setMutationApplyToRemoteDocument()` for an + * example). + */ +export declare abstract class Mutation { + abstract readonly type: MutationType; + abstract readonly key: DocumentKey; + abstract readonly precondition: Precondition; + abstract readonly fieldTransforms: FieldTransform[]; + /** + * Returns a `FieldMask` representing the fields that will be changed by + * applying this mutation. Returns `null` if the mutation will overwrite the + * entire document. + */ + abstract getFieldMask(): FieldMask | null; +} +/** + * A utility method to calculate a `Mutation` representing the overlay from the + * final state of the document, and a `FieldMask` representing the fields that + * are mutated by the local mutations. + */ +export declare function calculateOverlayMutation(doc: MutableDocument, mask: FieldMask | null): Mutation | null; +/** + * Applies this mutation to the given document for the purposes of computing a + * new remote document. If the input document doesn't match the expected state + * (e.g. it is invalid or outdated), the document type may transition to + * unknown. + * + * @param mutation - The mutation to apply. + * @param document - The document to mutate. The input document can be an + * invalid document if the client has no knowledge of the pre-mutation state + * of the document. + * @param mutationResult - The result of applying the mutation from the backend. + */ +export declare function mutationApplyToRemoteDocument(mutation: Mutation, document: MutableDocument, mutationResult: MutationResult): void; +/** + * Applies this mutation to the given document for the purposes of computing + * the new local view of a document. If the input document doesn't match the + * expected state, the document is not modified. + * + * @param mutation - The mutation to apply. + * @param document - The document to mutate. The input document can be an + * invalid document if the client has no knowledge of the pre-mutation state + * of the document. + * @param previousMask - The fields that have been updated before applying this mutation. + * @param localWriteTime - A timestamp indicating the local write time of the + * batch this mutation is a part of. + * @returns A `FieldMask` representing the fields that are changed by applying this mutation. + */ +export declare function mutationApplyToLocalView(mutation: Mutation, document: MutableDocument, previousMask: FieldMask | null, localWriteTime: Timestamp): FieldMask | null; +/** + * If this mutation is not idempotent, returns the base value to persist with + * this mutation. If a base value is returned, the mutation is always applied + * to this base value, even if document has already been updated. + * + * The base value is a sparse object that consists of only the document + * fields for which this mutation contains a non-idempotent transformation + * (e.g. a numeric increment). The provided value guarantees consistent + * behavior for non-idempotent transforms and allow us to return the same + * latency-compensated value even if the backend has already applied the + * mutation. The base value is null for idempotent mutations, as they can be + * re-played even if the backend has already applied them. + * + * @returns a base value to store along with the mutation, or null for + * idempotent mutations. + */ +export declare function mutationExtractBaseValue(mutation: Mutation, document: Document): ObjectValue | null; +export declare function mutationEquals(left: Mutation, right: Mutation): boolean; +/** + * A mutation that creates or replaces the document at the given key with the + * object value contents. + */ +export declare class SetMutation extends Mutation { + readonly key: DocumentKey; + readonly value: ObjectValue; + readonly precondition: Precondition; + readonly fieldTransforms: FieldTransform[]; + constructor(key: DocumentKey, value: ObjectValue, precondition: Precondition, fieldTransforms?: FieldTransform[]); + readonly type: MutationType; + getFieldMask(): FieldMask | null; +} +/** + * A mutation that modifies fields of the document at the given key with the + * given values. The values are applied through a field mask: + * + * * When a field is in both the mask and the values, the corresponding field + * is updated. + * * When a field is in neither the mask nor the values, the corresponding + * field is unmodified. + * * When a field is in the mask but not in the values, the corresponding field + * is deleted. + * * When a field is not in the mask but is in the values, the values map is + * ignored. + */ +export declare class PatchMutation extends Mutation { + readonly key: DocumentKey; + readonly data: ObjectValue; + readonly fieldMask: FieldMask; + readonly precondition: Precondition; + readonly fieldTransforms: FieldTransform[]; + constructor(key: DocumentKey, data: ObjectValue, fieldMask: FieldMask, precondition: Precondition, fieldTransforms?: FieldTransform[]); + readonly type: MutationType; + getFieldMask(): FieldMask | null; +} +/** A mutation that deletes the document at the given key. */ +export declare class DeleteMutation extends Mutation { + readonly key: DocumentKey; + readonly precondition: Precondition; + constructor(key: DocumentKey, precondition: Precondition); + readonly type: MutationType; + readonly fieldTransforms: FieldTransform[]; + getFieldMask(): FieldMask | null; +} +/** + * A mutation that verifies the existence of the document at the given key with + * the provided precondition. + * + * The `verify` operation is only used in Transactions, and this class serves + * primarily to facilitate serialization into protos. + */ +export declare class VerifyMutation extends Mutation { + readonly key: DocumentKey; + readonly precondition: Precondition; + constructor(key: DocumentKey, precondition: Precondition); + readonly type: MutationType; + readonly fieldTransforms: FieldTransform[]; + getFieldMask(): FieldMask | null; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/mutation_batch.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/mutation_batch.d.ts new file mode 100644 index 0000000..c05b01e --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/mutation_batch.d.ts @@ -0,0 +1,88 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { SnapshotVersion } from '../core/snapshot_version'; +import { BatchId } from '../core/types'; +import { Timestamp } from '../lite-api/timestamp'; +import { DocumentKeySet, MutationMap, DocumentVersionMap, OverlayedDocumentMap } from './collections'; +import { MutableDocument } from './document'; +import { FieldMask } from './field_mask'; +import { Mutation, MutationResult } from './mutation'; +/** + * A batch of mutations that will be sent as one unit to the backend. + */ +export declare class MutationBatch { + batchId: BatchId; + localWriteTime: Timestamp; + baseMutations: Mutation[]; + mutations: Mutation[]; + /** + * @param batchId - The unique ID of this mutation batch. + * @param localWriteTime - The original write time of this mutation. + * @param baseMutations - Mutations that are used to populate the base + * values when this mutation is applied locally. This can be used to locally + * overwrite values that are persisted in the remote document cache. Base + * mutations are never sent to the backend. + * @param mutations - The user-provided mutations in this mutation batch. + * User-provided mutations are applied both locally and remotely on the + * backend. + */ + constructor(batchId: BatchId, localWriteTime: Timestamp, baseMutations: Mutation[], mutations: Mutation[]); + /** + * Applies all the mutations in this MutationBatch to the specified document + * to compute the state of the remote document + * + * @param document - The document to apply mutations to. + * @param batchResult - The result of applying the MutationBatch to the + * backend. + */ + applyToRemoteDocument(document: MutableDocument, batchResult: MutationBatchResult): void; + /** + * Computes the local view of a document given all the mutations in this + * batch. + * + * @param document - The document to apply mutations to. + * @param mutatedFields - Fields that have been updated before applying this mutation batch. + * @returns A `FieldMask` representing all the fields that are mutated. + */ + applyToLocalView(document: MutableDocument, mutatedFields: FieldMask | null): FieldMask | null; + /** + * Computes the local view for all provided documents given the mutations in + * this batch. Returns a `DocumentKey` to `Mutation` map which can be used to + * replace all the mutation applications. + */ + applyToLocalDocumentSet(documentMap: OverlayedDocumentMap, documentsWithoutRemoteVersion: DocumentKeySet): MutationMap; + keys(): DocumentKeySet; + isEqual(other: MutationBatch): boolean; +} +/** The result of applying a mutation batch to the backend. */ +export declare class MutationBatchResult { + readonly batch: MutationBatch; + readonly commitVersion: SnapshotVersion; + readonly mutationResults: MutationResult[]; + /** + * A pre-computed mapping from each mutated document to the resulting + * version. + */ + readonly docVersions: DocumentVersionMap; + private constructor(); + /** + * Creates a new MutationBatchResult for the given batch and results. There + * must be one result for each mutation in the batch. This static factory + * caches a document=>version mapping (docVersions). + */ + static from(batch: MutationBatch, commitVersion: SnapshotVersion, results: MutationResult[]): MutationBatchResult; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/normalize.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/normalize.d.ts new file mode 100644 index 0000000..c279ba7 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/normalize.d.ts @@ -0,0 +1,33 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Timestamp } from '../protos/firestore_proto_api'; +import { ByteString } from '../util/byte_string'; +/** + * Converts the possible Proto values for a timestamp value into a "seconds and + * nanos" representation. + */ +export declare function normalizeTimestamp(date: Timestamp): { + seconds: number; + nanos: number; +}; +/** + * Converts the possible Proto types for numbers into a JavaScript number. + * Returns 0 if the value is not numeric. + */ +export declare function normalizeNumber(value: number | string | undefined): number; +/** Converts the possible Proto types for Blobs into a ByteString. */ +export declare function normalizeByteString(blob: string | Uint8Array): ByteString; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/object_value.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/object_value.d.ts new file mode 100644 index 0000000..d299e86 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/object_value.d.ts @@ -0,0 +1,78 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { MapValue as ProtoMapValue, Value as ProtoValue } from '../protos/firestore_proto_api'; +import { FieldMask } from './field_mask'; +import { FieldPath } from './path'; +export interface JsonObject { + [name: string]: T; +} +/** + * An ObjectValue represents a MapValue in the Firestore Proto and offers the + * ability to add and remove fields (via the ObjectValueBuilder). + */ +export declare class ObjectValue { + readonly value: { + mapValue: ProtoMapValue; + }; + constructor(value: { + mapValue: ProtoMapValue; + }); + static empty(): ObjectValue; + /** + * Returns the value at the given path or null. + * + * @param path - the path to search + * @returns The value at the path or null if the path is not set. + */ + field(path: FieldPath): ProtoValue | null; + /** + * Sets the field to the provided value. + * + * @param path - The field path to set. + * @param value - The value to set. + */ + set(path: FieldPath, value: ProtoValue): void; + /** + * Sets the provided fields to the provided values. + * + * @param data - A map of fields to values (or null for deletes). + */ + setAll(data: Map): void; + /** + * Removes the field at the specified path. If there is no field at the + * specified path, nothing is changed. + * + * @param path - The field path to remove. + */ + delete(path: FieldPath): void; + isEqual(other: ObjectValue): boolean; + /** + * Returns the map that contains the leaf element of `path`. If the parent + * entry does not yet exist, or if it is not a map, a new map will be created. + */ + private getFieldsMap; + /** + * Modifies `fieldsMap` by adding, replacing or deleting the specified + * entries. + */ + private applyChanges; + clone(): ObjectValue; +} +/** + * Returns a FieldMask built from all fields in a MapValue. + */ +export declare function extractFieldMask(value: ProtoMapValue): FieldMask; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/overlay.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/overlay.d.ts new file mode 100644 index 0000000..ef90621 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/overlay.d.ts @@ -0,0 +1,32 @@ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { DocumentKey } from './document_key'; +import { Mutation } from './mutation'; +/** + * Representation of an overlay computed by Firestore. + * + * Holds information about a mutation and the largest batch id in Firestore when + * the mutation was created. + */ +export declare class Overlay { + readonly largestBatchId: number; + readonly mutation: Mutation; + constructor(largestBatchId: number, mutation: Mutation); + getKey(): DocumentKey; + isEqual(other: Overlay | null): boolean; + toString(): string; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/path.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/path.d.ts new file mode 100644 index 0000000..a33f0e8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/path.d.ts @@ -0,0 +1,121 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export declare const DOCUMENT_KEY_NAME = "__name__"; +/** + * Path represents an ordered sequence of string segments. + */ +declare abstract class BasePath> { + private segments; + private offset; + private len; + constructor(segments: string[], offset?: number, length?: number); + /** + * Abstract constructor method to construct an instance of B with the given + * parameters. + */ + protected abstract construct(segments: string[], offset?: number, length?: number): B; + /** + * Returns a String representation. + * + * Implementing classes are required to provide deterministic implementations as + * the String representation is used to obtain canonical Query IDs. + */ + abstract toString(): string; + get length(): number; + isEqual(other: B): boolean; + child(nameOrPath: string | B): B; + /** The index of one past the last segment of the path. */ + private limit; + popFirst(size?: number): B; + popLast(): B; + firstSegment(): string; + lastSegment(): string; + get(index: number): string; + isEmpty(): boolean; + isPrefixOf(other: this): boolean; + isImmediateParentOf(potentialChild: this): boolean; + forEach(fn: (segment: string) => void): void; + toArray(): string[]; + /** + * Compare 2 paths segment by segment, prioritizing numeric IDs + * (e.g., "__id123__") in numeric ascending order, followed by string + * segments in lexicographical order. + */ + static comparator>(p1: BasePath, p2: BasePath): number; + private static compareSegments; + private static isNumericId; + private static extractNumericId; +} +/** + * A slash-separated path for navigating resources (documents and collections) + * within Firestore. + * + * @internal + */ +export declare class ResourcePath extends BasePath { + protected construct(segments: string[], offset?: number, length?: number): ResourcePath; + canonicalString(): string; + toString(): string; + /** + * Returns a string representation of this path + * where each path segment has been encoded with + * `encodeURIComponent`. + */ + toUriEncodedString(): string; + /** + * Creates a resource path from the given slash-delimited string. If multiple + * arguments are provided, all components are combined. Leading and trailing + * slashes from all components are ignored. + */ + static fromString(...pathComponents: string[]): ResourcePath; + static emptyPath(): ResourcePath; +} +/** + * A dot-separated path for navigating sub-objects within a document. + * @internal + */ +export declare class FieldPath extends BasePath { + protected construct(segments: string[], offset?: number, length?: number): FieldPath; + /** + * Returns true if the string could be used as a segment in a field path + * without escaping. + */ + private static isValidIdentifier; + canonicalString(): string; + toString(): string; + /** + * Returns true if this field references the key of a document. + */ + isKeyField(): boolean; + /** + * The field designating the key of a document. + */ + static keyField(): FieldPath; + /** + * Parses a field string from the given server-formatted string. + * + * - Splitting the empty string is not allowed (for now at least). + * - Empty segments within the string (e.g. if there are two consecutive + * separators) are not allowed. + * + * TODO(b/37244157): we should make this more strict. Right now, it allows + * non-identifier path components, even if they aren't escaped. + */ + static fromServerFormat(path: string): FieldPath; + static emptyPath(): FieldPath; +} +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/server_timestamps.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/server_timestamps.d.ts new file mode 100644 index 0000000..d4e8c4a --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/server_timestamps.d.ts @@ -0,0 +1,34 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Timestamp } from '../lite-api/timestamp'; +import { Value as ProtoValue } from '../protos/firestore_proto_api'; +export declare function isServerTimestamp(value: ProtoValue | null): boolean; +/** + * Creates a new ServerTimestamp proto value (using the internal format). + */ +export declare function serverTimestamp(localWriteTime: Timestamp, previousValue: ProtoValue | null): ProtoValue; +/** + * Returns the value of the field before this ServerTimestamp was set. + * + * Preserving the previous values allows the user to display the last resoled + * value until the backend responds with the timestamp. + */ +export declare function getPreviousValue(value: ProtoValue): ProtoValue | null; +/** + * Returns the local time at which this timestamp was first set. + */ +export declare function getLocalWriteTime(value: ProtoValue): Timestamp; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/target_index_matcher.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/target_index_matcher.d.ts new file mode 100644 index 0000000..d313f1e --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/target_index_matcher.d.ts @@ -0,0 +1,76 @@ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Target } from '../core/target'; +import { FieldIndex } from './field_index'; +/** + * A light query planner for Firestore. + * + * This class matches a `FieldIndex` against a Firestore Query `Target`. It + * determines whether a given index can be used to serve the specified target. + * + * The following table showcases some possible index configurations: + * + * Query | Index + * ----------------------------------------------------------------------------- + * where('a', '==', 'a').where('b', '==', 'b') | a ASC, b DESC + * where('a', '==', 'a').where('b', '==', 'b') | a ASC + * where('a', '==', 'a').where('b', '==', 'b') | b DESC + * where('a', '>=', 'a').orderBy('a') | a ASC + * where('a', '>=', 'a').orderBy('a', 'desc') | a DESC + * where('a', '>=', 'a').orderBy('a').orderBy('b') | a ASC, b ASC + * where('a', '>=', 'a').orderBy('a').orderBy('b') | a ASC + * where('a', 'array-contains', 'a').orderBy('b') | a CONTAINS, b ASCENDING + * where('a', 'array-contains', 'a').orderBy('b') | a CONTAINS + */ +export declare class TargetIndexMatcher { + private readonly collectionId; + private inequalityFilters; + private readonly equalityFilters; + private readonly orderBys; + constructor(target: Target); + get hasMultipleInequality(): boolean; + /** + * Returns whether the index can be used to serve the TargetIndexMatcher's + * target. + * + * An index is considered capable of serving the target when: + * - The target uses all index segments for its filters and orderBy clauses. + * The target can have additional filter and orderBy clauses, but not + * fewer. + * - If an ArrayContains/ArrayContainsAnyfilter is used, the index must also + * have a corresponding `CONTAINS` segment. + * - All directional index segments can be mapped to the target as a series of + * equality filters, a single inequality filter and a series of orderBy + * clauses. + * - The segments that represent the equality filters may appear out of order. + * - The optional segment for the inequality filter must appear after all + * equality segments. + * - The segments that represent that orderBy clause of the target must appear + * in order after all equality and inequality segments. Single orderBy + * clauses cannot be skipped, but a continuous orderBy suffix may be + * omitted. + */ + servedByIndex(index: FieldIndex): boolean; + /** + * Returns a full matched field index for this target. Currently multiple + * inequality query is not supported so function returns null. + */ + buildTargetIndex(): FieldIndex | null; + private hasMatchingEqualityFilter; + private matchesFilter; + private matchesOrderBy; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/transform_operation.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/transform_operation.d.ts new file mode 100644 index 0000000..be1e0f3 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/transform_operation.d.ts @@ -0,0 +1,75 @@ +/** + * @license + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Timestamp } from '../lite-api/timestamp'; +import { Value as ProtoValue } from '../protos/firestore_proto_api'; +import { Serializer } from '../remote/number_serializer'; +/** Used to represent a field transform on a mutation. */ +export declare class TransformOperation { + private _; +} +/** + * Computes the local transform result against the provided `previousValue`, + * optionally using the provided localWriteTime. + */ +export declare function applyTransformOperationToLocalView(transform: TransformOperation, previousValue: ProtoValue | null, localWriteTime: Timestamp): ProtoValue; +/** + * Computes a final transform result after the transform has been acknowledged + * by the server, potentially using the server-provided transformResult. + */ +export declare function applyTransformOperationToRemoteDocument(transform: TransformOperation, previousValue: ProtoValue | null, transformResult: ProtoValue | null): ProtoValue; +/** + * If this transform operation is not idempotent, returns the base value to + * persist for this transform. If a base value is returned, the transform + * operation is always applied to this base value, even if document has + * already been updated. + * + * Base values provide consistent behavior for non-idempotent transforms and + * allow us to return the same latency-compensated value even if the backend + * has already applied the transform operation. The base value is null for + * idempotent transforms, as they can be re-played even if the backend has + * already applied them. + * + * @returns a base value to store along with the mutation, or null for + * idempotent transforms. + */ +export declare function computeTransformOperationBaseValue(transform: TransformOperation, previousValue: ProtoValue | null): ProtoValue | null; +export declare function transformOperationEquals(left: TransformOperation, right: TransformOperation): boolean; +/** Transforms a value into a server-generated timestamp. */ +export declare class ServerTimestampTransform extends TransformOperation { +} +/** Transforms an array value via a union operation. */ +export declare class ArrayUnionTransformOperation extends TransformOperation { + readonly elements: ProtoValue[]; + constructor(elements: ProtoValue[]); +} +/** Transforms an array value via a remove operation. */ +export declare class ArrayRemoveTransformOperation extends TransformOperation { + readonly elements: ProtoValue[]; + constructor(elements: ProtoValue[]); +} +/** + * Implements the backend semantics for locally computed NUMERIC_ADD (increment) + * transforms. Converts all field values to integers or doubles, but unlike the + * backend does not cap integer values at 2^63. Instead, JavaScript number + * arithmetic is used and precision loss can occur for values greater than 2^53. + */ +export declare class NumericIncrementTransformOperation extends TransformOperation { + readonly serializer: Serializer; + readonly operand: ProtoValue; + constructor(serializer: Serializer, operand: ProtoValue); +} +export declare function applyNumericIncrementTransformOperationToLocalView(transform: NumericIncrementTransformOperation, previousValue: ProtoValue | null): ProtoValue; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/type_order.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/type_order.d.ts new file mode 100644 index 0000000..bb09c39 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/type_order.d.ts @@ -0,0 +1,38 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * All the different kinds of values that can be stored in fields in + * a document. The types of the same comparison order should be defined + * together as a group. The order of each group is defined by the Firestore + * backend and is available at: + * https://firebase.google.com/docs/firestore/manage-data/data-types + */ +export declare const enum TypeOrder { + NullValue = 0, + BooleanValue = 1, + NumberValue = 2, + TimestampValue = 3, + ServerTimestampValue = 4, + StringValue = 5, + BlobValue = 6, + RefValue = 7, + GeoPointValue = 8, + ArrayValue = 9, + VectorValue = 10, + ObjectValue = 11, + MaxValue = 9007199254740991 +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/values.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/values.d.ts new file mode 100644 index 0000000..94b377f --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/values.d.ts @@ -0,0 +1,114 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { DatabaseId } from '../core/database_info'; +import { ArrayValue, MapValue, Value as ProtoValue, Value } from '../protos/firestore_proto_api'; +import { DocumentKey } from './document_key'; +import { TypeOrder } from './type_order'; +export declare const TYPE_KEY = "__type__"; +export declare const MAX_VALUE: Value; +export declare const VECTOR_VALUE_SENTINEL = "__vector__"; +export declare const VECTOR_MAP_VECTORS_KEY = "value"; +export declare const MIN_VALUE: Value; +/** Extracts the backend's type order for the provided value. */ +export declare function typeOrder(value: Value): TypeOrder; +/** Tests `left` and `right` for equality based on the backend semantics. */ +export declare function valueEquals(left: Value, right: Value): boolean; +export declare function numberEquals(left: Value, right: Value): boolean; +/** Returns true if the ArrayValue contains the specified element. */ +export declare function arrayValueContains(haystack: ArrayValue, needle: Value): boolean; +export declare function valueCompare(left: Value, right: Value): number; +/** + * Generates the canonical ID for the provided field value (as used in Target + * serialization). + */ +export declare function canonicalId(value: Value): string; +/** + * Returns an approximate (and wildly inaccurate) in-memory size for the field + * value. + * + * The memory size takes into account only the actual user data as it resides + * in memory and ignores object overhead. + */ +export declare function estimateByteSize(value: Value): number; +/** Returns a reference value for the provided database and key. */ +export declare function refValue(databaseId: DatabaseId, key: DocumentKey): Value; +/** Returns true if `value` is an IntegerValue . */ +export declare function isInteger(value?: Value | null): value is { + integerValue: string | number; +}; +/** Returns true if `value` is a DoubleValue. */ +export declare function isDouble(value?: Value | null): value is { + doubleValue: string | number; +}; +/** Returns true if `value` is either an IntegerValue or a DoubleValue. */ +export declare function isNumber(value?: Value | null): boolean; +/** Returns true if `value` is an ArrayValue. */ +export declare function isArray(value?: Value | null): value is { + arrayValue: ArrayValue; +}; +/** Returns true if `value` is a ReferenceValue. */ +export declare function isReferenceValue(value?: Value | null): value is { + referenceValue: string; +}; +/** Returns true if `value` is a NullValue. */ +export declare function isNullValue(value?: Value | null): value is { + nullValue: 'NULL_VALUE'; +}; +/** Returns true if `value` is NaN. */ +export declare function isNanValue(value?: Value | null): value is { + doubleValue: 'NaN' | number; +}; +/** Returns true if `value` is a MapValue. */ +export declare function isMapValue(value?: Value | null): value is { + mapValue: MapValue; +}; +/** Returns true if `value` is a VetorValue. */ +export declare function isVectorValue(value: ProtoValue | null): boolean; +/** Creates a deep copy of `source`. */ +export declare function deepClone(source: Value): Value; +/** Returns true if the Value represents the canonical {@link #MAX_VALUE} . */ +export declare function isMaxValue(value: Value): boolean; +export declare const MIN_VECTOR_VALUE: { + mapValue: { + fields: { + __type__: { + stringValue: string; + }; + value: { + arrayValue: {}; + }; + }; + }; +}; +/** Returns the lowest value for the given value type (inclusive). */ +export declare function valuesGetLowerBound(value: Value): Value; +/** Returns the largest value for the given value type (exclusive). */ +export declare function valuesGetUpperBound(value: Value): Value; +export declare function lowerBoundCompare(left: { + value: Value; + inclusive: boolean; +}, right: { + value: Value; + inclusive: boolean; +}): number; +export declare function upperBoundCompare(left: { + value: Value; + inclusive: boolean; +}, right: { + value: Value; + inclusive: boolean; +}): number; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/base64.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/base64.d.ts new file mode 100644 index 0000000..999f234 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/base64.d.ts @@ -0,0 +1,25 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Converts a Base64 encoded string to a binary string. */ +export declare function decodeBase64(encoded: string): string; +/** Converts a binary string to a Base64 encoded string. */ +export declare function encodeBase64(raw: string): string; +/** + * True if and only if the Base64 conversion functions are available. + * @internal + */ +export declare function isBase64Available(): boolean; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser/base64.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser/base64.d.ts new file mode 100644 index 0000000..9ea2985 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser/base64.d.ts @@ -0,0 +1,22 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Converts a Base64 encoded string to a binary string. */ +export declare function decodeBase64(encoded: string): string; +/** Converts a binary string to a Base64 encoded string. */ +export declare function encodeBase64(raw: string): string; +/** True if and only if the Base64 conversion functions are available. */ +export declare function isBase64Available(): boolean; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser/byte_stream_reader.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser/byte_stream_reader.d.ts new file mode 100644 index 0000000..2b95861 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser/byte_stream_reader.d.ts @@ -0,0 +1,21 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { BundleSource } from '../../util/bundle_reader'; +/** + * On web, a `ReadableStream` is wrapped around by a `ByteStreamReader`. + */ +export declare function toByteStreamReader(source: BundleSource, bytesPerRead: number): ReadableStreamDefaultReader; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser/connection.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser/connection.d.ts new file mode 100644 index 0000000..9e35cd8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser/connection.d.ts @@ -0,0 +1,23 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { DatabaseInfo } from '../../core/database_info'; +import { Connection } from '../../remote/connection'; +import { ConnectivityMonitor } from '../../remote/connectivity_monitor'; +/** Initializes the WebChannelConnection for the browser. */ +export declare function newConnection(databaseInfo: DatabaseInfo): Connection; +/** Return the Platform-specific connectivity monitor. */ +export declare function newConnectivityMonitor(): ConnectivityMonitor; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser/connectivity_monitor.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser/connectivity_monitor.d.ts new file mode 100644 index 0000000..0f14bb7 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser/connectivity_monitor.d.ts @@ -0,0 +1,33 @@ +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { ConnectivityMonitor, NetworkStatus } from '../../remote/connectivity_monitor'; +/** + * Browser implementation of ConnectivityMonitor. + */ +export declare class BrowserConnectivityMonitor implements ConnectivityMonitor { + private readonly networkAvailableListener; + private readonly networkUnavailableListener; + private callbacks; + constructor(); + addCallback(callback: (status: NetworkStatus) => void): void; + shutdown(): void; + private configureNetworkMonitoring; + private onNetworkAvailable; + private onNetworkUnavailable; + /** Checks that all used attributes of window are available. */ + static isAvailable(): boolean; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser/dom.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser/dom.d.ts new file mode 100644 index 0000000..d2a5319 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser/dom.d.ts @@ -0,0 +1,20 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** The Platform's 'window' implementation or null if not available. */ +export declare function getWindow(): Window | null; +/** The Platform's 'document' implementation or null if not available. */ +export declare function getDocument(): Document | null; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser/format_json.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser/format_json.d.ts new file mode 100644 index 0000000..5e5f7ad --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser/format_json.d.ts @@ -0,0 +1,18 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Formats an object as a JSON string, suitable for logging. */ +export declare function formatJSON(value: unknown): string; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser/random_bytes.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser/random_bytes.d.ts new file mode 100644 index 0000000..672e612 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser/random_bytes.d.ts @@ -0,0 +1,22 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Generates `nBytes` of random bytes. + * + * If `nBytes < 0` , an error will be thrown. + */ +export declare function randomBytes(nBytes: number): Uint8Array; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser/serializer.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser/serializer.d.ts new file mode 100644 index 0000000..839e680 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser/serializer.d.ts @@ -0,0 +1,20 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Return the Platform-specific serializer monitor. */ +import { DatabaseId } from '../../core/database_info'; +import { JsonProtoSerializer } from '../../remote/serializer'; +export declare function newSerializer(databaseId: DatabaseId): JsonProtoSerializer; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser/snapshot_to_json.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser/snapshot_to_json.d.ts new file mode 100644 index 0000000..6a75f06 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser/snapshot_to_json.d.ts @@ -0,0 +1,23 @@ +/** + * @license + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Return the Platform-specific build JSON bundle implementations. */ +import { Firestore } from '../../api/database'; +import { Query } from '../../core/query'; +import { DocumentData } from '../../lite-api/reference'; +import { Document } from '../../model/document'; +export declare function buildDocumentSnapshotJsonBundle(db: Firestore, document: Document, docData: DocumentData, path: string): string; +export declare function buildQuerySnapshotJsonBundle(db: Firestore, query: Query, bundleName: string, parent: string, paths: string[], docs: Document[], documentData: DocumentData[]): string; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser/text_serializer.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser/text_serializer.d.ts new file mode 100644 index 0000000..47213fb --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser/text_serializer.d.ts @@ -0,0 +1,24 @@ +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An instance of the Platform's 'TextEncoder' implementation. + */ +export declare function newTextEncoder(): TextEncoder; +/** + * An instance of the Platform's 'TextDecoder' implementation. + */ +export declare function newTextDecoder(): TextDecoder; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser/webchannel_connection.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser/webchannel_connection.d.ts new file mode 100644 index 0000000..79117f7 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser/webchannel_connection.d.ts @@ -0,0 +1,47 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { WebChannel } from '@firebase/webchannel-wrapper/webchannel-blob'; +import { Token } from '../../api/credentials'; +import { DatabaseInfo } from '../../core/database_info'; +import { Stream } from '../../remote/connection'; +import { RestConnection } from '../../remote/rest_connection'; +import { StringMap } from '../../util/types'; +export declare class WebChannelConnection extends RestConnection { + private readonly forceLongPolling; + private readonly autoDetectLongPolling; + private readonly useFetchStreams; + private readonly longPollingOptions; + /** A collection of open WebChannel instances */ + private openWebChannels; + constructor(info: DatabaseInfo); + protected performRPCRequest(rpcName: string, url: string, headers: StringMap, body: Req, _forwardCredentials: boolean): Promise; + openStream(rpcName: string, authToken: Token | null, appCheckToken: Token | null): Stream; + /** + * Closes and cleans up any resources associated with the connection. + */ + terminate(): void; + /** + * Add a WebChannel instance to the collection of open instances. + * @param webChannel + */ + addOpenWebChannel(webChannel: WebChannel): void; + /** + * Remove a WebChannel instance from the collection of open instances. + * @param webChannel + */ + removeOpenWebChannel(webChannel: WebChannel): void; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser_lite/base64.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser_lite/base64.d.ts new file mode 100644 index 0000000..ae35760 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser_lite/base64.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export * from '../browser/base64'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser_lite/byte_stream_reader.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser_lite/byte_stream_reader.d.ts new file mode 100644 index 0000000..c91280a --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser_lite/byte_stream_reader.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export * from '../browser/byte_stream_reader'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser_lite/connection.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser_lite/connection.d.ts new file mode 100644 index 0000000..b347f61 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser_lite/connection.d.ts @@ -0,0 +1,21 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { DatabaseInfo } from '../../core/database_info'; +import { Connection } from '../../remote/connection'; +export { newConnectivityMonitor } from '../browser/connection'; +/** Initializes the HTTP connection for the REST API. */ +export declare function newConnection(databaseInfo: DatabaseInfo): Connection; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser_lite/dom.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser_lite/dom.d.ts new file mode 100644 index 0000000..778555d --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser_lite/dom.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export * from '../browser/dom'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser_lite/fetch_connection.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser_lite/fetch_connection.d.ts new file mode 100644 index 0000000..88105c0 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser_lite/fetch_connection.d.ts @@ -0,0 +1,28 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Token } from '../../api/credentials'; +import { Stream } from '../../remote/connection'; +import { RestConnection } from '../../remote/rest_connection'; +import { StringMap } from '../../util/types'; +/** + * A Rest-based connection that relies on the native HTTP stack + * (e.g. `fetch` or a polyfill). + */ +export declare class FetchConnection extends RestConnection { + openStream(rpcName: string, token: Token | null): Stream; + protected performRPCRequest(rpcName: string, url: string, headers: StringMap, body: Req, forwardCredentials: boolean): Promise; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser_lite/format_json.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser_lite/format_json.d.ts new file mode 100644 index 0000000..a9a0b71 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser_lite/format_json.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export * from '../browser/format_json'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser_lite/random_bytes.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser_lite/random_bytes.d.ts new file mode 100644 index 0000000..52e5798 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser_lite/random_bytes.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export * from '../browser/random_bytes'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser_lite/serializer.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser_lite/serializer.d.ts new file mode 100644 index 0000000..609f24f --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser_lite/serializer.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export * from '../browser/serializer'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser_lite/snapshot_to_json.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser_lite/snapshot_to_json.d.ts new file mode 100644 index 0000000..2ed408c --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser_lite/snapshot_to_json.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export * from '../browser/snapshot_to_json'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser_lite/text_serializer.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser_lite/text_serializer.d.ts new file mode 100644 index 0000000..a032af0 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser_lite/text_serializer.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export * from '../browser/text_serializer'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/byte_stream_reader.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/byte_stream_reader.d.ts new file mode 100644 index 0000000..566291c --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/byte_stream_reader.d.ts @@ -0,0 +1,18 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { BundleSource } from '../util/bundle_reader'; +export declare function toByteStreamReader(source: BundleSource, bytesPerRead?: number): ReadableStreamDefaultReader; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/connection.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/connection.d.ts new file mode 100644 index 0000000..0fba574 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/connection.d.ts @@ -0,0 +1,21 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { DatabaseInfo } from '../core/database_info'; +import { Connection } from '../remote/connection'; +import { ConnectivityMonitor } from '../remote/connectivity_monitor'; +export declare function newConnectivityMonitor(): ConnectivityMonitor; +export declare function newConnection(databaseInfo: DatabaseInfo): Connection; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/dom.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/dom.d.ts new file mode 100644 index 0000000..d2a5319 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/dom.d.ts @@ -0,0 +1,20 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** The Platform's 'window' implementation or null if not available. */ +export declare function getWindow(): Window | null; +/** The Platform's 'document' implementation or null if not available. */ +export declare function getDocument(): Document | null; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/format_json.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/format_json.d.ts new file mode 100644 index 0000000..5e5f7ad --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/format_json.d.ts @@ -0,0 +1,18 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Formats an object as a JSON string, suitable for logging. */ +export declare function formatJSON(value: unknown): string; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node/base64.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node/base64.d.ts new file mode 100644 index 0000000..9ea2985 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node/base64.d.ts @@ -0,0 +1,22 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Converts a Base64 encoded string to a binary string. */ +export declare function decodeBase64(encoded: string): string; +/** Converts a binary string to a Base64 encoded string. */ +export declare function encodeBase64(raw: string): string; +/** True if and only if the Base64 conversion functions are available. */ +export declare function isBase64Available(): boolean; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node/byte_stream_reader.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node/byte_stream_reader.d.ts new file mode 100644 index 0000000..efbd79a --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node/byte_stream_reader.d.ts @@ -0,0 +1,21 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { BundleSource } from '../../util/bundle_reader'; +/** + * On Node, only supported data source is a `Uint8Array` for now. + */ +export declare function toByteStreamReader(source: BundleSource, bytesPerRead: number): ReadableStreamDefaultReader; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node/connection.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node/connection.d.ts new file mode 100644 index 0000000..3be3c14 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node/connection.d.ts @@ -0,0 +1,23 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { DatabaseInfo } from '../../core/database_info'; +import { Connection } from '../../remote/connection'; +import { ConnectivityMonitor } from '../../remote/connectivity_monitor'; +/** Loads the GRPC stack */ +export declare function newConnection(databaseInfo: DatabaseInfo): Connection; +/** Return the Platform-specific connectivity monitor. */ +export declare function newConnectivityMonitor(): ConnectivityMonitor; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node/dom.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node/dom.d.ts new file mode 100644 index 0000000..d2a5319 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node/dom.d.ts @@ -0,0 +1,20 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** The Platform's 'window' implementation or null if not available. */ +export declare function getWindow(): Window | null; +/** The Platform's 'document' implementation or null if not available. */ +export declare function getDocument(): Document | null; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node/format_json.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node/format_json.d.ts new file mode 100644 index 0000000..5e5f7ad --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node/format_json.d.ts @@ -0,0 +1,18 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Formats an object as a JSON string, suitable for logging. */ +export declare function formatJSON(value: unknown): string; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node/grpc_connection.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node/grpc_connection.d.ts new file mode 100644 index 0000000..30cd921 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node/grpc_connection.d.ts @@ -0,0 +1,43 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import * as grpc from '@grpc/grpc-js'; +import { Token } from '../../api/credentials'; +import { DatabaseInfo } from '../../core/database_info'; +import { ResourcePath } from '../../model/path'; +import { Connection, Stream } from '../../remote/connection'; +/** + * A Connection implemented by GRPC-Node. + */ +export declare class GrpcConnection implements Connection { + private databaseInfo; + private readonly databasePath; + private readonly firestore; + private cachedStub; + get shouldResourcePathBeIncludedInRequest(): boolean; + constructor(protos: grpc.GrpcObject, databaseInfo: DatabaseInfo); + private ensureActiveStub; + invokeRPC(rpcName: string, path: ResourcePath, request: Req, authToken: Token | null, appCheckToken: Token | null): Promise; + invokeStreamingRPC(rpcName: string, path: ResourcePath, request: Req, authToken: Token | null, appCheckToken: Token | null, expectedResponseCount?: number): Promise; + openStream(rpcName: string, authToken: Token | null, appCheckToken: Token | null): Stream; + /** + * Closes and cleans up any resources associated with the GrpcConnection. + * If a gRPC client has been generated for this connection, the gRPC client + * is closed. Failure to call terminate on a GrpcConnection can result + * in leaked resources of the gRPC client. + */ + terminate(): void; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node/load_protos.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node/load_protos.d.ts new file mode 100644 index 0000000..f05a0e6 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node/load_protos.d.ts @@ -0,0 +1,28 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import * as grpc from '@grpc/grpc-js'; +import { IConversionOptions, Root } from 'protobufjs'; +/** Used by tests so we can match @grpc/proto-loader behavior. */ +export declare const protoLoaderOptions: IConversionOptions; +/** + * Loads the protocol buffer definitions for Firestore. + * + * @returns The GrpcObject representing our protos. + */ +export declare function loadProtos(): grpc.GrpcObject; +/** Used by tests so we can directly create ProtobufJS proto message objects from JSON protos. */ +export declare function loadRawProtos(): Root; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node/random_bytes.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node/random_bytes.d.ts new file mode 100644 index 0000000..672e612 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node/random_bytes.d.ts @@ -0,0 +1,22 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Generates `nBytes` of random bytes. + * + * If `nBytes < 0` , an error will be thrown. + */ +export declare function randomBytes(nBytes: number): Uint8Array; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node/serializer.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node/serializer.d.ts new file mode 100644 index 0000000..839e680 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node/serializer.d.ts @@ -0,0 +1,20 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Return the Platform-specific serializer monitor. */ +import { DatabaseId } from '../../core/database_info'; +import { JsonProtoSerializer } from '../../remote/serializer'; +export declare function newSerializer(databaseId: DatabaseId): JsonProtoSerializer; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node/snapshot_to_json.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node/snapshot_to_json.d.ts new file mode 100644 index 0000000..6a75f06 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node/snapshot_to_json.d.ts @@ -0,0 +1,23 @@ +/** + * @license + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Return the Platform-specific build JSON bundle implementations. */ +import { Firestore } from '../../api/database'; +import { Query } from '../../core/query'; +import { DocumentData } from '../../lite-api/reference'; +import { Document } from '../../model/document'; +export declare function buildDocumentSnapshotJsonBundle(db: Firestore, document: Document, docData: DocumentData, path: string): string; +export declare function buildQuerySnapshotJsonBundle(db: Firestore, query: Query, bundleName: string, parent: string, paths: string[], docs: Document[], documentData: DocumentData[]): string; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node/text_serializer.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node/text_serializer.d.ts new file mode 100644 index 0000000..f88ff0c --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node/text_serializer.d.ts @@ -0,0 +1,25 @@ +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { TextDecoder, TextEncoder } from 'util'; +/** + * An instance of the Platform's 'TextEncoder' implementation. + */ +export declare function newTextEncoder(): TextEncoder; +/** + * An instance of the Platform's 'TextDecoder' implementation. + */ +export declare function newTextDecoder(): TextDecoder; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node_lite/base64.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node_lite/base64.d.ts new file mode 100644 index 0000000..2d95aff --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node_lite/base64.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export * from '../node/base64'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node_lite/byte_stream_reader.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node_lite/byte_stream_reader.d.ts new file mode 100644 index 0000000..543020e --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node_lite/byte_stream_reader.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export * from '../node/byte_stream_reader'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node_lite/connection.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node_lite/connection.d.ts new file mode 100644 index 0000000..b347f61 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node_lite/connection.d.ts @@ -0,0 +1,21 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { DatabaseInfo } from '../../core/database_info'; +import { Connection } from '../../remote/connection'; +export { newConnectivityMonitor } from '../browser/connection'; +/** Initializes the HTTP connection for the REST API. */ +export declare function newConnection(databaseInfo: DatabaseInfo): Connection; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node_lite/dom.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node_lite/dom.d.ts new file mode 100644 index 0000000..6c880e0 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node_lite/dom.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export * from '../node/dom'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node_lite/format_json.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node_lite/format_json.d.ts new file mode 100644 index 0000000..428b6d9 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node_lite/format_json.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export * from '../node/format_json'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node_lite/random_bytes.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node_lite/random_bytes.d.ts new file mode 100644 index 0000000..132614e --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node_lite/random_bytes.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export * from '../node/random_bytes'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node_lite/serializer.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node_lite/serializer.d.ts new file mode 100644 index 0000000..dcf50ac --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node_lite/serializer.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export * from '../browser_lite/serializer'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node_lite/snapshot_to_json.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node_lite/snapshot_to_json.d.ts new file mode 100644 index 0000000..c85016c --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node_lite/snapshot_to_json.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export * from '../node/snapshot_to_json'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node_lite/text_serializer.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node_lite/text_serializer.d.ts new file mode 100644 index 0000000..3a5069e --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node_lite/text_serializer.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export * from '../browser_lite/text_serializer'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/random_bytes.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/random_bytes.d.ts new file mode 100644 index 0000000..672e612 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/random_bytes.d.ts @@ -0,0 +1,22 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Generates `nBytes` of random bytes. + * + * If `nBytes < 0` , an error will be thrown. + */ +export declare function randomBytes(nBytes: number): Uint8Array; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn/base64.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn/base64.d.ts new file mode 100644 index 0000000..9ea2985 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn/base64.d.ts @@ -0,0 +1,22 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Converts a Base64 encoded string to a binary string. */ +export declare function decodeBase64(encoded: string): string; +/** Converts a binary string to a Base64 encoded string. */ +export declare function encodeBase64(raw: string): string; +/** True if and only if the Base64 conversion functions are available. */ +export declare function isBase64Available(): boolean; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn/byte_stream_reader.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn/byte_stream_reader.d.ts new file mode 100644 index 0000000..939290b --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn/byte_stream_reader.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export { toByteStreamReader } from '../browser/byte_stream_reader'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn/connection.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn/connection.d.ts new file mode 100644 index 0000000..da831d6 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn/connection.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export { newConnection, newConnectivityMonitor } from '../browser/connection'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn/dom.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn/dom.d.ts new file mode 100644 index 0000000..4c629fc --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn/dom.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export { getWindow, getDocument } from '../browser/dom'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn/format_json.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn/format_json.d.ts new file mode 100644 index 0000000..d1d3dc7 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn/format_json.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export { formatJSON } from '../browser/format_json'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn/random_bytes.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn/random_bytes.d.ts new file mode 100644 index 0000000..6774017 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn/random_bytes.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export { randomBytes } from '../browser/random_bytes'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn/serializer.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn/serializer.d.ts new file mode 100644 index 0000000..c7a81ae --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn/serializer.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export { newSerializer } from '../browser/serializer'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn/snapshot_to_json.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn/snapshot_to_json.d.ts new file mode 100644 index 0000000..8ab87f6 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn/snapshot_to_json.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export { buildDocumentSnapshotJsonBundle, buildQuerySnapshotJsonBundle } from '../browser/snapshot_to_json'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn/text_serializer.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn/text_serializer.d.ts new file mode 100644 index 0000000..efcbff3 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn/text_serializer.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export { newTextEncoder, newTextDecoder } from '../browser/text_serializer'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn_lite/base64.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn_lite/base64.d.ts new file mode 100644 index 0000000..3d236cd --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn_lite/base64.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export * from '../rn/base64'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn_lite/byte_stream_reader.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn_lite/byte_stream_reader.d.ts new file mode 100644 index 0000000..9206b65 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn_lite/byte_stream_reader.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export * from '../rn/byte_stream_reader'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn_lite/connection.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn_lite/connection.d.ts new file mode 100644 index 0000000..6509c0c --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn_lite/connection.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export * from '../browser_lite/connection'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn_lite/dom.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn_lite/dom.d.ts new file mode 100644 index 0000000..0469362 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn_lite/dom.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export * from '../rn/dom'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn_lite/format_json.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn_lite/format_json.d.ts new file mode 100644 index 0000000..0a17cf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn_lite/format_json.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export * from '../rn/format_json'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn_lite/random_bytes.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn_lite/random_bytes.d.ts new file mode 100644 index 0000000..8ca59f3 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn_lite/random_bytes.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export * from '../rn/random_bytes'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn_lite/serializer.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn_lite/serializer.d.ts new file mode 100644 index 0000000..dcf50ac --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn_lite/serializer.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export * from '../browser_lite/serializer'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn_lite/snapshot_to_json.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn_lite/snapshot_to_json.d.ts new file mode 100644 index 0000000..939290b --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn_lite/snapshot_to_json.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export { toByteStreamReader } from '../browser/byte_stream_reader'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn_lite/text_serializer.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn_lite/text_serializer.d.ts new file mode 100644 index 0000000..3a5069e --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn_lite/text_serializer.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export * from '../browser_lite/text_serializer'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/serializer.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/serializer.d.ts new file mode 100644 index 0000000..25f5533 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/serializer.d.ts @@ -0,0 +1,19 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { DatabaseId } from '../core/database_info'; +import { JsonProtoSerializer } from '../remote/serializer'; +export declare function newSerializer(databaseId: DatabaseId): JsonProtoSerializer; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/snapshot_to_json.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/snapshot_to_json.d.ts new file mode 100644 index 0000000..83eadf0 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/snapshot_to_json.d.ts @@ -0,0 +1,28 @@ +/** + * @license + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Firestore } from '../api/database'; +import { Query } from '../core/query'; +import { DocumentData } from '../lite-api/reference'; +import { Document } from '../model/document'; +/** + * Constructs the bundle data for a DocumentSnapshot used in its toJSON serialization. + */ +export declare function buildDocumentSnapshotJsonBundle(db: Firestore, document: Document, docData: DocumentData, path: string): string; +/** + * Constructs the bundle data for a QuerySnapshot used in its toJSON serialization. + */ +export declare function buildQuerySnapshotJsonBundle(db: Firestore, query: Query, bundleName: string, parent: string, paths: string[], docs: Document[], documentData: DocumentData[]): string; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/text_serializer.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/text_serializer.d.ts new file mode 100644 index 0000000..47213fb --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/text_serializer.d.ts @@ -0,0 +1,24 @@ +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An instance of the Platform's 'TextEncoder' implementation. + */ +export declare function newTextEncoder(): TextEncoder; +/** + * An instance of the Platform's 'TextDecoder' implementation. + */ +export declare function newTextDecoder(): TextDecoder; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/protos/firestore_bundle_proto.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/protos/firestore_bundle_proto.d.ts new file mode 100644 index 0000000..e3f7740 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/protos/firestore_bundle_proto.d.ts @@ -0,0 +1,72 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { StructuredQuery, Timestamp, Document } from './firestore_proto_api'; +/** Properties of a BundledQuery. */ +export interface BundledQuery { + /** BundledQuery parent */ + parent?: string | null; + /** BundledQuery structuredQuery */ + structuredQuery?: StructuredQuery | null; + /** BundledQuery limitType */ + limitType?: LimitType | null; +} +/** LimitType enum. */ +export type LimitType = 'FIRST' | 'LAST'; +/** Properties of a NamedQuery. */ +export interface NamedQuery { + /** NamedQuery name */ + name?: string | null; + /** NamedQuery bundledQuery */ + bundledQuery?: BundledQuery | null; + /** NamedQuery readTime */ + readTime?: Timestamp | null; +} +/** Properties of a BundledDocumentMetadata. */ +export interface BundledDocumentMetadata { + /** BundledDocumentMetadata name */ + name?: string | null; + /** BundledDocumentMetadata readTime */ + readTime?: Timestamp | null; + /** BundledDocumentMetadata exists */ + exists?: boolean | null; + /** The names of the queries in this bundle that this document matches to. */ + queries?: string[]; +} +/** Properties of a BundleMetadata. */ +export interface BundleMetadata { + /** BundleMetadata id */ + id?: string | null; + /** BundleMetadata createTime */ + createTime?: Timestamp | null; + /** BundleMetadata version */ + version?: number | null; + /** BundleMetadata totalDocuments */ + totalDocuments?: number | null; + /** BundleMetadata totalBytes */ + totalBytes?: number | null; +} +/** Properties of a BundleElement. */ +export interface BundleElement { + /** BundleElement metadata */ + metadata?: BundleMetadata | null; + /** BundleElement namedQuery */ + namedQuery?: NamedQuery | null; + /** BundleElement documentMetadata */ + documentMetadata?: BundledDocumentMetadata | null; + /** BundleElement document */ + document?: Document | null; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/protos/firestore_proto_api.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/protos/firestore_proto_api.d.ts new file mode 100644 index 0000000..5f37ee6 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/protos/firestore_proto_api.d.ts @@ -0,0 +1,836 @@ +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export declare type ApiClientHookFactory = any; +export declare type PromiseRequestService = any; +export interface ApiClientObjectMap { + [k: string]: T; +} +export declare type Timestamp = string | { + seconds?: string | number; + nanos?: number; +}; +export declare type CompositeFilterOp = 'OPERATOR_UNSPECIFIED' | 'AND' | 'OR'; +export interface ICompositeFilterOpEnum { + OPERATOR_UNSPECIFIED: CompositeFilterOp; + AND: CompositeFilterOp; + values(): CompositeFilterOp[]; +} +export declare const CompositeFilterOpEnum: ICompositeFilterOpEnum; +export declare type FieldFilterOp = 'OPERATOR_UNSPECIFIED' | 'LESS_THAN' | 'LESS_THAN_OR_EQUAL' | 'GREATER_THAN' | 'GREATER_THAN_OR_EQUAL' | 'EQUAL' | 'NOT_EQUAL' | 'ARRAY_CONTAINS' | 'IN' | 'ARRAY_CONTAINS_ANY' | 'NOT_IN'; +export interface IFieldFilterOpEnum { + OPERATOR_UNSPECIFIED: FieldFilterOp; + LESS_THAN: FieldFilterOp; + LESS_THAN_OR_EQUAL: FieldFilterOp; + GREATER_THAN: FieldFilterOp; + GREATER_THAN_OR_EQUAL: FieldFilterOp; + EQUAL: FieldFilterOp; + NOT_EQUAL: FieldFilterOp; + ARRAY_CONTAINS: FieldFilterOp; + IN: FieldFilterOp; + ARRAY_CONTAINS_ANY: FieldFilterOp; + NOT_IN: FieldFilterOp; + values(): FieldFilterOp[]; +} +export declare const FieldFilterOpEnum: IFieldFilterOpEnum; +export declare type FieldTransformSetToServerValue = 'SERVER_VALUE_UNSPECIFIED' | 'REQUEST_TIME'; +export interface IFieldTransformSetToServerValueEnum { + SERVER_VALUE_UNSPECIFIED: FieldTransformSetToServerValue; + REQUEST_TIME: FieldTransformSetToServerValue; + values(): FieldTransformSetToServerValue[]; +} +export declare const FieldTransformSetToServerValueEnum: IFieldTransformSetToServerValueEnum; +export declare type IndexFieldMode = 'MODE_UNSPECIFIED' | 'ASCENDING' | 'DESCENDING'; +export interface IIndexFieldModeEnum { + MODE_UNSPECIFIED: IndexFieldMode; + ASCENDING: IndexFieldMode; + DESCENDING: IndexFieldMode; + values(): IndexFieldMode[]; +} +export declare const IndexFieldModeEnum: IIndexFieldModeEnum; +export declare type IndexState = 'STATE_UNSPECIFIED' | 'CREATING' | 'READY' | 'ERROR'; +export interface IIndexStateEnum { + STATE_UNSPECIFIED: IndexState; + CREATING: IndexState; + READY: IndexState; + ERROR: IndexState; + values(): IndexState[]; +} +export declare const IndexStateEnum: IIndexStateEnum; +export declare type OrderDirection = 'DIRECTION_UNSPECIFIED' | 'ASCENDING' | 'DESCENDING'; +export interface IOrderDirectionEnum { + DIRECTION_UNSPECIFIED: OrderDirection; + ASCENDING: OrderDirection; + DESCENDING: OrderDirection; + values(): OrderDirection[]; +} +export declare const OrderDirectionEnum: IOrderDirectionEnum; +export declare type TargetChangeTargetChangeType = 'NO_CHANGE' | 'ADD' | 'REMOVE' | 'CURRENT' | 'RESET'; +export interface ITargetChangeTargetChangeTypeEnum { + NO_CHANGE: TargetChangeTargetChangeType; + ADD: TargetChangeTargetChangeType; + REMOVE: TargetChangeTargetChangeType; + CURRENT: TargetChangeTargetChangeType; + RESET: TargetChangeTargetChangeType; + values(): TargetChangeTargetChangeType[]; +} +export declare const TargetChangeTargetChangeTypeEnum: ITargetChangeTargetChangeTypeEnum; +export declare type UnaryFilterOp = 'OPERATOR_UNSPECIFIED' | 'IS_NAN' | 'IS_NULL' | 'IS_NOT_NAN' | 'IS_NOT_NULL'; +export interface IUnaryFilterOpEnum { + OPERATOR_UNSPECIFIED: UnaryFilterOp; + IS_NAN: UnaryFilterOp; + IS_NULL: UnaryFilterOp; + IS_NOT_NAN: UnaryFilterOp; + IS_NOT_NULL: UnaryFilterOp; + values(): UnaryFilterOp[]; +} +export declare const UnaryFilterOpEnum: IUnaryFilterOpEnum; +export declare type ValueNullValue = 'NULL_VALUE'; +export interface IValueNullValueEnum { + NULL_VALUE: ValueNullValue; + values(): ValueNullValue[]; +} +export declare const ValueNullValueEnum: IValueNullValueEnum; +export declare namespace firestoreV1ApiClientInterfaces { + interface ArrayValue { + values?: Value[]; + } + interface BatchGetDocumentsRequest { + database?: string; + documents?: string[]; + mask?: DocumentMask; + transaction?: string; + newTransaction?: TransactionOptions; + readTime?: string; + } + interface BatchGetDocumentsResponse { + found?: Document; + missing?: string; + transaction?: string; + readTime?: string; + } + interface BeginTransactionRequest { + options?: TransactionOptions; + } + interface BeginTransactionResponse { + transaction?: string; + } + interface CollectionSelector { + collectionId?: string; + allDescendants?: boolean; + } + interface CommitRequest { + database?: string; + writes?: Write[]; + transaction?: string; + } + interface CommitResponse { + writeResults?: WriteResult[]; + commitTime?: string; + } + interface CompositeFilter { + op?: CompositeFilterOp; + filters?: Filter[]; + } + interface Cursor { + values?: Value[]; + before?: boolean; + } + interface Document { + name?: string; + fields?: ApiClientObjectMap; + createTime?: Timestamp; + updateTime?: Timestamp; + } + interface DocumentChange { + document?: Document; + targetIds?: number[]; + removedTargetIds?: number[]; + } + interface DocumentDelete { + document?: string; + removedTargetIds?: number[]; + readTime?: Timestamp; + } + interface DocumentMask { + fieldPaths?: string[]; + } + interface DocumentRemove { + document?: string; + removedTargetIds?: number[]; + readTime?: string; + } + interface DocumentTransform { + document?: string; + fieldTransforms?: FieldTransform[]; + } + interface DocumentsTarget { + documents?: string[]; + } + interface Empty { + } + interface ExistenceFilter { + targetId?: number; + count?: number; + unchangedNames?: BloomFilter; + } + interface BloomFilter { + bits?: BitSequence; + hashCount?: number; + } + interface BitSequence { + bitmap?: string | Uint8Array; + padding?: number; + } + interface FieldFilter { + field?: FieldReference; + op?: FieldFilterOp; + value?: Value; + } + interface FieldReference { + fieldPath?: string; + } + interface FieldTransform { + fieldPath?: string; + setToServerValue?: FieldTransformSetToServerValue; + appendMissingElements?: ArrayValue; + removeAllFromArray?: ArrayValue; + increment?: Value; + } + interface Filter { + compositeFilter?: CompositeFilter; + fieldFilter?: FieldFilter; + unaryFilter?: UnaryFilter; + } + interface Index { + name?: string; + collectionId?: string; + fields?: IndexField[]; + state?: IndexState; + } + interface IndexField { + fieldPath?: string; + mode?: IndexFieldMode; + } + interface LatLng { + latitude?: number; + longitude?: number; + } + interface ListCollectionIdsRequest { + pageSize?: number; + pageToken?: string; + } + interface ListCollectionIdsResponse { + collectionIds?: string[]; + nextPageToken?: string; + } + interface ListDocumentsResponse { + documents?: Document[]; + nextPageToken?: string; + } + interface ListIndexesResponse { + indexes?: Index[]; + nextPageToken?: string; + } + interface ListenRequest { + addTarget?: Target; + removeTarget?: number; + labels?: ApiClientObjectMap; + } + interface ListenResponse { + targetChange?: TargetChange; + documentChange?: DocumentChange; + documentDelete?: DocumentDelete; + documentRemove?: DocumentRemove; + filter?: ExistenceFilter; + } + interface MapValue { + fields?: ApiClientObjectMap; + } + interface Operation { + name?: string; + metadata?: ApiClientObjectMap; + done?: boolean; + error?: Status; + response?: ApiClientObjectMap; + } + interface Order { + field?: FieldReference; + direction?: OrderDirection; + } + interface Precondition { + exists?: boolean; + updateTime?: Timestamp; + } + interface Projection { + fields?: FieldReference[]; + } + interface QueryTarget { + parent?: string; + structuredQuery?: StructuredQuery; + } + interface ReadOnly { + readTime?: string; + } + interface ReadWrite { + retryTransaction?: string; + } + interface RollbackRequest { + transaction?: string; + } + interface RunQueryRequest { + parent?: string; + structuredQuery?: StructuredQuery; + transaction?: string; + newTransaction?: TransactionOptions; + readTime?: string; + } + interface RunQueryResponse { + transaction?: string; + document?: Document; + readTime?: string; + skippedResults?: number; + } + interface RunAggregationQueryRequest { + parent?: string; + structuredAggregationQuery?: StructuredAggregationQuery; + transaction?: string; + newTransaction?: TransactionOptions; + readTime?: string; + } + interface RunAggregationQueryResponse { + result?: AggregationResult; + transaction?: string; + readTime?: string; + } + interface AggregationResult { + aggregateFields?: ApiClientObjectMap; + } + interface StructuredAggregationQuery { + structuredQuery?: StructuredQuery; + aggregations?: Aggregation[]; + } + interface Aggregation { + count?: Count; + sum?: Sum; + avg?: Avg; + alias?: string; + } + interface Count { + upTo?: number; + } + interface Sum { + field?: FieldReference; + } + interface Avg { + field?: FieldReference; + } + interface Status { + code?: number; + message?: string; + details?: Array>; + } + interface StructuredQuery { + select?: Projection; + from?: CollectionSelector[]; + where?: Filter; + orderBy?: Order[]; + startAt?: Cursor; + endAt?: Cursor; + offset?: number; + limit?: number | { + value: number; + }; + } + interface Target { + query?: QueryTarget; + documents?: DocumentsTarget; + resumeToken?: string | Uint8Array; + readTime?: Timestamp; + targetId?: number; + once?: boolean; + expectedCount?: number | { + value: number; + }; + } + interface TargetChange { + targetChangeType?: TargetChangeTargetChangeType; + targetIds?: number[]; + cause?: Status; + resumeToken?: string | Uint8Array; + readTime?: Timestamp; + } + interface TransactionOptions { + readOnly?: ReadOnly; + readWrite?: ReadWrite; + } + interface UnaryFilter { + op?: UnaryFilterOp; + field?: FieldReference; + } + interface Value { + nullValue?: ValueNullValue; + booleanValue?: boolean; + integerValue?: string | number; + doubleValue?: string | number; + timestampValue?: Timestamp; + stringValue?: string; + bytesValue?: string | Uint8Array; + referenceValue?: string; + geoPointValue?: LatLng; + arrayValue?: ArrayValue; + mapValue?: MapValue; + } + interface Write { + update?: Document; + delete?: string; + verify?: string; + transform?: DocumentTransform; + updateMask?: DocumentMask; + updateTransforms?: FieldTransform[]; + currentDocument?: Precondition; + } + interface WriteRequest { + streamId?: string; + writes?: Write[]; + streamToken?: string | Uint8Array; + labels?: ApiClientObjectMap; + } + interface WriteResponse { + streamId?: string; + streamToken?: string | Uint8Array; + writeResults?: WriteResult[]; + commitTime?: Timestamp; + } + interface WriteResult { + updateTime?: Timestamp; + transformResults?: Value[]; + } +} +export declare type ArrayValue = firestoreV1ApiClientInterfaces.ArrayValue; +export declare type BatchGetDocumentsRequest = firestoreV1ApiClientInterfaces.BatchGetDocumentsRequest; +export declare type BatchGetDocumentsResponse = firestoreV1ApiClientInterfaces.BatchGetDocumentsResponse; +export declare type BeginTransactionRequest = firestoreV1ApiClientInterfaces.BeginTransactionRequest; +export declare type BeginTransactionResponse = firestoreV1ApiClientInterfaces.BeginTransactionResponse; +export declare type BloomFilter = firestoreV1ApiClientInterfaces.BloomFilter; +export declare type CollectionSelector = firestoreV1ApiClientInterfaces.CollectionSelector; +export declare type CommitRequest = firestoreV1ApiClientInterfaces.CommitRequest; +export declare type CommitResponse = firestoreV1ApiClientInterfaces.CommitResponse; +export declare type CompositeFilter = firestoreV1ApiClientInterfaces.CompositeFilter; +export declare type Cursor = firestoreV1ApiClientInterfaces.Cursor; +export declare type Document = firestoreV1ApiClientInterfaces.Document; +export declare type DocumentChange = firestoreV1ApiClientInterfaces.DocumentChange; +export declare type DocumentDelete = firestoreV1ApiClientInterfaces.DocumentDelete; +export declare type DocumentMask = firestoreV1ApiClientInterfaces.DocumentMask; +export declare type DocumentRemove = firestoreV1ApiClientInterfaces.DocumentRemove; +export declare type DocumentTransform = firestoreV1ApiClientInterfaces.DocumentTransform; +export declare type DocumentsTarget = firestoreV1ApiClientInterfaces.DocumentsTarget; +export declare type Empty = firestoreV1ApiClientInterfaces.Empty; +export declare type ExistenceFilter = firestoreV1ApiClientInterfaces.ExistenceFilter; +export declare type FieldFilter = firestoreV1ApiClientInterfaces.FieldFilter; +export declare type FieldReference = firestoreV1ApiClientInterfaces.FieldReference; +export declare type FieldTransform = firestoreV1ApiClientInterfaces.FieldTransform; +export declare type Filter = firestoreV1ApiClientInterfaces.Filter; +export declare type Index = firestoreV1ApiClientInterfaces.Index; +export declare type IndexField = firestoreV1ApiClientInterfaces.IndexField; +export declare type LatLng = firestoreV1ApiClientInterfaces.LatLng; +export declare type ListCollectionIdsRequest = firestoreV1ApiClientInterfaces.ListCollectionIdsRequest; +export declare type ListCollectionIdsResponse = firestoreV1ApiClientInterfaces.ListCollectionIdsResponse; +export declare type ListDocumentsResponse = firestoreV1ApiClientInterfaces.ListDocumentsResponse; +export declare type ListIndexesResponse = firestoreV1ApiClientInterfaces.ListIndexesResponse; +export declare type ListenRequest = firestoreV1ApiClientInterfaces.ListenRequest; +export declare type ListenResponse = firestoreV1ApiClientInterfaces.ListenResponse; +export declare type MapValue = firestoreV1ApiClientInterfaces.MapValue; +export declare type Operation = firestoreV1ApiClientInterfaces.Operation; +export declare type Order = firestoreV1ApiClientInterfaces.Order; +export declare type Precondition = firestoreV1ApiClientInterfaces.Precondition; +export declare type Projection = firestoreV1ApiClientInterfaces.Projection; +export declare type QueryTarget = firestoreV1ApiClientInterfaces.QueryTarget; +export declare type ReadOnly = firestoreV1ApiClientInterfaces.ReadOnly; +export declare type ReadWrite = firestoreV1ApiClientInterfaces.ReadWrite; +export declare type RollbackRequest = firestoreV1ApiClientInterfaces.RollbackRequest; +export declare type RunQueryRequest = firestoreV1ApiClientInterfaces.RunQueryRequest; +export declare type RunQueryResponse = firestoreV1ApiClientInterfaces.RunQueryResponse; +export declare type RunAggregationQueryRequest = firestoreV1ApiClientInterfaces.RunAggregationQueryRequest; +export declare type Aggregation = firestoreV1ApiClientInterfaces.Aggregation; +export declare type RunAggregationQueryResponse = firestoreV1ApiClientInterfaces.RunAggregationQueryResponse; +export declare type Status = firestoreV1ApiClientInterfaces.Status; +export declare type StructuredQuery = firestoreV1ApiClientInterfaces.StructuredQuery; +export declare type Target = firestoreV1ApiClientInterfaces.Target; +export declare type TargetChange = firestoreV1ApiClientInterfaces.TargetChange; +export declare type TransactionOptions = firestoreV1ApiClientInterfaces.TransactionOptions; +export declare type UnaryFilter = firestoreV1ApiClientInterfaces.UnaryFilter; +export declare type Value = firestoreV1ApiClientInterfaces.Value; +export declare type Write = firestoreV1ApiClientInterfaces.Write; +export declare type WriteRequest = firestoreV1ApiClientInterfaces.WriteRequest; +export declare type WriteResponse = firestoreV1ApiClientInterfaces.WriteResponse; +export declare type WriteResult = firestoreV1ApiClientInterfaces.WriteResult; +export declare type ProjectsDatabasesDocumentsApiClient$Xgafv = '1' | '2'; +export interface IProjectsDatabasesDocumentsApiClient$XgafvEnum { + 1: ProjectsDatabasesDocumentsApiClient$Xgafv; + 2: ProjectsDatabasesDocumentsApiClient$Xgafv; + values(): ProjectsDatabasesDocumentsApiClient$Xgafv[]; +} +export declare const ProjectsDatabasesDocumentsApiClient$XgafvEnum: IProjectsDatabasesDocumentsApiClient$XgafvEnum; +export declare type ProjectsDatabasesDocumentsApiClientAlt = 'json' | 'media' | 'proto'; +export interface IProjectsDatabasesDocumentsApiClientAltEnum { + JSON: ProjectsDatabasesDocumentsApiClientAlt; + MEDIA: ProjectsDatabasesDocumentsApiClientAlt; + PROTO: ProjectsDatabasesDocumentsApiClientAlt; + values(): ProjectsDatabasesDocumentsApiClientAlt[]; +} +export declare const ProjectsDatabasesDocumentsApiClientAltEnum: IProjectsDatabasesDocumentsApiClientAltEnum; +export interface ProjectsDatabasesDocumentsBatchGetNamedParameters { + access_token?: string; + alt?: ProjectsDatabasesDocumentsApiClientAlt; + bearer_token?: string; + callback?: string; + fields?: string; + key?: string; + oauth_token?: string; + pp?: boolean; + prettyPrint?: boolean; + quotaUser?: string; + upload_protocol?: string; + uploadType?: string; + $Xgafv?: ProjectsDatabasesDocumentsApiClient$Xgafv; +} +export interface ProjectsDatabasesDocumentsBeginTransactionNamedParameters { + access_token?: string; + alt?: ProjectsDatabasesDocumentsApiClientAlt; + bearer_token?: string; + callback?: string; + fields?: string; + key?: string; + oauth_token?: string; + pp?: boolean; + prettyPrint?: boolean; + quotaUser?: string; + upload_protocol?: string; + uploadType?: string; + $Xgafv?: ProjectsDatabasesDocumentsApiClient$Xgafv; +} +export interface ProjectsDatabasesDocumentsCommitNamedParameters { + access_token?: string; + alt?: ProjectsDatabasesDocumentsApiClientAlt; + bearer_token?: string; + callback?: string; + fields?: string; + key?: string; + oauth_token?: string; + pp?: boolean; + prettyPrint?: boolean; + quotaUser?: string; + upload_protocol?: string; + uploadType?: string; + $Xgafv?: ProjectsDatabasesDocumentsApiClient$Xgafv; +} +export interface ProjectsDatabasesDocumentsCreateDocumentNamedParameters { + access_token?: string; + alt?: ProjectsDatabasesDocumentsApiClientAlt; + bearer_token?: string; + callback?: string; + fields?: string; + key?: string; + oauth_token?: string; + pp?: boolean; + prettyPrint?: boolean; + quotaUser?: string; + upload_protocol?: string; + uploadType?: string; + $Xgafv?: ProjectsDatabasesDocumentsApiClient$Xgafv; + documentId?: string; + maskFieldPaths?: string[]; +} +export interface ProjectsDatabasesDocumentsDeleteNamedParameters { + access_token?: string; + alt?: ProjectsDatabasesDocumentsApiClientAlt; + bearer_token?: string; + callback?: string; + fields?: string; + key?: string; + oauth_token?: string; + pp?: boolean; + prettyPrint?: boolean; + quotaUser?: string; + upload_protocol?: string; + uploadType?: string; + $Xgafv?: ProjectsDatabasesDocumentsApiClient$Xgafv; + currentDocumentExists?: boolean; + currentDocumentUpdateTime?: string; +} +export interface ProjectsDatabasesDocumentsGetNamedParameters { + access_token?: string; + alt?: ProjectsDatabasesDocumentsApiClientAlt; + bearer_token?: string; + callback?: string; + fields?: string; + key?: string; + oauth_token?: string; + pp?: boolean; + prettyPrint?: boolean; + quotaUser?: string; + upload_protocol?: string; + uploadType?: string; + $Xgafv?: ProjectsDatabasesDocumentsApiClient$Xgafv; + maskFieldPaths?: string[]; + transaction?: string; + readTime?: string; +} +export interface ProjectsDatabasesDocumentsListCollectionIdsNamedParameters { + access_token?: string; + alt?: ProjectsDatabasesDocumentsApiClientAlt; + bearer_token?: string; + callback?: string; + fields?: string; + key?: string; + oauth_token?: string; + pp?: boolean; + prettyPrint?: boolean; + quotaUser?: string; + upload_protocol?: string; + uploadType?: string; + $Xgafv?: ProjectsDatabasesDocumentsApiClient$Xgafv; +} +export interface ProjectsDatabasesDocumentsListNamedParameters { + access_token?: string; + alt?: ProjectsDatabasesDocumentsApiClientAlt; + bearer_token?: string; + callback?: string; + fields?: string; + key?: string; + oauth_token?: string; + pp?: boolean; + prettyPrint?: boolean; + quotaUser?: string; + upload_protocol?: string; + uploadType?: string; + $Xgafv?: ProjectsDatabasesDocumentsApiClient$Xgafv; + pageSize?: number; + pageToken?: string; + orderBy?: string; + maskFieldPaths?: string[]; + transaction?: string; + readTime?: string; + showMissing?: boolean; +} +export interface ProjectsDatabasesDocumentsListenNamedParameters { + access_token?: string; + alt?: ProjectsDatabasesDocumentsApiClientAlt; + bearer_token?: string; + callback?: string; + fields?: string; + key?: string; + oauth_token?: string; + pp?: boolean; + prettyPrint?: boolean; + quotaUser?: string; + upload_protocol?: string; + uploadType?: string; + $Xgafv?: ProjectsDatabasesDocumentsApiClient$Xgafv; +} +export interface ProjectsDatabasesDocumentsPatchNamedParameters { + access_token?: string; + alt?: ProjectsDatabasesDocumentsApiClientAlt; + bearer_token?: string; + callback?: string; + fields?: string; + key?: string; + oauth_token?: string; + pp?: boolean; + prettyPrint?: boolean; + quotaUser?: string; + upload_protocol?: string; + uploadType?: string; + $Xgafv?: ProjectsDatabasesDocumentsApiClient$Xgafv; + updateMaskFieldPaths?: string[]; + maskFieldPaths?: string[]; + currentDocumentExists?: boolean; + currentDocumentUpdateTime?: string; +} +export interface ProjectsDatabasesDocumentsRollbackNamedParameters { + access_token?: string; + alt?: ProjectsDatabasesDocumentsApiClientAlt; + bearer_token?: string; + callback?: string; + fields?: string; + key?: string; + oauth_token?: string; + pp?: boolean; + prettyPrint?: boolean; + quotaUser?: string; + upload_protocol?: string; + uploadType?: string; + $Xgafv?: ProjectsDatabasesDocumentsApiClient$Xgafv; +} +export interface ProjectsDatabasesDocumentsRunQueryNamedParameters { + access_token?: string; + alt?: ProjectsDatabasesDocumentsApiClientAlt; + bearer_token?: string; + callback?: string; + fields?: string; + key?: string; + oauth_token?: string; + pp?: boolean; + prettyPrint?: boolean; + quotaUser?: string; + upload_protocol?: string; + uploadType?: string; + $Xgafv?: ProjectsDatabasesDocumentsApiClient$Xgafv; +} +export interface ProjectsDatabasesDocumentsWriteNamedParameters { + access_token?: string; + alt?: ProjectsDatabasesDocumentsApiClientAlt; + bearer_token?: string; + callback?: string; + fields?: string; + key?: string; + oauth_token?: string; + pp?: boolean; + prettyPrint?: boolean; + quotaUser?: string; + upload_protocol?: string; + uploadType?: string; + $Xgafv?: ProjectsDatabasesDocumentsApiClient$Xgafv; +} +export declare abstract class ProjectsDatabasesDocumentsApiClient { + private constructor(); + abstract batchGet(database: string, $requestBody: BatchGetDocumentsRequest, __namedParams__?: ProjectsDatabasesDocumentsBatchGetNamedParameters & object): Promise; + abstract beginTransaction(database: string, $requestBody: BeginTransactionRequest, __namedParams__?: ProjectsDatabasesDocumentsBeginTransactionNamedParameters & object): Promise; + abstract commit(database: string, $requestBody: CommitRequest, __namedParams__?: ProjectsDatabasesDocumentsCommitNamedParameters & object): Promise; + abstract createDocument(parent: string, collectionId: string, $requestBody: Document, __namedParams__?: ProjectsDatabasesDocumentsCreateDocumentNamedParameters & object): Promise; + abstract delete(name: string, __namedParams__?: ProjectsDatabasesDocumentsDeleteNamedParameters & object): Promise; + abstract get(name: string, __namedParams__?: ProjectsDatabasesDocumentsGetNamedParameters & object): Promise; + abstract list(parent: string, collectionId: string, __namedParams__?: ProjectsDatabasesDocumentsListNamedParameters & object): Promise; + abstract listCollectionIds(parent: string, $requestBody: ListCollectionIdsRequest, __namedParams__?: ProjectsDatabasesDocumentsListCollectionIdsNamedParameters & object): Promise; + abstract listen(database: string, $requestBody: ListenRequest, __namedParams__?: ProjectsDatabasesDocumentsListenNamedParameters & object): Promise; + abstract patch(name: string, $requestBody: Document, __namedParams__?: ProjectsDatabasesDocumentsPatchNamedParameters & object): Promise; + abstract rollback(database: string, $requestBody: RollbackRequest, __namedParams__?: ProjectsDatabasesDocumentsRollbackNamedParameters & object): Promise; + abstract runQuery(parent: string, $requestBody: RunQueryRequest, __namedParams__?: ProjectsDatabasesDocumentsRunQueryNamedParameters & object): Promise; + abstract write(database: string, $requestBody: WriteRequest, __namedParams__?: ProjectsDatabasesDocumentsWriteNamedParameters & object): Promise; +} +export declare class ProjectsDatabasesDocumentsApiClientImpl implements ProjectsDatabasesDocumentsApiClient { + private gapiVersion; + private $apiClient; + constructor(gapiVersion: string, gapiRequestService: PromiseRequestService, apiClientHookFactory?: ApiClientHookFactory | null); + batchGet(database: string, $requestBody: BatchGetDocumentsRequest, { $Xgafv, access_token, alt, bearer_token, callback, fields, key, oauth_token, pp, prettyPrint, quotaUser, uploadType, upload_protocol }?: ProjectsDatabasesDocumentsBatchGetNamedParameters & object): Promise; + beginTransaction(database: string, $requestBody: BeginTransactionRequest, { $Xgafv, access_token, alt, bearer_token, callback, fields, key, oauth_token, pp, prettyPrint, quotaUser, uploadType, upload_protocol }?: ProjectsDatabasesDocumentsBeginTransactionNamedParameters & object): Promise; + commit(database: string, $requestBody: CommitRequest, { $Xgafv, access_token, alt, bearer_token, callback, fields, key, oauth_token, pp, prettyPrint, quotaUser, uploadType, upload_protocol }?: ProjectsDatabasesDocumentsCommitNamedParameters & object): Promise; + createDocument(parent: string, collectionId: string, $requestBody: Document, { $Xgafv, access_token, alt, bearer_token, callback, documentId, fields, key, maskFieldPaths, oauth_token, pp, prettyPrint, quotaUser, uploadType, upload_protocol }?: ProjectsDatabasesDocumentsCreateDocumentNamedParameters & object): Promise; + delete(name: string, { $Xgafv, access_token, alt, bearer_token, callback, currentDocumentExists, currentDocumentUpdateTime, fields, key, oauth_token, pp, prettyPrint, quotaUser, uploadType, upload_protocol }?: ProjectsDatabasesDocumentsDeleteNamedParameters & object): Promise; + get(name: string, { $Xgafv, access_token, alt, bearer_token, callback, fields, key, maskFieldPaths, oauth_token, pp, prettyPrint, quotaUser, readTime, transaction, uploadType, upload_protocol }?: ProjectsDatabasesDocumentsGetNamedParameters & object): Promise; + list(parent: string, collectionId: string, { $Xgafv, access_token, alt, bearer_token, callback, fields, key, maskFieldPaths, oauth_token, orderBy, pageSize, pageToken, pp, prettyPrint, quotaUser, readTime, showMissing, transaction, uploadType, upload_protocol }?: ProjectsDatabasesDocumentsListNamedParameters & object): Promise; + listCollectionIds(parent: string, $requestBody: ListCollectionIdsRequest, { $Xgafv, access_token, alt, bearer_token, callback, fields, key, oauth_token, pp, prettyPrint, quotaUser, uploadType, upload_protocol }?: ProjectsDatabasesDocumentsListCollectionIdsNamedParameters & object): Promise; + listen(database: string, $requestBody: ListenRequest, { $Xgafv, access_token, alt, bearer_token, callback, fields, key, oauth_token, pp, prettyPrint, quotaUser, uploadType, upload_protocol }?: ProjectsDatabasesDocumentsListenNamedParameters & object): Promise; + patch(name: string, $requestBody: Document, { $Xgafv, access_token, alt, bearer_token, callback, currentDocumentExists, currentDocumentUpdateTime, fields, key, maskFieldPaths, oauth_token, pp, prettyPrint, quotaUser, updateMaskFieldPaths, uploadType, upload_protocol }?: ProjectsDatabasesDocumentsPatchNamedParameters & object): Promise; + rollback(database: string, $requestBody: RollbackRequest, { $Xgafv, access_token, alt, bearer_token, callback, fields, key, oauth_token, pp, prettyPrint, quotaUser, uploadType, upload_protocol }?: ProjectsDatabasesDocumentsRollbackNamedParameters & object): Promise; + runQuery(parent: string, $requestBody: RunQueryRequest, { $Xgafv, access_token, alt, bearer_token, callback, fields, key, oauth_token, pp, prettyPrint, quotaUser, uploadType, upload_protocol }?: ProjectsDatabasesDocumentsRunQueryNamedParameters & object): Promise; + write(database: string, $requestBody: WriteRequest, { $Xgafv, access_token, alt, bearer_token, callback, fields, key, oauth_token, pp, prettyPrint, quotaUser, uploadType, upload_protocol }?: ProjectsDatabasesDocumentsWriteNamedParameters & object): Promise; +} +export declare type ProjectsDatabasesIndexesApiClient$Xgafv = '1' | '2'; +export interface IProjectsDatabasesIndexesApiClient$XgafvEnum { + 1: ProjectsDatabasesIndexesApiClient$Xgafv; + 2: ProjectsDatabasesIndexesApiClient$Xgafv; + values(): ProjectsDatabasesIndexesApiClient$Xgafv[]; +} +export declare const ProjectsDatabasesIndexesApiClient$XgafvEnum: IProjectsDatabasesIndexesApiClient$XgafvEnum; +export declare type ProjectsDatabasesIndexesApiClientAlt = 'json' | 'media' | 'proto'; +export interface IProjectsDatabasesIndexesApiClientAltEnum { + JSON: ProjectsDatabasesIndexesApiClientAlt; + MEDIA: ProjectsDatabasesIndexesApiClientAlt; + PROTO: ProjectsDatabasesIndexesApiClientAlt; + values(): ProjectsDatabasesIndexesApiClientAlt[]; +} +export declare const ProjectsDatabasesIndexesApiClientAltEnum: IProjectsDatabasesIndexesApiClientAltEnum; +export interface ProjectsDatabasesIndexesCreateNamedParameters { + access_token?: string; + alt?: ProjectsDatabasesIndexesApiClientAlt; + bearer_token?: string; + callback?: string; + fields?: string; + key?: string; + oauth_token?: string; + pp?: boolean; + prettyPrint?: boolean; + quotaUser?: string; + upload_protocol?: string; + uploadType?: string; + $Xgafv?: ProjectsDatabasesIndexesApiClient$Xgafv; +} +export interface ProjectsDatabasesIndexesDeleteNamedParameters { + access_token?: string; + alt?: ProjectsDatabasesIndexesApiClientAlt; + bearer_token?: string; + callback?: string; + fields?: string; + key?: string; + oauth_token?: string; + pp?: boolean; + prettyPrint?: boolean; + quotaUser?: string; + upload_protocol?: string; + uploadType?: string; + $Xgafv?: ProjectsDatabasesIndexesApiClient$Xgafv; +} +export interface ProjectsDatabasesIndexesGetNamedParameters { + access_token?: string; + alt?: ProjectsDatabasesIndexesApiClientAlt; + bearer_token?: string; + callback?: string; + fields?: string; + key?: string; + oauth_token?: string; + pp?: boolean; + prettyPrint?: boolean; + quotaUser?: string; + upload_protocol?: string; + uploadType?: string; + $Xgafv?: ProjectsDatabasesIndexesApiClient$Xgafv; +} +export interface ProjectsDatabasesIndexesListNamedParameters { + access_token?: string; + alt?: ProjectsDatabasesIndexesApiClientAlt; + bearer_token?: string; + callback?: string; + fields?: string; + key?: string; + oauth_token?: string; + pp?: boolean; + prettyPrint?: boolean; + quotaUser?: string; + upload_protocol?: string; + uploadType?: string; + $Xgafv?: ProjectsDatabasesIndexesApiClient$Xgafv; + filter?: string; + pageSize?: number; + pageToken?: string; +} +export declare abstract class ProjectsDatabasesIndexesApiClient { + private constructor(); + abstract create(parent: string, $requestBody: Index, __namedParams__?: ProjectsDatabasesIndexesCreateNamedParameters & object): Promise; + abstract delete(name: string, __namedParams__?: ProjectsDatabasesIndexesDeleteNamedParameters & object): Promise; + abstract get(name: string, __namedParams__?: ProjectsDatabasesIndexesGetNamedParameters & object): Promise; + abstract list(parent: string, __namedParams__?: ProjectsDatabasesIndexesListNamedParameters & object): Promise; +} +export declare class ProjectsDatabasesIndexesApiClientImpl implements ProjectsDatabasesIndexesApiClient { + private gapiVersion; + private $apiClient; + constructor(gapiVersion: string, gapiRequestService: PromiseRequestService, apiClientHookFactory?: ApiClientHookFactory | null); + create(parent: string, $requestBody: Index, { $Xgafv, access_token, alt, bearer_token, callback, fields, key, oauth_token, pp, prettyPrint, quotaUser, uploadType, upload_protocol }?: ProjectsDatabasesIndexesCreateNamedParameters & object): Promise; + delete(name: string, { $Xgafv, access_token, alt, bearer_token, callback, fields, key, oauth_token, pp, prettyPrint, quotaUser, uploadType, upload_protocol }?: ProjectsDatabasesIndexesDeleteNamedParameters & object): Promise; + get(name: string, { $Xgafv, access_token, alt, bearer_token, callback, fields, key, oauth_token, pp, prettyPrint, quotaUser, uploadType, upload_protocol }?: ProjectsDatabasesIndexesGetNamedParameters & object): Promise; + list(parent: string, { $Xgafv, access_token, alt, bearer_token, callback, fields, filter, key, oauth_token, pageSize, pageToken, pp, prettyPrint, quotaUser, uploadType, upload_protocol }?: ProjectsDatabasesIndexesListNamedParameters & object): Promise; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/register.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/register.d.ts new file mode 100644 index 0000000..6f9da17 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/register.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export declare function registerFirestore(variant?: string, useFetchStreams?: boolean): void; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/backoff.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/backoff.d.ts new file mode 100644 index 0000000..cb0bc76 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/backoff.d.ts @@ -0,0 +1,106 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { AsyncQueue, TimerId } from '../util/async_queue'; +/** + * A helper for running delayed tasks following an exponential backoff curve + * between attempts. + * + * Each delay is made up of a "base" delay which follows the exponential + * backoff curve, and a +/- 50% "jitter" that is calculated and added to the + * base delay. This prevents clients from accidentally synchronizing their + * delays causing spikes of load to the backend. + */ +export declare class ExponentialBackoff { + /** + * The AsyncQueue to run backoff operations on. + */ + private readonly queue; + /** + * The ID to use when scheduling backoff operations on the AsyncQueue. + */ + private readonly timerId; + /** + * The initial delay (used as the base delay on the first retry attempt). + * Note that jitter will still be applied, so the actual delay could be as + * little as 0.5*initialDelayMs. + */ + private readonly initialDelayMs; + /** + * The multiplier to use to determine the extended base delay after each + * attempt. + */ + private readonly backoffFactor; + /** + * The maximum base delay after which no further backoff is performed. + * Note that jitter will still be applied, so the actual delay could be as + * much as 1.5*maxDelayMs. + */ + private readonly maxDelayMs; + private currentBaseMs; + private timerPromise; + /** The last backoff attempt, as epoch milliseconds. */ + private lastAttemptTime; + constructor( + /** + * The AsyncQueue to run backoff operations on. + */ + queue: AsyncQueue, + /** + * The ID to use when scheduling backoff operations on the AsyncQueue. + */ + timerId: TimerId, + /** + * The initial delay (used as the base delay on the first retry attempt). + * Note that jitter will still be applied, so the actual delay could be as + * little as 0.5*initialDelayMs. + */ + initialDelayMs?: number, + /** + * The multiplier to use to determine the extended base delay after each + * attempt. + */ + backoffFactor?: number, + /** + * The maximum base delay after which no further backoff is performed. + * Note that jitter will still be applied, so the actual delay could be as + * much as 1.5*maxDelayMs. + */ + maxDelayMs?: number); + /** + * Resets the backoff delay. + * + * The very next backoffAndWait() will have no delay. If it is called again + * (i.e. due to an error), initialDelayMs (plus jitter) will be used, and + * subsequent ones will increase according to the backoffFactor. + */ + reset(): void; + /** + * Resets the backoff delay to the maximum delay (e.g. for use after a + * RESOURCE_EXHAUSTED error). + */ + resetToMax(): void; + /** + * Returns a promise that resolves after currentDelayMs, and increases the + * delay for any subsequent attempts. If there was a pending backoff operation + * already, it will be canceled. + */ + backoffAndRun(op: () => Promise): void; + skipBackoff(): void; + cancel(): void; + /** Returns a random value in the range [-currentBaseMs/2, currentBaseMs/2] */ + private jitterDelayMs; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/bloom_filter.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/bloom_filter.d.ts new file mode 100644 index 0000000..d80eb83 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/bloom_filter.d.ts @@ -0,0 +1,34 @@ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export declare class BloomFilter { + readonly bitmap: Uint8Array; + readonly padding: number; + readonly hashCount: number; + readonly bitCount: number; + private readonly bitCountInInteger; + constructor(bitmap: Uint8Array, padding: number, hashCount: number); + private getBitIndex; + private isBitSet; + mightContain(value: string): boolean; + /** Create bloom filter for testing purposes only. */ + static create(bitCount: number, hashCount: number, contains: string[]): BloomFilter; + private insert; + private setBit; +} +export declare class BloomFilterError extends Error { + readonly name = "BloomFilterError"; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/connection.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/connection.d.ts new file mode 100644 index 0000000..87afea6 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/connection.d.ts @@ -0,0 +1,99 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Token } from '../api/credentials'; +import { ResourcePath } from '../model/path'; +import { FirestoreError } from '../util/error'; +/** + * A connected RPC interface to a remote Datastore. + * + * Responsible for maintaining a connection to the backend (and informing when + * that connection state changes via onConnectionStateChange) and sending RPCs + * when possible. + * + * The Connection is not responsible for queueing RPCs to the backend when + * the connection is down. + * + * RPC messages are expected to be JavaScript objects representing the JSON that + * would be sent over the REST/JSON API to Datastore or used as input to + * creating the equivalent protocol buffers for GRPC. + */ +export interface Connection { + /** + * Invokes an RPC by name, given a request message as a JavaScript object + * representing the JSON to send. + * + * @param rpcName - the name of the RPC to invoke + * @param path - the path to invoke this RPC on. An array of path segments + * that will be encoded and joined with path separators when required. + * @param request - the Raw JSON object encoding of the request message + * @param token - the Token to use for the RPC. + * @returns a Promise containing the JSON object encoding of the response + */ + invokeRPC(rpcName: string, path: ResourcePath, request: Req, authToken: Token | null, appCheckToken: Token | null): Promise; + /** + * Invokes a streaming RPC by name, given a request message as a JavaScript + * object representing the JSON to send. The responses will be consumed to + * completion and then returned as an array. + * + * @param rpcName - the name of the RPC to invoke + * @param path - the path to invoke this RPC on. An array of path segments + * that will be encoded and joined with path separators when required. + * @param request - the Raw JSON object encoding of the request message + * @param token - the Token to use for the RPC. + * @returns a Promise containing an array with the JSON object encodings of the + * responses + */ + invokeStreamingRPC(rpcName: string, path: ResourcePath, request: Req, authToken: Token | null, appCheckToken: Token | null, expectedResponseCount?: number): Promise; + /** + * Opens a stream to the given stream RPC endpoint. Returns a stream which + * will try to open itself. + * @param rpcName - the name of the RPC to open the stream on + * @param token - the Token to use for the RPC. + */ + openStream(rpcName: string, authToken: Token | null, appCheckToken: Token | null): Stream; + /** + * Returns whether or not the implementation requires that the "path" of the resource + * (a document or a collection) be present in the request message. If true, then the + * request message must include the path. If false, then the request message must NOT + * include the path. + */ + readonly shouldResourcePathBeIncludedInRequest: boolean; + /** + * Closes and cleans up any resources associated with the connection. Actual + * resources cleaned are implementation specific. Failure to call `terminate` + * on a connection may result in resource leaks. + */ + terminate(): void; +} +/** + * A bidirectional stream that can be used to send an receive messages. + * + * A stream can be closed locally with close() or can be closed remotely or + * through network errors. onClose is guaranteed to be called. onOpen will be + * called once the stream is ready to send messages (which may or may not be + * before an actual connection to the backend has been established). The + * onConnected event is called when an actual, physical connection with the + * backend has been established, and may occur before or after the onOpen event. + */ +export interface Stream { + onConnected(callback: () => void): void; + onOpen(callback: () => void): void; + onClose(callback: (err?: FirestoreError) => void): void; + onMessage(callback: (msg: O) => void): void; + send(msg: I): void; + close(): void; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/connectivity_monitor.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/connectivity_monitor.d.ts new file mode 100644 index 0000000..e02b7d2 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/connectivity_monitor.d.ts @@ -0,0 +1,47 @@ +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * The set of network states is deliberately simplified -- we only care about + * states such that transition between them should break currently + * established connections. + */ +export declare const enum NetworkStatus { + AVAILABLE = 0, + UNAVAILABLE = 1 +} +export type ConnectivityMonitorCallback = (status: NetworkStatus) => void; +/** + * A base class for monitoring changes in network connectivity; it is expected + * that each platform will have its own system-dependent implementation. + */ +export interface ConnectivityMonitor { + /** + * Adds a callback to be called when connectivity changes. + * + * Callbacks are not made on the initial state of connectivity, since this + * monitor is primarily used for resetting backoff in the remote store when + * connectivity changes. As such, the initial connectivity state is + * irrelevant here. + */ + addCallback(callback: ConnectivityMonitorCallback): void; + /** + * Stops monitoring connectivity. After this call completes, no further + * callbacks will be triggered. After shutdown() is called, no further calls + * are allowed on this instance. + */ + shutdown(): void; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/connectivity_monitor_noop.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/connectivity_monitor_noop.d.ts new file mode 100644 index 0000000..42bb25c --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/connectivity_monitor_noop.d.ts @@ -0,0 +1,21 @@ +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { ConnectivityMonitor, NetworkStatus } from './connectivity_monitor'; +export declare class NoopConnectivityMonitor implements ConnectivityMonitor { + addCallback(callback: (status: NetworkStatus) => void): void; + shutdown(): void; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/datastore.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/datastore.d.ts new file mode 100644 index 0000000..fe095c0 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/datastore.d.ts @@ -0,0 +1,44 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { CredentialsProvider } from '../api/credentials'; +import { User } from '../auth/user'; +import { Aggregate } from '../core/aggregate'; +import { Query } from '../core/query'; +import { Document } from '../model/document'; +import { DocumentKey } from '../model/document_key'; +import { Mutation } from '../model/mutation'; +import { ApiClientObjectMap, Value } from '../protos/firestore_proto_api'; +import { AsyncQueue } from '../util/async_queue'; +import { Connection } from './connection'; +import { PersistentListenStream, PersistentWriteStream, WatchStreamListener, WriteStreamListener } from './persistent_stream'; +import { JsonProtoSerializer } from './serializer'; +/** + * Datastore and its related methods are a wrapper around the external Google + * Cloud Datastore grpc API, which provides an interface that is more convenient + * for the rest of the client SDK architecture to consume. + */ +export declare abstract class Datastore { + abstract terminate(): void; + abstract serializer: JsonProtoSerializer; +} +export declare function newDatastore(authCredentials: CredentialsProvider, appCheckCredentials: CredentialsProvider, connection: Connection, serializer: JsonProtoSerializer): Datastore; +export declare function invokeCommitRpc(datastore: Datastore, mutations: Mutation[]): Promise; +export declare function invokeBatchGetDocumentsRpc(datastore: Datastore, keys: DocumentKey[]): Promise; +export declare function invokeRunQueryRpc(datastore: Datastore, query: Query): Promise; +export declare function invokeRunAggregationQueryRpc(datastore: Datastore, query: Query, aggregates: Aggregate[]): Promise>; +export declare function newPersistentWriteStream(datastore: Datastore, queue: AsyncQueue, listener: WriteStreamListener): PersistentWriteStream; +export declare function newPersistentWatchStream(datastore: Datastore, queue: AsyncQueue, listener: WatchStreamListener): PersistentListenStream; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/existence_filter.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/existence_filter.d.ts new file mode 100644 index 0000000..10ed5e5 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/existence_filter.d.ts @@ -0,0 +1,22 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { BloomFilter as ProtoBloomFilter } from '../protos/firestore_proto_api'; +export declare class ExistenceFilter { + count: number; + unchangedNames?: ProtoBloomFilter | undefined; + constructor(count: number, unchangedNames?: ProtoBloomFilter | undefined); +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/internal_serializer.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/internal_serializer.d.ts new file mode 100644 index 0000000..cd1f08d --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/internal_serializer.d.ts @@ -0,0 +1,46 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { AggregateSpec } from '../lite-api/aggregate_types'; +import { Query } from '../lite-api/reference'; +/** + * @internal + * @private + * + * This function is for internal use only. + * + * Returns the `QueryTarget` representation of the given query. Returns `null` + * if the Firestore client associated with the given query has not been + * initialized or has been terminated. + * + * @param query - The Query to convert to proto representation. + */ +export declare function _internalQueryToProtoQueryTarget(query: Query): any; +/** + * @internal + * @private + * + * This function is for internal use only. + * + * Returns `RunAggregationQueryRequest` which contains the proto representation + * of the given aggregation query request. Returns null if the Firestore client + * associated with the given query has not been initialized or has been + * terminated. + * + * @param query - The Query to convert to proto representation. + * @param aggregateSpec - The set of aggregations and their aliases. + */ +export declare function _internalAggregationQueryToProtoRunAggregationQueryRequest(query: Query, aggregateSpec: AggregateSpecType): any; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/number_serializer.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/number_serializer.d.ts new file mode 100644 index 0000000..cec4398 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/number_serializer.d.ts @@ -0,0 +1,36 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Value as ProtoValue } from '../protos/firestore_proto_api'; +/** Base interface for the Serializer implementation. */ +export interface Serializer { + readonly useProto3Json: boolean; +} +/** + * Returns an DoubleValue for `value` that is encoded based the serializer's + * `useProto3Json` setting. + */ +export declare function toDouble(serializer: Serializer, value: number): ProtoValue; +/** + * Returns an IntegerValue for `value`. + */ +export declare function toInteger(value: number): ProtoValue; +/** + * Returns a value for a number that's appropriate to put into a proto. + * The return value is an IntegerValue if it can safely represent the value, + * otherwise a DoubleValue is returned. + */ +export declare function toNumber(serializer: Serializer, value: number): ProtoValue; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/online_state_tracker.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/online_state_tracker.d.ts new file mode 100644 index 0000000..8a9bf8d --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/online_state_tracker.d.ts @@ -0,0 +1,81 @@ +/** + * @license + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { OnlineState } from '../core/types'; +import { AsyncQueue } from '../util/async_queue'; +import { FirestoreError } from '../util/error'; +/** + * A component used by the RemoteStore to track the OnlineState (that is, + * whether or not the client as a whole should be considered to be online or + * offline), implementing the appropriate heuristics. + * + * In particular, when the client is trying to connect to the backend, we + * allow up to MAX_WATCH_STREAM_FAILURES within ONLINE_STATE_TIMEOUT_MS for + * a connection to succeed. If we have too many failures or the timeout elapses, + * then we set the OnlineState to Offline, and the client will behave as if + * it is offline (get()s will return cached data, etc.). + */ +export declare class OnlineStateTracker { + private asyncQueue; + private onlineStateHandler; + /** The current OnlineState. */ + private state; + /** + * A count of consecutive failures to open the stream. If it reaches the + * maximum defined by MAX_WATCH_STREAM_FAILURES, we'll set the OnlineState to + * Offline. + */ + private watchStreamFailures; + /** + * A timer that elapses after ONLINE_STATE_TIMEOUT_MS, at which point we + * transition from OnlineState.Unknown to OnlineState.Offline without waiting + * for the stream to actually fail (MAX_WATCH_STREAM_FAILURES times). + */ + private onlineStateTimer; + /** + * Whether the client should log a warning message if it fails to connect to + * the backend (initially true, cleared after a successful stream, or if we've + * logged the message already). + */ + private shouldWarnClientIsOffline; + constructor(asyncQueue: AsyncQueue, onlineStateHandler: (onlineState: OnlineState) => void); + /** + * Called by RemoteStore when a watch stream is started (including on each + * backoff attempt). + * + * If this is the first attempt, it sets the OnlineState to Unknown and starts + * the onlineStateTimer. + */ + handleWatchStreamStart(): void; + /** + * Updates our OnlineState as appropriate after the watch stream reports a + * failure. The first failure moves us to the 'Unknown' state. We then may + * allow multiple failures (based on MAX_WATCH_STREAM_FAILURES) before we + * actually transition to the 'Offline' state. + */ + handleWatchStreamFailure(error: FirestoreError): void; + /** + * Explicitly sets the OnlineState to the specified state. + * + * Note that this resets our timers / failure counters, etc. used by our + * Offline heuristics, so must not be used in place of + * handleWatchStreamStart() and handleWatchStreamFailure(). + */ + set(newState: OnlineState): void; + private setAndBroadcast; + private logClientOfflineWarningIfNecessary; + private clearOnlineStateTimer; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/persistent_stream.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/persistent_stream.d.ts new file mode 100644 index 0000000..aacaf2d --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/persistent_stream.d.ts @@ -0,0 +1,308 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { CredentialsProvider, Token } from '../api/credentials'; +import { User } from '../auth/user'; +import { SnapshotVersion } from '../core/snapshot_version'; +import { TargetId } from '../core/types'; +import { TargetData } from '../local/target_data'; +import { Mutation, MutationResult } from '../model/mutation'; +import { ListenRequest as ProtoListenRequest, ListenResponse as ProtoListenResponse, WriteRequest as ProtoWriteRequest, WriteResponse as ProtoWriteResponse } from '../protos/firestore_proto_api'; +import { AsyncQueue, TimerId } from '../util/async_queue'; +import { FirestoreError } from '../util/error'; +import { ExponentialBackoff } from './backoff'; +import { Connection, Stream } from './connection'; +import { JsonProtoSerializer } from './serializer'; +import { WatchChange } from './watch_change'; +export interface WriteRequest extends ProtoWriteRequest { + database?: string; +} +/** + * Provides a common interface that is shared by the listeners for stream + * events by the concrete implementation classes. + */ +export interface PersistentStreamListener { + /** + * Called after receiving an acknowledgement from the server, confirming that + * we are able to connect to it. + */ + onConnected: () => Promise; + /** + * Called after the stream was established and can accept outgoing + * messages + */ + onOpen: () => Promise; + /** + * Called after the stream has closed. If there was an error, the + * FirestoreError will be set. + */ + onClose: (err?: FirestoreError) => Promise; +} +/** + * A PersistentStream is an abstract base class that represents a streaming RPC + * to the Firestore backend. It's built on top of the connections own support + * for streaming RPCs, and adds several critical features for our clients: + * + * - Exponential backoff on failure + * - Authentication via CredentialsProvider + * - Dispatching all callbacks into the shared worker queue + * - Closing idle streams after 60 seconds of inactivity + * + * Subclasses of PersistentStream implement serialization of models to and + * from the JSON representation of the protocol buffers for a specific + * streaming RPC. + * + * ## Starting and Stopping + * + * Streaming RPCs are stateful and need to be start()ed before messages can + * be sent and received. The PersistentStream will call the onOpen() function + * of the listener once the stream is ready to accept requests. + * + * Should a start() fail, PersistentStream will call the registered onClose() + * listener with a FirestoreError indicating what went wrong. + * + * A PersistentStream can be started and stopped repeatedly. + * + * Generic types: + * SendType: The type of the outgoing message of the underlying + * connection stream + * ReceiveType: The type of the incoming message of the underlying + * connection stream + * ListenerType: The type of the listener that will be used for callbacks + */ +export declare abstract class PersistentStream { + private queue; + private idleTimerId; + private healthTimerId; + protected connection: Connection; + private authCredentialsProvider; + private appCheckCredentialsProvider; + protected listener: ListenerType; + private state; + /** + * A close count that's incremented every time the stream is closed; used by + * getCloseGuardedDispatcher() to invalidate callbacks that happen after + * close. + */ + private closeCount; + private idleTimer; + private healthCheck; + private stream; + protected backoff: ExponentialBackoff; + constructor(queue: AsyncQueue, connectionTimerId: TimerId, idleTimerId: TimerId, healthTimerId: TimerId, connection: Connection, authCredentialsProvider: CredentialsProvider, appCheckCredentialsProvider: CredentialsProvider, listener: ListenerType); + /** + * Count of response messages received. + */ + protected responseCount: number; + /** + * Returns true if start() has been called and no error has occurred. True + * indicates the stream is open or in the process of opening (which + * encompasses respecting backoff, getting auth tokens, and starting the + * actual RPC). Use isOpen() to determine if the stream is open and ready for + * outbound requests. + */ + isStarted(): boolean; + /** + * Returns true if the underlying RPC is open (the onOpen() listener has been + * called) and the stream is ready for outbound requests. + */ + isOpen(): boolean; + /** + * Starts the RPC. Only allowed if isStarted() returns false. The stream is + * not immediately ready for use: onOpen() will be invoked when the RPC is + * ready for outbound requests, at which point isOpen() will return true. + * + * When start returns, isStarted() will return true. + */ + start(): void; + /** + * Stops the RPC. This call is idempotent and allowed regardless of the + * current isStarted() state. + * + * When stop returns, isStarted() and isOpen() will both return false. + */ + stop(): Promise; + /** + * After an error the stream will usually back off on the next attempt to + * start it. If the error warrants an immediate restart of the stream, the + * sender can use this to indicate that the receiver should not back off. + * + * Each error will call the onClose() listener. That function can decide to + * inhibit backoff if required. + */ + inhibitBackoff(): void; + /** + * Marks this stream as idle. If no further actions are performed on the + * stream for one minute, the stream will automatically close itself and + * notify the stream's onClose() handler with Status.OK. The stream will then + * be in a !isStarted() state, requiring the caller to start the stream again + * before further use. + * + * Only streams that are in state 'Open' can be marked idle, as all other + * states imply pending network operations. + */ + markIdle(): void; + /** Sends a message to the underlying stream. */ + protected sendRequest(msg: SendType): void; + /** Called by the idle timer when the stream should close due to inactivity. */ + private handleIdleCloseTimer; + /** Marks the stream as active again. */ + private cancelIdleCheck; + /** Cancels the health check delayed operation. */ + private cancelHealthCheck; + /** + * Closes the stream and cleans up as necessary: + * + * * closes the underlying GRPC stream; + * * calls the onClose handler with the given 'error'; + * * sets internal stream state to 'finalState'; + * * adjusts the backoff timer based on the error + * + * A new stream can be opened by calling start(). + * + * @param finalState - the intended state of the stream after closing. + * @param error - the error the connection was closed with. + */ + private close; + /** + * Can be overridden to perform additional cleanup before the stream is closed. + * Calling super.tearDown() is not required. + */ + protected tearDown(): void; + /** + * Used by subclasses to start the concrete RPC and return the underlying + * connection stream. + */ + protected abstract startRpc(authToken: Token | null, appCheckToken: Token | null): Stream; + /** + * Called when the stream receives first message. + * The function will be called on the right queue and must return a Promise. + * @param message - The message received from the stream. + */ + protected abstract onFirst(message: ReceiveType): Promise; + /** + * Called on subsequent messages after the stream has received first message. + * The function will be called on the right queue and must return a Promise. + * @param message - The message received from the stream. + */ + protected abstract onNext(message: ReceiveType): Promise; + private auth; + private startStream; + private performBackoff; + handleStreamClose(error?: FirestoreError): Promise; + /** + * Returns a "dispatcher" function that dispatches operations onto the + * AsyncQueue but only runs them if closeCount remains unchanged. This allows + * us to turn auth / stream callbacks into no-ops if the stream is closed / + * re-opened, etc. + */ + private getCloseGuardedDispatcher; +} +/** Listener for the PersistentWatchStream */ +export interface WatchStreamListener extends PersistentStreamListener { + /** + * Called on a watchChange. The snapshot parameter will be MIN if the watch + * change did not have a snapshot associated with it. + */ + onWatchChange: (watchChange: WatchChange, snapshot: SnapshotVersion) => Promise; +} +/** + * A PersistentStream that implements the Listen RPC. + * + * Once the Listen stream has called the onOpen() listener, any number of + * listen() and unlisten() calls can be made to control what changes will be + * sent from the server for ListenResponses. + */ +export declare class PersistentListenStream extends PersistentStream { + private serializer; + constructor(queue: AsyncQueue, connection: Connection, authCredentials: CredentialsProvider, appCheckCredentials: CredentialsProvider, serializer: JsonProtoSerializer, listener: WatchStreamListener); + protected startRpc(authToken: Token | null, appCheckToken: Token | null): Stream; + protected onFirst(watchChangeProto: ProtoListenResponse): Promise; + protected onNext(watchChangeProto: ProtoListenResponse): Promise; + /** + * Registers interest in the results of the given target. If the target + * includes a resumeToken it will be included in the request. Results that + * affect the target will be streamed back as WatchChange messages that + * reference the targetId. + */ + watch(targetData: TargetData): void; + /** + * Unregisters interest in the results of the target associated with the + * given targetId. + */ + unwatch(targetId: TargetId): void; +} +/** Listener for the PersistentWriteStream */ +export interface WriteStreamListener extends PersistentStreamListener { + /** + * Called by the PersistentWriteStream upon a successful handshake response + * from the server, which is the receiver's cue to send any pending writes. + */ + onHandshakeComplete: () => Promise; + /** + * Called by the PersistentWriteStream upon receiving a StreamingWriteResponse + * from the server that contains a mutation result. + */ + onMutationResult: (commitVersion: SnapshotVersion, results: MutationResult[]) => Promise; +} +/** + * A Stream that implements the Write RPC. + * + * The Write RPC requires the caller to maintain special streamToken + * state in between calls, to help the server understand which responses the + * client has processed by the time the next request is made. Every response + * will contain a streamToken; this value must be passed to the next + * request. + * + * After calling start() on this stream, the next request must be a handshake, + * containing whatever streamToken is on hand. Once a response to this + * request is received, all pending mutations may be submitted. When + * submitting multiple batches of mutations at the same time, it's + * okay to use the same streamToken for the calls to writeMutations. + * + * TODO(b/33271235): Use proto types + */ +export declare class PersistentWriteStream extends PersistentStream { + private serializer; + constructor(queue: AsyncQueue, connection: Connection, authCredentials: CredentialsProvider, appCheckCredentials: CredentialsProvider, serializer: JsonProtoSerializer, listener: WriteStreamListener); + /** + * The last received stream token from the server, used to acknowledge which + * responses the client has processed. Stream tokens are opaque checkpoint + * markers whose only real value is their inclusion in the next request. + * + * PersistentWriteStream manages propagating this value from responses to the + * next request. + */ + private lastStreamToken; + /** + * Tracks whether or not a handshake has been successfully exchanged and + * the stream is ready to accept mutations. + */ + get handshakeComplete(): boolean; + start(): void; + protected tearDown(): void; + protected startRpc(authToken: Token | null, appCheckToken: Token | null): Stream; + protected onFirst(responseProto: ProtoWriteResponse): Promise; + protected onNext(responseProto: ProtoWriteResponse): Promise; + /** + * Sends an initial streamToken to the server, performing the handshake + * required to make the StreamingWrite RPC work. Subsequent + * calls should wait until onHandshakeComplete was called. + */ + writeHandshake(): void; + /** Sends a group of mutations to the Firestore backend to apply. */ + writeMutations(mutations: Mutation[]): void; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/remote_event.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/remote_event.d.ts new file mode 100644 index 0000000..9bafaf3 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/remote_event.d.ts @@ -0,0 +1,156 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { SnapshotVersion } from '../core/snapshot_version'; +import { TargetId } from '../core/types'; +import { TargetPurpose } from '../local/target_data'; +import { DocumentKeySet, MutableDocumentMap } from '../model/collections'; +import { ByteString } from '../util/byte_string'; +import { SortedMap } from '../util/sorted_map'; +/** + * An event from the RemoteStore. It is split into targetChanges (changes to the + * state or the set of documents in our watched targets) and documentUpdates + * (changes to the actual documents). + */ +export declare class RemoteEvent { + /** + * The snapshot version this event brings us up to, or MIN if not set. + */ + readonly snapshotVersion: SnapshotVersion; + /** + * A map from target to changes to the target. See TargetChange. + */ + readonly targetChanges: Map; + /** + * A map of targets that is known to be inconsistent, and the purpose for + * re-listening. Listens for these targets should be re-established without + * resume tokens. + */ + readonly targetMismatches: SortedMap; + /** + * A set of which documents have changed or been deleted, along with the + * doc's new values (if not deleted). + */ + readonly documentUpdates: MutableDocumentMap; + /** + * A set of which document updates are due only to limbo resolution targets. + */ + readonly resolvedLimboDocuments: DocumentKeySet; + constructor( + /** + * The snapshot version this event brings us up to, or MIN if not set. + */ + snapshotVersion: SnapshotVersion, + /** + * A map from target to changes to the target. See TargetChange. + */ + targetChanges: Map, + /** + * A map of targets that is known to be inconsistent, and the purpose for + * re-listening. Listens for these targets should be re-established without + * resume tokens. + */ + targetMismatches: SortedMap, + /** + * A set of which documents have changed or been deleted, along with the + * doc's new values (if not deleted). + */ + documentUpdates: MutableDocumentMap, + /** + * A set of which document updates are due only to limbo resolution targets. + */ + resolvedLimboDocuments: DocumentKeySet); + /** + * HACK: Views require RemoteEvents in order to determine whether the view is + * CURRENT, but secondary tabs don't receive remote events. So this method is + * used to create a synthesized RemoteEvent that can be used to apply a + * CURRENT status change to a View, for queries executed in a different tab. + */ + static createSynthesizedRemoteEventForCurrentChange(targetId: TargetId, current: boolean, resumeToken: ByteString): RemoteEvent; +} +/** + * A TargetChange specifies the set of changes for a specific target as part of + * a RemoteEvent. These changes track which documents are added, modified or + * removed, as well as the target's resume token and whether the target is + * marked CURRENT. + * The actual changes *to* documents are not part of the TargetChange since + * documents may be part of multiple targets. + */ +export declare class TargetChange { + /** + * An opaque, server-assigned token that allows watching a query to be resumed + * after disconnecting without retransmitting all the data that matches the + * query. The resume token essentially identifies a point in time from which + * the server should resume sending results. + */ + readonly resumeToken: ByteString; + /** + * The "current" (synced) status of this target. Note that "current" + * has special meaning in the RPC protocol that implies that a target is + * both up-to-date and consistent with the rest of the watch stream. + */ + readonly current: boolean; + /** + * The set of documents that were newly assigned to this target as part of + * this remote event. + */ + readonly addedDocuments: DocumentKeySet; + /** + * The set of documents that were already assigned to this target but received + * an update during this remote event. + */ + readonly modifiedDocuments: DocumentKeySet; + /** + * The set of documents that were removed from this target as part of this + * remote event. + */ + readonly removedDocuments: DocumentKeySet; + constructor( + /** + * An opaque, server-assigned token that allows watching a query to be resumed + * after disconnecting without retransmitting all the data that matches the + * query. The resume token essentially identifies a point in time from which + * the server should resume sending results. + */ + resumeToken: ByteString, + /** + * The "current" (synced) status of this target. Note that "current" + * has special meaning in the RPC protocol that implies that a target is + * both up-to-date and consistent with the rest of the watch stream. + */ + current: boolean, + /** + * The set of documents that were newly assigned to this target as part of + * this remote event. + */ + addedDocuments: DocumentKeySet, + /** + * The set of documents that were already assigned to this target but received + * an update during this remote event. + */ + modifiedDocuments: DocumentKeySet, + /** + * The set of documents that were removed from this target as part of this + * remote event. + */ + removedDocuments: DocumentKeySet); + /** + * This method is used to create a synthesized TargetChanges that can be used to + * apply a CURRENT status change to a View (for queries executed in a different + * tab) or for new queries (to raise snapshots with correct CURRENT status). + */ + static createSynthesizedTargetChangeForCurrentChange(targetId: TargetId, current: boolean, resumeToken: ByteString): TargetChange; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/remote_store.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/remote_store.d.ts new file mode 100644 index 0000000..c6c2416 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/remote_store.d.ts @@ -0,0 +1,85 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { User } from '../auth/user'; +import { OnlineState, TargetId } from '../core/types'; +import { LocalStore } from '../local/local_store'; +import { TargetData } from '../local/target_data'; +import { AsyncQueue } from '../util/async_queue'; +import { ConnectivityMonitor } from './connectivity_monitor'; +import { Datastore } from './datastore'; +import { RemoteSyncer } from './remote_syncer'; +/** + * RemoteStore - An interface to remotely stored data, basically providing a + * wrapper around the Datastore that is more reliable for the rest of the + * system. + * + * RemoteStore is responsible for maintaining the connection to the server. + * - maintaining a list of active listens. + * - reconnecting when the connection is dropped. + * - resuming all the active listens on reconnect. + * + * RemoteStore handles all incoming events from the Datastore. + * - listening to the watch stream and repackaging the events as RemoteEvents + * - notifying SyncEngine of any changes to the active listens. + * + * RemoteStore takes writes from other components and handles them reliably. + * - pulling pending mutations from LocalStore and sending them to Datastore. + * - retrying mutations that failed because of network problems. + * - acking mutations to the SyncEngine once they are accepted or rejected. + */ +export interface RemoteStore { + /** + * SyncEngine to notify of watch and write events. This must be set + * immediately after construction. + */ + remoteSyncer: RemoteSyncer; +} +export declare function newRemoteStore(localStore: LocalStore, datastore: Datastore, asyncQueue: AsyncQueue, onlineStateHandler: (onlineState: OnlineState) => void, connectivityMonitor: ConnectivityMonitor): RemoteStore; +/** Re-enables the network. Idempotent. */ +export declare function remoteStoreEnableNetwork(remoteStore: RemoteStore): Promise; +/** + * Temporarily disables the network. The network can be re-enabled using + * enableNetwork(). + */ +export declare function remoteStoreDisableNetwork(remoteStore: RemoteStore): Promise; +export declare function remoteStoreShutdown(remoteStore: RemoteStore): Promise; +/** + * Starts new listen for the given target. Uses resume token if provided. It + * is a no-op if the target of given `TargetData` is already being listened to. + */ +export declare function remoteStoreListen(remoteStore: RemoteStore, targetData: TargetData): void; +/** + * Removes the listen from server. It is a no-op if the given target id is + * not being listened to. + */ +export declare function remoteStoreUnlisten(remoteStore: RemoteStore, targetId: TargetId): void; +export declare function canUseNetwork(remoteStore: RemoteStore): boolean; +/** + * Attempts to fill our write pipeline with writes from the LocalStore. + * + * Called internally to bootstrap or refill the write pipeline and by + * SyncEngine whenever there are new mutations to process. + * + * Starts the write stream if necessary. + */ +export declare function fillWritePipeline(remoteStore: RemoteStore): Promise; +export declare function outstandingWrites(remoteStore: RemoteStore): number; +export declare function remoteStoreHandleCredentialChange(remoteStore: RemoteStore, user: User): Promise; +/** + * Toggles the network state when the client gains or loses its primary lease. + */ +export declare function remoteStoreApplyPrimaryState(remoteStore: RemoteStore, isPrimary: boolean): Promise; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/remote_syncer.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/remote_syncer.d.ts new file mode 100644 index 0000000..949bc21 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/remote_syncer.d.ts @@ -0,0 +1,68 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { User } from '../auth/user'; +import { BatchId, TargetId } from '../core/types'; +import { DocumentKeySet } from '../model/collections'; +import { MutationBatchResult } from '../model/mutation_batch'; +import { FirestoreError } from '../util/error'; +import { RemoteEvent } from './remote_event'; +/** + * An interface that describes the actions the RemoteStore needs to perform on + * a cooperating synchronization engine. + */ +export interface RemoteSyncer { + /** + * Applies one remote event to the sync engine, notifying any views of the + * changes, and releasing any pending mutation batches that would become + * visible because of the snapshot version the remote event contains. + */ + applyRemoteEvent?(remoteEvent: RemoteEvent): Promise; + /** + * Rejects the listen for the given targetID. This can be triggered by the + * backend for any active target. + * + * @param targetId - The targetID corresponds to one previously initiated by + * the user as part of TargetData passed to listen() on RemoteStore. + * @param error - A description of the condition that has forced the rejection. + * Nearly always this will be an indication that the user is no longer + * authorized to see the data matching the target. + */ + rejectListen?(targetId: TargetId, error: FirestoreError): Promise; + /** + * Applies the result of a successful write of a mutation batch to the sync + * engine, emitting snapshots in any views that the mutation applies to, and + * removing the batch from the mutation queue. + */ + applySuccessfulWrite?(result: MutationBatchResult): Promise; + /** + * Rejects the batch, removing the batch from the mutation queue, recomputing + * the local view of any documents affected by the batch and then, emitting + * snapshots with the reverted value. + */ + rejectFailedWrite?(batchId: BatchId, error: FirestoreError): Promise; + /** + * Returns the set of remote document keys for the given target ID. This list + * includes the documents that were assigned to the target when we received + * the last snapshot. + */ + getRemoteKeysForTarget?(targetId: TargetId): DocumentKeySet; + /** + * Updates all local state to match the pending mutations for the given user. + * May be called repeatedly for the same user. + */ + handleCredentialChange?(user: User): Promise; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/rest_connection.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/rest_connection.d.ts new file mode 100644 index 0000000..1e58386 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/rest_connection.d.ts @@ -0,0 +1,53 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Token } from '../api/credentials'; +import { DatabaseId, DatabaseInfo } from '../core/database_info'; +import { ResourcePath } from '../model/path'; +import { StringMap } from '../util/types'; +import { Connection, Stream } from './connection'; +/** + * Base class for all Rest-based connections to the backend (WebChannel and + * HTTP). + */ +export declare abstract class RestConnection implements Connection { + private readonly databaseInfo; + protected readonly databaseId: DatabaseId; + protected readonly baseUrl: string; + private readonly databasePath; + private readonly requestParams; + get shouldResourcePathBeIncludedInRequest(): boolean; + constructor(databaseInfo: DatabaseInfo); + invokeRPC(rpcName: string, path: ResourcePath, req: Req, authToken: Token | null, appCheckToken: Token | null): Promise; + invokeStreamingRPC(rpcName: string, path: ResourcePath, request: Req, authToken: Token | null, appCheckToken: Token | null, expectedResponseCount?: number): Promise; + abstract openStream(rpcName: string, authToken: Token | null, appCheckToken: Token | null): Stream; + /** + * Modifies the headers for a request, adding any authorization token if + * present and any additional headers for the request. + */ + protected modifyHeadersForRequest(headers: StringMap, authToken: Token | null, appCheckToken: Token | null): void; + /** + * Performs an RPC request using an implementation specific networking layer. + */ + protected abstract performRPCRequest(rpcName: string, url: string, headers: StringMap, body: Req, _forwardCredentials: boolean): Promise; + private makeUrl; + /** + * Closes and cleans up any resources associated with the connection. This + * implementation is a no-op because there are no resources associated + * with the RestConnection that need to be cleaned up. + */ + terminate(): void; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/rpc_error.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/rpc_error.d.ts new file mode 100644 index 0000000..90d075c --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/rpc_error.d.ts @@ -0,0 +1,74 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Code } from '../util/error'; +/** + * Determines whether an error code represents a permanent error when received + * in response to a non-write operation. + * + * See isPermanentWriteError for classifying write errors. + */ +export declare function isPermanentError(code: Code): boolean; +/** + * Determines whether an error code represents a permanent error when received + * in response to a write operation. + * + * Write operations must be handled specially because as of b/119437764, ABORTED + * errors on the write stream should be retried too (even though ABORTED errors + * are not generally retryable). + * + * Note that during the initial handshake on the write stream an ABORTED error + * signals that we should discard our stream token (i.e. it is permanent). This + * means a handshake error should be classified with isPermanentError, above. + */ +export declare function isPermanentWriteError(code: Code): boolean; +/** + * Maps an error Code from a GRPC status identifier like 'NOT_FOUND'. + * + * @returns The Code equivalent to the given status string or undefined if + * there is no match. + */ +export declare function mapCodeFromRpcStatus(status: string): Code | undefined; +/** + * Maps an error Code from GRPC status code number, like 0, 1, or 14. These + * are not the same as HTTP status codes. + * + * @returns The Code equivalent to the given GRPC status code. Fails if there + * is no match. + */ +export declare function mapCodeFromRpcCode(code: number | undefined): Code; +/** + * Maps an RPC code from a Code. This is the reverse operation from + * mapCodeFromRpcCode and should really only be used in tests. + */ +export declare function mapRpcCodeFromCode(code: Code | undefined): number; +/** + * Converts an HTTP Status Code to the equivalent error code. + * + * @param status - An HTTP Status Code, like 200, 404, 503, etc. + * @returns The equivalent Code. Unknown status codes are mapped to + * Code.UNKNOWN. + */ +export declare function mapCodeFromHttpStatus(status?: number): Code; +/** + * Converts an HTTP response's error status to the equivalent error code. + * + * @param status - An HTTP error response status ("FAILED_PRECONDITION", + * "UNKNOWN", etc.) + * @returns The equivalent Code. Non-matching responses are mapped to + * Code.UNKNOWN. + */ +export declare function mapCodeFromHttpResponseErrorStatus(status: string): Code; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/serializer.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/serializer.d.ts new file mode 100644 index 0000000..bb1aeb9 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/serializer.d.ts @@ -0,0 +1,124 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Aggregate } from '../core/aggregate'; +import { DatabaseId } from '../core/database_info'; +import { CompositeFilter, CompositeOperator, FieldFilter, Filter, Operator } from '../core/filter'; +import { Direction, OrderBy } from '../core/order_by'; +import { Query } from '../core/query'; +import { SnapshotVersion } from '../core/snapshot_version'; +import { Target } from '../core/target'; +import { Timestamp } from '../lite-api/timestamp'; +import { TargetData, TargetPurpose } from '../local/target_data'; +import { MutableDocument } from '../model/document'; +import { DocumentKey } from '../model/document_key'; +import { FieldMask } from '../model/field_mask'; +import { Mutation, MutationResult } from '../model/mutation'; +import { ObjectValue } from '../model/object_value'; +import { FieldPath, ResourcePath } from '../model/path'; +import { ApiClientObjectMap as ProtoApiClientObjectMap, BatchGetDocumentsResponse as ProtoBatchGetDocumentsResponse, CompositeFilterOp as ProtoCompositeFilterOp, Document as ProtoDocument, DocumentMask as ProtoDocumentMask, DocumentsTarget as ProtoDocumentsTarget, FieldFilterOp as ProtoFieldFilterOp, FieldReference as ProtoFieldReference, Filter as ProtoFilter, ListenResponse as ProtoListenResponse, Order as ProtoOrder, OrderDirection as ProtoOrderDirection, QueryTarget as ProtoQueryTarget, RunAggregationQueryRequest as ProtoRunAggregationQueryRequest, Target as ProtoTarget, Timestamp as ProtoTimestamp, Write as ProtoWrite, WriteResult as ProtoWriteResult } from '../protos/firestore_proto_api'; +import { ByteString } from '../util/byte_string'; +import { Serializer } from './number_serializer'; +import { WatchChange } from './watch_change'; +/** + * This class generates JsonObject values for the Datastore API suitable for + * sending to either GRPC stub methods or via the JSON/HTTP REST API. + * + * The serializer supports both Protobuf.js and Proto3 JSON formats. By + * setting `useProto3Json` to true, the serializer will use the Proto3 JSON + * format. + * + * For a description of the Proto3 JSON format check + * https://developers.google.com/protocol-buffers/docs/proto3#json + * + * TODO(klimt): We can remove the databaseId argument if we keep the full + * resource name in documents. + */ +export declare class JsonProtoSerializer implements Serializer { + readonly databaseId: DatabaseId; + readonly useProto3Json: boolean; + constructor(databaseId: DatabaseId, useProto3Json: boolean); +} +/** + * Returns a value for a Date that's appropriate to put into a proto. + */ +export declare function toTimestamp(serializer: JsonProtoSerializer, timestamp: Timestamp): ProtoTimestamp; +/** + * Returns a Timestamp typed object given protobuf timestamp value. + */ +export declare function fromTimestamp(date: ProtoTimestamp): Timestamp; +/** + * Returns a value for bytes that's appropriate to put in a proto. + * + * Visible for testing. + */ +export declare function toBytes(serializer: JsonProtoSerializer, bytes: ByteString): string | Uint8Array; +/** + * Returns a ByteString based on the proto string value. + */ +export declare function fromBytes(serializer: JsonProtoSerializer, value: string | Uint8Array | undefined): ByteString; +export declare function toVersion(serializer: JsonProtoSerializer, version: SnapshotVersion): ProtoTimestamp; +export declare function fromVersion(version: ProtoTimestamp): SnapshotVersion; +export declare function toResourceName(databaseId: DatabaseId, path: ResourcePath): string; +export declare function toResourcePath(databaseId: DatabaseId, path?: ResourcePath): ResourcePath; +export declare function toName(serializer: JsonProtoSerializer, key: DocumentKey): string; +export declare function fromName(serializer: JsonProtoSerializer, name: string): DocumentKey; +export declare function getEncodedDatabaseId(serializer: JsonProtoSerializer): string; +/** Creates a Document proto from key and fields (but no create/update time) */ +export declare function toMutationDocument(serializer: JsonProtoSerializer, key: DocumentKey, fields: ObjectValue): ProtoDocument; +export declare function toDocument(serializer: JsonProtoSerializer, document: MutableDocument): ProtoDocument; +export declare function fromDocument(serializer: JsonProtoSerializer, document: ProtoDocument, hasCommittedMutations?: boolean): MutableDocument; +export declare function fromBatchGetDocumentsResponse(serializer: JsonProtoSerializer, result: ProtoBatchGetDocumentsResponse): MutableDocument; +export declare function fromWatchChange(serializer: JsonProtoSerializer, change: ProtoListenResponse): WatchChange; +export declare function versionFromListenResponse(change: ProtoListenResponse): SnapshotVersion; +export declare function toMutation(serializer: JsonProtoSerializer, mutation: Mutation): ProtoWrite; +export declare function fromMutation(serializer: JsonProtoSerializer, proto: ProtoWrite): Mutation; +export declare function fromWriteResults(protos: ProtoWriteResult[] | undefined, commitTime?: ProtoTimestamp): MutationResult[]; +export declare function toDocumentsTarget(serializer: JsonProtoSerializer, target: Target): ProtoDocumentsTarget; +export declare function fromDocumentsTarget(documentsTarget: ProtoDocumentsTarget): Target; +export declare function toQueryTarget(serializer: JsonProtoSerializer, target: Target): { + queryTarget: ProtoQueryTarget; + parent: ResourcePath; +}; +export declare function toRunAggregationQueryRequest(serializer: JsonProtoSerializer, target: Target, aggregates: Aggregate[], skipAliasing?: boolean): { + request: ProtoRunAggregationQueryRequest; + aliasMap: Record; + parent: ResourcePath; +}; +export declare function convertQueryTargetToQuery(target: ProtoQueryTarget): Query; +export declare function fromQueryTarget(target: ProtoQueryTarget): Target; +export declare function toListenRequestLabels(serializer: JsonProtoSerializer, targetData: TargetData): ProtoApiClientObjectMap | null; +export declare function toLabel(purpose: TargetPurpose): string | null; +export declare function toTarget(serializer: JsonProtoSerializer, targetData: TargetData): ProtoTarget; +export declare function toDirection(dir: Direction): ProtoOrderDirection; +export declare function fromDirection(dir: ProtoOrderDirection | undefined): Direction | undefined; +export declare function toOperatorName(op: Operator): ProtoFieldFilterOp; +export declare function toCompositeOperatorName(op: CompositeOperator): ProtoCompositeFilterOp; +export declare function fromOperatorName(op: ProtoFieldFilterOp): Operator; +export declare function fromCompositeOperatorName(op: ProtoCompositeFilterOp): CompositeOperator; +export declare function toFieldPathReference(path: FieldPath): ProtoFieldReference; +export declare function fromFieldPathReference(fieldReference: ProtoFieldReference): FieldPath; +export declare function toPropertyOrder(orderBy: OrderBy): ProtoOrder; +export declare function fromPropertyOrder(orderBy: ProtoOrder): OrderBy; +export declare function toFilter(filter: Filter): ProtoFilter; +export declare function toCompositeFilter(filter: CompositeFilter): ProtoFilter; +export declare function toUnaryOrFieldFilter(filter: FieldFilter): ProtoFilter; +export declare function fromUnaryFilter(filter: ProtoFilter): Filter; +export declare function fromFieldFilter(filter: ProtoFilter): FieldFilter; +export declare function fromCompositeFilter(filter: ProtoFilter): CompositeFilter; +export declare function toDocumentMask(fieldMask: FieldMask): ProtoDocumentMask; +export declare function fromDocumentMask(proto: ProtoDocumentMask): FieldMask; +export declare function isValidResourceName(path: ResourcePath): boolean; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/stream_bridge.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/stream_bridge.d.ts new file mode 100644 index 0000000..f17a080 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/stream_bridge.d.ts @@ -0,0 +1,45 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { FirestoreError } from '../util/error'; +import { Stream } from './connection'; +/** + * Provides a simple helper class that implements the Stream interface to + * bridge to other implementations that are streams but do not implement the + * interface. The stream callbacks are invoked with the callOn... methods. + */ +export declare class StreamBridge implements Stream { + private wrappedOnConnected; + private wrappedOnOpen; + private wrappedOnClose; + private wrappedOnMessage; + private sendFn; + private closeFn; + constructor(args: { + sendFn: (msg: I) => void; + closeFn: () => void; + }); + onConnected(callback: () => void): void; + onOpen(callback: () => void): void; + onClose(callback: (err?: FirestoreError) => void): void; + onMessage(callback: (msg: O) => void): void; + close(): void; + send(msg: I): void; + callOnConnected(): void; + callOnOpen(): void; + callOnClose(err?: FirestoreError): void; + callOnMessage(msg: O): void; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/watch_change.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/watch_change.d.ts new file mode 100644 index 0000000..1510515 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/watch_change.d.ts @@ -0,0 +1,231 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { DatabaseId } from '../core/database_info'; +import { SnapshotVersion } from '../core/snapshot_version'; +import { TargetId } from '../core/types'; +import { TargetData } from '../local/target_data'; +import { DocumentKeySet } from '../model/collections'; +import { MutableDocument } from '../model/document'; +import { DocumentKey } from '../model/document_key'; +import { ByteString } from '../util/byte_string'; +import { FirestoreError } from '../util/error'; +import { ExistenceFilter } from './existence_filter'; +import { RemoteEvent } from './remote_event'; +/** + * Internal representation of the watcher API protocol buffers. + */ +export type WatchChange = DocumentWatchChange | WatchTargetChange | ExistenceFilterChange; +/** + * Represents a changed document and a list of target ids to which this change + * applies. + * + * If document has been deleted NoDocument will be provided. + */ +export declare class DocumentWatchChange { + /** The new document applies to all of these targets. */ + updatedTargetIds: TargetId[]; + /** The new document is removed from all of these targets. */ + removedTargetIds: TargetId[]; + /** The key of the document for this change. */ + key: DocumentKey; + /** + * The new document or NoDocument if it was deleted. Is null if the + * document went out of view without the server sending a new document. + */ + newDoc: MutableDocument | null; + constructor( + /** The new document applies to all of these targets. */ + updatedTargetIds: TargetId[], + /** The new document is removed from all of these targets. */ + removedTargetIds: TargetId[], + /** The key of the document for this change. */ + key: DocumentKey, + /** + * The new document or NoDocument if it was deleted. Is null if the + * document went out of view without the server sending a new document. + */ + newDoc: MutableDocument | null); +} +export declare class ExistenceFilterChange { + targetId: TargetId; + existenceFilter: ExistenceFilter; + constructor(targetId: TargetId, existenceFilter: ExistenceFilter); +} +export declare const enum WatchTargetChangeState { + NoChange = 0, + Added = 1, + Removed = 2, + Current = 3, + Reset = 4 +} +export declare class WatchTargetChange { + /** What kind of change occurred to the watch target. */ + state: WatchTargetChangeState; + /** The target IDs that were added/removed/set. */ + targetIds: TargetId[]; + /** + * An opaque, server-assigned token that allows watching a target to be + * resumed after disconnecting without retransmitting all the data that + * matches the target. The resume token essentially identifies a point in + * time from which the server should resume sending results. + */ + resumeToken: ByteString; + /** An RPC error indicating why the watch failed. */ + cause: FirestoreError | null; + constructor( + /** What kind of change occurred to the watch target. */ + state: WatchTargetChangeState, + /** The target IDs that were added/removed/set. */ + targetIds: TargetId[], + /** + * An opaque, server-assigned token that allows watching a target to be + * resumed after disconnecting without retransmitting all the data that + * matches the target. The resume token essentially identifies a point in + * time from which the server should resume sending results. + */ + resumeToken?: ByteString, + /** An RPC error indicating why the watch failed. */ + cause?: FirestoreError | null); +} +/** + * Interface implemented by RemoteStore to expose target metadata to the + * WatchChangeAggregator. + */ +export interface TargetMetadataProvider { + /** + * Returns the set of remote document keys for the given target ID as of the + * last raised snapshot. + */ + getRemoteKeysForTarget(targetId: TargetId): DocumentKeySet; + /** + * Returns the TargetData for an active target ID or 'null' if this target + * has become inactive + */ + getTargetDataForTarget(targetId: TargetId): TargetData | null; + /** + * Returns the database ID of the Firestore instance. + */ + getDatabaseId(): DatabaseId; +} +/** + * A helper class to accumulate watch changes into a RemoteEvent. + */ +export declare class WatchChangeAggregator { + private metadataProvider; + constructor(metadataProvider: TargetMetadataProvider); + /** The internal state of all tracked targets. */ + private targetStates; + /** Keeps track of the documents to update since the last raised snapshot. */ + private pendingDocumentUpdates; + private pendingDocumentUpdatesByTarget; + /** A mapping of document keys to their set of target IDs. */ + private pendingDocumentTargetMapping; + /** + * A map of targets with existence filter mismatches. These targets are + * known to be inconsistent and their listens needs to be re-established by + * RemoteStore. + */ + private pendingTargetResets; + /** + * Processes and adds the DocumentWatchChange to the current set of changes. + */ + handleDocumentChange(docChange: DocumentWatchChange): void; + /** Processes and adds the WatchTargetChange to the current set of changes. */ + handleTargetChange(targetChange: WatchTargetChange): void; + /** + * Iterates over all targetIds that the watch change applies to: either the + * targetIds explicitly listed in the change or the targetIds of all currently + * active targets. + */ + forEachTarget(targetChange: WatchTargetChange, fn: (targetId: TargetId) => void): void; + /** + * Handles existence filters and synthesizes deletes for filter mismatches. + * Targets that are invalidated by filter mismatches are added to + * `pendingTargetResets`. + */ + handleExistenceFilter(watchChange: ExistenceFilterChange): void; + /** + * Parse the bloom filter from the "unchanged_names" field of an existence + * filter. + */ + private parseBloomFilter; + /** + * Apply bloom filter to remove the deleted documents, and return the + * application status. + */ + private applyBloomFilter; + /** + * Filter out removed documents based on bloom filter membership result and + * return number of documents removed. + */ + private filterRemovedDocuments; + /** + * Converts the currently accumulated state into a remote event at the + * provided snapshot version. Resets the accumulated changes before returning. + */ + createRemoteEvent(snapshotVersion: SnapshotVersion): RemoteEvent; + /** + * Adds the provided document to the internal list of document updates and + * its document key to the given target's mapping. + */ + addDocumentToTarget(targetId: TargetId, document: MutableDocument): void; + /** + * Removes the provided document from the target mapping. If the + * document no longer matches the target, but the document's state is still + * known (e.g. we know that the document was deleted or we received the change + * that caused the filter mismatch), the new document can be provided + * to update the remote document cache. + */ + removeDocumentFromTarget(targetId: TargetId, key: DocumentKey, updatedDocument: MutableDocument | null): void; + removeTarget(targetId: TargetId): void; + /** + * Returns the current count of documents in the target. This includes both + * the number of documents that the LocalStore considers to be part of the + * target as well as any accumulated changes. + */ + private getCurrentDocumentCountForTarget; + /** + * Increment the number of acks needed from watch before we can consider the + * server to be 'in-sync' with the client's active targets. + */ + recordPendingTargetRequest(targetId: TargetId): void; + private ensureTargetState; + private ensureDocumentTargetMapping; + private ensureDocumentUpdateByTarget; + /** + * Verifies that the user is still interested in this target (by calling + * `getTargetDataForTarget()`) and that we are not waiting for pending ADDs + * from watch. + */ + protected isActiveTarget(targetId: TargetId): boolean; + /** + * Returns the TargetData for an active target (i.e. a target that the user + * is still interested in that has no outstanding target change requests). + */ + protected targetDataForActiveTarget(targetId: TargetId): TargetData | null; + /** + * Resets the state of a Watch target to its initial state (e.g. sets + * 'current' to false, clears the resume token and removes its target mapping + * from all documents). + */ + private resetTarget; + /** + * Returns whether the LocalStore considers the document to be part of the + * specified target. + */ + private targetContainsDocument; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/array.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/array.d.ts new file mode 100644 index 0000000..8be6593 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/array.d.ts @@ -0,0 +1,70 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Returns true iff the array contains the value using strong equality. + */ +export declare function includes(array: T[], value: T): boolean; +/** + * Returns true iff the array contains any value matching the predicate + */ +export declare function some(array: T[], predicate: (t: T) => boolean): boolean; +/** + * Calls predicate function for each item in the array until the predicate + * returns true, at which point the index of that item is returned. If the + * predicate does not return true for any item, null is returned. + */ +export declare function findIndex(array: A[], predicate: (value: A) => boolean): number | null; +/** + * Compares two array for equality using comparator. The method computes the + * intersection and invokes `onAdd` for every element that is in `after` but not + * `before`. `onRemove` is invoked for every element in `before` but missing + * from `after`. + * + * The method creates a copy of both `before` and `after` and runs in O(n log + * n), where n is the size of the two lists. + * + * @param before - The elements that exist in the original array. + * @param after - The elements to diff against the original array. + * @param comparator - The comparator for the elements in before and after. + * @param onAdd - A function to invoke for every element that is part of ` + * after` but not `before`. + * @param onRemove - A function to invoke for every element that is part of + * `before` but not `after`. + */ +export declare function diffArrays(before: T[], after: T[], comparator: (l: T, r: T) => number, onAdd: (entry: T) => void, onRemove: (entry: T) => void): void; +/** + * Verifies equality for an array of objects using the `isEqual` interface. + * + * @private + * @internal + * @param left Array of objects supporting `isEqual`. + * @param right Array of objects supporting `isEqual`. + * @return True if arrays are equal. + */ +export declare function isArrayEqual boolean; +}>(left: T[], right: T[]): boolean; +/** + * Verifies equality for an array of primitives. + * + * @private + * @internal + * @param left Array of primitives. + * @param right Array of primitives. + * @return True if arrays are equal. + */ +export declare function isPrimitiveArrayEqual(left: T[], right: T[]): boolean; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/assert.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/assert.d.ts new file mode 100644 index 0000000..294b08a --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/assert.d.ts @@ -0,0 +1,78 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Unconditionally fails, throwing an Error with the given message. + * Messages are stripped in production builds. + * + * Returns `never` and can be used in expressions: + * @example + * let futureVar = fail('not implemented yet'); + * + * @param code generate a new unique value with `yarn assertion-id:generate` + * Search for an existing value using `yarn assertion-id:find X` + */ +export declare function fail(code: number, message: string, context?: Record): never; +/** + * Unconditionally fails, throwing an Error with the given message. + * Messages are stripped in production builds. + * + * Returns `never` and can be used in expressions: + * @example + * let futureVar = fail('not implemented yet'); + * + * @param id generate a new unique value with `yarn assertion-id:generate` + * Search for an existing value using `yarn assertion-id:find X` + */ +export declare function fail(id: number, context?: Record): never; +/** + * Fails if the given assertion condition is false, throwing an Error with the + * given message if it did. + * + * Messages are stripped in production builds. + * + * @param id generate a new unique value with `yarn assertion-idgenerate`. + * Search for an existing value using `yarn assertion-id:find X` + */ +export declare function hardAssert(assertion: boolean, id: number, message: string, context?: Record): asserts assertion; +/** + * Fails if the given assertion condition is false, throwing an Error with the + * given message if it did. + * + * Messages are stripped in production builds. + * + * @param id generate a new unique value with `yarn assertion-id:generate`. + * Search for an existing value using `yarn assertion-id:find X` + */ +export declare function hardAssert(assertion: boolean, id: number, context?: Record): asserts assertion; +/** + * Fails if the given assertion condition is false, throwing an Error with the + * given message if it did. + * + * The code of callsites invoking this function are stripped out in production + * builds. Any side-effects of code within the debugAssert() invocation will not + * happen in this case. + * + * @internal + */ +export declare function debugAssert(assertion: boolean, message: string): asserts assertion; +/** + * Casts `obj` to `T`. In non-production builds, verifies that `obj` is an + * instance of `T` before casting. + */ +export declare function debugCast(obj: object, constructor: { + new (...args: any[]): T; +}): T | never; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/async_observer.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/async_observer.d.ts new file mode 100644 index 0000000..21a965e --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/async_observer.d.ts @@ -0,0 +1,31 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Observer } from '../core/event_manager'; +import { FirestoreError } from './error'; +export declare class AsyncObserver implements Observer { + private observer; + /** + * When set to true, will not raise future events. Necessary to deal with + * async detachment of listener. + */ + private muted; + constructor(observer: Partial>); + next(value: T): void; + error(error: FirestoreError): void; + mute(): void; + private scheduleEvent; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/async_queue.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/async_queue.d.ts new file mode 100644 index 0000000..098746b --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/async_queue.d.ts @@ -0,0 +1,180 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { FirestoreError } from './error'; +/** + * Wellknown "timer" IDs used when scheduling delayed operations on the + * AsyncQueue. These IDs can then be used from tests to check for the presence + * of operations or to run them early. + * + * The string values are used when encoding these timer IDs in JSON spec tests. + */ +export declare const enum TimerId { + /** All can be used with runDelayedOperationsEarly() to run all timers. */ + All = "all", + /** + * The following 5 timers are used in persistent_stream.ts for the listen and + * write streams. The "Idle" timer is used to close the stream due to + * inactivity. The "ConnectionBackoff" timer is used to restart a stream once + * the appropriate backoff delay has elapsed. The health check is used to mark + * a stream healthy if it has not received an error during its initial setup. + */ + ListenStreamIdle = "listen_stream_idle", + ListenStreamConnectionBackoff = "listen_stream_connection_backoff", + WriteStreamIdle = "write_stream_idle", + WriteStreamConnectionBackoff = "write_stream_connection_backoff", + HealthCheckTimeout = "health_check_timeout", + /** + * A timer used in online_state_tracker.ts to transition from + * OnlineState.Unknown to Offline after a set timeout, rather than waiting + * indefinitely for success or failure. + */ + OnlineStateTimeout = "online_state_timeout", + /** + * A timer used to update the client metadata in IndexedDb, which is used + * to determine the primary leaseholder. + */ + ClientMetadataRefresh = "client_metadata_refresh", + /** A timer used to periodically attempt LRU Garbage collection */ + LruGarbageCollection = "lru_garbage_collection", + /** + * A timer used to retry transactions. Since there can be multiple concurrent + * transactions, multiple of these may be in the queue at a given time. + */ + TransactionRetry = "transaction_retry", + /** + * A timer used to retry operations scheduled via retryable AsyncQueue + * operations. + */ + AsyncQueueRetry = "async_queue_retry", + /** + * A timer used to periodically attempt index backfill. + */ + IndexBackfill = "index_backfill" +} +/** + * Represents an operation scheduled to be run in the future on an AsyncQueue. + * + * It is created via DelayedOperation.createAndSchedule(). + * + * Supports cancellation (via cancel()) and early execution (via skipDelay()). + * + * Note: We implement `PromiseLike` instead of `Promise`, as the `Promise` type + * in newer versions of TypeScript defines `finally`, which is not available in + * IE. + */ +export declare class DelayedOperation implements PromiseLike { + private readonly asyncQueue; + readonly timerId: TimerId; + readonly targetTimeMs: number; + private readonly op; + private readonly removalCallback; + private timerHandle; + private readonly deferred; + private constructor(); + get promise(): Promise; + /** + * Creates and returns a DelayedOperation that has been scheduled to be + * executed on the provided asyncQueue after the provided delayMs. + * + * @param asyncQueue - The queue to schedule the operation on. + * @param id - A Timer ID identifying the type of operation this is. + * @param delayMs - The delay (ms) before the operation should be scheduled. + * @param op - The operation to run. + * @param removalCallback - A callback to be called synchronously once the + * operation is executed or canceled, notifying the AsyncQueue to remove it + * from its delayedOperations list. + * PORTING NOTE: This exists to prevent making removeDelayedOperation() and + * the DelayedOperation class public. + */ + static createAndSchedule(asyncQueue: AsyncQueue, timerId: TimerId, delayMs: number, op: () => Promise, removalCallback: (op: DelayedOperation) => void): DelayedOperation; + /** + * Starts the timer. This is called immediately after construction by + * createAndSchedule(). + */ + private start; + /** + * Queues the operation to run immediately (if it hasn't already been run or + * canceled). + */ + skipDelay(): void; + /** + * Cancels the operation if it hasn't already been executed or canceled. The + * promise will be rejected. + * + * As long as the operation has not yet been run, calling cancel() provides a + * guarantee that the operation will not be run. + */ + cancel(reason?: string): void; + then: (onfulfilled?: ((value: T) => TResult1 | PromiseLike) | null | undefined, onrejected?: ((reason: any) => TResult2 | PromiseLike) | null | undefined) => Promise; + private handleDelayElapsed; + private clearTimeout; +} +export interface AsyncQueue { + readonly isShuttingDown: boolean; + /** + * Adds a new operation to the queue without waiting for it to complete (i.e. + * we ignore the Promise result). + */ + enqueueAndForget(op: () => Promise): void; + /** + * Regardless if the queue has initialized shutdown, adds a new operation to the + * queue without waiting for it to complete (i.e. we ignore the Promise result). + */ + enqueueAndForgetEvenWhileRestricted(op: () => Promise): void; + /** + * Initialize the shutdown of this queue. Once this method is called, the + * only possible way to request running an operation is through + * `enqueueEvenWhileRestricted()`. + * + * @param purgeExistingTasks Whether already enqueued tasked should be + * rejected (unless enqueued with `enqueueEvenWhileRestricted()`). Defaults + * to false. + */ + enterRestrictedMode(purgeExistingTasks?: boolean): void; + /** + * Adds a new operation to the queue. Returns a promise that will be resolved + * when the promise returned by the new operation is (with its value). + */ + enqueue(op: () => Promise): Promise; + /** + * Enqueue a retryable operation. + * + * A retryable operation is rescheduled with backoff if it fails with a + * IndexedDbTransactionError (the error type used by SimpleDb). All + * retryable operations are executed in order and only run if all prior + * operations were retried successfully. + */ + enqueueRetryable(op: () => Promise): void; + /** + * Schedules an operation to be queued on the AsyncQueue once the specified + * `delayMs` has elapsed. The returned DelayedOperation can be used to cancel + * or fast-forward the operation prior to its running. + */ + enqueueAfterDelay(timerId: TimerId, delayMs: number, op: () => Promise): DelayedOperation; + /** + * Verifies there's an operation currently in-progress on the AsyncQueue. + * Unfortunately we can't verify that the running code is in the promise chain + * of that operation, so this isn't a foolproof check, but it should be enough + * to catch some bugs. + */ + verifyOperationInProgress(): void; +} +/** + * Returns a FirestoreError that can be surfaced to the user if the provided + * error is an IndexedDbTransactionError. Re-throws the error otherwise. + */ +export declare function wrapInUserErrorIfRecoverable(e: Error, msg: string): FirestoreError; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/async_queue_impl.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/async_queue_impl.d.ts new file mode 100644 index 0000000..6dedc85 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/async_queue_impl.d.ts @@ -0,0 +1,75 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { AsyncQueue, DelayedOperation, TimerId } from './async_queue'; +import { FirestoreError } from './error'; +export declare class AsyncQueueImpl implements AsyncQueue { + private tail; + private retryableOps; + private _isShuttingDown; + private delayedOperations; + failure: FirestoreError | null; + private operationInProgress; + private skipNonRestrictedTasks; + private timerIdsToSkip; + private backoff; + private visibilityHandler; + constructor(tail?: Promise); + get isShuttingDown(): boolean; + /** + * Adds a new operation to the queue without waiting for it to complete (i.e. + * we ignore the Promise result). + */ + enqueueAndForget(op: () => Promise): void; + enqueueAndForgetEvenWhileRestricted(op: () => Promise): void; + enterRestrictedMode(purgeExistingTasks?: boolean): void; + enqueue(op: () => Promise): Promise; + enqueueRetryable(op: () => Promise): void; + /** + * Runs the next operation from the retryable queue. If the operation fails, + * reschedules with backoff. + */ + private retryNextOp; + private enqueueInternal; + enqueueAfterDelay(timerId: TimerId, delayMs: number, op: () => Promise): DelayedOperation; + private verifyNotFailed; + verifyOperationInProgress(): void; + /** + * Waits until all currently queued tasks are finished executing. Delayed + * operations are not run. + */ + drain(): Promise; + /** + * For Tests: Determine if a delayed operation with a particular TimerId + * exists. + */ + containsDelayedOperation(timerId: TimerId): boolean; + /** + * For Tests: Runs some or all delayed operations early. + * + * @param lastTimerId - Delayed operations up to and including this TimerId + * will be drained. Pass TimerId.All to run all delayed operations. + * @returns a Promise that resolves once all operations have been run. + */ + runAllDelayedOperationsUntil(lastTimerId: TimerId): Promise; + /** + * For Tests: Skip all subsequent delays for a timer id. + */ + skipDelaysForTimerId(timerId: TimerId): void; + /** Called once a DelayedOperation is run or canceled. */ + private removeDelayedOperation; +} +export declare function newAsyncQueue(): AsyncQueue; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/base64_decode_error.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/base64_decode_error.d.ts new file mode 100644 index 0000000..18800ff --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/base64_decode_error.d.ts @@ -0,0 +1,22 @@ +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An error encountered while decoding base64 string. + */ +export declare class Base64DecodeError extends Error { + readonly name = "Base64DecodeError"; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/bundle_builder_impl.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/bundle_builder_impl.d.ts new file mode 100644 index 0000000..57e978c --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/bundle_builder_impl.d.ts @@ -0,0 +1,97 @@ +/** + * @license + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Firestore } from '../api/database'; +import { Query } from '../core/query'; +import { DocumentData } from '../lite-api/reference'; +import { Timestamp } from '../lite-api/timestamp'; +import { DocumentKey } from '../model/document_key'; +/** + * Builds a Firestore data bundle with results from the given document and query snapshots. + */ +export declare class BundleBuilder { + private firestore; + readonly bundleId: string; + private documents; + private namedQueries; + private latestReadTime; + private databaseId; + private readonly serializer; + private readonly userDataReader; + constructor(firestore: Firestore, bundleId: string); + /** + * Adds data from a DocumentSnapshot to the bundle. + * @internal + * @param docBundleData A DocumentSnapshotBundleData containing information from the + * DocumentSnapshot. Note we cannot accept a DocumentSnapshot directly due to a circular + * dependency error. + * @param queryName The name of the QuerySnapshot if this document is part of a Query. + */ + addBundleDocument(docBundleData: DocumentSnapshotBundleData, queryName?: string): void; + /** + * Adds data from a QuerySnapshot to the bundle. + * @internal + * @param docBundleData A QuerySnapshotBundleData containing information from the + * QuerySnapshot. Note we cannot accept a QuerySnapshot directly due to a circular + * dependency error. + */ + addBundleQuery(queryBundleData: QuerySnapshotBundleData): void; + /** + * Convert data from a DocumentSnapshot into the serialized form within a bundle. + * @private + * @internal + * @param docBundleData a DocumentSnapshotBundleData containing the data required to + * serialize a document. + */ + private toBundleDocument; + /** + * Converts a IBundleElement to a Buffer whose content is the length prefixed JSON representation + * of the element. + * @private + * @internal + * @param bundleElement A ProtoBundleElement that is expected to be Proto3 JSON compatible. + */ + private lengthPrefixedString; + /** + * Construct a serialized string containing document and query information that has previously + * been added to the BundleBuilder through the addBundleDocument and addBundleQuery methods. + * @internal + */ + build(): string; +} +/** + * Interface for an object that contains data required to bundle a DocumentSnapshot. + * @internal + */ +export interface DocumentSnapshotBundleData { + documentData: DocumentData; + documentKey: DocumentKey; + documentPath: string; + documentExists: boolean; + createdTime: Timestamp; + readTime?: Timestamp; + versionTime: Timestamp; +} +/** + * Interface for an object that contains data required to bundle a QuerySnapshot. + * @internal + */ +export interface QuerySnapshotBundleData { + name: string; + query: Query; + parent: string; + docBundleDataArray: DocumentSnapshotBundleData[]; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/bundle_reader.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/bundle_reader.d.ts new file mode 100644 index 0000000..cfe6dbd --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/bundle_reader.d.ts @@ -0,0 +1,67 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { BundleElement, BundleMetadata } from '../protos/firestore_bundle_proto'; +import { JsonProtoSerializer } from '../remote/serializer'; +/** + * A complete element in the bundle stream, together with the byte length it + * occupies in the stream. + */ +export declare class SizedBundleElement { + readonly payload: BundleElement; + readonly byteLength: number; + constructor(payload: BundleElement, byteLength: number); + isBundleMetadata(): boolean; +} +export type BundleSource = ReadableStream | ArrayBuffer | Uint8Array; +/** + * A class representing a bundle. + * + * Takes a bundle stream or buffer, and presents abstractions to read bundled + * elements out of the underlying content. + */ +export interface BundleReader { + serializer: JsonProtoSerializer; + close(): Promise; + /** + * Returns the metadata of the bundle. + */ + getMetadata(): Promise; + /** + * Returns the next BundleElement (together with its byte size in the bundle) + * that has not been read from underlying ReadableStream. Returns null if we + * have reached the end of the stream. + */ + nextElement(): Promise; +} +/** + * A class representing a synchronized bundle reader. + * + * Takes a bundle string buffer, parses the data, and provides accessors to the data contained + * within it. + */ +export interface BundleReaderSync { + serializer: JsonProtoSerializer; + /** + * Returns the metadata of the bundle. + */ + getMetadata(): BundleMetadata; + /** + * Returns BundleElements parsed from the bundle. Returns an empty array if no bundle elements + * exist. + */ + getElements(): SizedBundleElement[]; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/bundle_reader_impl.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/bundle_reader_impl.d.ts new file mode 100644 index 0000000..0858a93 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/bundle_reader_impl.d.ts @@ -0,0 +1,19 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { JsonProtoSerializer } from '../remote/serializer'; +import { BundleReader } from './bundle_reader'; +export declare function newBundleReader(reader: ReadableStreamDefaultReader, serializer: JsonProtoSerializer): BundleReader; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/bundle_reader_sync_impl.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/bundle_reader_sync_impl.d.ts new file mode 100644 index 0000000..638497f --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/bundle_reader_sync_impl.d.ts @@ -0,0 +1,59 @@ +/** + * @license + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { BundleMetadata } from '../protos/firestore_bundle_proto'; +import { JsonProtoSerializer } from '../remote/serializer'; +import { BundleReaderSync, SizedBundleElement } from './bundle_reader'; +/** + * A class that can parse a bundle form the string serialization of a bundle. + */ +export declare class BundleReaderSyncImpl implements BundleReaderSync { + private bundleData; + readonly serializer: JsonProtoSerializer; + private metadata; + private elements; + private cursor; + constructor(bundleData: string, serializer: JsonProtoSerializer); + getMetadata(): BundleMetadata; + getElements(): SizedBundleElement[]; + /** + * Parses the next element of the bundle. + * + * @returns a SizedBundleElement representation of the next element in the bundle, or null if + * no more elements exist. + */ + private nextElement; + /** + * Reads from a specified position from the bundleData string, for a specified + * number of bytes. + * + * @param length how many characters to read. + * @returns a string parsed from the bundle. + */ + private readJsonString; + /** + * Reads from the current cursor until the first '{'. + * + * @returns A string to integer represention of the parsed value. + * @throws An {@link Error} if the cursor has reached the end of the stream, since lengths + * prefix bundle objects. + */ + private readLength; +} +/** + * Creates an instance of BundleReader without exposing the BundleReaderSyncImpl class type. + */ +export declare function newBundleReaderSync(bundleData: string, serializer: JsonProtoSerializer): BundleReaderSync; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/byte_stream.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/byte_stream.d.ts new file mode 100644 index 0000000..72d8ed7 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/byte_stream.d.ts @@ -0,0 +1,29 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * How many bytes to read each time when `ReadableStreamReader.read()` is + * called. Only applicable for byte streams that we control (e.g. those backed + * by an UInt8Array). + */ +export declare const DEFAULT_BYTES_PER_READ = 10240; +/** + * Builds a `ByteStreamReader` from a UInt8Array. + * @param source - The data source to use. + * @param bytesPerRead - How many bytes each `read()` from the returned reader + * will read. + */ +export declare function toByteStreamReaderHelper(source: Uint8Array, bytesPerRead?: number): ReadableStreamDefaultReader; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/byte_string.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/byte_string.d.ts new file mode 100644 index 0000000..9aec389 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/byte_string.d.ts @@ -0,0 +1,46 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Immutable class that represents a "proto" byte string. + * + * Proto byte strings can either be Base64-encoded strings or Uint8Arrays when + * sent on the wire. This class abstracts away this differentiation by holding + * the proto byte string in a common class that must be converted into a string + * before being sent as a proto. + * @internal + */ +export declare class ByteString { + private readonly binaryString; + static readonly EMPTY_BYTE_STRING: ByteString; + private constructor(); + static fromBase64String(base64: string): ByteString; + static fromUint8Array(array: Uint8Array): ByteString; + [Symbol.iterator](): Iterator; + toBase64(): string; + toUint8Array(): Uint8Array; + approximateByteSize(): number; + compareTo(other: ByteString): number; + isEqual(other: ByteString): boolean; +} +/** + * Helper function to convert an Uint8array to a binary string. + */ +export declare function binaryStringFromUint8Array(array: Uint8Array): string; +/** + * Helper function to convert a binary string to an Uint8Array. + */ +export declare function uint8ArrayFromBinaryString(binaryString: string): Uint8Array; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/debug_uid.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/debug_uid.d.ts new file mode 100644 index 0000000..b590233 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/debug_uid.d.ts @@ -0,0 +1,28 @@ +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Generates and returns a unique ID as a hexadecimal string. + * + * The returned ID is intended to be used in debug logging messages to help + * correlate log messages that may be spatially separated in the logs, but + * logically related. For example, a network connection could include the same + * "debug ID" string in all of its log messages to help trace a specific + * connection over time. + * + * @return the 10-character generated ID (e.g. "0xa1b2c3d4"). + */ +export declare function generateUniqueDebugId(): string; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/error.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/error.d.ts new file mode 100644 index 0000000..e49c172 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/error.d.ts @@ -0,0 +1,195 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { FirebaseError } from '@firebase/util'; +/** + * The set of Firestore status codes. The codes are the same at the ones + * exposed by gRPC here: + * https://github.com/grpc/grpc/blob/master/doc/statuscodes.md + * + * Possible values: + * - 'cancelled': The operation was cancelled (typically by the caller). + * - 'unknown': Unknown error or an error from a different error domain. + * - 'invalid-argument': Client specified an invalid argument. Note that this + * differs from 'failed-precondition'. 'invalid-argument' indicates + * arguments that are problematic regardless of the state of the system + * (e.g. an invalid field name). + * - 'deadline-exceeded': Deadline expired before operation could complete. + * For operations that change the state of the system, this error may be + * returned even if the operation has completed successfully. For example, + * a successful response from a server could have been delayed long enough + * for the deadline to expire. + * - 'not-found': Some requested document was not found. + * - 'already-exists': Some document that we attempted to create already + * exists. + * - 'permission-denied': The caller does not have permission to execute the + * specified operation. + * - 'resource-exhausted': Some resource has been exhausted, perhaps a + * per-user quota, or perhaps the entire file system is out of space. + * - 'failed-precondition': Operation was rejected because the system is not + * in a state required for the operation's execution. + * - 'aborted': The operation was aborted, typically due to a concurrency + * issue like transaction aborts, etc. + * - 'out-of-range': Operation was attempted past the valid range. + * - 'unimplemented': Operation is not implemented or not supported/enabled. + * - 'internal': Internal errors. Means some invariants expected by + * underlying system has been broken. If you see one of these errors, + * something is very broken. + * - 'unavailable': The service is currently unavailable. This is most likely + * a transient condition and may be corrected by retrying with a backoff. + * - 'data-loss': Unrecoverable data loss or corruption. + * - 'unauthenticated': The request does not have valid authentication + * credentials for the operation. + */ +export type FirestoreErrorCode = 'cancelled' | 'unknown' | 'invalid-argument' | 'deadline-exceeded' | 'not-found' | 'already-exists' | 'permission-denied' | 'resource-exhausted' | 'failed-precondition' | 'aborted' | 'out-of-range' | 'unimplemented' | 'internal' | 'unavailable' | 'data-loss' | 'unauthenticated'; +/** + * Error Codes describing the different ways Firestore can fail. These come + * directly from GRPC. + */ +export type Code = FirestoreErrorCode; +export declare const Code: { + /** Not an error; returned on success. */ + OK: FirestoreErrorCode; + /** The operation was cancelled (typically by the caller). */ + CANCELLED: FirestoreErrorCode; + /** Unknown error or an error from a different error domain. */ + UNKNOWN: FirestoreErrorCode; + /** + * Client specified an invalid argument. Note that this differs from + * FAILED_PRECONDITION. INVALID_ARGUMENT indicates arguments that are + * problematic regardless of the state of the system (e.g., a malformed file + * name). + */ + INVALID_ARGUMENT: FirestoreErrorCode; + /** + * Deadline expired before operation could complete. For operations that + * change the state of the system, this error may be returned even if the + * operation has completed successfully. For example, a successful response + * from a server could have been delayed long enough for the deadline to + * expire. + */ + DEADLINE_EXCEEDED: FirestoreErrorCode; + /** Some requested entity (e.g., file or directory) was not found. */ + NOT_FOUND: FirestoreErrorCode; + /** + * Some entity that we attempted to create (e.g., file or directory) already + * exists. + */ + ALREADY_EXISTS: FirestoreErrorCode; + /** + * The caller does not have permission to execute the specified operation. + * PERMISSION_DENIED must not be used for rejections caused by exhausting + * some resource (use RESOURCE_EXHAUSTED instead for those errors). + * PERMISSION_DENIED must not be used if the caller cannot be identified + * (use UNAUTHENTICATED instead for those errors). + */ + PERMISSION_DENIED: FirestoreErrorCode; + /** + * The request does not have valid authentication credentials for the + * operation. + */ + UNAUTHENTICATED: FirestoreErrorCode; + /** + * Some resource has been exhausted, perhaps a per-user quota, or perhaps the + * entire file system is out of space. + */ + RESOURCE_EXHAUSTED: FirestoreErrorCode; + /** + * Operation was rejected because the system is not in a state required for + * the operation's execution. For example, directory to be deleted may be + * non-empty, an rmdir operation is applied to a non-directory, etc. + * + * A litmus test that may help a service implementor in deciding + * between FAILED_PRECONDITION, ABORTED, and UNAVAILABLE: + * (a) Use UNAVAILABLE if the client can retry just the failing call. + * (b) Use ABORTED if the client should retry at a higher-level + * (e.g., restarting a read-modify-write sequence). + * (c) Use FAILED_PRECONDITION if the client should not retry until + * the system state has been explicitly fixed. E.g., if an "rmdir" + * fails because the directory is non-empty, FAILED_PRECONDITION + * should be returned since the client should not retry unless + * they have first fixed up the directory by deleting files from it. + * (d) Use FAILED_PRECONDITION if the client performs conditional + * REST Get/Update/Delete on a resource and the resource on the + * server does not match the condition. E.g., conflicting + * read-modify-write on the same resource. + */ + FAILED_PRECONDITION: FirestoreErrorCode; + /** + * The operation was aborted, typically due to a concurrency issue like + * sequencer check failures, transaction aborts, etc. + * + * See litmus test above for deciding between FAILED_PRECONDITION, ABORTED, + * and UNAVAILABLE. + */ + ABORTED: FirestoreErrorCode; + /** + * Operation was attempted past the valid range. E.g., seeking or reading + * past end of file. + * + * Unlike INVALID_ARGUMENT, this error indicates a problem that may be fixed + * if the system state changes. For example, a 32-bit file system will + * generate INVALID_ARGUMENT if asked to read at an offset that is not in the + * range [0,2^32-1], but it will generate OUT_OF_RANGE if asked to read from + * an offset past the current file size. + * + * There is a fair bit of overlap between FAILED_PRECONDITION and + * OUT_OF_RANGE. We recommend using OUT_OF_RANGE (the more specific error) + * when it applies so that callers who are iterating through a space can + * easily look for an OUT_OF_RANGE error to detect when they are done. + */ + OUT_OF_RANGE: FirestoreErrorCode; + /** Operation is not implemented or not supported/enabled in this service. */ + UNIMPLEMENTED: FirestoreErrorCode; + /** + * Internal errors. Means some invariants expected by underlying System has + * been broken. If you see one of these errors, Something is very broken. + */ + INTERNAL: FirestoreErrorCode; + /** + * The service is currently unavailable. This is a most likely a transient + * condition and may be corrected by retrying with a backoff. + * + * See litmus test above for deciding between FAILED_PRECONDITION, ABORTED, + * and UNAVAILABLE. + */ + UNAVAILABLE: FirestoreErrorCode; + /** Unrecoverable data loss or corruption. */ + DATA_LOSS: FirestoreErrorCode; +}; +/** An error returned by a Firestore operation. */ +export declare class FirestoreError extends FirebaseError { + /** + * The backend error code associated with this error. + */ + readonly code: FirestoreErrorCode; + /** + * A custom error description. + */ + readonly message: string; + /** The stack of the error. */ + readonly stack?: string; + /** @hideconstructor */ + constructor( + /** + * The backend error code associated with this error. + */ + code: FirestoreErrorCode, + /** + * A custom error description. + */ + message: string); +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/input_validation.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/input_validation.d.ts new file mode 100644 index 0000000..c62ae20 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/input_validation.d.ts @@ -0,0 +1,56 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { ResourcePath } from '../model/path'; +/** Types accepted by validateType() and related methods for validation. */ +export type ValidationType = 'undefined' | 'object' | 'function' | 'boolean' | 'number' | 'string' | 'non-empty string'; +export declare function validateNonEmptyArgument(functionName: string, argumentName: string, argument?: string): asserts argument is string; +/** + * Validates that two boolean options are not set at the same time. + * @internal + */ +export declare function validateIsNotUsedTogether(optionName1: string, argument1: boolean | undefined, optionName2: string, argument2: boolean | undefined): void; +/** + * Validates that `path` refers to a document (indicated by the fact it contains + * an even numbers of segments). + */ +export declare function validateDocumentPath(path: ResourcePath): void; +/** + * Validates that `path` refers to a collection (indicated by the fact it + * contains an odd numbers of segments). + */ +export declare function validateCollectionPath(path: ResourcePath): void; +/** + * Returns true if it's a non-null object without a custom prototype + * (i.e. excludes Array, Date, etc.). + */ +export declare function isPlainObject(input: unknown): boolean; +/** Returns a string describing the type / value of the provided input. */ +export declare function valueDescription(input: unknown): string; +/** try to get the constructor name for an object. */ +export declare function tryGetCustomObjectType(input: object): string | null; +/** + * Casts `obj` to `T`, optionally unwrapping Compat types to expose the + * underlying instance. Throws if `obj` is not an instance of `T`. + * + * This cast is used in the Lite and Full SDK to verify instance types for + * arguments passed to the public API. + * @internal + */ +export declare function cast(obj: object, constructor: { + new (...args: any[]): T; +}): T | never; +export declare function validatePositiveNumber(functionName: string, n: number): void; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/json_validation.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/json_validation.d.ts new file mode 100644 index 0000000..df52006 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/json_validation.d.ts @@ -0,0 +1,70 @@ +/** + * @license + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A list of data types Firestore objects may serialize in their toJSON implemenetations. + * @private + * @internal + */ +export type JsonTypeDesc = 'object' | 'string' | 'number' | 'boolean' | 'null' | 'undefined'; +/** + * An association of JsonTypeDesc values to their native types. + * @private + * @internal + */ +export type TSType = T extends 'object' ? object : T extends 'string' ? string : T extends 'number' ? number : T extends 'boolean' ? boolean : T extends 'null' ? null : T extends 'undefined' ? undefined : never; +/** + * The representation of a JSON object property name and its type value. + * @private + * @internal + */ +export interface Property { + value?: TSType; + typeString: JsonTypeDesc; +} +/** + * A type Firestore data types may use to define the fields used in their JSON serialization. + * @private + * @internal + */ +export interface JsonSchema { + [key: string]: Property; +} +/** + * Associates the JSON property type to the native type and sets them to be Required. + * @private + * @internal + */ +export type Json = { + [K in keyof T]: Required['value']; +}; +/** + * Helper function to define a JSON schema {@link Property}. + * @private + * @internal + */ +export declare function property(typeString: T, optionalValue?: TSType): Property; +/** + * Validates the JSON object based on the provided schema, and narrows the type to the provided + * JSON schema. + * @private + * @internal + * + * @param json A JSON object to validate. + * @param scheme a {@link JsonSchema} that defines the properties to validate. + * @returns true if the JSON schema exists within the object. Throws a FirestoreError otherwise. + */ +export declare function validateJSON(json: object, schema: S): json is Json; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/log.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/log.d.ts new file mode 100644 index 0000000..f638baa --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/log.d.ts @@ -0,0 +1,39 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { LogLevel, LogLevelString } from '@firebase/logger'; +export { LogLevel, LogLevelString }; +export declare function getLogLevel(): LogLevel; +/** + * Sets the verbosity of Cloud Firestore logs (debug, error, or silent). + * + * @param logLevel - The verbosity you set for activity and error logging. Can + * be any of the following values: + * + *

+ */ +export declare function setLogLevel(logLevel: LogLevelString): void; +export declare function logDebug(msg: string, ...obj: unknown[]): void; +export declare function logError(msg: string, ...obj: unknown[]): void; +/** + * @internal + */ +export declare function logWarn(msg: string, ...obj: unknown[]): void; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/logic_utils.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/logic_utils.d.ts new file mode 100644 index 0000000..2333586 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/logic_utils.d.ts @@ -0,0 +1,52 @@ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { CompositeFilter, Filter } from '../core/filter'; +/** + * Provides utility functions that help with boolean logic transformations needed for handling + * complex filters used in queries. + */ +/** + * The `in` filter is only a syntactic sugar over a disjunction of equalities. For instance: `a in + * [1,2,3]` is in fact `a==1 || a==2 || a==3`. This method expands any `in` filter in the given + * input into a disjunction of equality filters and returns the expanded filter. + */ +export declare function computeInExpansion(filter: Filter): Filter; +/** + * Given a composite filter, returns the list of terms in its disjunctive normal form. + * + *

Each element in the return value is one term of the resulting DNF. For instance: For the + * input: (A || B) && C, the DNF form is: (A && C) || (B && C), and the return value is a list + * with two elements: a composite filter that performs (A && C), and a composite filter that + * performs (B && C). + * + * @param filter the composite filter to calculate DNF transform for. + * @return the terms in the DNF transform. + */ +export declare function getDnfTerms(filter: CompositeFilter): Filter[]; +export declare function computeDistributedNormalForm(filter: Filter): Filter; +export declare function applyDistribution(lhs: Filter, rhs: Filter): Filter; +/** + * Applies the associativity property to the given filter and returns the resulting filter. + * + *

    + *
  • A | (B | C) == (A | B) | C == (A | B | C) + *
  • A & (B & C) == (A & B) & C == (A & B & C) + *
+ * + *

For more info, visit: https://en.wikipedia.org/wiki/Associative_property#Propositional_logic + */ +export declare function applyAssociation(filter: Filter): Filter; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/misc.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/misc.d.ts new file mode 100644 index 0000000..95d4d43 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/misc.d.ts @@ -0,0 +1,46 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export type EventHandler = (value: E) => void; +export interface Indexable { + [k: string]: unknown; +} +/** + * A utility class for generating unique alphanumeric IDs of a specified length. + * + * @internal + * Exported internally for testing purposes. + */ +export declare class AutoId { + static newId(): string; +} +export declare function primitiveComparator(left: T, right: T): number; +export interface Equatable { + isEqual(other: T): boolean; +} +/** Compare strings in UTF-8 encoded byte order */ +export declare function compareUtf8Strings(left: string, right: string): number; +export declare function isSurrogate(s: string): boolean; +export interface Iterable { + forEach: (cb: (v: V) => void) => void; +} +/** Helper to compare arrays using isEqual(). */ +export declare function arrayEquals(left: T[], right: T[], comparator: (l: T, r: T) => boolean): boolean; +/** + * Returns the immediate lexicographically-following string. This is useful to + * construct an inclusive range for indexeddb iterators. + */ +export declare function immediateSuccessor(s: string): string; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/node_api.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/node_api.d.ts new file mode 100644 index 0000000..2285e8e --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/node_api.d.ts @@ -0,0 +1,58 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Creates a node-style callback that resolves or rejects a new Promise. The + * callback is passed to the given action which can then use the callback as + * a parameter to a node-style function. + * + * The intent is to directly bridge a node-style function (which takes a + * callback) into a Promise without manually converting between the node-style + * callback and the promise at each call. + * + * In effect it allows you to convert: + * + * @example + * new Promise((resolve: (value?: fs.Stats) => void, + * reject: (error?: any) => void) => { + * fs.stat(path, (error?: any, stat?: fs.Stats) => { + * if (error) { + * reject(error); + * } else { + * resolve(stat); + * } + * }); + * }); + * + * Into + * @example + * nodePromise((callback: NodeCallback) => { + * fs.stat(path, callback); + * }); + * + * @param action - a function that takes a node-style callback as an argument + * and then uses that callback to invoke some node-style API. + * @returns a new Promise which will be rejected if the callback is given the + * first Error parameter or will resolve to the value given otherwise. + */ +export declare function nodePromise(action: (callback: NodeCallback) => void): Promise; +/** + * A node-style callback which passes an Error as the first argument if there + * was an error, or passes null and a proper value + */ +export interface NodeCallback { + (error?: unknown, value?: R): void; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/obj.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/obj.d.ts new file mode 100644 index 0000000..90bf468 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/obj.d.ts @@ -0,0 +1,23 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export interface Dict { + [stringKey: string]: V; +} +export declare function objectSize(obj: object): number; +export declare function forEach(obj: Dict | undefined, fn: (key: string, val: V) => void): void; +export declare function mapToArray(obj: Dict, fn: (element: V, key: string, obj: Dict) => R): R[]; +export declare function isEmpty(obj: Dict): boolean; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/obj_map.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/obj_map.d.ts new file mode 100644 index 0000000..f858bcf --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/obj_map.d.ts @@ -0,0 +1,48 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A map implementation that uses objects as keys. Objects must have an + * associated equals function and must be immutable. Entries in the map are + * stored together with the key being produced from the mapKeyFn. This map + * automatically handles collisions of keys. + */ +export declare class ObjectMap { + private mapKeyFn; + private equalsFn; + /** + * The inner map for a key/value pair. Due to the possibility of collisions we + * keep a list of entries that we do a linear search through to find an actual + * match. Note that collisions should be rare, so we still expect near + * constant time lookups in practice. + */ + private inner; + /** The number of entries stored in the map */ + private innerSize; + constructor(mapKeyFn: (key: KeyType) => string, equalsFn: (l: KeyType, r: KeyType) => boolean); + /** Get a value for this key, or undefined if it does not exist. */ + get(key: KeyType): ValueType | undefined; + has(key: KeyType): boolean; + /** Put this key and value in the map. */ + set(key: KeyType, value: ValueType): void; + /** + * Remove this key from the map. Returns a boolean if anything was deleted. + */ + delete(key: KeyType): boolean; + forEach(fn: (key: KeyType, val: ValueType) => void): void; + isEmpty(): boolean; + size(): number; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/promise.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/promise.d.ts new file mode 100644 index 0000000..f966068 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/promise.d.ts @@ -0,0 +1,34 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export interface Resolver { + (value: R | Promise): void; +} +export interface Rejecter { + (reason?: Error): void; +} +export declare class Deferred { + promise: Promise; + resolve: Resolver; + reject: Rejecter; + constructor(); +} +/** + * Takes an array of values and a function from a value to a Promise. The function is run on each + * value sequentially, waiting for the previous promise to resolve before starting the next one. + * The returned promise resolves once the function has been run on all values. + */ +export declare function sequence(values: T[], fn: (value: T) => Promise): Promise; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/sorted_map.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/sorted_map.d.ts new file mode 100644 index 0000000..5060fa5 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/sorted_map.d.ts @@ -0,0 +1,100 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export type Comparator = (key1: K, key2: K) => number; +export interface Entry { + key: K; + value: V; +} +export declare class SortedMap { + comparator: Comparator; + root: LLRBNode | LLRBEmptyNode; + constructor(comparator: Comparator, root?: LLRBNode | LLRBEmptyNode); + insert(key: K, value: V): SortedMap; + remove(key: K): SortedMap; + get(key: K): V | null; + indexOf(key: K): number; + isEmpty(): boolean; + get size(): number; + minKey(): K | null; + maxKey(): K | null; + inorderTraversal(action: (k: K, v: V) => T): T; + forEach(fn: (k: K, v: V) => void): void; + toString(): string; + reverseTraversal(action: (k: K, v: V) => T): T; + getIterator(): SortedMapIterator; + getIteratorFrom(key: K): SortedMapIterator; + getReverseIterator(): SortedMapIterator; + getReverseIteratorFrom(key: K): SortedMapIterator; +} +export declare class SortedMapIterator { + private isReverse; + private nodeStack; + constructor(node: LLRBNode | LLRBEmptyNode, startKey: K | null, comparator: Comparator, isReverse: boolean); + getNext(): Entry; + hasNext(): boolean; + peek(): Entry | null; +} +export declare class LLRBNode { + key: K; + value: V; + readonly color: boolean; + readonly left: LLRBNode | LLRBEmptyNode; + readonly right: LLRBNode | LLRBEmptyNode; + readonly size: number; + static EMPTY: LLRBEmptyNode; + static RED: boolean; + static BLACK: boolean; + constructor(key: K, value: V, color?: boolean, left?: LLRBNode | LLRBEmptyNode, right?: LLRBNode | LLRBEmptyNode); + copy(key: K | null, value: V | null, color: boolean | null, left: LLRBNode | LLRBEmptyNode | null, right: LLRBNode | LLRBEmptyNode | null): LLRBNode; + isEmpty(): boolean; + inorderTraversal(action: (k: K, v: V) => T): T; + reverseTraversal(action: (k: K, v: V) => T): T; + private min; + minKey(): K | null; + maxKey(): K | null; + insert(key: K, value: V, comparator: Comparator): LLRBNode; + private removeMin; + remove(key: K, comparator: Comparator): LLRBNode | LLRBEmptyNode; + isRed(): boolean; + private fixUp; + private moveRedLeft; + private moveRedRight; + private rotateLeft; + private rotateRight; + private colorFlip; + checkMaxDepth(): boolean; + protected check(): number; +} +export declare class LLRBEmptyNode { + get key(): never; + get value(): never; + get color(): never; + get left(): never; + get right(): never; + size: number; + copy(key: K | null, value: V | null, color: boolean | null, left: LLRBNode | LLRBEmptyNode | null, right: LLRBNode | LLRBEmptyNode | null): LLRBEmptyNode; + insert(key: K, value: V, comparator: Comparator): LLRBNode; + remove(key: K, comparator: Comparator): LLRBEmptyNode; + isEmpty(): boolean; + inorderTraversal(action: (k: K, v: V) => boolean): boolean; + reverseTraversal(action: (k: K, v: V) => boolean): boolean; + minKey(): K | null; + maxKey(): K | null; + isRed(): boolean; + checkMaxDepth(): boolean; + protected check(): 0; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/sorted_set.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/sorted_set.d.ts new file mode 100644 index 0000000..ff6aedc --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/sorted_set.d.ts @@ -0,0 +1,80 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { SortedMapIterator } from './sorted_map'; +/** + * SortedSet is an immutable (copy-on-write) collection that holds elements + * in order specified by the provided comparator. + * + * NOTE: if provided comparator returns 0 for two elements, we consider them to + * be equal! + */ +export declare class SortedSet { + private comparator; + private data; + constructor(comparator: (left: T, right: T) => number); + has(elem: T): boolean; + first(): T | null; + last(): T | null; + get size(): number; + indexOf(elem: T): number; + /** Iterates elements in order defined by "comparator" */ + forEach(cb: (elem: T) => void): void; + /** Iterates over `elem`s such that: range[0] <= elem < range[1]. */ + forEachInRange(range: [T, T], cb: (elem: T) => void): void; + /** + * Iterates over `elem`s such that: start <= elem until false is returned. + */ + forEachWhile(cb: (elem: T) => boolean, start?: T): void; + /** Finds the least element greater than or equal to `elem`. */ + firstAfterOrEqual(elem: T): T | null; + getIterator(): SortedSetIterator; + getIteratorFrom(key: T): SortedSetIterator; + /** Inserts or updates an element */ + add(elem: T): SortedSet; + /** Deletes an element */ + delete(elem: T): SortedSet; + isEmpty(): boolean; + unionWith(other: SortedSet): SortedSet; + isEqual(other: SortedSet): boolean; + toArray(): T[]; + toString(): string; + private copy; +} +export declare class SortedSetIterator { + private iter; + constructor(iter: SortedMapIterator); + getNext(): T; + hasNext(): boolean; +} +/** + * Compares two sorted sets for equality using their natural ordering. The + * method computes the intersection and invokes `onAdd` for every element that + * is in `after` but not `before`. `onRemove` is invoked for every element in + * `before` but missing from `after`. + * + * The method creates a copy of both `before` and `after` and runs in O(n log + * n), where n is the size of the two lists. + * + * @param before - The elements that exist in the original set. + * @param after - The elements to diff against the original set. + * @param comparator - The comparator for the elements in before and after. + * @param onAdd - A function to invoke for every element that is part of ` + * after` but not `before`. + * @param onRemove - A function to invoke for every element that is part of + * `before` but not `after`. + */ +export declare function diffSortedSets(before: SortedSet, after: SortedSet, comparator: (l: T, r: T) => number, onAdd: (entry: T) => void, onRemove: (entry: T) => void): void; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/testing_hooks.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/testing_hooks.d.ts new file mode 100644 index 0000000..90c6a65 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/testing_hooks.d.ts @@ -0,0 +1,52 @@ +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Unsubscribe } from '../api/reference_impl'; +import { ExistenceFilterMismatchInfo } from './testing_hooks_spi'; +/** + * Testing hooks for use by Firestore's integration test suite to reach into the + * SDK internals to validate logic and behavior that is not visible from the + * public API surface. + * + * @internal + */ +export declare class TestingHooks { + private constructor(); + /** + * Registers a callback to be notified when an existence filter mismatch + * occurs in the Watch listen stream. + * + * The relative order in which callbacks are notified is unspecified; do not + * rely on any particular ordering. If a given callback is registered multiple + * times then it will be notified multiple times, once per registration. + * + * @param callback the callback to invoke upon existence filter mismatch. + * + * @return a function that, when called, unregisters the given callback; only + * the first invocation of the returned function does anything; all subsequent + * invocations do nothing. + */ + static onExistenceFilterMismatch(callback: ExistenceFilterMismatchCallback): Unsubscribe; +} +/** + * The signature of callbacks registered with + * `TestingUtils.onExistenceFilterMismatch()`. + * + * The return value, if any, is ignored. + * + * @internal + */ +export type ExistenceFilterMismatchCallback = (info: ExistenceFilterMismatchInfo) => unknown; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/testing_hooks_spi.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/testing_hooks_spi.d.ts new file mode 100644 index 0000000..3d456e9 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/testing_hooks_spi.d.ts @@ -0,0 +1,93 @@ +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * The global, singleton instance of TestingHooksSpi. + * + * This variable will be `null` in all cases _except_ when running from + * integration tests that have registered callbacks to be notified of events + * that happen during the test execution. + */ +export declare let testingHooksSpi: TestingHooksSpi | null; +/** + * Sets the value of the `testingHooksSpi` object. + * @param instance the instance to set. + */ +export declare function setTestingHooksSpi(instance: TestingHooksSpi): void; +/** + * The "service provider interface" for the testing hooks. + * + * The implementation of this object will handle the callbacks made by the SDK + * to be handled by the integration tests. + * + * This "SPI" is separated from the implementation to avoid import cycles and + * to enable production builds to fully tree-shake away the testing hooks logic. + */ +export interface TestingHooksSpi { + /** + * Invokes all callbacks registered with + * `TestingHooks.onExistenceFilterMismatch()` with the given info. + */ + notifyOnExistenceFilterMismatch(info: ExistenceFilterMismatchInfo): void; +} +/** + * Information about an existence filter mismatch. + * @internal + */ +export interface ExistenceFilterMismatchInfo { + /** The number of documents that matched the query in the local cache. */ + localCacheCount: number; + /** + * The number of documents that matched the query on the server, as specified + * in the ExistenceFilter message's `count` field. + */ + existenceFilterCount: number; + /** + * The projectId used when checking documents for membership in the bloom + * filter. + */ + projectId: string; + /** + * The databaseId used when checking documents for membership in the bloom + * filter. + */ + databaseId: string; + /** + * Information about the bloom filter provided by Watch in the ExistenceFilter + * message's `unchangedNames` field. If this property is omitted or undefined + * then that means that Watch did _not_ provide a bloom filter. + */ + bloomFilter?: { + /** + * Whether a full requery was averted by using the bloom filter. If false, + * then something happened, such as a false positive, to prevent using the + * bloom filter to avoid a full requery. + */ + applied: boolean; + /** The number of hash functions used in the bloom filter. */ + hashCount: number; + /** The number of bytes in the bloom filter's bitmask. */ + bitmapLength: number; + /** The number of bits of padding in the last byte of the bloom filter. */ + padding: number; + /** + * Tests the given string for membership in the bloom filter created from + * the existence filter; will be undefined if creating the bloom filter + * failed. + */ + mightContain?: (value: string) => boolean; + }; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/types.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/types.d.ts new file mode 100644 index 0000000..a6842fe --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/types.d.ts @@ -0,0 +1,45 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Sentinel value that sorts before any Mutation Batch ID. */ +export declare const BATCHID_UNKNOWN = -1; +export interface StringMap { + [key: string]: string; +} +/** + * Returns whether a variable is either undefined or null. + */ +export declare function isNullOrUndefined(value: unknown): value is null | undefined; +/** Returns whether the value represents -0. */ +export declare function isNegativeZero(value: number): boolean; +/** + * Returns whether a value is an integer and in the safe integer range + * @param value - The value to test for being an integer and in the safe range + */ +export declare function isSafeInteger(value: unknown): boolean; +/** The subset of the browser's Window interface used by the SDK. */ +export interface WindowLike { + readonly localStorage: Storage; + readonly indexedDB: IDBFactory | null; + addEventListener(type: string, listener: EventListener): void; + removeEventListener(type: string, listener: EventListener): void; +} +/** The subset of the browser's Document interface used by the SDK. */ +export interface DocumentLike { + readonly visibilityState: DocumentVisibilityState; + addEventListener(type: string, listener: EventListener): void; + removeEventListener(type: string, listener: EventListener): void; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/aggregation.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/aggregation.test.d.ts new file mode 100644 index 0000000..9b0c1ff --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/aggregation.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/array_transforms.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/array_transforms.test.d.ts new file mode 100644 index 0000000..c53048a --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/array_transforms.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/batch_writes.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/batch_writes.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/batch_writes.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/bundle.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/bundle.test.d.ts new file mode 100644 index 0000000..e2ec7a1 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/bundle.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export declare const encoder: TextEncoder; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/composite_index_query.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/composite_index_query.test.d.ts new file mode 100644 index 0000000..615869e --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/composite_index_query.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/cursor.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/cursor.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/cursor.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/database.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/database.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/database.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/fields.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/fields.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/fields.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/get_options.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/get_options.test.d.ts new file mode 100644 index 0000000..c53048a --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/get_options.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/index_configuration.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/index_configuration.test.d.ts new file mode 100644 index 0000000..daa6d5d --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/index_configuration.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/numeric_transforms.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/numeric_transforms.test.d.ts new file mode 100644 index 0000000..c53048a --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/numeric_transforms.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/persistent_cache_index_manager.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/persistent_cache_index_manager.test.d.ts new file mode 100644 index 0000000..615869e --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/persistent_cache_index_manager.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/provider.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/provider.test.d.ts new file mode 100644 index 0000000..9b0c1ff --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/provider.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/query.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/query.test.d.ts new file mode 100644 index 0000000..777341d --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/query.test.d.ts @@ -0,0 +1,18 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { DocumentChange, DocumentChangeType } from '../util/firebase_export'; +export declare function verifyDocumentChange(change: DocumentChange, id: string, oldIndex: number, newIndex: number, type: DocumentChangeType): void; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/server_timestamp.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/server_timestamp.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/server_timestamp.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/smoke.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/smoke.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/smoke.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/snapshot_listener_source.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/snapshot_listener_source.test.d.ts new file mode 100644 index 0000000..88c3c0e --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/snapshot_listener_source.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/transactions.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/transactions.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/transactions.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/type.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/type.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/type.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/validation.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/validation.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/validation.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api_internal/auth.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api_internal/auth.test.d.ts new file mode 100644 index 0000000..daa6d5d --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api_internal/auth.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api_internal/database.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api_internal/database.test.d.ts new file mode 100644 index 0000000..1c93d90 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api_internal/database.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api_internal/idle_timeout.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api_internal/idle_timeout.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api_internal/idle_timeout.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api_internal/transaction.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api_internal/transaction.test.d.ts new file mode 100644 index 0000000..1c93d90 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api_internal/transaction.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/bootstrap.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/bootstrap.d.ts new file mode 100644 index 0000000..1391c20 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/bootstrap.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import '../../src/index'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/browser/indexeddb.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/browser/indexeddb.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/browser/indexeddb.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/browser/webchannel.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/browser/webchannel.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/browser/webchannel.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/prime_backend.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/prime_backend.test.d.ts new file mode 100644 index 0000000..c53048a --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/prime_backend.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/remote/remote.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/remote/remote.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/remote/remote.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/remote/stream.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/remote/stream.test.d.ts new file mode 100644 index 0000000..4f1864c --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/remote/stream.test.d.ts @@ -0,0 +1,54 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { EmptyAuthCredentialsProvider } from '../../../src/api/credentials'; +import { SnapshotVersion } from '../../../src/core/snapshot_version'; +import { MutationResult } from '../../../src/model/mutation'; +import { PersistentListenStream, PersistentWriteStream, WatchStreamListener, WriteStreamListener } from '../../../src/remote/persistent_stream'; +import { DocumentWatchChange, ExistenceFilterChange, WatchTargetChange } from '../../../src/remote/watch_change'; +import { AsyncQueueImpl } from '../../../src/util/async_queue_impl'; +import { FirestoreError } from '../../../src/util/error'; +/** + * StreamEventType combines the events that can be observed by the + * WatchStreamListener and WriteStreamListener. + */ +type StreamEventType = 'handshakeComplete' | 'mutationResult' | 'watchChange' | 'open' | 'close' | 'connected'; +declare class StreamStatusListener implements WatchStreamListener, WriteStreamListener { + private pendingCallbacks; + private pendingPromises; + /** + * Returns a Promise that resolves when the next callback fires. Resolves the + * returned Promise immediately if there is already an unprocessed callback. + * + * This method asserts that the observed callback type matches + * `expectedCallback`. + */ + awaitCallback(expectedCallback: StreamEventType): Promise; + /** + * Verifies that we did not encounter any unexpected callbacks. + */ + verifyNoPendingCallbacks(): void; + onHandshakeComplete(): Promise; + onMutationResult(commitVersion: SnapshotVersion, results: MutationResult[]): Promise; + onWatchChange(watchChange: DocumentWatchChange | WatchTargetChange | ExistenceFilterChange, snapshot: SnapshotVersion): Promise; + onConnected(): Promise; + onOpen(): Promise; + onClose(err?: FirestoreError): Promise; + private resolvePending; +} +export declare function withTestWriteStream(fn: (writeStream: PersistentWriteStream, streamListener: StreamStatusListener, queue: AsyncQueueImpl) => Promise, credentialsProvider?: EmptyAuthCredentialsProvider): Promise; +export declare function withTestWatchStream(fn: (watchStream: PersistentListenStream, streamListener: StreamStatusListener) => Promise): Promise; +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/util/composite_index_test_helper.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/util/composite_index_test_helper.d.ts new file mode 100644 index 0000000..39316df --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/util/composite_index_test_helper.d.ts @@ -0,0 +1,41 @@ +import { CollectionReference, DocumentData, Firestore, Query, QueryConstraint, DocumentReference, QueryCompositeFilterConstraint, QueryNonFilterConstraint, DocumentSnapshot, UpdateData, QuerySnapshot } from './firebase_export'; +import { PERSISTENCE_MODE_UNSPECIFIED, PersistenceMode } from './helpers'; +/** + * This helper class is designed to facilitate integration testing of Firestore queries that + * require composite indexes within a controlled testing environment. + * + *

Key Features: + * + *

    + *
  • Runs tests against the dedicated test collection with predefined composite indexes. + *
  • Automatically associates a test ID with documents for data isolation. + *
  • Utilizes TTL policy for automatic test data cleanup. + *
  • Constructs Firestore queries with test ID filters. + *
+ */ +export declare class CompositeIndexTestHelper { + private readonly testId; + private readonly TEST_ID_FIELD; + private readonly TTL_FIELD; + constructor(); + withTestDocs(persistence: PersistenceMode | typeof PERSISTENCE_MODE_UNSPECIFIED, docs: { + [key: string]: DocumentData; + }, fn: (collection: CollectionReference, db: Firestore) => Promise): Promise; + withTestCollection(persistence: PersistenceMode | typeof PERSISTENCE_MODE_UNSPECIFIED, fn: (collection: CollectionReference, db: Firestore) => Promise): Promise; + private toHashedId; + private toHashedIds; + addTestSpecificFieldsToDoc(doc: DocumentData): DocumentData; + private removeTestSpecificFieldsFromDoc; + private prepareTestDocuments; + assertOnlineAndOfflineResultsMatch(collection: CollectionReference, query: Query, ...expectedDocs: string[]): Promise; + assertSnapshotResultIdsMatch(snapshot: QuerySnapshot, expectedIds: string[]): void; + query(query_: Query, ...queryConstraints: QueryConstraint[]): Query; + compositeQuery(query_: Query, compositeFilter: QueryCompositeFilterConstraint, ...queryConstraints: QueryNonFilterConstraint[]): Query; + getDocRef(coll: CollectionReference, docId: string): DocumentReference; + addDoc(reference: CollectionReference, data: object): Promise>; + setDoc(reference: DocumentReference, data: object): Promise; + updateDoc(reference: DocumentReference, data: UpdateData): Promise; + deleteDoc(reference: DocumentReference): Promise; + getDoc(docRef: DocumentReference): Promise>; + getDocs(query_: Query): Promise>; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/util/events_accumulator.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/util/events_accumulator.d.ts new file mode 100644 index 0000000..629d5a9 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/util/events_accumulator.d.ts @@ -0,0 +1,39 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { DocumentSnapshot, QuerySnapshot } from './firebase_export'; +/** + * A helper object that can accumulate an arbitrary amount of events and resolve + * a promise when expected number has been emitted. + */ +export declare class EventsAccumulator { + private events; + private waitingFor; + private deferred; + private rejectAdditionalEvents; + storeEvent: (evt: T) => void; + awaitEvents(length: number): Promise; + awaitEvent(): Promise; + /** Waits for a latency compensated local snapshot. */ + awaitLocalEvent(): Promise; + /** Waits for multiple latency compensated local snapshot. */ + awaitLocalEvents(count: number): Promise; + /** Waits for a snapshot that has no pending writes */ + awaitRemoteEvent(): Promise; + assertNoAdditionalEvents(): Promise; + allowAdditionalEvents(): void; + private checkFulfilled; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/util/firebase_export.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/util/firebase_export.d.ts new file mode 100644 index 0000000..7d96efd --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/util/firebase_export.d.ts @@ -0,0 +1,23 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { FirebaseApp } from '@firebase/app'; +import { Firestore } from '../../../src'; +import { PrivateSettings } from '../../../src/lite-api/settings'; +export declare function newTestApp(projectId: string, appName?: string): FirebaseApp; +export declare function newTestFirestore(app: FirebaseApp, settings?: PrivateSettings, dbName?: string): Firestore; +export * from '../../../src'; +export { PrivateSettings }; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/util/helpers.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/util/helpers.d.ts new file mode 100644 index 0000000..731369e --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/util/helpers.d.ts @@ -0,0 +1,138 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { CollectionReference, DocumentData, DocumentReference, Firestore, MemoryLocalCache, PersistentLocalCache, PrivateSettings, QuerySnapshot, SnapshotListenOptions, Query } from './firebase_export'; +export interface PersistenceMode { + readonly name: string; + readonly storage: 'memory' | 'indexeddb'; + readonly gc: 'eager' | 'lru'; + /** + * Creates and returns a new `PersistenceMode` object that is the nearest + * equivalent to this persistence mode but uses eager garbage collection. + */ + toEagerGc(): PersistenceMode; + /** + * Creates and returns a new `PersistenceMode` object that is the nearest + * equivalent to this persistence mode but uses LRU garbage collection. + */ + toLruGc(): PersistenceMode; + /** + * Creates and returns a new "local cache" object corresponding to this + * persistence type. + */ + asLocalCacheFirestoreSettings(): MemoryLocalCache | PersistentLocalCache; +} +export declare class MemoryEagerPersistenceMode implements PersistenceMode { + readonly name = "memory"; + readonly storage = "memory"; + readonly gc = "eager"; + toEagerGc(): MemoryEagerPersistenceMode; + toLruGc(): MemoryLruPersistenceMode; + asLocalCacheFirestoreSettings(): MemoryLocalCache; +} +export declare class MemoryLruPersistenceMode implements PersistenceMode { + readonly name = "memory_lru_gc"; + readonly storage = "memory"; + readonly gc = "lru"; + toEagerGc(): MemoryEagerPersistenceMode; + toLruGc(): MemoryLruPersistenceMode; + asLocalCacheFirestoreSettings(): MemoryLocalCache; +} +export declare class IndexedDbPersistenceMode implements PersistenceMode { + readonly name = "indexeddb"; + readonly storage = "indexeddb"; + readonly gc = "lru"; + toEagerGc(): MemoryEagerPersistenceMode; + toLruGc(): IndexedDbPersistenceMode; + asLocalCacheFirestoreSettings(): PersistentLocalCache; +} +export declare const PERSISTENCE_MODE_UNSPECIFIED: unique symbol; +export declare function isPersistenceAvailable(): boolean; +type ApiSuiteFunction = (message: string, testSuite: (persistence: PersistenceMode) => void) => void; +interface ApiDescribe { + (message: string, testSuite: (persistence: PersistenceMode) => void): void; + skip: ApiSuiteFunction; + only: ApiSuiteFunction; +} +export declare const apiDescribe: ApiDescribe; +/** Converts the documents in a QuerySnapshot to an array with the data of each document. */ +export declare function toDataArray(docSet: QuerySnapshot): DocumentData[]; +/** Converts the changes in a QuerySnapshot to an array with the data of each document. */ +export declare function toChangesArray(docSet: QuerySnapshot, options?: SnapshotListenOptions): DocumentData[]; +export declare function toDataMap(docSet: QuerySnapshot): { + [field: string]: DocumentData; +}; +/** Converts a DocumentSet to an array with the id of each document */ +export declare function toIds(docSet: QuerySnapshot): string[]; +export declare function withTestDb(persistence: PersistenceMode | typeof PERSISTENCE_MODE_UNSPECIFIED, fn: (db: Firestore) => Promise): Promise; +/** Runs provided fn with a db for an alternate project id. */ +export declare function withAlternateTestDb(persistence: PersistenceMode | typeof PERSISTENCE_MODE_UNSPECIFIED, fn: (db: Firestore) => Promise): Promise; +export declare function withTestDbs(persistence: PersistenceMode | typeof PERSISTENCE_MODE_UNSPECIFIED, numDbs: number, fn: (db: Firestore[]) => Promise): Promise; +export declare function withTestDbsSettings(persistence: PersistenceMode | typeof PERSISTENCE_MODE_UNSPECIFIED, projectId: string, settings: PrivateSettings, numDbs: number, fn: (db: Firestore[]) => Promise): Promise; +export declare function withNamedTestDbsOrSkipUnlessUsingEmulator(persistence: PersistenceMode, dbNames: string[], fn: (db: Firestore[]) => Promise): Promise; +export declare function withTestDoc(persistence: PersistenceMode | typeof PERSISTENCE_MODE_UNSPECIFIED, fn: (doc: DocumentReference, db: Firestore) => Promise): Promise; +export declare function withTestDocAndSettings(persistence: PersistenceMode | typeof PERSISTENCE_MODE_UNSPECIFIED, settings: PrivateSettings, fn: (doc: DocumentReference) => Promise): Promise; +export declare function withTestDocAndInitialData(persistence: PersistenceMode | typeof PERSISTENCE_MODE_UNSPECIFIED, initialData: DocumentData | null, fn: (doc: DocumentReference, db: Firestore) => Promise): Promise; +export declare class RetryError extends Error { + readonly name = "FirestoreIntegrationTestRetryError"; +} +export declare function withRetry(fn: (attemptNumber: number) => Promise): Promise; +export declare function withTestCollection(persistence: PersistenceMode | typeof PERSISTENCE_MODE_UNSPECIFIED, docs: { + [key: string]: DocumentData; +}, fn: (collection: CollectionReference, db: Firestore) => Promise): Promise; +export declare function withEmptyTestCollection(persistence: PersistenceMode | typeof PERSISTENCE_MODE_UNSPECIFIED, fn: (collection: CollectionReference, db: Firestore) => Promise): Promise; +export declare function withTestCollectionSettings(persistence: PersistenceMode | typeof PERSISTENCE_MODE_UNSPECIFIED, settings: PrivateSettings, docs: { + [key: string]: DocumentData; +}, fn: (collection: CollectionReference, db: Firestore) => Promise): Promise; +export declare function batchCommitDocsToCollection(persistence: PersistenceMode | typeof PERSISTENCE_MODE_UNSPECIFIED, settings: PrivateSettings, docs: { + [key: string]: DocumentData; +}, collectionId: string, fn: (collection: CollectionReference, db: Firestore) => Promise): Promise; +/** + * Creates a `docs` argument suitable for specifying to `withTestCollection()` + * that defines subsets of documents with different document data. + * + * This can be useful for pre-populating a collection with some documents that + * match a query and others that do _not_ match that query. + * + * Each key of the given `partitions` object will be considered a partition + * "name". The returned object will specify `documentCount` documents with the + * `documentData` whose document IDs are prefixed with the partition "name". + */ +export declare function partitionedTestDocs(partitions: { + [partitionName: string]: { + documentData: DocumentData; + documentCount: number; + }; +}): { + [key: string]: DocumentData; +}; +/** + * Checks that running the query while online (against the backend/emulator) results in the same + * documents as running the query while offline. If `expectedDocs` is provided, it also checks + * that both online and offline query result is equal to the expected documents. + * + * This function first performs a "get" for the entire COLLECTION from the server. + * It then performs the QUERY from CACHE which, results in `executeFullCollectionScan()` + * It then performs the QUERY from SERVER. + * It then performs the QUERY from CACHE again, which results in `performQueryUsingRemoteKeys()`. + * It then ensure that all the above QUERY results are the same. + * + * @param collection The collection on which the query is performed. + * @param query The query to check + * @param expectedDocs Ordered list of document keys that are expected to match the query + */ +export declare function checkOnlineAndOfflineResultsMatch(collection: Query, query: Query, ...expectedDocs: string[]): Promise; +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/util/internal_helpers.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/util/internal_helpers.d.ts new file mode 100644 index 0000000..cd23cb2 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/util/internal_helpers.d.ts @@ -0,0 +1,34 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { CredentialChangeListener, CredentialsProvider, EmptyAuthCredentialsProvider } from '../../../src/api/credentials'; +import { User } from '../../../src/auth/user'; +import { DatabaseInfo } from '../../../src/core/database_info'; +import { Datastore } from '../../../src/remote/datastore'; +import { AsyncQueue } from '../../../src/util/async_queue'; +import { AsyncQueueImpl } from '../../../src/util/async_queue_impl'; +import { Firestore } from './firebase_export'; +import { PersistenceMode } from './helpers'; +export declare function asyncQueue(db: Firestore): AsyncQueueImpl; +export declare function getDefaultDatabaseInfo(): DatabaseInfo; +export declare function withTestDatastore(fn: (datastore: Datastore) => Promise, authCredentialsProvider?: CredentialsProvider, appCheckTokenProvider?: CredentialsProvider): Promise; +export declare class MockAuthCredentialsProvider extends EmptyAuthCredentialsProvider { + private listener; + private asyncQueue; + triggerUserChange(newUser: User): void; + start(asyncQueue: AsyncQueue, listener: CredentialChangeListener): void; +} +export declare function withMockCredentialProviderTestDb(persistence: PersistenceMode, fn: (db: Firestore, mockCredential: MockAuthCredentialsProvider) => Promise): Promise; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/util/settings.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/util/settings.d.ts new file mode 100644 index 0000000..850a5f2 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/util/settings.d.ts @@ -0,0 +1,24 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { PrivateSettings } from './firebase_export'; +export declare const TARGET_DB_ID: string | '(default)'; +export declare const USE_EMULATOR: boolean; +export declare const DEFAULT_SETTINGS: PrivateSettings; +export declare function getEmulatorPort(): number; +export declare const DEFAULT_PROJECT_ID: any; +export declare const ALT_PROJECT_ID = "test-db2"; +export declare const COMPOSITE_INDEX_TEST_COLLECTION = "composite-index-test-collection"; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/util/testing_hooks_util.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/util/testing_hooks_util.d.ts new file mode 100644 index 0000000..600f0fd --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/util/testing_hooks_util.d.ts @@ -0,0 +1,44 @@ +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { DocumentReference } from './firebase_export'; +/** + * Captures all existence filter mismatches in the Watch 'Listen' stream that + * occur during the execution of the given code block. + * @param callback The callback to invoke; during the invocation of this + * callback all existence filter mismatches will be captured. + * @return the captured existence filter mismatches and the result of awaiting + * the given callback. + */ +export declare function captureExistenceFilterMismatches(callback: () => Promise): Promise<[ExistenceFilterMismatchInfo[], T]>; +/** + * Information about an existence filter mismatch, captured during an invocation + * of `captureExistenceFilterMismatches()`. + * + * See the documentation of `ExistenceFilterMismatchInfo` in + * `testing_hooks_spi.ts` for the meaning of these values. + */ +export interface ExistenceFilterMismatchInfo { + localCacheCount: number; + existenceFilterCount: number; + bloomFilter?: { + applied: boolean; + hashCount: number; + bitmapLength: number; + padding: number; + mightContain(documentRef: DocumentReference): boolean; + }; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/lite/bootstrap.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/lite/bootstrap.d.ts new file mode 100644 index 0000000..731d2d9 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/lite/bootstrap.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/lite/helpers.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/lite/helpers.d.ts new file mode 100644 index 0000000..1033563 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/lite/helpers.d.ts @@ -0,0 +1,41 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Firestore } from '../../src/lite-api/database'; +import { DocumentData, CollectionReference, DocumentReference, SetOptions, PartialWithFieldValue } from '../../src/lite-api/reference'; +import { FirestoreSettings } from '../../src/lite-api/settings'; +import { QueryDocumentSnapshot } from '../../src/lite-api/snapshot'; +export declare function withTestDbSettings(projectId: string, settings: FirestoreSettings, fn: (db: Firestore) => void | Promise): Promise; +export declare function withTestDb(fn: (db: Firestore) => void | Promise): Promise; +export declare function withTestDoc(fn: (doc: DocumentReference) => void | Promise): Promise; +export declare function withTestDocAndInitialData(data: DocumentData, fn: (doc: DocumentReference) => void | Promise): Promise; +export declare function withTestCollectionAndInitialData(data: DocumentData[], fn: (collRef: CollectionReference) => void | Promise): Promise; +export declare function withTestCollection(fn: (collRef: CollectionReference) => void | Promise): Promise; +export declare class Post { + readonly title: string; + readonly author: string; + readonly id: number; + constructor(title: string, author: string, id?: number); + byline(): string; +} +export declare const postConverter: { + toFirestore(post: Post): DocumentData; + fromFirestore(snapshot: QueryDocumentSnapshot): Post; +}; +export declare const postConverterMerge: { + toFirestore(post: PartialWithFieldValue, options?: SetOptions): DocumentData; + fromFirestore(snapshot: QueryDocumentSnapshot): Post; +}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/lite/integration.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/lite/integration.test.d.ts new file mode 100644 index 0000000..731d2d9 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/lite/integration.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/register.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/register.d.ts new file mode 100644 index 0000000..daa6d5d --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/register.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/api/aggregate.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/api/aggregate.test.d.ts new file mode 100644 index 0000000..9b0c1ff --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/api/aggregate.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/api/bytes.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/api/bytes.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/api/bytes.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/api/database.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/api/database.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/api/database.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/api/document_change.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/api/document_change.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/api/document_change.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/api/field_path.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/api/field_path.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/api/field_path.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/api/field_value.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/api/field_value.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/api/field_value.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/api/geo_point.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/api/geo_point.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/api/geo_point.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/api/long_polling_options.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/api/long_polling_options.test.d.ts new file mode 100644 index 0000000..615869e --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/api/long_polling_options.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/api/timestamp.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/api/timestamp.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/api/timestamp.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/api/vector_value.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/api/vector_value.test.d.ts new file mode 100644 index 0000000..1a6762b --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/api/vector_value.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/bootstrap.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/bootstrap.d.ts new file mode 100644 index 0000000..6a6eae7 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/bootstrap.d.ts @@ -0,0 +1,24 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * This will include all of the test files and compile them as needed + * + * Taken from karma-webpack source: + * https://github.com/webpack-contrib/karma-webpack#alternative-usage + */ +declare const testsContext: any; +declare const browserTests: any; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/core/event_manager.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/core/event_manager.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/core/event_manager.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/core/filter.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/core/filter.test.d.ts new file mode 100644 index 0000000..9b0c1ff --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/core/filter.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/core/listen_sequence.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/core/listen_sequence.test.d.ts new file mode 100644 index 0000000..c53048a --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/core/listen_sequence.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/core/query.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/core/query.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/core/query.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/core/view.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/core/view.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/core/view.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/core/webchannel_wrapper.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/core/webchannel_wrapper.test.d.ts new file mode 100644 index 0000000..9b0c1ff --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/core/webchannel_wrapper.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/index/firestore_index_value_writer.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/index/firestore_index_value_writer.test.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/index/firestore_index_value_writer.test.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/index/ordered_code_writer.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/index/ordered_code_writer.test.d.ts new file mode 100644 index 0000000..23f261f --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/index/ordered_code_writer.test.d.ts @@ -0,0 +1 @@ +export declare function compare(left: Uint8Array, right: Uint8Array): number; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/lite-api/types.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/lite-api/types.test.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/lite-api/types.test.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/bundle_cache.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/bundle_cache.test.d.ts new file mode 100644 index 0000000..731d2d9 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/bundle_cache.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/counting_query_engine.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/counting_query_engine.d.ts new file mode 100644 index 0000000..f2f4574 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/counting_query_engine.d.ts @@ -0,0 +1,60 @@ +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Query } from '../../../src/core/query'; +import { SnapshotVersion } from '../../../src/core/snapshot_version'; +import { IndexManager } from '../../../src/local/index_manager'; +import { LocalDocumentsView } from '../../../src/local/local_documents_view'; +import { PersistencePromise } from '../../../src/local/persistence_promise'; +import { PersistenceTransaction } from '../../../src/local/persistence_transaction'; +import { QueryEngine } from '../../../src/local/query_engine'; +import { DocumentKeySet, DocumentMap } from '../../../src/model/collections'; +import { MutationType } from '../../../src/model/mutation'; +/** + * A test-only query engine that forwards all API calls and exposes the number + * of documents and mutations read. + */ +export declare class CountingQueryEngine extends QueryEngine { + /** + * The number of overlays returned by the DocumentOverlayCache's + * `getOverlaysByCollection(Group)` API (since the last call to + * `resetCounts()`) + */ + overlaysReadByCollection: number; + /** + * The number of overlays returned by the DocumentOverlayCache's + * `getOverlay(s)` APIs (since the last call to `resetCounts()`) + */ + overlaysReadByKey: number; + overlayTypes: { + [k: string]: MutationType; + }; + /** + * The number of documents returned by the RemoteDocumentCache's + * `getAll()` API (since the last call to `resetCounts()`). + */ + documentsReadByCollection: number; + /** + * The number of documents returned by the RemoteDocumentCache's `getEntry()` + * and `getEntries()` APIs (since the last call to `resetCounts()`) + */ + documentsReadByKey: number; + resetCounts(): void; + getDocumentsMatchingQuery(transaction: PersistenceTransaction, query: Query, lastLimboFreeSnapshotVersion: SnapshotVersion, remoteKeys: DocumentKeySet): PersistencePromise; + initialize(localDocuments: LocalDocumentsView, indexManager: IndexManager): void; + private wrapRemoteDocumentCache; + private wrapOverlayCache; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/document_overlay_cache.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/document_overlay_cache.test.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/document_overlay_cache.test.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/encoded_resource_path.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/encoded_resource_path.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/encoded_resource_path.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/globals_cache.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/globals_cache.test.d.ts new file mode 100644 index 0000000..88c3c0e --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/globals_cache.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/index_backfiller.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/index_backfiller.test.d.ts new file mode 100644 index 0000000..9b0c1ff --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/index_backfiller.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/index_manager.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/index_manager.test.d.ts new file mode 100644 index 0000000..1c93d90 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/index_manager.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/indexeddb_persistence.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/indexeddb_persistence.test.d.ts new file mode 100644 index 0000000..c53048a --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/indexeddb_persistence.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/local_serializer.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/local_serializer.test.d.ts new file mode 100644 index 0000000..731d2d9 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/local_serializer.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/local_store.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/local_store.test.d.ts new file mode 100644 index 0000000..2ec9c10 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/local_store.test.d.ts @@ -0,0 +1,24 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { LocalStore } from '../../../src/local/local_store'; +import { Persistence } from '../../../src/local/persistence'; +import { CountingQueryEngine } from './counting_query_engine'; +export interface LocalStoreComponents { + queryEngine: CountingQueryEngine; + persistence: Persistence; + localStore: LocalStore; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/local_store_indexeddb.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/local_store_indexeddb.test.d.ts new file mode 100644 index 0000000..9b0c1ff --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/local_store_indexeddb.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/lru_garbage_collector.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/lru_garbage_collector.test.d.ts new file mode 100644 index 0000000..c53048a --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/lru_garbage_collector.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/mutation_queue.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/mutation_queue.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/mutation_queue.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/persistence_promise.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/persistence_promise.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/persistence_promise.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/persistence_test_helpers.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/persistence_test_helpers.d.ts new file mode 100644 index 0000000..bb4c627 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/persistence_test_helpers.d.ts @@ -0,0 +1,67 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { User } from '../../../src/auth/user'; +import { DatabaseId } from '../../../src/core/database_info'; +import { SequenceNumberSyncer } from '../../../src/core/listen_sequence'; +import { BatchId, TargetId } from '../../../src/core/types'; +import { IndexedDbPersistence } from '../../../src/local/indexeddb_persistence'; +import { LocalSerializer } from '../../../src/local/local_serializer'; +import { LruParams } from '../../../src/local/lru_garbage_collector'; +import { MemoryPersistence } from '../../../src/local/memory_persistence'; +import { ClientId } from '../../../src/local/shared_client_state'; +import { JsonProtoSerializer } from '../../../src/remote/serializer'; +import { AsyncQueue } from '../../../src/util/async_queue'; +import { WindowLike } from '../../../src/util/types'; +export declare const MOCK_SEQUENCE_NUMBER_SYNCER: SequenceNumberSyncer; +/** The Database ID used by most tests that use a serializer. */ +export declare const TEST_PROJECT = "test-project"; +export declare const TEST_DATABASE_ID: DatabaseId; +export declare const TEST_PERSISTENCE_KEY = "[PersistenceTestHelpers]"; +export declare const TEST_APP_ID = "test-app-id"; +/** The persistence prefix used for testing in IndexedBD and LocalStorage. */ +export declare const TEST_PERSISTENCE_PREFIX: string; +/** + * The database name used by tests that access IndexedDb. To be used in + * conjunction with `TEST_DATABASE_INFO` and + * `TEST_DATABASE_ID`. + */ +export declare const INDEXEDDB_TEST_DATABASE_NAME: string; +export declare const JSON_SERIALIZER: JsonProtoSerializer; +/** + * IndexedDb serializer that uses `TEST_DATABASE_ID` as its database + * id. + */ +export declare const TEST_SERIALIZER: LocalSerializer; +/** + * Creates and starts an IndexedDbPersistence instance for testing, destroying + * any previous contents if they existed. + */ +export declare function testIndexedDbPersistence(options?: { + dontPurgeData?: boolean; + synchronizeTabs?: boolean; + queue?: AsyncQueue; + schemaVersion?: number; +}, lruParams?: LruParams): Promise; +/** Creates and starts a MemoryPersistence instance for testing. */ +export declare function testMemoryEagerPersistence(): Promise; +export declare function testMemoryLruPersistence(params?: LruParams): Promise; +/** Clears the persistence in tests */ +export declare function clearTestPersistence(): Promise; +/** + * Populates Web Storage with instance data from a preexisting client. + */ +export declare function populateWebStorage(user: User, window: WindowLike, existingClientId: ClientId, existingMutationBatchIds: BatchId[], existingQueryTargetIds: TargetId[]): Promise; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/persistence_transaction.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/persistence_transaction.test.d.ts new file mode 100644 index 0000000..1c93d90 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/persistence_transaction.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/query_engine.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/query_engine.test.d.ts new file mode 100644 index 0000000..1c93d90 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/query_engine.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/reference_set.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/reference_set.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/reference_set.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/remote_document_cache.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/remote_document_cache.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/remote_document_cache.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/remote_document_change_buffer.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/remote_document_change_buffer.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/remote_document_change_buffer.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/simple_db.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/simple_db.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/simple_db.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/target_cache.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/target_cache.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/target_cache.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/test_bundle_cache.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/test_bundle_cache.d.ts new file mode 100644 index 0000000..faff4b4 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/test_bundle_cache.d.ts @@ -0,0 +1,32 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { BundleMetadata, NamedQuery } from '../../../src/core/bundle'; +import { Persistence } from '../../../src/local/persistence'; +import { NamedQuery as ProtoNamedQuery, BundleMetadata as ProtoBundleMetadata } from '../../../src/protos/firestore_bundle_proto'; +/** + * A wrapper around a BundleCache that automatically creates a + * transaction around every operation to reduce test boilerplate. + */ +export declare class TestBundleCache { + private readonly persistence; + private readonly cache; + constructor(persistence: Persistence); + getBundleMetadata(bundleId: string): Promise; + saveBundleMetadata(metadata: ProtoBundleMetadata): Promise; + getNamedQuery(name: string): Promise; + setNamedQuery(query: ProtoNamedQuery): Promise; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/test_document_overlay_cache.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/test_document_overlay_cache.d.ts new file mode 100644 index 0000000..c0d0c66 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/test_document_overlay_cache.d.ts @@ -0,0 +1,39 @@ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { DocumentOverlayCache } from '../../../src/local/document_overlay_cache'; +import { Persistence } from '../../../src/local/persistence'; +import { DocumentKeySet, MutationMap, OverlayMap } from '../../../src/model/collections'; +import { DocumentKey } from '../../../src/model/document_key'; +import { Mutation } from '../../../src/model/mutation'; +import { Overlay } from '../../../src/model/overlay'; +import { ResourcePath } from '../../../src/model/path'; +/** + * A wrapper around a DocumentOverlayCache that automatically creates a + * transaction around every operation to reduce test boilerplate. + */ +export declare class TestDocumentOverlayCache { + private persistence; + private cache; + constructor(persistence: Persistence, cache: DocumentOverlayCache); + saveOverlays(largestBatch: number, data: MutationMap): Promise; + getOverlay(key: DocumentKey): Promise; + getOverlays(keys: DocumentKey[]): Promise; + getOverlayMutation(docKey: string): Promise; + getOverlaysForCollection(path: ResourcePath, sinceBatchId: number): Promise; + getOverlaysForCollectionGroup(collectionGroup: string, sinceBatchId: number, count: number): Promise; + removeOverlaysForBatchId(documentKeys: DocumentKeySet, batchId: number): Promise; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/test_globals_cache.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/test_globals_cache.d.ts new file mode 100644 index 0000000..7388b22 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/test_globals_cache.d.ts @@ -0,0 +1,29 @@ +/** + * @license + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Persistence } from '../../../src/local/persistence'; +import { ByteString } from '../../../src/util/byte_string'; +/** + * A wrapper around a GlobalsCache that automatically creates a + * transaction around every operation to reduce test boilerplate. + */ +export declare class TestGlobalsCache { + private readonly persistence; + private readonly cache; + constructor(persistence: Persistence); + getSessionToken(): Promise; + setSessionToken(sessionToken: ByteString): Promise; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/test_index_manager.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/test_index_manager.d.ts new file mode 100644 index 0000000..9cd64e1 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/test_index_manager.d.ts @@ -0,0 +1,44 @@ +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Target } from '../../../src/core/target'; +import { IndexManager, IndexType } from '../../../src/local/index_manager'; +import { Persistence } from '../../../src/local/persistence'; +import { DocumentMap } from '../../../src/model/collections'; +import { DocumentKey } from '../../../src/model/document_key'; +import { FieldIndex, IndexOffset } from '../../../src/model/field_index'; +import { ResourcePath } from '../../../src/model/path'; +/** + * A wrapper around IndexManager that automatically creates a + * transaction around every operation to reduce test boilerplate. + */ +export declare class TestIndexManager { + persistence: Persistence; + indexManager: IndexManager; + constructor(persistence: Persistence, indexManager: IndexManager); + addToCollectionParentIndex(collectionPath: ResourcePath): Promise; + getCollectionParents(collectionId: string): Promise; + addFieldIndex(index: FieldIndex): Promise; + deleteFieldIndex(index: FieldIndex): Promise; + createTargetIndexes(target: Target): Promise; + deleteAllFieldIndexes(): Promise; + getFieldIndexes(collectionGroup?: string): Promise; + getIndexType(target: Target): Promise; + getDocumentsMatchingTarget(target: Target): Promise; + getNextCollectionGroupToUpdate(): Promise; + updateCollectionGroup(collectionGroup: string, offset: IndexOffset): Promise; + updateIndexEntries(documents: DocumentMap): Promise; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/test_mutation_queue.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/test_mutation_queue.d.ts new file mode 100644 index 0000000..56dae50 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/test_mutation_queue.d.ts @@ -0,0 +1,43 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Query } from '../../../src/core/query'; +import { BatchId } from '../../../src/core/types'; +import { MutationQueue } from '../../../src/local/mutation_queue'; +import { Persistence } from '../../../src/local/persistence'; +import { DocumentKeySet } from '../../../src/model/collections'; +import { DocumentKey } from '../../../src/model/document_key'; +import { Mutation } from '../../../src/model/mutation'; +import { MutationBatch } from '../../../src/model/mutation_batch'; +/** + * A wrapper around a MutationQueue that automatically creates a + * transaction around every operation to reduce test boilerplate. + */ +export declare class TestMutationQueue { + persistence: Persistence; + queue: MutationQueue; + constructor(persistence: Persistence, queue: MutationQueue); + checkEmpty(): Promise; + countBatches(): Promise; + addMutationBatch(mutations: Mutation[]): Promise; + lookupMutationBatch(batchId: BatchId): Promise; + getNextMutationBatchAfterBatchId(batchId: BatchId): Promise; + getAllMutationBatches(): Promise; + getAllMutationBatchesAffectingDocumentKey(documentKey: DocumentKey): Promise; + getAllMutationBatchesAffectingDocumentKeys(documentKeys: DocumentKeySet): Promise; + getAllMutationBatchesAffectingQuery(query: Query): Promise; + removeMutationBatch(batch: MutationBatch): Promise; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/test_remote_document_cache.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/test_remote_document_cache.d.ts new file mode 100644 index 0000000..67fda41 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/test_remote_document_cache.d.ts @@ -0,0 +1,54 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Query } from '../../../src/core/query'; +import { SnapshotVersion } from '../../../src/core/snapshot_version'; +import { IndexManager } from '../../../src/local/index_manager'; +import { Persistence } from '../../../src/local/persistence'; +import { RemoteDocumentChangeBuffer } from '../../../src/local/remote_document_change_buffer'; +import { DocumentKeySet, MutableDocumentMap, OverlayMap } from '../../../src/model/collections'; +import { MutableDocument } from '../../../src/model/document'; +import { DocumentKey } from '../../../src/model/document_key'; +import { IndexOffset } from '../../../src/model/field_index'; +/** + * A wrapper around a RemoteDocumentCache that automatically creates a + * transaction around every operation to reduce test boilerplate. + */ +export declare class TestRemoteDocumentCache { + private readonly persistence; + private readonly cache; + constructor(persistence: Persistence); + setIndexManager(indexManager: IndexManager): void; + /** + * Reads all of the documents first so we can safely add them and keep the size calculation in + * sync. + */ + addEntries(documents: MutableDocument[]): Promise; + /** + * Adds a single document using the document's version as its read time. + * Reads the document first to track the document size internally. + */ + addEntry(document: MutableDocument): Promise; + removeEntry(documentKey: DocumentKey, version?: SnapshotVersion): Promise; + getEntry(documentKey: DocumentKey): Promise; + getEntries(documentKeys: DocumentKeySet): Promise; + getDocumentsMatchingQuery(query: Query, offset: IndexOffset, mutatedDocs: OverlayMap): Promise; + getAllFromCollectionGroup(collectionGroup: string, offset: IndexOffset, limit: number): Promise; + getSize(): Promise; + newChangeBuffer(options?: { + trackRemovals: boolean; + }): RemoteDocumentChangeBuffer; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/test_remote_document_change_buffer.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/test_remote_document_change_buffer.d.ts new file mode 100644 index 0000000..9abb942 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/test_remote_document_change_buffer.d.ts @@ -0,0 +1,34 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { SnapshotVersion } from '../../../src/core/snapshot_version'; +import { Persistence } from '../../../src/local/persistence'; +import { RemoteDocumentChangeBuffer } from '../../../src/local/remote_document_change_buffer'; +import { MutableDocument } from '../../../src/model/document'; +import { DocumentKey } from '../../../src/model/document_key'; +/** + * A wrapper around a RemoteDocumentChangeBuffer that automatically creates a + * transaction around operations to reduce test boilerplate. + */ +export declare class TestRemoteDocumentChangeBuffer { + persistence: Persistence; + buffer: RemoteDocumentChangeBuffer; + constructor(persistence: Persistence, buffer: RemoteDocumentChangeBuffer); + addEntry(document: MutableDocument, readTime: SnapshotVersion): void; + removeEntry(key: DocumentKey, readTime: SnapshotVersion): void; + getEntry(documentKey: DocumentKey): Promise; + apply(): Promise; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/test_target_cache.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/test_target_cache.d.ts new file mode 100644 index 0000000..590e9ff --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/test_target_cache.d.ts @@ -0,0 +1,46 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { SnapshotVersion } from '../../../src/core/snapshot_version'; +import { Target } from '../../../src/core/target'; +import { ListenSequenceNumber, TargetId } from '../../../src/core/types'; +import { Persistence } from '../../../src/local/persistence'; +import { TargetCache } from '../../../src/local/target_cache'; +import { TargetData } from '../../../src/local/target_data'; +import { DocumentKey } from '../../../src/model/document_key'; +/** + * A wrapper around a TargetCache that automatically creates a + * transaction around every operation to reduce test boilerplate. + */ +export declare class TestTargetCache { + persistence: Persistence; + cache: TargetCache; + constructor(persistence: Persistence, cache: TargetCache); + addTargetData(targetData: TargetData): Promise; + updateTargetData(targetData: TargetData): Promise; + getTargetCount(): Promise; + removeTargetData(targetData: TargetData): Promise; + getTargetData(target: Target): Promise; + getLastRemoteSnapshotVersion(): Promise; + getHighestSequenceNumber(): Promise; + allocateTargetId(): Promise; + addMatchingKeys(keys: DocumentKey[], targetId: TargetId): Promise; + removeMatchingKeys(keys: DocumentKey[], targetId: TargetId): Promise; + getMatchingKeysForTargetId(targetId: TargetId): Promise; + removeMatchingKeysForTargetId(targetId: TargetId): Promise; + containsKey(key: DocumentKey): Promise; + setTargetsMetadata(highestListenSequenceNumber: ListenSequenceNumber, lastRemoteSnapshotVersion?: SnapshotVersion): Promise; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/web_storage_shared_client_state.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/web_storage_shared_client_state.test.d.ts new file mode 100644 index 0000000..342959e --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/web_storage_shared_client_state.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * withOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/model/document.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/model/document.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/model/document.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/model/document_set.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/model/document_set.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/model/document_set.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/model/field_index.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/model/field_index.test.d.ts new file mode 100644 index 0000000..9b0c1ff --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/model/field_index.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/model/mutation.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/model/mutation.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/model/mutation.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/model/object_value.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/model/object_value.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/model/object_value.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/model/object_value_builder.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/model/object_value_builder.test.d.ts new file mode 100644 index 0000000..731d2d9 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/model/object_value_builder.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/model/path.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/model/path.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/model/path.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/model/target.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/model/target.test.d.ts new file mode 100644 index 0000000..9b0c1ff --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/model/target.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/model/target_index_matcher.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/model/target_index_matcher.test.d.ts new file mode 100644 index 0000000..9b0c1ff --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/model/target_index_matcher.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/model/values.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/model/values.test.d.ts new file mode 100644 index 0000000..731d2d9 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/model/values.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/remote/bloom_filter.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/remote/bloom_filter.test.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/remote/bloom_filter.test.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/remote/bloom_filter_golden_test_data/index.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/remote/bloom_filter_golden_test_data/index.d.ts new file mode 100644 index 0000000..fda7b1b --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/remote/bloom_filter_golden_test_data/index.d.ts @@ -0,0 +1,40 @@ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export { default as count1Rate1TestData } from './Validation_BloomFilterTest_MD5_1_1_bloom_filter_proto.json'; +export { default as count1Rate1TestResult } from './Validation_BloomFilterTest_MD5_1_1_membership_test_result.json'; +export { default as count1Rate01TestData } from './Validation_BloomFilterTest_MD5_1_01_bloom_filter_proto.json'; +export { default as count1Rate01TestResult } from './Validation_BloomFilterTest_MD5_1_01_membership_test_result.json'; +export { default as count1Rate0001TestData } from './Validation_BloomFilterTest_MD5_1_0001_bloom_filter_proto.json'; +export { default as count1Rate0001TestResult } from './Validation_BloomFilterTest_MD5_1_0001_membership_test_result.json'; +export { default as count500Rate1TestData } from './Validation_BloomFilterTest_MD5_500_1_bloom_filter_proto.json'; +export { default as count500Rate1TestResult } from './Validation_BloomFilterTest_MD5_500_1_membership_test_result.json'; +export { default as count500Rate01TestData } from './Validation_BloomFilterTest_MD5_500_01_bloom_filter_proto.json'; +export { default as count500Rate01TestResult } from './Validation_BloomFilterTest_MD5_500_01_membership_test_result.json'; +export { default as count500Rate0001TestData } from './Validation_BloomFilterTest_MD5_500_0001_bloom_filter_proto.json'; +export { default as count500Rate0001TestResult } from './Validation_BloomFilterTest_MD5_500_0001_membership_test_result.json'; +export { default as count5000Rate1TestData } from './Validation_BloomFilterTest_MD5_5000_1_bloom_filter_proto.json'; +export { default as count5000Rate1TestResult } from './Validation_BloomFilterTest_MD5_5000_1_membership_test_result.json'; +export { default as count5000Rate01TestData } from './Validation_BloomFilterTest_MD5_5000_01_bloom_filter_proto.json'; +export { default as count5000Rate01TestResult } from './Validation_BloomFilterTest_MD5_5000_01_membership_test_result.json'; +export { default as count5000Rate0001TestData } from './Validation_BloomFilterTest_MD5_5000_0001_bloom_filter_proto.json'; +export { default as count5000Rate0001TestResult } from './Validation_BloomFilterTest_MD5_5000_0001_membership_test_result.json'; +export { default as count50000Rate1TestData } from './Validation_BloomFilterTest_MD5_50000_1_bloom_filter_proto.json'; +export { default as count50000Rate1TestResult } from './Validation_BloomFilterTest_MD5_50000_1_membership_test_result.json'; +export { default as count50000Rate01TestData } from './Validation_BloomFilterTest_MD5_50000_01_bloom_filter_proto.json'; +export { default as count50000Rate01TestResult } from './Validation_BloomFilterTest_MD5_50000_01_membership_test_result.json'; +export { default as count50000Rate0001TestData } from './Validation_BloomFilterTest_MD5_50000_0001_bloom_filter_proto.json'; +export { default as count50000Rate0001TestResult } from './Validation_BloomFilterTest_MD5_50000_0001_membership_test_result.json'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/remote/datastore.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/remote/datastore.test.d.ts new file mode 100644 index 0000000..daa6d5d --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/remote/datastore.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/remote/fetch_connection.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/remote/fetch_connection.test.d.ts new file mode 100644 index 0000000..1a6762b --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/remote/fetch_connection.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/remote/remote_event.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/remote/remote_event.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/remote/remote_event.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/remote/rest_connection.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/remote/rest_connection.test.d.ts new file mode 100644 index 0000000..a6fa156 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/remote/rest_connection.test.d.ts @@ -0,0 +1,28 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Token } from '../../../src/api/credentials'; +import { Stream } from '../../../src/remote/connection'; +import { RestConnection } from '../../../src/remote/rest_connection'; +import { StringMap } from '../../../src/util/types'; +export declare class TestRestConnection extends RestConnection { + lastUrl: string; + lastHeaders: StringMap; + lastRequestBody: unknown; + nextResponse: Promise; + openStream(rpcName: string, authToken: Token | null, appCheckToken: Token | null): Stream; + protected performRPCRequest(rpcName: string, url: string, headers: StringMap, body: Req): Promise; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/remote/serializer.browser.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/remote/serializer.browser.test.d.ts new file mode 100644 index 0000000..731d2d9 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/remote/serializer.browser.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/remote/serializer.helper.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/remote/serializer.helper.d.ts new file mode 100644 index 0000000..238e66b --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/remote/serializer.helper.d.ts @@ -0,0 +1,25 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import * as api from '../../../src/protos/firestore_proto_api'; +/** + * Runs the serializer test with an optional ProtobufJS verification step + * (only provided in Node). + * + * These tests are initialized in 'serializer.browser.test.ts' and + * 'serializer.node.test.ts'. + */ +export declare function serializerTest(protobufJsVerifier?: (jsonValue: api.Value) => void): void; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/remote/serializer.node.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/remote/serializer.node.test.d.ts new file mode 100644 index 0000000..94e3acc --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/remote/serializer.node.test.d.ts @@ -0,0 +1,21 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import * as api from '../../../src/protos/firestore_proto_api'; +/** + * Verifies full round-trip of JSON protos through ProtobufJs. + */ +export declare function verifyProtobufJsRoundTrip(jsonValue: api.Value): void; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/bundle_spec.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/bundle_spec.test.d.ts new file mode 100644 index 0000000..18aa444 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/bundle_spec.test.d.ts @@ -0,0 +1,36 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Query } from '../../../src/core/query'; +import { DocumentKey } from '../../../src/model/document_key'; +import { JsonObject } from '../../../src/model/object_value'; +import { LimitType } from '../../../src/protos/firestore_bundle_proto'; +import { TestSnapshotVersion } from '../../util/helpers'; +interface TestBundleDocument { + key: DocumentKey; + readTime: TestSnapshotVersion; + createTime?: TestSnapshotVersion; + updateTime?: TestSnapshotVersion; + content?: JsonObject; +} +interface TestBundledQuery { + name: string; + readTime: TestSnapshotVersion; + query: Query; + limitType?: LimitType; +} +export declare function bundleWithDocumentAndQuery(testDoc: TestBundleDocument, testQuery?: TestBundledQuery): string; +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/collection_spec.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/collection_spec.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/collection_spec.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/describe_spec.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/describe_spec.d.ts new file mode 100644 index 0000000..8804b64 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/describe_spec.d.ts @@ -0,0 +1,44 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { SpecBuilder } from './spec_builder'; +export declare const MULTI_CLIENT_TAG = "multi-client"; +/** + * If you call this function before your describeSpec, then the spec test will + * be written using the given function instead of running as a normal test. + */ +export declare function setSpecJSONHandler(writer: (json: string) => void): void; +/** + * Like it(), but for spec tests. + * @param name - A name to give the test. + * @param tags - Tags to apply to the test (e.g. 'exclusive' to only run + * individual tests) + * @param builder - A function that returns a spec. + * If writeToJSONFile has been called, the spec will be stored in + * `specsInThisTest`. Otherwise, it will be run, just as it() would run it. + */ +export declare function specTest(name: string, tags: string[], builder: () => SpecBuilder): void; +export declare function specTest(name: string, tags: string[], comment: string, builder: () => SpecBuilder): void; +/** + * Like describe, but for spec tests. + * @param name - A name to give the test. + * @param tags - Tags to apply to all tests in the spec (e.g. 'exclusive' to + * only run individual tests) + * @param builder - A function that calls specTest for each test case. + * If writeToJSONFile has been called, the specs will be stored in + * that file. Otherwise, they will be run, just as describe would run. + */ +export declare function describeSpec(name: string, tags: string[], builder: () => void): void; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/existence_filter_spec.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/existence_filter_spec.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/existence_filter_spec.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/garbage_collection_spec.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/garbage_collection_spec.test.d.ts new file mode 100644 index 0000000..615869e --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/garbage_collection_spec.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/index_spec.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/index_spec.test.d.ts new file mode 100644 index 0000000..9b0c1ff --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/index_spec.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/limbo_spec.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/limbo_spec.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/limbo_spec.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/limit_spec.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/limit_spec.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/limit_spec.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/listen_source_spec.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/listen_source_spec.test.d.ts new file mode 100644 index 0000000..88c3c0e --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/listen_source_spec.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/listen_spec.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/listen_spec.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/listen_spec.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/offline_spec.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/offline_spec.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/offline_spec.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/orderby_spec.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/orderby_spec.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/orderby_spec.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/perf_spec.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/perf_spec.test.d.ts new file mode 100644 index 0000000..c53048a --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/perf_spec.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/persistence_spec.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/persistence_spec.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/persistence_spec.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/query_spec.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/query_spec.test.d.ts new file mode 100644 index 0000000..1c93d90 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/query_spec.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/recovery_spec.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/recovery_spec.test.d.ts new file mode 100644 index 0000000..731d2d9 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/recovery_spec.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/remote_store_spec.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/remote_store_spec.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/remote_store_spec.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/resume_token_spec.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/resume_token_spec.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/resume_token_spec.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/spec_builder.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/spec_builder.d.ts new file mode 100644 index 0000000..00705ca --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/spec_builder.d.ts @@ -0,0 +1,287 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { IndexConfiguration } from '../../../src/api/index_configuration'; +import { Query } from '../../../src/core/query'; +import { Target } from '../../../src/core/target'; +import { TargetIdGenerator } from '../../../src/core/target_id_generator'; +import { TargetId } from '../../../src/core/types'; +import { TargetPurpose } from '../../../src/local/target_data'; +import { Document } from '../../../src/model/document'; +import { DocumentKey } from '../../../src/model/document_key'; +import { FieldIndex } from '../../../src/model/field_index'; +import { JsonObject } from '../../../src/model/object_value'; +import { BloomFilter as ProtoBloomFilter } from '../../../src/protos/firestore_proto_api'; +import { TimerId } from '../../../src/util/async_queue'; +import { Code } from '../../../src/util/error'; +import { ObjectMap } from '../../../src/util/obj_map'; +import { TestSnapshotVersion } from '../../util/helpers'; +import { RpcError } from './spec_rpc_error'; +import { PersistenceAction, SpecConfig, SpecQuery, SpecStep } from './spec_test_runner'; +export interface LimboMap { + [key: string]: TargetId; +} +export interface ActiveTargetSpec { + queries: SpecQuery[]; + targetPurpose?: TargetPurpose; + resumeToken?: string; + readTime?: TestSnapshotVersion; + expectedCount?: number; +} +export interface ActiveTargetMap { + [targetId: string]: ActiveTargetSpec; +} +export interface ResumeSpec { + resumeToken?: string; + readTime?: TestSnapshotVersion; + expectedCount?: number; +} +/** + * Tracks the expected memory state of a client (e.g. the expected active watch + * targets based on userListens(), userUnlistens(), and watchRemoves() + * as well as the expectActiveTargets() and expectLimboDocs() expectations). + * + * Automatically keeping track of the active targets makes writing tests + * much simpler and the tests much easier to follow. + * + * Whenever the map changes, the expected state is automatically encoded in + * the tests. + */ +export declare class ClientMemoryState { + activeTargets: ActiveTargetMap; + queryMapping: ObjectMap; + limboMapping: LimboMap; + limboIdGenerator: TargetIdGenerator; + injectFailures: boolean; + constructor(); + /** Reset all internal memory state (as done during a client restart). */ + reset(): void; + /** + * Reset the internal limbo mapping (as done during a primary lease failover). + */ + resetLimboMapping(): void; +} +/** + * Provides a high-level language to construct spec tests that can be exported + * to the spec JSON format or be run as a spec test directly. + * + * Exported JSON tests can be used in other clients without the need to + * duplicate tests in every client. + */ +export declare class SpecBuilder { + protected config: SpecConfig; + protected currentStep: SpecStep | null; + private steps; + private queryIdGenerator; + private readonly currentClientState; + protected get clientState(): ClientMemoryState; + private get limboIdGenerator(); + private get queryMapping(); + private get limboMapping(); + private get activeTargets(); + private get injectFailures(); + private set injectFailures(value); + /** + * Exports the spec steps as a JSON object that be used in the spec runner. + */ + toJSON(): { + config: SpecConfig; + steps: SpecStep[]; + }; + /** + * Run the spec as a test. If persistence is available it will run it with and + * without persistence enabled. + */ + runAsTest(name: string, tags: string[], usePersistence: boolean): Promise; + ensureManualLruGC(): this; + withMaxConcurrentLimboResolutions(value?: number): this; + private addUserListenStep; + userListens(query: Query, resume?: ResumeSpec): this; + /** Listen to query using the same options as executing a getDoc or getDocs */ + userListensForGet(query: Query, resume?: ResumeSpec): this; + userListensToCache(query: Query, resume?: ResumeSpec): this; + /** + * Registers a previously active target with the test expectations after a + * stream disconnect. + */ + restoreListen(query: Query, resumeToken: string, expectedCount?: number): this; + userUnlistens(query: Query, shouldRemoveWatchTarget?: boolean): this; + userUnlistensToCache(query: Query): this; + userSets(key: string, value: JsonObject): this; + userPatches(key: string, value: JsonObject): this; + userDeletes(key: string): this; + userAddsSnapshotsInSyncListener(): this; + userRemovesSnapshotsInSyncListener(): this; + loadBundle(bundleContent: string): this; + setIndexConfiguration(jsonOrConfiguration: string | IndexConfiguration): this; + becomeHidden(): this; + becomeVisible(): this; + runTimer(timerId: TimerId): this; + changeUser(uid: string | null): this; + disableNetwork(): this; + enableNetwork(): this; + clearPersistence(): this; + restart(): this; + shutdown(): this; + /** + * Fails the specified database transaction until `recoverDatabase()` is + * called. + */ + failDatabaseTransactions(...actions: PersistenceAction[]): this; + /** Stops failing database operations. */ + recoverDatabase(): this; + expectIsShutdown(): this; + /** Expects indexes to exist (in any order) */ + expectIndexes(indexes: FieldIndex[]): this; + /** Overrides the currently expected set of active targets. */ + expectActiveTargets(...targets: Array<{ + query: Query; + targetPurpose?: TargetPurpose; + resumeToken?: string; + readTime?: TestSnapshotVersion; + expectedCount?: number; + }>): this; + /** + * Expects a document to be in limbo. A targetId is assigned if it's not in + * limbo yet. + */ + expectLimboDocs(...keys: DocumentKey[]): this; + /** + * Expects a document to be in limbo, enqueued for limbo resolution, and + * therefore *without* an active targetId. + */ + expectEnqueuedLimboDocs(...keys: DocumentKey[]): this; + /** + * Special helper for limbo documents that acks with either a document or + * with no document for NoDocument. This is translated into normal watch + * messages. + */ + ackLimbo(version: TestSnapshotVersion, doc: Document): this; + /** + * Special helper for limbo documents that acks an unlisten for a limbo doc + * with either a document or with no document for NoDocument. This is + * translated into normal watch messages. + */ + watchRemovesLimboTarget(doc: Document): this; + /** + * Acks a write with a version and optional additional options. + * + * expectUserCallback defaults to true if omitted. + */ + writeAcks(doc: string, version: TestSnapshotVersion, options?: { + expectUserCallback?: boolean; + keepInQueue?: boolean; + }): this; + /** + * Fails a write with an error and optional additional options. + * + * expectUserCallback defaults to true if omitted. + */ + failWrite(doc: string, error: RpcError, options?: { + expectUserCallback?: boolean; + keepInQueue?: boolean; + }): this; + watchAcks(query: Query): this; + watchCurrents(query: Query, resumeToken: string): this; + watchRemoves(query: Query, cause?: RpcError): this; + watchSends(targets: { + affects?: Query[]; + removed?: Query[]; + }, ...docs: Document[]): this; + watchRemovesDoc(key: DocumentKey, ...targets: Query[]): this; + watchDeletesDoc(key: DocumentKey, version: TestSnapshotVersion, ...targets: Query[]): this; + watchFilters(queries: Query[], docs?: DocumentKey[], bloomFilter?: ProtoBloomFilter): this; + watchResets(...queries: Query[]): this; + watchSnapshots(version: TestSnapshotVersion, targets?: Query[], resumeToken?: string): this; + watchAcksFull(query: Query, version: TestSnapshotVersion, ...docs: Document[]): this; + watchStreamCloses(error: Code, opts?: { + runBackoffTimer: boolean; + }): this; + waitForPendingWrites(): this; + expectUserCallbacks(docs: { + acknowledged?: string[]; + rejected?: string[]; + }): this; + expectEvents(query: Query, events: { + fromCache?: boolean; + hasPendingWrites?: boolean; + added?: Document[]; + modified?: Document[]; + removed?: Document[]; + metadata?: Document[]; + errorCode?: Code; + }): this; + private registerQuery; + /** Registers a query that is active in another tab. */ + expectListen(query: Query, resume?: ResumeSpec): this; + /** Registers a query that is listening to cache and active in another tab. */ + expectListenToCache(query: Query, resume?: ResumeSpec): this; + removeQuery(query: Query, shouldRemoveWatchTarget?: boolean): this; + /** Removes a query that is no longer active in any tab. */ + expectUnlisten(query: Query): this; + /** Removes a query that is listening to cache and no longer active in any tab. */ + expectUnlistenToCache(query: Query): this; + /** + * Verifies the total number of requests sent to the write backend since test + * initialization. + */ + expectWriteStreamRequestCount(num: number): this; + /** + * Verifies the total number of requests sent to the watch backend since test + * initialization. + */ + expectWatchStreamRequestCount(num: number): this; + expectNumOutstandingWrites(num: number): this; + expectNumActiveClients(num: number): this; + expectPrimaryState(isPrimary: boolean): this; + expectSnapshotsInSyncEvent(count?: number): this; + expectWaitForPendingWritesEvent(count?: number): this; + triggerLruGC(cacheThreshold: number): this; + removeExpectedTargetMapping(query: Query): this; + private static queryToSpec; + private static docToSpec; + private static keyToSpec; + protected nextStep(): void; + /** + * Add the specified `Query` under give active targe id. If it is already + * added, this is a no-op. + */ + private addQueryToActiveTargets; + private removeQueryFromActiveTargets; + private assertStep; + private getTargetId; +} +/** + * SpecBuilder that supports serialized interactions between different clients. + * + * Use `client(clientIndex)` to switch between clients. + */ +export declare class MultiClientSpecBuilder extends SpecBuilder { + private activeClientIndex; + private clientStates; + protected get clientState(): ClientMemoryState; + client(clientIndex: number): MultiClientSpecBuilder; + /** + * Take the primary lease, even if another client has already obtained the + * lease. + */ + stealPrimaryLease(): this; + protected nextStep(): void; +} +/** Starts a new single-client SpecTest. */ +export declare function spec(): SpecBuilder; +/** Starts a new multi-client SpecTest. */ +export declare function client(num: number): MultiClientSpecBuilder; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/spec_rpc_error.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/spec_rpc_error.d.ts new file mode 100644 index 0000000..a104309 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/spec_rpc_error.d.ts @@ -0,0 +1,24 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Code } from '../../../src/util/error'; +/** + * An error encountered making RPCs. + */ +export declare class RpcError extends Error { + code: number; + constructor(code: Code | number, message: string); +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/spec_test_components.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/spec_test_components.d.ts new file mode 100644 index 0000000..0152128 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/spec_test_components.d.ts @@ -0,0 +1,156 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Token } from '../../../src/api/credentials'; +import { ComponentConfiguration, MemoryOfflineComponentProvider, OnlineComponentProvider, MultiTabOfflineComponentProvider } from '../../../src/core/component_provider'; +import { Observer } from '../../../src/core/event_manager'; +import { Query } from '../../../src/core/query'; +import { ViewSnapshot } from '../../../src/core/view_snapshot'; +import { IndexedDbPersistence } from '../../../src/local/indexeddb_persistence'; +import { LocalStore } from '../../../src/local/local_store'; +import { MemoryPersistence } from '../../../src/local/memory_persistence'; +import { Scheduler, Persistence } from '../../../src/local/persistence'; +import { PersistencePromise } from '../../../src/local/persistence_promise'; +import { PersistenceTransaction, PersistenceTransactionMode } from '../../../src/local/persistence_transaction'; +import { SharedClientState } from '../../../src/local/shared_client_state'; +import { Mutation } from '../../../src/model/mutation'; +import * as api from '../../../src/protos/firestore_proto_api'; +import { ApiClientObjectMap } from '../../../src/protos/firestore_proto_api'; +import { Connection, Stream } from '../../../src/remote/connection'; +import { Datastore } from '../../../src/remote/datastore'; +import { StreamBridge } from '../../../src/remote/stream_bridge'; +import { AsyncQueue } from '../../../src/util/async_queue'; +import { FirestoreError } from '../../../src/util/error'; +import { Deferred } from '../../../src/util/promise'; +import { WindowLike } from '../../../src/util/types'; +import { FakeDocument } from '../../util/test_platform'; +import { PersistenceAction } from './spec_test_runner'; +/** + * A test-only MemoryPersistence implementation that is able to inject + * transaction failures. + */ +export declare class MockMemoryPersistence extends MemoryPersistence { + injectFailures: PersistenceAction[]; + runTransaction(action: string, mode: PersistenceTransactionMode, transactionOperation: (transaction: PersistenceTransaction) => PersistencePromise): Promise; +} +/** + * A test-only IndexedDbPersistence implementation that is able to inject + * transaction failures. + */ +export declare class MockIndexedDbPersistence extends IndexedDbPersistence { + injectFailures: PersistenceAction[]; + runTransaction(action: string, mode: PersistenceTransactionMode, transactionOperation: (transaction: PersistenceTransaction) => PersistencePromise): Promise; +} +export declare class MockOnlineComponentProvider extends OnlineComponentProvider { + private readonly connection; + constructor(connection: MockConnection); + createDatastore(cfg: ComponentConfiguration): Datastore; +} +export declare class MockMultiTabOfflineComponentProvider extends MultiTabOfflineComponentProvider { + private readonly window; + private readonly document; + persistence: MockIndexedDbPersistence; + constructor(window: WindowLike, document: FakeDocument, onlineComponentProvider: OnlineComponentProvider); + createGarbageCollectionScheduler(cfg: ComponentConfiguration, localStore: LocalStore): Scheduler | null; + createIndexBackfillerScheduler(cfg: ComponentConfiguration, localStore: LocalStore): Scheduler | null; + createSharedClientState(cfg: ComponentConfiguration): SharedClientState; + createPersistence(cfg: ComponentConfiguration): MockIndexedDbPersistence; +} +export declare class MockMemoryOfflineComponentProvider extends MemoryOfflineComponentProvider { + private readonly eagerGCEnabled; + persistence: MockMemoryPersistence; + connection: MockConnection; + constructor(eagerGCEnabled: boolean); + createGarbageCollectionScheduler(cfg: ComponentConfiguration): Scheduler | null; + createPersistence(cfg: ComponentConfiguration): Persistence; +} +export declare class MockConnection implements Connection { + private queue; + watchStream: StreamBridge | null; + writeStream: StreamBridge | null; + /** + * Used to make sure a write was actually sent out on the network before the + * test runner continues. + */ + writeSendBarriers: Array>; + /** + * The set of mutations sent out before there was a corresponding + * writeSendBarrier. + */ + earlyWrites: api.WriteRequest[]; + /** The total number of requests sent to the watch stream. */ + watchStreamRequestCount: number; + /** The total number of requests sent to the write stream. */ + writeStreamRequestCount: number; + nextWriteStreamToken: number; + constructor(queue: AsyncQueue); + terminate(): void; + shouldResourcePathBeIncludedInRequest: boolean; + /** + * Tracks the currently active watch targets as detected by the mock watch // + * stream, as a mapping from target ID to query Target. // + */ + activeTargets: { + [targetId: number]: { + target: api.Target; + labels?: ApiClientObjectMap; + }; + }; + /** A Deferred that is resolved once watch opens. */ + watchOpen: Deferred; + /** Whether the Watch stream is open. */ + isWatchOpen: boolean; + invokeRPC(rpcName: string, request: Req): never; + invokeStreamingRPC(rpcName: string, request: Req): never; + waitForWriteRequest(): Promise; + waitForWatchOpen(): Promise; + ackWrite(commitTime?: api.Timestamp, mutationResults?: api.WriteResult[]): void; + failWrite(err: FirestoreError): void; + private resetAndCloseWriteStream; + failWatchStream(err?: FirestoreError): void; + private resetAndCloseWatchStream; + openStream(rpcName: string, token: Token | null): Stream; +} +/** + * An Observer that forwards events to the provided callback. + */ +export declare class EventAggregator implements Observer { + private query; + private pushEvent; + constructor(query: Query, pushEvent: (e: QueryEvent) => void); + next(view: ViewSnapshot): void; + error(error: Error): void; +} +/** + * FIFO queue that tracks all outstanding mutations for a single test run. + * As these mutations are shared among the set of active clients, any client can + * add or retrieve mutations. + */ +export declare class SharedWriteTracker { + private writes; + push(write: Mutation[]): void; + peek(): Mutation[]; + shift(): Mutation[]; +} +/** + * Interface used for object that contain exactly one of either a view snapshot + * or an error for the given query. + */ +export interface QueryEvent { + query: Query; + view?: ViewSnapshot; + error?: FirestoreError; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/spec_test_runner.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/spec_test_runner.d.ts new file mode 100644 index 0000000..50d1714 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/spec_test_runner.d.ts @@ -0,0 +1,323 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { IndexConfiguration } from '../../../src/api/index_configuration'; +import { ListenOptions } from '../../../src/core/event_manager'; +import { Query } from '../../../src/core/query'; +import { TargetId } from '../../../src/core/types'; +import { FieldIndex } from '../../../src/model/field_index'; +import { JsonObject } from '../../../src/model/object_value'; +import * as api from '../../../src/protos/firestore_proto_api'; +import { TestSnapshotVersion } from '../../util/helpers'; +import { ActiveTargetMap } from './spec_builder'; +interface DocumentOptions { + hasLocalMutations?: boolean; + hasCommittedMutations?: boolean; +} +export declare function parseQuery(querySpec: string | SpecQuery): Query; +/** + * Runs a spec test case. + * + * The spec consists of an array of individual steps to run in sequence. + */ +export declare function runSpec(name: string, tags: string[], usePersistence: boolean, config: SpecConfig, steps: SpecStep[]): Promise; +/** Specifies initial configuration information for the test. */ +export interface SpecConfig { + /** A boolean to enable / disable eager GC for memory persistence. */ + useEagerGCForMemory: boolean; + /** The number of active clients for this test run. */ + numClients: number; + /** + * The maximum number of concurrently-active listens for limbo resolutions. + * This value must be strictly greater than zero, or undefined to use the + * default value. + */ + maxConcurrentLimboResolutions?: number; +} +/** + * The cumulative list of actions run against Persistence. This is used by the + * Spec tests to fail specific types of actions. + */ +export type PersistenceAction = 'Get next mutation batch' | 'read document' | 'Allocate target' | 'Release target' | 'Execute query' | 'Handle user change' | 'Locally write mutations' | 'Acknowledge batch' | 'Reject batch' | 'Get highest unacknowledged batch id' | 'Get last stream token' | 'Set last stream token' | 'Get last remote snapshot version' | 'Set last remote snapshot version' | 'Apply remote event' | 'notifyLocalViewChanges' | 'Remote document keys' | 'Collect garbage' | 'maybeGarbageCollectMultiClientState' | 'Lookup mutation documents' | 'Get target data' | 'Get new document changes' | 'Synchronize last document change read time' | 'updateClientMetadataAndTryBecomePrimary' | 'getHighestListenSequenceNumber'; +/** + * Union type for each step. The step consists of exactly one `field` + * set and optionally expected events in the `expect` field. + */ +export interface SpecStep { + /** The index of the local client for multi-client spec tests. */ + clientIndex?: number; + /** Listen to a new query (must be unique) */ + userListen?: SpecUserListen; + /** Unlisten from a query (must be listened to) */ + userUnlisten?: SpecUserUnlisten; + /** Perform a user initiated set */ + userSet?: SpecUserSet; + /** Perform a user initiated patch */ + userPatch?: SpecUserPatch; + /** Perform a user initiated delete */ + userDelete?: SpecUserDelete; + /** Listens to a SnapshotsInSync event. */ + addSnapshotsInSyncListener?: true; + /** Unlistens from a SnapshotsInSync event. */ + removeSnapshotsInSyncListener?: true; + /** Loads a bundle from a string. */ + loadBundle?: string; + /** Ack for a query in the watch stream */ + watchAck?: SpecWatchAck; + /** Marks the query results as current */ + watchCurrent?: SpecWatchCurrent; + /** Reset the results of a query */ + watchReset?: SpecWatchReset; + /** Ack for remove or rejection of a query in the watch stream */ + watchRemove?: SpecWatchRemove; + /** Document update in the watch stream */ + watchEntity?: SpecWatchEntity; + /** Existence filter in the watch stream */ + watchFilter?: SpecWatchFilter; + /** Snapshot ("NO_CHANGE") event in the watch stream. */ + watchSnapshot?: SpecWatchSnapshot; + /** A step that the watch stream restarts. */ + watchStreamClose?: SpecWatchStreamClose; + /** Ack the last write */ + writeAck?: SpecWriteAck; + /** Fail a write */ + failWrite?: SpecWriteFailure; + /** Add a new `waitForPendingWrites` listener. */ + waitForPendingWrites?: true; + /** Fails the listed database actions. */ + failDatabase?: false | PersistenceAction[]; + /** + * Set Index Configuration + */ + setIndexConfiguration?: string | IndexConfiguration; + /** + * Run a queued timer task (without waiting for the delay to expire). See + * TimerId enum definition for possible values). + */ + runTimer?: string; + /** + * Process all events currently enqueued in the AsyncQueue. + */ + drainQueue?: true; + /** Enable or disable RemoteStore's network connection. */ + enableNetwork?: boolean; + /** Clears the persistent storage in IndexedDB. */ + clearPersistence?: true; + /** Changes the metadata state of a client instance. */ + applyClientState?: SpecClientState; + /** Change to a new active user (specified by uid or null for anonymous). */ + changeUser?: string | null; + /** Trigger a GC event with given cache threshold in bytes. */ + triggerLruGC?: number; + /** + * Restarts the SyncEngine from scratch, except re-uses persistence and auth + * components. This allows you to queue writes, get documents into cache, + * etc. and then simulate an app restart. + */ + restart?: true; + /** Shut down the client and close it network connection. */ + shutdown?: true; + /** + * Optional list of expected events. + * If not provided, the test will fail if the step causes events to be raised. + */ + expectedSnapshotEvents?: SnapshotEvent[]; + /** + * Optional dictionary of expected states. + */ + expectedState?: StateExpectation; + /** + * Optional expected number of onSnapshotsInSync callbacks to be called. + * If not provided, the test will fail if the step causes events to be raised. + */ + expectedSnapshotsInSyncEvents?: number; + /** + * Optional expected number of waitForPendingWrite callbacks to be called. + * If not provided, the test will fail if the step causes events to be raised. + */ + expectedWaitForPendingWritesEvents?: number; +} +export interface SpecUserListen { + targetId: TargetId; + query: string | SpecQuery; + options?: ListenOptions; +} +/** [, ] */ +export type SpecUserUnlisten = [TargetId, string | SpecQuery]; +/** [, ] */ +export type SpecUserSet = [string, JsonObject]; +/** [, ] */ +export type SpecUserPatch = [string, JsonObject]; +/** key */ +export type SpecUserDelete = string; +/** [, ...] */ +export type SpecWatchAck = TargetId[]; +/** [[, ...], ] */ +export type SpecWatchCurrent = [TargetId[], string]; +/** [, ...] */ +export type SpecWatchReset = TargetId[]; +export interface SpecError { + code: number; + message: string; +} +export interface SpecWatchRemove { + targetIds: TargetId[]; + cause?: SpecError; +} +export interface SpecWatchSnapshot { + version: TestSnapshotVersion; + targetIds: TargetId[]; + resumeToken?: string; +} +export interface SpecWatchStreamClose { + error: SpecError; + runBackoffTimer: boolean; +} +export interface SpecWriteAck { + /** The version the backend uses to ack the write. */ + version: TestSnapshotVersion; + /** + * Whether we should keep the write in our internal queue. This should only + * be set to 'true' if the client ignores the write (e.g. a secondary client + * which ignores write acknowledgments). + * + * Defaults to false. + */ + keepInQueue?: boolean; +} +export interface SpecWriteFailure { + /** The error the backend uses to fail the write. */ + error: SpecError; + /** + * Whether we should keep the write in our internal queue. This should be set + * to 'true' for transient errors or if the client ignores the failure + * (e.g. a secondary client which ignores write rejections). + * + * Defaults to false. + */ + keepInQueue?: boolean; +} +export interface SpecWatchEntity { + key?: string; + /** [, , ] */ + doc?: SpecDocument; + /** [, , ][] */ + docs?: SpecDocument[]; + /** [, ...] */ + targets?: TargetId[]; + /** [, ...] */ + removedTargets?: TargetId[]; +} +export interface SpecClientState { + /** The visibility state of the browser tab running the client. */ + visibility?: DocumentVisibilityState; + /** Whether this tab should try to forcefully become primary. */ + primary?: true; +} +/** + * The filter is based of a list of keys to match in the existence filter + */ +export interface SpecWatchFilter { + targetIds: TargetId[]; + keys: string[]; + bloomFilter?: api.BloomFilter; +} +export type SpecLimitType = 'LimitToFirst' | 'LimitToLast'; +/** + * [field, op, value] + * Op must be the `name` of an `Operator`. + */ +export type SpecQueryFilter = [string, string, unknown]; +/** + * [field, direction] + * Direction can be 'asc' or 'desc'. + */ +export type SpecQueryOrderBy = [string, string]; +/** + * A representation of a query. + */ +export interface SpecQuery { + path: string; + collectionGroup?: string; + limit?: number; + limitType?: SpecLimitType; + filters?: SpecQueryFilter[]; + orderBys?: SpecQueryOrderBy[]; +} +/** + * [, , , (optional), ...] + * Represents a document. is null for deleted documents. + * Doc options are: + * 'local': document has local modifications + */ +export interface SpecDocument { + key: string; + version: TestSnapshotVersion; + createTime: TestSnapshotVersion; + value: JsonObject | null; + options?: DocumentOptions; +} +export interface SnapshotEvent { + query: SpecQuery; + errorCode?: number; + fromCache?: boolean; + hasPendingWrites?: boolean; + added?: SpecDocument[]; + removed?: SpecDocument[]; + modified?: SpecDocument[]; + metadata?: SpecDocument[]; +} +export interface StateExpectation { + /** Number of outstanding writes in the datastore queue. */ + numOutstandingWrites?: number; + /** Number of clients currently marked active. Used in multi-client tests. */ + numActiveClients?: number; + /** Number of requests sent to the write stream. */ + writeStreamRequestCount?: number; + /** Number of requests sent to the watch stream. */ + watchStreamRequestCount?: number; + /** + * Current documents in limbo that have an active target. + * Verified in each step until overwritten. + */ + activeLimboDocs?: string[]; + /** + * Current documents in limbo that are enqueued and therefore do not have an + * active target. + * Verified in each step until overwritten. + */ + enqueuedLimboDocs?: string[]; + /** + * Whether the instance holds the primary lease. Used in multi-client tests. + */ + isPrimary?: boolean; + /** Whether the client is shutdown. */ + isShutdown?: boolean; + /** + * Current expected active targets. Verified in each step until overwritten. + */ + activeTargets?: ActiveTargetMap; + /** + * Expected set of callbacks for previously written docs. + */ + userCallbacks?: { + acknowledgedDocs: string[]; + rejectedDocs: string[]; + }; + /** Indexes */ + indexes?: FieldIndex[]; +} +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/write_spec.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/write_spec.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/write_spec.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/util/array.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/util/array.test.d.ts new file mode 100644 index 0000000..9b0c1ff --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/util/array.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/util/assert.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/util/assert.test.d.ts new file mode 100644 index 0000000..1a6762b --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/util/assert.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/util/async_queue.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/util/async_queue.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/util/async_queue.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/util/base64.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/util/base64.test.d.ts new file mode 100644 index 0000000..731d2d9 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/util/base64.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/util/bundle.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/util/bundle.test.d.ts new file mode 100644 index 0000000..56e142c --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/util/bundle.test.d.ts @@ -0,0 +1,8 @@ +/** + * Create a `ReadableStream` from a string. + * + * @param content - Bundle in string. + * @param bytesPerRead - How many bytes to read from the underlying buffer from + * each read through the stream. + */ +export declare function byteStreamReaderFromString(content: string, bytesPerRead: number): ReadableStreamDefaultReader; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/util/bundle_data.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/util/bundle_data.d.ts new file mode 100644 index 0000000..de7a107 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/util/bundle_data.d.ts @@ -0,0 +1,50 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { DatabaseId } from '../../../src/core/database_info'; +import { Query } from '../../../src/core/query'; +import { DocumentKey } from '../../../src/model/document_key'; +import { BundleElement } from '../../../src/protos/firestore_bundle_proto'; +import * as api from '../../../src/protos/firestore_proto_api'; +import { Value } from '../../../src/protos/firestore_proto_api'; +export declare const encoder: TextEncoder; +export declare class TestBundleBuilder { + private databaseId; + readonly elements: BundleElement[]; + private serializer; + constructor(databaseId: DatabaseId); + addDocumentMetadata(docKey: DocumentKey, readTime: api.Timestamp, exists: boolean): TestBundleBuilder; + addDocument(docKey: DocumentKey, createTime: api.Timestamp, updateTime: api.Timestamp, fields: api.ApiClientObjectMap): TestBundleBuilder; + addNamedQuery(name: string, readTime: api.Timestamp, query: Query): TestBundleBuilder; + getMetadataElement(id: string, createTime: api.Timestamp, version?: number): BundleElement; + build(id: string, createTime: api.Timestamp, version?: number): string; +} +export declare const meta: BundleElement; +export declare const metaString: string; +export declare const doc1Meta: BundleElement; +export declare const doc1MetaString: string; +export declare const doc1: BundleElement; +export declare const doc1String: string; +export declare const doc2Meta: BundleElement; +export declare const doc2MetaString: string; +export declare const doc2: BundleElement; +export declare const doc2String: string; +export declare const noDocMeta: BundleElement; +export declare const noDocMetaString: string; +export declare const limitQuery: BundleElement; +export declare const limitQueryString: string; +export declare const limitToLastQuery: BundleElement; +export declare const limitToLastQueryString: string; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/util/logic_utils.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/util/logic_utils.test.d.ts new file mode 100644 index 0000000..9b0c1ff --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/util/logic_utils.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/util/misc.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/util/misc.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/util/misc.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/util/node_api.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/util/node_api.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/util/node_api.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/util/obj_map.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/util/obj_map.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/util/obj_map.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/util/sorted_map.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/util/sorted_map.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/util/sorted_map.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/util/sorted_set.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/util/sorted_set.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/util/sorted_set.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/util/api_helpers.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/util/api_helpers.d.ts new file mode 100644 index 0000000..a4a9b0c --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/util/api_helpers.d.ts @@ -0,0 +1,49 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { DocumentReference, Firestore, Query, CollectionReference, QuerySnapshot, DocumentSnapshot } from '../../src'; +import { DocumentKeySet } from '../../src/model/collections'; +import { JsonObject } from '../../src/model/object_value'; +/** + * A mock Firestore. Will not work for integration test. + */ +export declare const FIRESTORE: Firestore; +export declare function firestore(): Firestore; +export declare function newTestFirestore(projectId?: string): Firestore; +export declare function collectionReference(path: string): CollectionReference; +export declare function documentReference(path: string): DocumentReference; +export declare function documentSnapshot(path: string, data: JsonObject | null, fromCache: boolean, hasPendingWrites?: boolean): DocumentSnapshot; +export declare function query(path: string): Query; +/** + * A convenience method for creating a particular query snapshot for tests. + * + * @param path - To be used in constructing the query. + * @param oldDocs - Provides the prior set of documents in the QuerySnapshot. + * Each entry maps to a document, with the key being the document id, and the + * value being the document contents. + * @param docsToAdd - Specifies data to be added into the query snapshot as of + * now. Each entry maps to a document, with the key being the document id, and + * the value being the document contents. + * @param mutatedKeys - The list of document with pending writes. + * @param fromCache - Whether the query snapshot is cache result. + * @param syncStateChanged - Whether the sync state has changed. + * @returns A query snapshot that consists of both sets of documents. + */ +export declare function querySnapshot(path: string, oldDocs: { + [key: string]: JsonObject; +}, docsToAdd: { + [key: string]: JsonObject; +}, mutatedKeys: DocumentKeySet, fromCache: boolean, syncStateChanged: boolean, hasCachedResults?: boolean): QuerySnapshot; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/util/equality_matcher.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/util/equality_matcher.d.ts new file mode 100644 index 0000000..d019ad2 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/util/equality_matcher.d.ts @@ -0,0 +1,33 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Duck-typed interface for objects that have an isEqual() method. + * + * Note: This is copied from src/util/misc.ts to avoid importing private types. + */ +export interface Equatable { + isEqual(other: T): boolean; +} +/** + * Custom equals override for types that have a free-standing equals functions + * (such as `queryEquals()`). + */ +export interface CustomMatcher { + equalsFn: (left: T, right: T) => boolean; + forType: Function; +} +export declare function addEqualityMatcher(...customMatchers: Array>): void; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/util/helpers.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/util/helpers.d.ts new file mode 100644 index 0000000..c8acefd --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/util/helpers.d.ts @@ -0,0 +1,206 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Bytes, DocumentReference } from '../../src'; +import { Bound } from '../../src/core/bound'; +import { BundledDocuments } from '../../src/core/bundle'; +import { DatabaseId } from '../../src/core/database_info'; +import { FieldFilter, CompositeFilter, Filter } from '../../src/core/filter'; +import { OrderBy } from '../../src/core/order_by'; +import { Query } from '../../src/core/query'; +import { SnapshotVersion } from '../../src/core/snapshot_version'; +import { TargetId } from '../../src/core/types'; +import { LimboDocumentChange, View, ViewChange } from '../../src/core/view'; +import { UserDataReader } from '../../src/lite-api/user_data_reader'; +import { LocalViewChanges } from '../../src/local/local_view_changes'; +import { TargetData, TargetPurpose } from '../../src/local/target_data'; +import { DocumentKeySet, DocumentMap } from '../../src/model/collections'; +import { Document, MutableDocument } from '../../src/model/document'; +import { DocumentComparator } from '../../src/model/document_comparator'; +import { DocumentKey } from '../../src/model/document_key'; +import { DocumentSet } from '../../src/model/document_set'; +import { FieldIndex, IndexKind, IndexOffset } from '../../src/model/field_index'; +import { FieldMask } from '../../src/model/field_mask'; +import { DeleteMutation, MutationResult, PatchMutation, Precondition, SetMutation } from '../../src/model/mutation'; +import { JsonObject, ObjectValue } from '../../src/model/object_value'; +import { FieldPath, ResourcePath } from '../../src/model/path'; +import { NamedQuery as ProtoNamedQuery, BundleMetadata as ProtoBundleMetadata, LimitType as ProtoLimitType } from '../../src/protos/firestore_bundle_proto'; +import * as api from '../../src/protos/firestore_proto_api'; +import { RemoteEvent, TargetChange } from '../../src/remote/remote_event'; +import { ByteString } from '../../src/util/byte_string'; +import { Code } from '../../src/util/error'; +import { Dict } from '../../src/util/obj'; +import { SortedMap } from '../../src/util/sorted_map'; +import { SortedSet } from '../../src/util/sorted_set'; +export type TestSnapshotVersion = number; +export declare function testUserDataReader(useProto3Json?: boolean): UserDataReader; +export declare function version(v: TestSnapshotVersion): SnapshotVersion; +export declare function ref(key: string, offset?: number): DocumentReference; +export declare function doc(keyStr: string, ver: TestSnapshotVersion, jsonOrObjectValue: JsonObject | ObjectValue, createTime?: TestSnapshotVersion): MutableDocument; +export declare function deletedDoc(keyStrOrDocumentKey: string | DocumentKey, ver: TestSnapshotVersion): MutableDocument; +export declare function unknownDoc(keyStr: string, ver: TestSnapshotVersion): MutableDocument; +export declare function removedDoc(keyStr: string): MutableDocument; +export declare function invalidDoc(keyStr: string): MutableDocument; +export declare function wrap(value: unknown): api.Value; +export declare function wrapObject(obj: JsonObject): ObjectValue; +export declare function dbId(project: string, database?: string): DatabaseId; +export declare function key(path: string): DocumentKey; +export declare function keys(...documents: Array): DocumentKeySet; +export declare function path(path: string, offset?: number): ResourcePath; +export declare function field(path: string): FieldPath; +export declare function fieldIndex(collectionGroup: string, options?: { + id?: number; + fields?: Array<[field: string, kind: IndexKind]>; + offset?: IndexOffset; + sequenceNumber?: number; +}): FieldIndex; +export declare function mask(...paths: string[]): FieldMask; +export declare function blob(...bytes: number[]): Bytes; +export declare function filter(path: string, op: string, value: unknown): FieldFilter; +export declare function andFilter(...filters: Filter[]): CompositeFilter; +export declare function orFilter(...filters: Filter[]): CompositeFilter; +export declare function setMutation(keyStr: string, json: JsonObject): SetMutation; +export declare function patchMutation(keyStr: string, json: JsonObject, precondition?: Precondition): PatchMutation; +export declare function mergeMutation(keyStr: string, json: JsonObject, updateMask: FieldPath[]): PatchMutation; +export declare function deleteMutation(keyStr: string): DeleteMutation; +export declare function mutationResult(testVersion: TestSnapshotVersion): MutationResult; +export declare function bound(values: unknown[], inclusive: boolean): Bound; +export declare function query(resourcePath: string, ...constraints: Array): Query; +export declare function targetData(targetId: TargetId, queryPurpose: TargetPurpose, path: string): TargetData; +export declare function noChangeEvent(targetId: number, snapshotVersion: number, resumeToken?: ByteString): RemoteEvent; +export declare function existenceFilterEvent(targetId: number, syncedKeys: DocumentKeySet, remoteCount: number, snapshotVersion: number, bloomFilter?: api.BloomFilter): RemoteEvent; +export declare function docAddedRemoteEvent(docOrDocs: MutableDocument | MutableDocument[], updatedInTargets?: TargetId[], removedFromTargets?: TargetId[], activeTargets?: TargetId[]): RemoteEvent; +export declare function docUpdateRemoteEvent(doc: MutableDocument, updatedInTargets?: TargetId[], removedFromTargets?: TargetId[], limboTargets?: TargetId[]): RemoteEvent; +export declare class TestBundledDocuments { + documents: BundledDocuments; + bundleName: string; + constructor(documents: BundledDocuments, bundleName: string); +} +export declare function bundledDocuments(documents: MutableDocument[], queryNames?: string[][], bundleName?: string): TestBundledDocuments; +export declare class TestNamedQuery { + namedQuery: ProtoNamedQuery; + matchingDocuments: DocumentKeySet; + constructor(namedQuery: ProtoNamedQuery, matchingDocuments: DocumentKeySet); +} +export declare function namedQuery(name: string, query: Query, limitType: ProtoLimitType, readTime: SnapshotVersion, matchingDocuments?: DocumentKeySet): TestNamedQuery; +export declare function bundleMetadata(id: string, createTime: TestSnapshotVersion, version?: number, totalDocuments?: number, totalBytes?: number): ProtoBundleMetadata; +export declare function updateMapping(snapshotVersion: SnapshotVersion, added: Array, modified: Array, removed: Array, current?: boolean): TargetChange; +export declare function addTargetMapping(...docsOrKeys: Array): TargetChange; +export declare function ackTarget(...docsOrKeys: Array): TargetChange; +export declare function limboChanges(changes: { + added?: Document[]; + removed?: Document[]; +}): LimboDocumentChange[]; +export declare function localViewChanges(targetId: TargetId, fromCache: boolean, changes: { + added?: string[]; + removed?: string[]; +}): LocalViewChanges; +/** + * Returns a ByteString representation for the platform from the given string. + */ +export declare function byteStringFromString(value: string): ByteString; +/** + * Decodes a base 64 decoded string. + * + * Note that this is typed to accept Uint8Arrays to match the types used + * by the spec tests. Since the spec tests only use JSON strings, this method + * throws if an Uint8Array is passed. + */ +export declare function stringFromBase64String(value?: string | Uint8Array): string; +/** Creates a resume token to match the given snapshot version. */ +export declare function resumeTokenForSnapshot(snapshotVersion: SnapshotVersion): ByteString; +export declare function orderBy(path: string, op?: string): OrderBy; +/** + * Converts a sorted map to an array with inorder traversal + */ +export declare function mapAsArray(sortedMap: SortedMap): Array<{ + key: K; + value: V; +}>; +/** + * Converts a list of documents or document keys to a sorted map. A document + * key is used to represent a deletion and maps to null. + */ +export declare function documentUpdates(...docsOrKeys: Array): DocumentMap; +/** + * Short for view.applyChanges(view.computeDocChanges(documentUpdates(docs))). + */ +export declare function applyDocChanges(view: View, ...docsOrKeys: Array): ViewChange; +/** + * Constructs a document set. + */ +export declare function documentSet(comp: DocumentComparator, ...docs: Document[]): DocumentSet; +export declare function documentSet(...docs: Document[]): DocumentSet; +/** + * Constructs a document key set. + */ +export declare function keySet(...keys: DocumentKey[]): DocumentKeySet; +/** Converts a DocumentSet to an array. */ +export declare function documentSetAsArray(docs: DocumentSet): Document[]; +export declare class DocComparator { + static byField(...fields: string[]): DocumentComparator; +} +/** + * Two helper functions to simplify testing isEqual() method. + */ +export declare function expectEqual(left: any, right: any, message?: string): void; +export declare function expectNotEqual(left: any, right: any, message?: string): void; +export declare function expectEqualArrays(left: unknown[], right: unknown[], message?: string): void; +/** + * Checks that an ordered array of elements yields the correct pair-wise + * comparison result for the supplied comparator + */ +export declare function expectCorrectComparisons(array: T[], comp: (left: T, right: T) => number): void; +/** + * Takes an array of "equality group" arrays and asserts that the comparator + * returns the same as comparing the indexes of the "equality groups" + * (0 for items in the same group). + */ +export declare function expectCorrectComparisonGroups(groups: T[][], comp: (left: T, right: T) => number): void; +/** Compares SortedSet to an array */ +export declare function expectSetToEqual(set: SortedSet, arr: T[]): void; +/** + * Takes an array of array of elements and compares each of the elements + * to every other element. + * + * Elements in the same inner array are expect to be equal with regard to + * the provided equality function to all other elements from the same array + * (including itself) and unequal to all other elements from the other array + */ +export declare function expectEqualitySets(elems: T[][], equalityFn: (v1: T, v2: T) => boolean, stringifyFn?: (v: T) => string): void; +export declare function validateFirestoreError(expectedCode: Code, actualError: Error): void; +export declare function forEachNumber(obj: Dict, fn: (key: number, val: V) => void): void; +/** + * Returns all possible permutations of the given array. + * For `[a, b]`, this method returns `[[a, b], [b, a]]`. + */ +export declare function computePermutations(input: T[]): T[][]; +/** + * Returns all possible combinations of the given array, including an empty + * array. For `[a, b, c]` this method returns + * `[[], [a], [a, b], [a, c], [b, c], [a, b, c]`. + */ +export declare function computeCombinations(input: T[]): T[][]; +/** + * Helper method to generate bloom filter proto value for mocking watch + * existence filter response. + */ +export declare function generateBloomFilterProto(config: { + contains: MutableDocument[]; + notContains: MutableDocument[]; + hashCount?: number; + bitCount?: number; +}): api.BloomFilter; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/util/node_persistence.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/util/node_persistence.d.ts new file mode 100644 index 0000000..c53048a --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/util/node_persistence.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/util/promise.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/util/promise.d.ts new file mode 100644 index 0000000..d3f8374 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/util/promise.d.ts @@ -0,0 +1,28 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export interface Resolver { + (value: R | Promise): void; +} +export interface Rejecter { + (reason?: Error): void; +} +export declare class Deferred { + promise: Promise; + resolve: Resolver; + reject: Rejecter; + constructor(); +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/util/spec_test_helpers.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/util/spec_test_helpers.d.ts new file mode 100644 index 0000000..1ae9b67 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/util/spec_test_helpers.d.ts @@ -0,0 +1,19 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import * as api from '../../src/protos/firestore_proto_api'; +import { WatchChange } from '../../src/remote/watch_change'; +export declare function encodeWatchChange(watchChange: WatchChange): api.ListenResponse; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/util/test_platform.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/util/test_platform.d.ts new file mode 100644 index 0000000..8417eb4 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/util/test_platform.d.ts @@ -0,0 +1,61 @@ +/** + * @license + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { DocumentLike, WindowLike } from '../../src/util/types'; +/** + * `Window` fake that implements the event and storage API that is used by + * Firestore. + */ +export declare class FakeWindow implements WindowLike { + private readonly fakeStorageArea; + private readonly fakeIndexedDb; + private storageListeners; + constructor(sharedFakeStorage: SharedFakeWebStorage, fakeIndexedDb?: IDBFactory); + get localStorage(): Storage; + get indexedDB(): IDBFactory | null; + addEventListener(type: string, listener: EventListener): void; + removeEventListener(type: string, listener: EventListener): void; +} +export declare function testWindow(sharedWebStorage?: SharedFakeWebStorage): FakeWindow; +/** + * `Document` fake that implements the `visibilitychange` API used by Firestore. + */ +export declare class FakeDocument implements DocumentLike { + private _visibilityState; + private visibilityListener; + get visibilityState(): DocumentVisibilityState; + addEventListener(type: string, listener: EventListener): void; + removeEventListener(type: string, listener: EventListener): void; + raiseVisibilityEvent(visibility: DocumentVisibilityState): void; +} +export declare function testDocument(): FakeDocument; +/** + * `WebStorage` mock that implements the WebStorage behavior for multiple + * clients. To get a client-specific storage area that implements the WebStorage + * API, invoke `getStorageArea(storageListener)`. + */ +export declare class SharedFakeWebStorage { + private readonly data; + private readonly activeClients; + getStorageArea(storageListener: EventListener): Storage; + private clear; + private getItem; + private key; + private removeItem; + private setItem; + private get length(); + private raiseStorageEvent; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/index.browser.esm.js b/frontend-old/node_modules/@firebase/firestore/dist/lite/index.browser.esm.js new file mode 100644 index 0000000..e44dcac --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/index.browser.esm.js @@ -0,0 +1,7660 @@ +import { _registerComponent, registerVersion, _isFirebaseServerApp, _getProvider, getApp, _removeServiceInstance, SDK_VERSION } from '@firebase/app'; +import { Component } from '@firebase/component'; +import { Logger, LogLevel } from '@firebase/logger'; +import { FirebaseError, getDefaultEmulatorHostnameAndPort, isCloudWorkstation, pingServer, updateEmulatorBanner, deepEqual, createMockUserToken, getModularInstance } from '@firebase/util'; +import { Integer } from '@firebase/webchannel-wrapper/bloom-blob'; + +const P = "4.9.2"; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Simple wrapper around a nullable UID. Mostly exists to make code more + * readable. + */ class User { + constructor(t) { + this.uid = t; + } + isAuthenticated() { + return null != this.uid; + } + /** + * Returns a key representing this user, suitable for inclusion in a + * dictionary. + */ toKey() { + return this.isAuthenticated() ? "uid:" + this.uid : "anonymous-user"; + } + isEqual(t) { + return t.uid === this.uid; + } +} + +/** A user with a null UID. */ User.UNAUTHENTICATED = new User(null), +// TODO(mikelehen): Look into getting a proper uid-equivalent for +// non-FirebaseAuth providers. +User.GOOGLE_CREDENTIALS = new User("google-credentials-uid"), User.FIRST_PARTY = new User("first-party-uid"), +User.MOCK_USER = new User("mock-user"); + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +let A = "12.3.0"; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const R = new Logger("@firebase/firestore"); + +/** + * Sets the verbosity of Cloud Firestore logs (debug, error, or silent). + * + * @param logLevel - The verbosity you set for activity and error logging. Can + * be any of the following values: + * + *
    + *
  • `debug` for the most verbose logging level, primarily for + * debugging.
  • + *
  • `error` to log errors only.
  • + *
  • `silent` to turn off logging.
  • + *
+ */ function setLogLevel(t) { + R.setLogLevel(t); +} + +function __PRIVATE_logDebug(t, ...e) { + if (R.logLevel <= LogLevel.DEBUG) { + const r = e.map(__PRIVATE_argToString); + R.debug(`Firestore (${A}): ${t}`, ...r); + } +} + +function __PRIVATE_logError(t, ...e) { + if (R.logLevel <= LogLevel.ERROR) { + const r = e.map(__PRIVATE_argToString); + R.error(`Firestore (${A}): ${t}`, ...r); + } +} + +/** + * @internal + */ function __PRIVATE_logWarn(t, ...e) { + if (R.logLevel <= LogLevel.WARN) { + const r = e.map(__PRIVATE_argToString); + R.warn(`Firestore (${A}): ${t}`, ...r); + } +} + +/** + * Converts an additional log parameter to a string representation. + */ function __PRIVATE_argToString(t) { + if ("string" == typeof t) return t; + try { + /** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + /** Formats an object as a JSON string, suitable for logging. */ + return function __PRIVATE_formatJSON(t) { + return JSON.stringify(t); + }(t); + } catch (e) { + // Converting to JSON failed, just log the object directly + return t; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ function fail(t, e, r) { + let n = "Unexpected state"; + "string" == typeof e ? n = e : r = e, __PRIVATE__fail(t, n, r); +} + +function __PRIVATE__fail(t, e, r) { + // Log the failure in addition to throw an exception, just in case the + // exception is swallowed. + let n = `FIRESTORE (${A}) INTERNAL ASSERTION FAILED: ${e} (ID: ${t.toString(16)})`; + if (void 0 !== r) try { + n += " CONTEXT: " + JSON.stringify(r); + } catch (t) { + n += " CONTEXT: " + r; + } + // NOTE: We don't use FirestoreError here because these are internal failures + // that cannot be handled by the user. (Also it would create a circular + // dependency between the error and assert modules which doesn't work.) + throw __PRIVATE_logError(n), new Error(n); +} + +function __PRIVATE_hardAssert(t, e, r, n) { + let i = "Unexpected state"; + "string" == typeof r ? i = r : n = r, t || __PRIVATE__fail(e, i, n); +} + +/** + * Casts `obj` to `T`. In non-production builds, verifies that `obj` is an + * instance of `T` before casting. + */ function __PRIVATE_debugCast(t, +// eslint-disable-next-line @typescript-eslint/no-explicit-any +e) { + return t; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ const V = "ok", I = "cancelled", p = "unknown", y = "invalid-argument", g = "deadline-exceeded", w = "not-found", F = "already-exists", v = "permission-denied", D = "unauthenticated", b = "resource-exhausted", S = "failed-precondition", C = "aborted", N = "out-of-range", O = "unimplemented", q = "internal", B = "unavailable", $ = "data-loss"; + +/** An error returned by a Firestore operation. */ class FirestoreError extends FirebaseError { + /** @hideconstructor */ + constructor( + /** + * The backend error code associated with this error. + */ + t, + /** + * A custom error description. + */ + e) { + super(t, e), this.code = t, this.message = e, + // HACK: We write a toString property directly because Error is not a real + // class and so inheritance does not work correctly. We could alternatively + // do the same "back-door inheritance" trick that FirebaseError does. + this.toString = () => `${this.name}: [code=${this.code}]: ${this.message}`; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ class __PRIVATE_Deferred { + constructor() { + this.promise = new Promise(((t, e) => { + this.resolve = t, this.reject = e; + })); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ class __PRIVATE_OAuthToken { + constructor(t, e) { + this.user = e, this.type = "OAuth", this.headers = new Map, this.headers.set("Authorization", `Bearer ${t}`); + } +} + +/** + * A CredentialsProvider that always yields an empty token. + * @internal + */ class __PRIVATE_EmptyAuthCredentialsProvider { + getToken() { + return Promise.resolve(null); + } + invalidateToken() {} + start(t, e) { + // Fire with initial user. + t.enqueueRetryable((() => e(User.UNAUTHENTICATED))); + } + shutdown() {} +} + +/** + * A CredentialsProvider that always returns a constant token. Used for + * emulator token mocking. + */ class __PRIVATE_EmulatorAuthCredentialsProvider { + constructor(t) { + this.token = t, + /** + * Stores the listener registered with setChangeListener() + * This isn't actually necessary since the UID never changes, but we use this + * to verify the listen contract is adhered to in tests. + */ + this.changeListener = null; + } + getToken() { + return Promise.resolve(this.token); + } + invalidateToken() {} + start(t, e) { + this.changeListener = e, + // Fire with initial user. + t.enqueueRetryable((() => e(this.token.user))); + } + shutdown() { + this.changeListener = null; + } +} + +/** Credential provider for the Lite SDK. */ class __PRIVATE_LiteAuthCredentialsProvider { + constructor(t) { + this.auth = null, t.onInit((t => { + this.auth = t; + })); + } + getToken() { + return this.auth ? this.auth.getToken().then((t => t ? (__PRIVATE_hardAssert("string" == typeof t.accessToken, 42297, { + t: t + }), new __PRIVATE_OAuthToken(t.accessToken, new User(this.auth.getUid()))) : null)) : Promise.resolve(null); + } + invalidateToken() {} + start(t, e) {} + shutdown() {} +} + +/* + * FirstPartyToken provides a fresh token each time its value + * is requested, because if the token is too old, requests will be rejected. + * Technically this may no longer be necessary since the SDK should gracefully + * recover from unauthenticated errors (see b/33147818 for context), but it's + * safer to keep the implementation as-is. + */ class __PRIVATE_FirstPartyToken { + constructor(t, e, r) { + this.i = t, this.o = e, this.u = r, this.type = "FirstParty", this.user = User.FIRST_PARTY, + this.l = new Map; + } + /** + * Gets an authorization token, using a provided factory function, or return + * null. + */ h() { + return this.u ? this.u() : null; + } + get headers() { + this.l.set("X-Goog-AuthUser", this.i); + // Use array notation to prevent minification + const t = this.h(); + return t && this.l.set("Authorization", t), this.o && this.l.set("X-Goog-Iam-Authorization-Token", this.o), + this.l; + } +} + +/* + * Provides user credentials required for the Firestore JavaScript SDK + * to authenticate the user, using technique that is only available + * to applications hosted by Google. + */ class __PRIVATE_FirstPartyAuthCredentialsProvider { + constructor(t, e, r) { + this.i = t, this.o = e, this.u = r; + } + getToken() { + return Promise.resolve(new __PRIVATE_FirstPartyToken(this.i, this.o, this.u)); + } + start(t, e) { + // Fire with initial uid. + t.enqueueRetryable((() => e(User.FIRST_PARTY))); + } + shutdown() {} + invalidateToken() {} +} + +class AppCheckToken { + constructor(t) { + this.value = t, this.type = "AppCheck", this.headers = new Map, t && t.length > 0 && this.headers.set("x-firebase-appcheck", this.value); + } +} + +/** AppCheck token provider for the Lite SDK. */ class __PRIVATE_LiteAppCheckTokenProvider { + constructor(e, r) { + this.m = r, this.appCheck = null, this.T = null, _isFirebaseServerApp(e) && e.settings.appCheckToken && (this.T = e.settings.appCheckToken), + r.onInit((t => { + this.appCheck = t; + })); + } + getToken() { + return this.T ? Promise.resolve(new AppCheckToken(this.T)) : this.appCheck ? this.appCheck.getToken().then((t => t ? (__PRIVATE_hardAssert("string" == typeof t.token, 3470, { + tokenResult: t + }), new AppCheckToken(t.token)) : null)) : Promise.resolve(null); + } + invalidateToken() {} + start(t, e) {} + shutdown() {} +} + +/** + * Builds a CredentialsProvider depending on the type of + * the credentials passed in. + */ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class DatabaseInfo { + /** + * Constructs a DatabaseInfo using the provided host, databaseId and + * persistenceKey. + * + * @param databaseId - The database to use. + * @param appId - The Firebase App Id. + * @param persistenceKey - A unique identifier for this Firestore's local + * storage (used in conjunction with the databaseId). + * @param host - The Firestore backend host to connect to. + * @param ssl - Whether to use SSL when connecting. + * @param forceLongPolling - Whether to use the forceLongPolling option + * when using WebChannel as the network transport. + * @param autoDetectLongPolling - Whether to use the detectBufferingProxy + * option when using WebChannel as the network transport. + * @param longPollingOptions Options that configure long-polling. + * @param useFetchStreams Whether to use the Fetch API instead of + * XMLHTTPRequest + */ + constructor(t, e, r, n, i, s, o, a, u, _) { + this.databaseId = t, this.appId = e, this.persistenceKey = r, this.host = n, this.ssl = i, + this.forceLongPolling = s, this.autoDetectLongPolling = o, this.longPollingOptions = a, + this.useFetchStreams = u, this.isUsingEmulator = _; + } +} + +/** The default database name for a project. */ const Q = "(default)"; + +/** + * Represents the database ID a Firestore client is associated with. + * @internal + */ class DatabaseId { + constructor(t, e) { + this.projectId = t, this.database = e || Q; + } + static empty() { + return new DatabaseId("", ""); + } + get isDefaultDatabase() { + return this.database === Q; + } + isEqual(t) { + return t instanceof DatabaseId && t.projectId === this.projectId && t.database === this.database; + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Generates `nBytes` of random bytes. + * + * If `nBytes < 0` , an error will be thrown. + */ +function __PRIVATE_randomBytes(t) { + // Polyfills for IE and WebWorker by using `self` and `msCrypto` when `crypto` is not available. + const e = + // eslint-disable-next-line @typescript-eslint/no-explicit-any + "undefined" != typeof self && (self.crypto || self.msCrypto), r = new Uint8Array(t); + if (e && "function" == typeof e.getRandomValues) e.getRandomValues(r); else + // Falls back to Math.random + for (let e = 0; e < t; e++) r[e] = Math.floor(256 * Math.random()); + return r; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A utility class for generating unique alphanumeric IDs of a specified length. + * + * @internal + * Exported internally for testing purposes. + */ class __PRIVATE_AutoId { + static newId() { + // Alphanumeric characters + const t = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", e = 62 * Math.floor(256 / 62); + // The largest byte value that is a multiple of `char.length`. + let r = ""; + for (;r.length < 20; ) { + const n = __PRIVATE_randomBytes(40); + for (let i = 0; i < n.length; ++i) + // Only accept values that are [0, maxMultiple), this ensures they can + // be evenly mapped to indices of `chars` via a modulo operation. + r.length < 20 && n[i] < e && (r += t.charAt(n[i] % 62)); + } + return r; + } +} + +function __PRIVATE_primitiveComparator(t, e) { + return t < e ? -1 : t > e ? 1 : 0; +} + +/** Compare strings in UTF-8 encoded byte order */ function __PRIVATE_compareUtf8Strings(t, e) { + // Find the first differing character (a.k.a. "UTF-16 code unit") in the two strings and, + // if found, use that character to determine the relative ordering of the two strings as a + // whole. Comparing UTF-16 strings in UTF-8 byte order can be done simply and efficiently by + // comparing the UTF-16 code units (chars). This serendipitously works because of the way UTF-8 + // and UTF-16 happen to represent Unicode code points. + // After finding the first pair of differing characters, there are two cases: + // Case 1: Both characters are non-surrogates (code points less than or equal to 0xFFFF) or + // both are surrogates from a surrogate pair (that collectively represent code points greater + // than 0xFFFF). In this case their numeric order as UTF-16 code units is the same as the + // lexicographical order of their corresponding UTF-8 byte sequences. A direct comparison is + // sufficient. + // Case 2: One character is a surrogate and the other is not. In this case the surrogate- + // containing string is always ordered after the non-surrogate. This is because surrogates are + // used to represent code points greater than 0xFFFF which have 4-byte UTF-8 representations + // and are lexicographically greater than the 1, 2, or 3-byte representations of code points + // less than or equal to 0xFFFF. + // An example of why Case 2 is required is comparing the following two Unicode code points: + // |-----------------------|------------|---------------------|-----------------| + // | Name | Code Point | UTF-8 Encoding | UTF-16 Encoding | + // |-----------------------|------------|---------------------|-----------------| + // | Replacement Character | U+FFFD | 0xEF 0xBF 0xBD | 0xFFFD | + // | Grinning Face | U+1F600 | 0xF0 0x9F 0x98 0x80 | 0xD83D 0xDE00 | + // |-----------------------|------------|---------------------|-----------------| + // A lexicographical comparison of the UTF-8 encodings of these code points would order + // "Replacement Character" _before_ "Grinning Face" because 0xEF is less than 0xF0. However, a + // direct comparison of the UTF-16 code units, as would be done in case 1, would erroneously + // produce the _opposite_ ordering, because 0xFFFD is _greater than_ 0xD83D. As it turns out, + // this relative ordering holds for all comparisons of UTF-16 code points requiring a surrogate + // pair with those that do not. + const r = Math.min(t.length, e.length); + for (let n = 0; n < r; n++) { + const r = t.charAt(n), i = e.charAt(n); + if (r !== i) return __PRIVATE_isSurrogate(r) === __PRIVATE_isSurrogate(i) ? __PRIVATE_primitiveComparator(r, i) : __PRIVATE_isSurrogate(r) ? 1 : -1; + } + // Use the lengths of the strings to determine the overall comparison result since either the + // strings were equal or one is a prefix of the other. + return __PRIVATE_primitiveComparator(t.length, e.length); +} + +const k = 55296, L = 57343; + +function __PRIVATE_isSurrogate(t) { + const e = t.charCodeAt(0); + return e >= k && e <= L; +} + +/** Helper to compare arrays using isEqual(). */ function __PRIVATE_arrayEquals(t, e, r) { + return t.length === e.length && t.every(((t, n) => r(t, e[n]))); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ const M = "__name__"; + +/** + * Path represents an ordered sequence of string segments. + */ class BasePath { + constructor(t, e, r) { + void 0 === e ? e = 0 : e > t.length && fail(637, { + offset: e, + range: t.length + }), void 0 === r ? r = t.length - e : r > t.length - e && fail(1746, { + length: r, + range: t.length - e + }), this.segments = t, this.offset = e, this.len = r; + } + get length() { + return this.len; + } + isEqual(t) { + return 0 === BasePath.comparator(this, t); + } + child(t) { + const e = this.segments.slice(this.offset, this.limit()); + return t instanceof BasePath ? t.forEach((t => { + e.push(t); + })) : e.push(t), this.construct(e); + } + /** The index of one past the last segment of the path. */ limit() { + return this.offset + this.length; + } + popFirst(t) { + return t = void 0 === t ? 1 : t, this.construct(this.segments, this.offset + t, this.length - t); + } + popLast() { + return this.construct(this.segments, this.offset, this.length - 1); + } + firstSegment() { + return this.segments[this.offset]; + } + lastSegment() { + return this.get(this.length - 1); + } + get(t) { + return this.segments[this.offset + t]; + } + isEmpty() { + return 0 === this.length; + } + isPrefixOf(t) { + if (t.length < this.length) return !1; + for (let e = 0; e < this.length; e++) if (this.get(e) !== t.get(e)) return !1; + return !0; + } + isImmediateParentOf(t) { + if (this.length + 1 !== t.length) return !1; + for (let e = 0; e < this.length; e++) if (this.get(e) !== t.get(e)) return !1; + return !0; + } + forEach(t) { + for (let e = this.offset, r = this.limit(); e < r; e++) t(this.segments[e]); + } + toArray() { + return this.segments.slice(this.offset, this.limit()); + } + /** + * Compare 2 paths segment by segment, prioritizing numeric IDs + * (e.g., "__id123__") in numeric ascending order, followed by string + * segments in lexicographical order. + */ static comparator(t, e) { + const r = Math.min(t.length, e.length); + for (let n = 0; n < r; n++) { + const r = BasePath.compareSegments(t.get(n), e.get(n)); + if (0 !== r) return r; + } + return __PRIVATE_primitiveComparator(t.length, e.length); + } + static compareSegments(t, e) { + const r = BasePath.isNumericId(t), n = BasePath.isNumericId(e); + return r && !n ? -1 : !r && n ? 1 : r && n ? BasePath.extractNumericId(t).compare(BasePath.extractNumericId(e)) : __PRIVATE_compareUtf8Strings(t, e); + } + // Checks if a segment is a numeric ID (starts with "__id" and ends with "__"). + static isNumericId(t) { + return t.startsWith("__id") && t.endsWith("__"); + } + static extractNumericId(t) { + return Integer.fromString(t.substring(4, t.length - 2)); + } +} + +/** + * A slash-separated path for navigating resources (documents and collections) + * within Firestore. + * + * @internal + */ class ResourcePath extends BasePath { + construct(t, e, r) { + return new ResourcePath(t, e, r); + } + canonicalString() { + // NOTE: The client is ignorant of any path segments containing escape + // sequences (e.g. __id123__) and just passes them through raw (they exist + // for legacy reasons and should not be used frequently). + return this.toArray().join("/"); + } + toString() { + return this.canonicalString(); + } + /** + * Returns a string representation of this path + * where each path segment has been encoded with + * `encodeURIComponent`. + */ toUriEncodedString() { + return this.toArray().map(encodeURIComponent).join("/"); + } + /** + * Creates a resource path from the given slash-delimited string. If multiple + * arguments are provided, all components are combined. Leading and trailing + * slashes from all components are ignored. + */ static fromString(...t) { + // NOTE: The client is ignorant of any path segments containing escape + // sequences (e.g. __id123__) and just passes them through raw (they exist + // for legacy reasons and should not be used frequently). + const e = []; + for (const r of t) { + if (r.indexOf("//") >= 0) throw new FirestoreError(y, `Invalid segment (${r}). Paths must not contain // in them.`); + // Strip leading and trailing slashed. + e.push(...r.split("/").filter((t => t.length > 0))); + } + return new ResourcePath(e); + } + static emptyPath() { + return new ResourcePath([]); + } +} + +const x = /^[_a-zA-Z][_a-zA-Z0-9]*$/; + +/** + * A dot-separated path for navigating sub-objects within a document. + * @internal + */ class FieldPath$1 extends BasePath { + construct(t, e, r) { + return new FieldPath$1(t, e, r); + } + /** + * Returns true if the string could be used as a segment in a field path + * without escaping. + */ static isValidIdentifier(t) { + return x.test(t); + } + canonicalString() { + return this.toArray().map((t => (t = t.replace(/\\/g, "\\\\").replace(/`/g, "\\`"), + FieldPath$1.isValidIdentifier(t) || (t = "`" + t + "`"), t))).join("."); + } + toString() { + return this.canonicalString(); + } + /** + * Returns true if this field references the key of a document. + */ isKeyField() { + return 1 === this.length && this.get(0) === M; + } + /** + * The field designating the key of a document. + */ static keyField() { + return new FieldPath$1([ M ]); + } + /** + * Parses a field string from the given server-formatted string. + * + * - Splitting the empty string is not allowed (for now at least). + * - Empty segments within the string (e.g. if there are two consecutive + * separators) are not allowed. + * + * TODO(b/37244157): we should make this more strict. Right now, it allows + * non-identifier path components, even if they aren't escaped. + */ static fromServerFormat(t) { + const e = []; + let r = "", n = 0; + const __PRIVATE_addCurrentSegment = () => { + if (0 === r.length) throw new FirestoreError(y, `Invalid field path (${t}). Paths must not be empty, begin with '.', end with '.', or contain '..'`); + e.push(r), r = ""; + }; + let i = !1; + for (;n < t.length; ) { + const e = t[n]; + if ("\\" === e) { + if (n + 1 === t.length) throw new FirestoreError(y, "Path has trailing escape character: " + t); + const e = t[n + 1]; + if ("\\" !== e && "." !== e && "`" !== e) throw new FirestoreError(y, "Path has invalid escape sequence: " + t); + r += e, n += 2; + } else "`" === e ? (i = !i, n++) : "." !== e || i ? (r += e, n++) : (__PRIVATE_addCurrentSegment(), + n++); + } + if (__PRIVATE_addCurrentSegment(), i) throw new FirestoreError(y, "Unterminated ` in path: " + t); + return new FieldPath$1(e); + } + static emptyPath() { + return new FieldPath$1([]); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @internal + */ class DocumentKey { + constructor(t) { + this.path = t; + } + static fromPath(t) { + return new DocumentKey(ResourcePath.fromString(t)); + } + static fromName(t) { + return new DocumentKey(ResourcePath.fromString(t).popFirst(5)); + } + static empty() { + return new DocumentKey(ResourcePath.emptyPath()); + } + get collectionGroup() { + return this.path.popLast().lastSegment(); + } + /** Returns true if the document is in the specified collectionId. */ hasCollectionId(t) { + return this.path.length >= 2 && this.path.get(this.path.length - 2) === t; + } + /** Returns the collection group (i.e. the name of the parent collection) for this key. */ getCollectionGroup() { + return this.path.get(this.path.length - 2); + } + /** Returns the fully qualified path to the parent collection. */ getCollectionPath() { + return this.path.popLast(); + } + isEqual(t) { + return null !== t && 0 === ResourcePath.comparator(this.path, t.path); + } + toString() { + return this.path.toString(); + } + static comparator(t, e) { + return ResourcePath.comparator(t.path, e.path); + } + static isDocumentKey(t) { + return t.length % 2 == 0; + } + /** + * Creates and returns a new document key with the given segments. + * + * @param segments - The segments of the path to the document + * @returns A new instance of DocumentKey + */ static fromSegments(t) { + return new DocumentKey(new ResourcePath(t.slice())); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ function __PRIVATE_validateNonEmptyArgument(t, e, r) { + if (!r) throw new FirestoreError(y, `Function ${t}() cannot be called with an empty ${e}.`); +} + +/** + * Validates that two boolean options are not set at the same time. + * @internal + */ +/** + * Validates that `path` refers to a document (indicated by the fact it contains + * an even numbers of segments). + */ +function __PRIVATE_validateDocumentPath(t) { + if (!DocumentKey.isDocumentKey(t)) throw new FirestoreError(y, `Invalid document reference. Document references must have an even number of segments, but ${t} has ${t.length}.`); +} + +/** + * Validates that `path` refers to a collection (indicated by the fact it + * contains an odd numbers of segments). + */ function __PRIVATE_validateCollectionPath(t) { + if (DocumentKey.isDocumentKey(t)) throw new FirestoreError(y, `Invalid collection reference. Collection references must have an odd number of segments, but ${t} has ${t.length}.`); +} + +/** + * Returns true if it's a non-null object without a custom prototype + * (i.e. excludes Array, Date, etc.). + */ function __PRIVATE_isPlainObject(t) { + return "object" == typeof t && null !== t && (Object.getPrototypeOf(t) === Object.prototype || null === Object.getPrototypeOf(t)); +} + +/** Returns a string describing the type / value of the provided input. */ function __PRIVATE_valueDescription(t) { + if (void 0 === t) return "undefined"; + if (null === t) return "null"; + if ("string" == typeof t) return t.length > 20 && (t = `${t.substring(0, 20)}...`), + JSON.stringify(t); + if ("number" == typeof t || "boolean" == typeof t) return "" + t; + if ("object" == typeof t) { + if (t instanceof Array) return "an array"; + { + const e = + /** try to get the constructor name for an object. */ + function __PRIVATE_tryGetCustomObjectType(t) { + if (t.constructor) return t.constructor.name; + return null; + } + /** + * Casts `obj` to `T`, optionally unwrapping Compat types to expose the + * underlying instance. Throws if `obj` is not an instance of `T`. + * + * This cast is used in the Lite and Full SDK to verify instance types for + * arguments passed to the public API. + * @internal + */ (t); + return e ? `a custom ${e} object` : "an object"; + } + } + return "function" == typeof t ? "a function" : fail(12329, { + type: typeof t + }); +} + +function __PRIVATE_cast(t, +// eslint-disable-next-line @typescript-eslint/no-explicit-any +e) { + if ("_delegate" in t && ( + // Unwrap Compat types + // eslint-disable-next-line @typescript-eslint/no-explicit-any + t = t._delegate), !(t instanceof e)) { + if (e.name === t.constructor.name) throw new FirestoreError(y, "Type does not match the expected instance. Did you pass a reference from a different Firestore SDK?"); + { + const r = __PRIVATE_valueDescription(t); + throw new FirestoreError(y, `Expected type '${e.name}', but it was: ${r}`); + } + } + return t; +} + +function __PRIVATE_validatePositiveNumber(t, e) { + if (e <= 0) throw new FirestoreError(y, `Function ${t}() requires a positive number, but it was: ${e}.`); +} + +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Compares two `ExperimentalLongPollingOptions` objects for equality. + */ +/** + * Creates and returns a new `ExperimentalLongPollingOptions` with the same + * option values as the given instance. + */ +function __PRIVATE_cloneLongPollingOptions(t) { + const e = {}; + return void 0 !== t.timeoutSeconds && (e.timeoutSeconds = t.timeoutSeconds), e; +} + +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * The value returned from the most recent invocation of + * `generateUniqueDebugId()`, or null if it has never been invoked. + */ let U = null; + +/** + * Generates and returns an initial value for `lastUniqueDebugId`. + * + * The returned value is randomly selected from a range of integers that are + * represented as 8 hexadecimal digits. This means that (within reason) any + * numbers generated by incrementing the returned number by 1 will also be + * represented by 8 hexadecimal digits. This leads to all "IDs" having the same + * length when converted to a hexadecimal string, making reading logs containing + * these IDs easier to follow. And since the return value is randomly selected + * it will help to differentiate between logs from different executions. + */ +/** + * Generates and returns a unique ID as a hexadecimal string. + * + * The returned ID is intended to be used in debug logging messages to help + * correlate log messages that may be spatially separated in the logs, but + * logically related. For example, a network connection could include the same + * "debug ID" string in all of its log messages to help trace a specific + * connection over time. + * + * @return the 10-character generated ID (e.g. "0xa1b2c3d4"). + */ +function __PRIVATE_generateUniqueDebugId() { + return null === U ? U = function __PRIVATE_generateInitialUniqueDebugId() { + return 268435456 + Math.round(2147483648 * Math.random()); + }() : U++, "0x" + U.toString(16); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Returns whether a variable is either undefined or null. + */ function __PRIVATE_isNullOrUndefined(t) { + return null == t; +} + +/** Returns whether the value represents -0. */ function __PRIVATE_isNegativeZero(t) { + // Detect if the value is -0.0. Based on polyfill from + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is + return 0 === t && 1 / t == -1 / 0; +} + +/** + * Returns whether a value is an integer and in the safe integer range + * @param value - The value to test for being an integer and in the safe range + */ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const j = "RestConnection", z = { + BatchGetDocuments: "batchGet", + Commit: "commit", + RunQuery: "runQuery", + RunAggregationQuery: "runAggregationQuery" +}; + +/** + * Maps RPC names to the corresponding REST endpoint name. + * + * We use array notation to avoid mangling. + */ +/** + * Base class for all Rest-based connections to the backend (WebChannel and + * HTTP). + */ +class __PRIVATE_RestConnection { + get P() { + // Both `invokeRPC()` and `invokeStreamingRPC()` use their `path` arguments to determine + // where to run the query, and expect the `request` to NOT specify the "path". + return !1; + } + constructor(t) { + this.databaseInfo = t, this.databaseId = t.databaseId; + const e = t.ssl ? "https" : "http", r = encodeURIComponent(this.databaseId.projectId), n = encodeURIComponent(this.databaseId.database); + this.A = e + "://" + t.host, this.R = `projects/${r}/databases/${n}`, this.V = this.databaseId.database === Q ? `project_id=${r}` : `project_id=${r}&database_id=${n}`; + } + I(t, e, r, n, i) { + const s = __PRIVATE_generateUniqueDebugId(), o = this.p(t, e.toUriEncodedString()); + __PRIVATE_logDebug(j, `Sending RPC '${t}' ${s}:`, o, r); + const a = { + "google-cloud-resource-prefix": this.R, + "x-goog-request-params": this.V + }; + this.F(a, n, i); + const {host: u} = new URL(o), _ = isCloudWorkstation(u); + return this.v(t, o, a, r, _).then((e => (__PRIVATE_logDebug(j, `Received RPC '${t}' ${s}: `, e), + e)), (e => { + throw __PRIVATE_logWarn(j, `RPC '${t}' ${s} failed with error: `, e, "url: ", o, "request:", r), + e; + })); + } + D(t, e, r, n, i, s) { + // The REST API automatically aggregates all of the streamed results, so we + // can just use the normal invoke() method. + return this.I(t, e, r, n, i); + } + /** + * Modifies the headers for a request, adding any authorization token if + * present and any additional headers for the request. + */ F(t, e, r) { + t["X-Goog-Api-Client"] = + // SDK_VERSION is updated to different value at runtime depending on the entry point, + // so we need to get its value when we need it in a function. + function __PRIVATE_getGoogApiClientValue() { + return "gl-js/ fire/" + A; + }(), + // Content-Type: text/plain will avoid preflight requests which might + // mess with CORS and redirects by proxies. If we add custom headers + // we will need to change this code to potentially use the $httpOverwrite + // parameter supported by ESF to avoid triggering preflight requests. + t["Content-Type"] = "text/plain", this.databaseInfo.appId && (t["X-Firebase-GMPID"] = this.databaseInfo.appId), + e && e.headers.forEach(((e, r) => t[r] = e)), r && r.headers.forEach(((e, r) => t[r] = e)); + } + p(t, e) { + const r = z[t]; + return `${this.A}/v1/${e}:${r}`; + } + /** + * Closes and cleans up any resources associated with the connection. This + * implementation is a no-op because there are no resources associated + * with the RestConnection that need to be cleaned up. + */ terminate() { + // No-op + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Error Codes describing the different ways GRPC can fail. These are copied + * directly from GRPC's sources here: + * + * https://github.com/grpc/grpc/blob/bceec94ea4fc5f0085d81235d8e1c06798dc341a/include/grpc%2B%2B/impl/codegen/status_code_enum.h + * + * Important! The names of these identifiers matter because the string forms + * are used for reverse lookups from the webchannel stream. Do NOT change the + * names of these identifiers or change this into a const enum. + */ var W, K; + +/** + * Converts an HTTP Status Code to the equivalent error code. + * + * @param status - An HTTP Status Code, like 200, 404, 503, etc. + * @returns The equivalent Code. Unknown status codes are mapped to + * Code.UNKNOWN. + */ +function __PRIVATE_mapCodeFromHttpStatus(t) { + if (void 0 === t) return __PRIVATE_logError("RPC_ERROR", "HTTP error has no status"), + p; + // The canonical error codes for Google APIs [1] specify mapping onto HTTP + // status codes but the mapping is not bijective. In each case of ambiguity + // this function chooses a primary error. + + // [1] + // https://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto + switch (t) { + case 200: + // OK + return V; + + case 400: + // Bad Request + return S; + + // Other possibilities based on the forward mapping + // return Code.INVALID_ARGUMENT; + // return Code.OUT_OF_RANGE; + case 401: + // Unauthorized + return D; + + case 403: + // Forbidden + return v; + + case 404: + // Not Found + return w; + + case 409: + // Conflict + return C; + + // Other possibilities: + // return Code.ALREADY_EXISTS; + case 416: + // Range Not Satisfiable + return N; + + case 429: + // Too Many Requests + return b; + + case 499: + // Client Closed Request + return I; + + case 500: + // Internal Server Error + return p; + + // Other possibilities: + // return Code.INTERNAL; + // return Code.DATA_LOSS; + case 501: + // Unimplemented + return O; + + case 503: + // Service Unavailable + return B; + + case 504: + // Gateway Timeout + return g; + + default: + return t >= 200 && t < 300 ? V : t >= 400 && t < 500 ? S : t >= 500 && t < 600 ? q : p; + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A Rest-based connection that relies on the native HTTP stack + * (e.g. `fetch` or a polyfill). + */ (K = W || (W = {}))[K.OK = 0] = "OK", K[K.CANCELLED = 1] = "CANCELLED", K[K.UNKNOWN = 2] = "UNKNOWN", +K[K.INVALID_ARGUMENT = 3] = "INVALID_ARGUMENT", K[K.DEADLINE_EXCEEDED = 4] = "DEADLINE_EXCEEDED", +K[K.NOT_FOUND = 5] = "NOT_FOUND", K[K.ALREADY_EXISTS = 6] = "ALREADY_EXISTS", K[K.PERMISSION_DENIED = 7] = "PERMISSION_DENIED", +K[K.UNAUTHENTICATED = 16] = "UNAUTHENTICATED", K[K.RESOURCE_EXHAUSTED = 8] = "RESOURCE_EXHAUSTED", +K[K.FAILED_PRECONDITION = 9] = "FAILED_PRECONDITION", K[K.ABORTED = 10] = "ABORTED", +K[K.OUT_OF_RANGE = 11] = "OUT_OF_RANGE", K[K.UNIMPLEMENTED = 12] = "UNIMPLEMENTED", +K[K.INTERNAL = 13] = "INTERNAL", K[K.UNAVAILABLE = 14] = "UNAVAILABLE", K[K.DATA_LOSS = 15] = "DATA_LOSS"; + +class __PRIVATE_FetchConnection extends __PRIVATE_RestConnection { + S(t, e) { + throw new Error("Not supported by FetchConnection"); + } + async v(t, e, r, n, i) { + const s = JSON.stringify(n); + let o; + try { + const t = { + method: "POST", + headers: r, + body: s + }; + i && (t.credentials = "include"), o = await fetch(e, t); + } catch (t) { + const e = t; + throw new FirestoreError(__PRIVATE_mapCodeFromHttpStatus(e.status), "Request failed with error: " + e.statusText); + } + if (!o.ok) { + let t = await o.json(); + Array.isArray(t) && (t = t[0]); + const e = t?.error?.message; + throw new FirestoreError(__PRIVATE_mapCodeFromHttpStatus(o.status), `Request failed with error: ${e ?? o.statusText}`); + } + return o.json(); + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Initializes the HTTP connection for the REST API. */ +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Concrete implementation of the Aggregate type. + */ +class __PRIVATE_AggregateImpl { + constructor(t, e, r) { + this.alias = t, this.aggregateType = e, this.fieldPath = r; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ function __PRIVATE_objectSize(t) { + let e = 0; + for (const r in t) Object.prototype.hasOwnProperty.call(t, r) && e++; + return e; +} + +function forEach(t, e) { + for (const r in t) Object.prototype.hasOwnProperty.call(t, r) && e(r, t[r]); +} + +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An error encountered while decoding base64 string. + */ +class __PRIVATE_Base64DecodeError extends Error { + constructor() { + super(...arguments), this.name = "Base64DecodeError"; + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Converts a Base64 encoded string to a binary string. */ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Immutable class that represents a "proto" byte string. + * + * Proto byte strings can either be Base64-encoded strings or Uint8Arrays when + * sent on the wire. This class abstracts away this differentiation by holding + * the proto byte string in a common class that must be converted into a string + * before being sent as a proto. + * @internal + */ +class ByteString { + constructor(t) { + this.binaryString = t; + } + static fromBase64String(t) { + const e = function __PRIVATE_decodeBase64(t) { + try { + return atob(t); + } catch (t) { + // Check that `DOMException` is defined before using it to avoid + // "ReferenceError: Property 'DOMException' doesn't exist" in react-native. + // (https://github.com/firebase/firebase-js-sdk/issues/7115) + throw "undefined" != typeof DOMException && t instanceof DOMException ? new __PRIVATE_Base64DecodeError("Invalid base64 string: " + t) : t; + } + } + /** Converts a binary string to a Base64 encoded string. */ (t); + return new ByteString(e); + } + static fromUint8Array(t) { + // TODO(indexing); Remove the copy of the byte string here as this method + // is frequently called during indexing. + const e = + /** + * Helper function to convert an Uint8array to a binary string. + */ + function __PRIVATE_binaryStringFromUint8Array(t) { + let e = ""; + for (let r = 0; r < t.length; ++r) e += String.fromCharCode(t[r]); + return e; + } + /** + * Helper function to convert a binary string to an Uint8Array. + */ (t); + return new ByteString(e); + } + [Symbol.iterator]() { + let t = 0; + return { + next: () => t < this.binaryString.length ? { + value: this.binaryString.charCodeAt(t++), + done: !1 + } : { + value: void 0, + done: !0 + } + }; + } + toBase64() { + return function __PRIVATE_encodeBase64(t) { + return btoa(t); + }(this.binaryString); + } + toUint8Array() { + return function __PRIVATE_uint8ArrayFromBinaryString(t) { + const e = new Uint8Array(t.length); + for (let r = 0; r < t.length; r++) e[r] = t.charCodeAt(r); + return e; + } + /** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + // A RegExp matching ISO 8601 UTC timestamps with optional fraction. + (this.binaryString); + } + approximateByteSize() { + return 2 * this.binaryString.length; + } + compareTo(t) { + return __PRIVATE_primitiveComparator(this.binaryString, t.binaryString); + } + isEqual(t) { + return this.binaryString === t.binaryString; + } +} + +ByteString.EMPTY_BYTE_STRING = new ByteString(""); + +const G = new RegExp(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.(\d+))?Z$/); + +/** + * Converts the possible Proto values for a timestamp value into a "seconds and + * nanos" representation. + */ function __PRIVATE_normalizeTimestamp(t) { + // The json interface (for the browser) will return an iso timestamp string, + // while the proto js library (for node) will return a + // google.protobuf.Timestamp instance. + if (__PRIVATE_hardAssert(!!t, 39018), "string" == typeof t) { + // The date string can have higher precision (nanos) than the Date class + // (millis), so we do some custom parsing here. + // Parse the nanos right out of the string. + let e = 0; + const r = G.exec(t); + if (__PRIVATE_hardAssert(!!r, 46558, { + timestamp: t + }), r[1]) { + // Pad the fraction out to 9 digits (nanos). + let t = r[1]; + t = (t + "000000000").substr(0, 9), e = Number(t); + } + // Parse the date to get the seconds. + const n = new Date(t); + return { + seconds: Math.floor(n.getTime() / 1e3), + nanos: e + }; + } + return { + seconds: __PRIVATE_normalizeNumber(t.seconds), + nanos: __PRIVATE_normalizeNumber(t.nanos) + }; +} + +/** + * Converts the possible Proto types for numbers into a JavaScript number. + * Returns 0 if the value is not numeric. + */ function __PRIVATE_normalizeNumber(t) { + // TODO(bjornick): Handle int64 greater than 53 bits. + return "number" == typeof t ? t : "string" == typeof t ? Number(t) : 0; +} + +/** Converts the possible Proto types for Blobs into a ByteString. */ function __PRIVATE_normalizeByteString(t) { + return "string" == typeof t ? ByteString.fromBase64String(t) : ByteString.fromUint8Array(t); +} + +/** + * @license + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Helper function to define a JSON schema {@link Property}. + * @private + * @internal + */ function property(t, e) { + const r = { + typeString: t + }; + return e && (r.value = e), r; +} + +/** + * Validates the JSON object based on the provided schema, and narrows the type to the provided + * JSON schema. + * @private + * @internal + * + * @param json A JSON object to validate. + * @param scheme a {@link JsonSchema} that defines the properties to validate. + * @returns true if the JSON schema exists within the object. Throws a FirestoreError otherwise. + */ function __PRIVATE_validateJSON(t, e) { + if (!__PRIVATE_isPlainObject(t)) throw new FirestoreError(y, "JSON must be an object"); + let r; + for (const n in e) if (e[n]) { + const i = e[n].typeString, s = "value" in e[n] ? { + value: e[n].value + } : void 0; + if (!(n in t)) { + r = `JSON missing required field: '${n}'`; + break; + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const o = t[n]; + if (i && typeof o !== i) { + r = `JSON field '${n}' must be a ${i}.`; + break; + } + if (void 0 !== s && o !== s.value) { + r = `Expected '${n}' field to equal '${s.value}'`; + break; + } + } + if (r) throw new FirestoreError(y, r); + return !0; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// The earliest date supported by Firestore timestamps (0001-01-01T00:00:00Z). +const J = -62135596800, H = 1e6; + +// Number of nanoseconds in a millisecond. +/** + * A `Timestamp` represents a point in time independent of any time zone or + * calendar, represented as seconds and fractions of seconds at nanosecond + * resolution in UTC Epoch time. + * + * It is encoded using the Proleptic Gregorian Calendar which extends the + * Gregorian calendar backwards to year one. It is encoded assuming all minutes + * are 60 seconds long, i.e. leap seconds are "smeared" so that no leap second + * table is needed for interpretation. Range is from 0001-01-01T00:00:00Z to + * 9999-12-31T23:59:59.999999999Z. + * + * For examples and further specifications, refer to the + * {@link https://github.com/google/protobuf/blob/master/src/google/protobuf/timestamp.proto | Timestamp definition}. + */ +class Timestamp { + /** + * Creates a new timestamp with the current date, with millisecond precision. + * + * @returns a new timestamp representing the current date. + */ + static now() { + return Timestamp.fromMillis(Date.now()); + } + /** + * Creates a new timestamp from the given date. + * + * @param date - The date to initialize the `Timestamp` from. + * @returns A new `Timestamp` representing the same point in time as the given + * date. + */ static fromDate(t) { + return Timestamp.fromMillis(t.getTime()); + } + /** + * Creates a new timestamp from the given number of milliseconds. + * + * @param milliseconds - Number of milliseconds since Unix epoch + * 1970-01-01T00:00:00Z. + * @returns A new `Timestamp` representing the same point in time as the given + * number of milliseconds. + */ static fromMillis(t) { + const e = Math.floor(t / 1e3), r = Math.floor((t - 1e3 * e) * H); + return new Timestamp(e, r); + } + /** + * Creates a new timestamp. + * + * @param seconds - The number of seconds of UTC time since Unix epoch + * 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to + * 9999-12-31T23:59:59Z inclusive. + * @param nanoseconds - The non-negative fractions of a second at nanosecond + * resolution. Negative second values with fractions must still have + * non-negative nanoseconds values that count forward in time. Must be + * from 0 to 999,999,999 inclusive. + */ constructor( + /** + * The number of seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z. + */ + t, + /** + * The fractions of a second at nanosecond resolution.* + */ + e) { + if (this.seconds = t, this.nanoseconds = e, e < 0) throw new FirestoreError(y, "Timestamp nanoseconds out of range: " + e); + if (e >= 1e9) throw new FirestoreError(y, "Timestamp nanoseconds out of range: " + e); + if (t < J) throw new FirestoreError(y, "Timestamp seconds out of range: " + t); + // This will break in the year 10,000. + if (t >= 253402300800) throw new FirestoreError(y, "Timestamp seconds out of range: " + t); + } + /** + * Converts a `Timestamp` to a JavaScript `Date` object. This conversion + * causes a loss of precision since `Date` objects only support millisecond + * precision. + * + * @returns JavaScript `Date` object representing the same point in time as + * this `Timestamp`, with millisecond precision. + */ toDate() { + return new Date(this.toMillis()); + } + /** + * Converts a `Timestamp` to a numeric timestamp (in milliseconds since + * epoch). This operation causes a loss of precision. + * + * @returns The point in time corresponding to this timestamp, represented as + * the number of milliseconds since Unix epoch 1970-01-01T00:00:00Z. + */ toMillis() { + return 1e3 * this.seconds + this.nanoseconds / H; + } + _compareTo(t) { + return this.seconds === t.seconds ? __PRIVATE_primitiveComparator(this.nanoseconds, t.nanoseconds) : __PRIVATE_primitiveComparator(this.seconds, t.seconds); + } + /** + * Returns true if this `Timestamp` is equal to the provided one. + * + * @param other - The `Timestamp` to compare against. + * @returns true if this `Timestamp` is equal to the provided one. + */ isEqual(t) { + return t.seconds === this.seconds && t.nanoseconds === this.nanoseconds; + } + /** Returns a textual representation of this `Timestamp`. */ toString() { + return "Timestamp(seconds=" + this.seconds + ", nanoseconds=" + this.nanoseconds + ")"; + } + /** + * Returns a JSON-serializable representation of this `Timestamp`. + */ toJSON() { + return { + type: Timestamp._jsonSchemaVersion, + seconds: this.seconds, + nanoseconds: this.nanoseconds + }; + } + /** + * Builds a `Timestamp` instance from a JSON object created by {@link Timestamp.toJSON}. + */ static fromJSON(t) { + if (__PRIVATE_validateJSON(t, Timestamp._jsonSchema)) return new Timestamp(t.seconds, t.nanoseconds); + } + /** + * Converts this object to a primitive string, which allows `Timestamp` objects + * to be compared using the `>`, `<=`, `>=` and `>` operators. + */ valueOf() { + // This method returns a string of the form . where + // is translated to have a non-negative value and both + // and are left-padded with zeroes to be a consistent length. + // Strings with this format then have a lexicographical ordering that matches + // the expected ordering. The translation is done to avoid having + // a leading negative sign (i.e. a leading '-' character) in its string + // representation, which would affect its lexicographical ordering. + const t = this.seconds - J; + // Note: Up to 12 decimal digits are required to represent all valid + // 'seconds' values. + return String(t).padStart(12, "0") + "." + String(this.nanoseconds).padStart(9, "0"); + } +} + +Timestamp._jsonSchemaVersion = "firestore/timestamp/1.0", Timestamp._jsonSchema = { + type: property("string", Timestamp._jsonSchemaVersion), + seconds: property("number"), + nanoseconds: property("number") +}; + +function __PRIVATE_isServerTimestamp(t) { + const e = (t?.mapValue?.fields || {}).__type__?.stringValue; + return "server_timestamp" === e; +} + +/** + * Returns the value of the field before this ServerTimestamp was set. + * + * Preserving the previous values allows the user to display the last resoled + * value until the backend responds with the timestamp. + */ function __PRIVATE_getPreviousValue(t) { + const e = t.mapValue.fields.__previous_value__; + return __PRIVATE_isServerTimestamp(e) ? __PRIVATE_getPreviousValue(e) : e; +} + +/** + * Returns the local time at which this timestamp was first set. + */ function __PRIVATE_getLocalWriteTime(t) { + const e = __PRIVATE_normalizeTimestamp(t.mapValue.fields.__local_write_time__.timestampValue); + return new Timestamp(e.seconds, e.nanos); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ const Y = "__type__", Z = "__max__", X = { + fields: { + __type__: { + stringValue: Z + } + } +}, tt = "__vector__", et = "value"; + +/** Extracts the backend's type order for the provided value. */ +function __PRIVATE_typeOrder(t) { + return "nullValue" in t ? 0 /* TypeOrder.NullValue */ : "booleanValue" in t ? 1 /* TypeOrder.BooleanValue */ : "integerValue" in t || "doubleValue" in t ? 2 /* TypeOrder.NumberValue */ : "timestampValue" in t ? 3 /* TypeOrder.TimestampValue */ : "stringValue" in t ? 5 /* TypeOrder.StringValue */ : "bytesValue" in t ? 6 /* TypeOrder.BlobValue */ : "referenceValue" in t ? 7 /* TypeOrder.RefValue */ : "geoPointValue" in t ? 8 /* TypeOrder.GeoPointValue */ : "arrayValue" in t ? 9 /* TypeOrder.ArrayValue */ : "mapValue" in t ? __PRIVATE_isServerTimestamp(t) ? 4 /* TypeOrder.ServerTimestampValue */ : + /** Returns true if the Value represents the canonical {@link #MAX_VALUE} . */ + function __PRIVATE_isMaxValue(t) { + return (((t.mapValue || {}).fields || {}).__type__ || {}).stringValue === Z; + } + /** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + /** + * Represents a bound of a query. + * + * The bound is specified with the given components representing a position and + * whether it's just before or just after the position (relative to whatever the + * query order is). + * + * The position represents a logical index position for a query. It's a prefix + * of values for the (potentially implicit) order by clauses of a query. + * + * Bound provides a function to determine whether a document comes before or + * after a bound. This is influenced by whether the position is just before or + * just after the provided values. + */ (t) ? 9007199254740991 /* TypeOrder.MaxValue */ : + /** Returns true if `value` is a VetorValue. */ + function __PRIVATE_isVectorValue(t) { + const e = (t?.mapValue?.fields || {})[Y]?.stringValue; + return e === tt; + } + /** Creates a deep copy of `source`. */ (t) ? 10 /* TypeOrder.VectorValue */ : 11 /* TypeOrder.ObjectValue */ : fail(28295, { + value: t + }); +} + +/** Tests `left` and `right` for equality based on the backend semantics. */ function __PRIVATE_valueEquals(t, e) { + if (t === e) return !0; + const r = __PRIVATE_typeOrder(t); + if (r !== __PRIVATE_typeOrder(e)) return !1; + switch (r) { + case 0 /* TypeOrder.NullValue */ : + case 9007199254740991 /* TypeOrder.MaxValue */ : + return !0; + + case 1 /* TypeOrder.BooleanValue */ : + return t.booleanValue === e.booleanValue; + + case 4 /* TypeOrder.ServerTimestampValue */ : + return __PRIVATE_getLocalWriteTime(t).isEqual(__PRIVATE_getLocalWriteTime(e)); + + case 3 /* TypeOrder.TimestampValue */ : + return function __PRIVATE_timestampEquals(t, e) { + if ("string" == typeof t.timestampValue && "string" == typeof e.timestampValue && t.timestampValue.length === e.timestampValue.length) + // Use string equality for ISO 8601 timestamps + return t.timestampValue === e.timestampValue; + const r = __PRIVATE_normalizeTimestamp(t.timestampValue), n = __PRIVATE_normalizeTimestamp(e.timestampValue); + return r.seconds === n.seconds && r.nanos === n.nanos; + }(t, e); + + case 5 /* TypeOrder.StringValue */ : + return t.stringValue === e.stringValue; + + case 6 /* TypeOrder.BlobValue */ : + return function __PRIVATE_blobEquals(t, e) { + return __PRIVATE_normalizeByteString(t.bytesValue).isEqual(__PRIVATE_normalizeByteString(e.bytesValue)); + }(t, e); + + case 7 /* TypeOrder.RefValue */ : + return t.referenceValue === e.referenceValue; + + case 8 /* TypeOrder.GeoPointValue */ : + return function __PRIVATE_geoPointEquals(t, e) { + return __PRIVATE_normalizeNumber(t.geoPointValue.latitude) === __PRIVATE_normalizeNumber(e.geoPointValue.latitude) && __PRIVATE_normalizeNumber(t.geoPointValue.longitude) === __PRIVATE_normalizeNumber(e.geoPointValue.longitude); + }(t, e); + + case 2 /* TypeOrder.NumberValue */ : + return function __PRIVATE_numberEquals(t, e) { + if ("integerValue" in t && "integerValue" in e) return __PRIVATE_normalizeNumber(t.integerValue) === __PRIVATE_normalizeNumber(e.integerValue); + if ("doubleValue" in t && "doubleValue" in e) { + const r = __PRIVATE_normalizeNumber(t.doubleValue), n = __PRIVATE_normalizeNumber(e.doubleValue); + return r === n ? __PRIVATE_isNegativeZero(r) === __PRIVATE_isNegativeZero(n) : isNaN(r) && isNaN(n); + } + return !1; + }(t, e); + + case 9 /* TypeOrder.ArrayValue */ : + return __PRIVATE_arrayEquals(t.arrayValue.values || [], e.arrayValue.values || [], __PRIVATE_valueEquals); + + case 10 /* TypeOrder.VectorValue */ : + case 11 /* TypeOrder.ObjectValue */ : + return function __PRIVATE_objectEquals(t, e) { + const r = t.mapValue.fields || {}, n = e.mapValue.fields || {}; + if (__PRIVATE_objectSize(r) !== __PRIVATE_objectSize(n)) return !1; + for (const t in r) if (r.hasOwnProperty(t) && (void 0 === n[t] || !__PRIVATE_valueEquals(r[t], n[t]))) return !1; + return !0; + } + /** Returns true if the ArrayValue contains the specified element. */ (t, e); + + default: + return fail(52216, { + left: t + }); + } +} + +function __PRIVATE_arrayValueContains(t, e) { + return void 0 !== (t.values || []).find((t => __PRIVATE_valueEquals(t, e))); +} + +function __PRIVATE_valueCompare(t, e) { + if (t === e) return 0; + const r = __PRIVATE_typeOrder(t), n = __PRIVATE_typeOrder(e); + if (r !== n) return __PRIVATE_primitiveComparator(r, n); + switch (r) { + case 0 /* TypeOrder.NullValue */ : + case 9007199254740991 /* TypeOrder.MaxValue */ : + return 0; + + case 1 /* TypeOrder.BooleanValue */ : + return __PRIVATE_primitiveComparator(t.booleanValue, e.booleanValue); + + case 2 /* TypeOrder.NumberValue */ : + return function __PRIVATE_compareNumbers(t, e) { + const r = __PRIVATE_normalizeNumber(t.integerValue || t.doubleValue), n = __PRIVATE_normalizeNumber(e.integerValue || e.doubleValue); + return r < n ? -1 : r > n ? 1 : r === n ? 0 : + // one or both are NaN. + isNaN(r) ? isNaN(n) ? 0 : -1 : 1; + }(t, e); + + case 3 /* TypeOrder.TimestampValue */ : + return __PRIVATE_compareTimestamps(t.timestampValue, e.timestampValue); + + case 4 /* TypeOrder.ServerTimestampValue */ : + return __PRIVATE_compareTimestamps(__PRIVATE_getLocalWriteTime(t), __PRIVATE_getLocalWriteTime(e)); + + case 5 /* TypeOrder.StringValue */ : + return __PRIVATE_compareUtf8Strings(t.stringValue, e.stringValue); + + case 6 /* TypeOrder.BlobValue */ : + return function __PRIVATE_compareBlobs(t, e) { + const r = __PRIVATE_normalizeByteString(t), n = __PRIVATE_normalizeByteString(e); + return r.compareTo(n); + }(t.bytesValue, e.bytesValue); + + case 7 /* TypeOrder.RefValue */ : + return function __PRIVATE_compareReferences(t, e) { + const r = t.split("/"), n = e.split("/"); + for (let t = 0; t < r.length && t < n.length; t++) { + const e = __PRIVATE_primitiveComparator(r[t], n[t]); + if (0 !== e) return e; + } + return __PRIVATE_primitiveComparator(r.length, n.length); + }(t.referenceValue, e.referenceValue); + + case 8 /* TypeOrder.GeoPointValue */ : + return function __PRIVATE_compareGeoPoints(t, e) { + const r = __PRIVATE_primitiveComparator(__PRIVATE_normalizeNumber(t.latitude), __PRIVATE_normalizeNumber(e.latitude)); + if (0 !== r) return r; + return __PRIVATE_primitiveComparator(__PRIVATE_normalizeNumber(t.longitude), __PRIVATE_normalizeNumber(e.longitude)); + }(t.geoPointValue, e.geoPointValue); + + case 9 /* TypeOrder.ArrayValue */ : + return __PRIVATE_compareArrays(t.arrayValue, e.arrayValue); + + case 10 /* TypeOrder.VectorValue */ : + return function __PRIVATE_compareVectors(t, e) { + const r = t.fields || {}, n = e.fields || {}, i = r[et]?.arrayValue, s = n[et]?.arrayValue, o = __PRIVATE_primitiveComparator(i?.values?.length || 0, s?.values?.length || 0); + if (0 !== o) return o; + return __PRIVATE_compareArrays(i, s); + }(t.mapValue, e.mapValue); + + case 11 /* TypeOrder.ObjectValue */ : + return function __PRIVATE_compareMaps(t, e) { + if (t === X && e === X) return 0; + if (t === X) return 1; + if (e === X) return -1; + const r = t.fields || {}, n = Object.keys(r), i = e.fields || {}, s = Object.keys(i); + // Even though MapValues are likely sorted correctly based on their insertion + // order (e.g. when received from the backend), local modifications can bring + // elements out of order. We need to re-sort the elements to ensure that + // canonical IDs are independent of insertion order. + n.sort(), s.sort(); + for (let t = 0; t < n.length && t < s.length; ++t) { + const e = __PRIVATE_compareUtf8Strings(n[t], s[t]); + if (0 !== e) return e; + const o = __PRIVATE_valueCompare(r[n[t]], i[s[t]]); + if (0 !== o) return o; + } + return __PRIVATE_primitiveComparator(n.length, s.length); + } + /** Returns a reference value for the provided database and key. */ (t.mapValue, e.mapValue); + + default: + throw fail(23264, { + C: r + }); + } +} + +function __PRIVATE_compareTimestamps(t, e) { + if ("string" == typeof t && "string" == typeof e && t.length === e.length) return __PRIVATE_primitiveComparator(t, e); + const r = __PRIVATE_normalizeTimestamp(t), n = __PRIVATE_normalizeTimestamp(e), i = __PRIVATE_primitiveComparator(r.seconds, n.seconds); + return 0 !== i ? i : __PRIVATE_primitiveComparator(r.nanos, n.nanos); +} + +function __PRIVATE_compareArrays(t, e) { + const r = t.values || [], n = e.values || []; + for (let t = 0; t < r.length && t < n.length; ++t) { + const e = __PRIVATE_valueCompare(r[t], n[t]); + if (e) return e; + } + return __PRIVATE_primitiveComparator(r.length, n.length); +} + +function __PRIVATE_refValue(t, e) { + return { + referenceValue: `projects/${t.projectId}/databases/${t.database}/documents/${e.path.canonicalString()}` + }; +} + +/** Returns true if `value` is an ArrayValue. */ function isArray(t) { + return !!t && "arrayValue" in t; +} + +/** Returns true if `value` is a NullValue. */ function __PRIVATE_isNullValue(t) { + return !!t && "nullValue" in t; +} + +/** Returns true if `value` is NaN. */ function __PRIVATE_isNanValue(t) { + return !!t && "doubleValue" in t && isNaN(Number(t.doubleValue)); +} + +/** Returns true if `value` is a MapValue. */ function __PRIVATE_isMapValue(t) { + return !!t && "mapValue" in t; +} + +function __PRIVATE_deepClone(t) { + if (t.geoPointValue) return { + geoPointValue: { + ...t.geoPointValue + } + }; + if (t.timestampValue && "object" == typeof t.timestampValue) return { + timestampValue: { + ...t.timestampValue + } + }; + if (t.mapValue) { + const e = { + mapValue: { + fields: {} + } + }; + return forEach(t.mapValue.fields, ((t, r) => e.mapValue.fields[t] = __PRIVATE_deepClone(r))), + e; + } + if (t.arrayValue) { + const e = { + arrayValue: { + values: [] + } + }; + for (let r = 0; r < (t.arrayValue.values || []).length; ++r) e.arrayValue.values[r] = __PRIVATE_deepClone(t.arrayValue.values[r]); + return e; + } + return { + ...t + }; +} + +class Bound { + constructor(t, e) { + this.position = t, this.inclusive = e; + } +} + +function __PRIVATE_boundEquals(t, e) { + if (null === t) return null === e; + if (null === e) return !1; + if (t.inclusive !== e.inclusive || t.position.length !== e.position.length) return !1; + for (let r = 0; r < t.position.length; r++) { + if (!__PRIVATE_valueEquals(t.position[r], e.position[r])) return !1; + } + return !0; +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ class Filter {} + +class FieldFilter extends Filter { + constructor(t, e, r) { + super(), this.field = t, this.op = e, this.value = r; + } + /** + * Creates a filter based on the provided arguments. + */ static create(t, e, r) { + return t.isKeyField() ? "in" /* Operator.IN */ === e || "not-in" /* Operator.NOT_IN */ === e ? this.createKeyFieldInFilter(t, e, r) : new __PRIVATE_KeyFieldFilter(t, e, r) : "array-contains" /* Operator.ARRAY_CONTAINS */ === e ? new __PRIVATE_ArrayContainsFilter(t, r) : "in" /* Operator.IN */ === e ? new __PRIVATE_InFilter(t, r) : "not-in" /* Operator.NOT_IN */ === e ? new __PRIVATE_NotInFilter(t, r) : "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ === e ? new __PRIVATE_ArrayContainsAnyFilter(t, r) : new FieldFilter(t, e, r); + } + static createKeyFieldInFilter(t, e, r) { + return "in" /* Operator.IN */ === e ? new __PRIVATE_KeyFieldInFilter(t, r) : new __PRIVATE_KeyFieldNotInFilter(t, r); + } + matches(t) { + const e = t.data.field(this.field); + // Types do not have to match in NOT_EQUAL filters. + return "!=" /* Operator.NOT_EQUAL */ === this.op ? null !== e && void 0 === e.nullValue && this.matchesComparison(__PRIVATE_valueCompare(e, this.value)) : null !== e && __PRIVATE_typeOrder(this.value) === __PRIVATE_typeOrder(e) && this.matchesComparison(__PRIVATE_valueCompare(e, this.value)); + // Only compare types with matching backend order (such as double and int). + } + matchesComparison(t) { + switch (this.op) { + case "<" /* Operator.LESS_THAN */ : + return t < 0; + + case "<=" /* Operator.LESS_THAN_OR_EQUAL */ : + return t <= 0; + + case "==" /* Operator.EQUAL */ : + return 0 === t; + + case "!=" /* Operator.NOT_EQUAL */ : + return 0 !== t; + + case ">" /* Operator.GREATER_THAN */ : + return t > 0; + + case ">=" /* Operator.GREATER_THAN_OR_EQUAL */ : + return t >= 0; + + default: + return fail(47266, { + operator: this.op + }); + } + } + isInequality() { + return [ "<" /* Operator.LESS_THAN */ , "<=" /* Operator.LESS_THAN_OR_EQUAL */ , ">" /* Operator.GREATER_THAN */ , ">=" /* Operator.GREATER_THAN_OR_EQUAL */ , "!=" /* Operator.NOT_EQUAL */ , "not-in" /* Operator.NOT_IN */ ].indexOf(this.op) >= 0; + } + getFlattenedFilters() { + return [ this ]; + } + getFilters() { + return [ this ]; + } +} + +class CompositeFilter extends Filter { + constructor(t, e) { + super(), this.filters = t, this.op = e, this.N = null; + } + /** + * Creates a filter based on the provided arguments. + */ static create(t, e) { + return new CompositeFilter(t, e); + } + matches(t) { + return function __PRIVATE_compositeFilterIsConjunction(t) { + return "and" /* CompositeOperator.AND */ === t.op; + }(this) ? void 0 === this.filters.find((e => !e.matches(t))) : void 0 !== this.filters.find((e => e.matches(t))); + } + getFlattenedFilters() { + return null !== this.N || (this.N = this.filters.reduce(((t, e) => t.concat(e.getFlattenedFilters())), [])), + this.N; + } + // Returns a mutable copy of `this.filters` + getFilters() { + return Object.assign([], this.filters); + } +} + +function __PRIVATE_filterEquals(t, e) { + return t instanceof FieldFilter ? function __PRIVATE_fieldFilterEquals(t, e) { + return e instanceof FieldFilter && t.op === e.op && t.field.isEqual(e.field) && __PRIVATE_valueEquals(t.value, e.value); + }(t, e) : t instanceof CompositeFilter ? function __PRIVATE_compositeFilterEquals(t, e) { + if (e instanceof CompositeFilter && t.op === e.op && t.filters.length === e.filters.length) { + return t.filters.reduce(((t, r, n) => t && __PRIVATE_filterEquals(r, e.filters[n])), !0); + } + return !1; + } + /** Filter that matches on key fields (i.e. '__name__'). */ (t, e) : void fail(19439); +} + +class __PRIVATE_KeyFieldFilter extends FieldFilter { + constructor(t, e, r) { + super(t, e, r), this.key = DocumentKey.fromName(r.referenceValue); + } + matches(t) { + const e = DocumentKey.comparator(t.key, this.key); + return this.matchesComparison(e); + } +} + +/** Filter that matches on key fields within an array. */ class __PRIVATE_KeyFieldInFilter extends FieldFilter { + constructor(t, e) { + super(t, "in" /* Operator.IN */ , e), this.keys = __PRIVATE_extractDocumentKeysFromArrayValue("in" /* Operator.IN */ , e); + } + matches(t) { + return this.keys.some((e => e.isEqual(t.key))); + } +} + +/** Filter that matches on key fields not present within an array. */ class __PRIVATE_KeyFieldNotInFilter extends FieldFilter { + constructor(t, e) { + super(t, "not-in" /* Operator.NOT_IN */ , e), this.keys = __PRIVATE_extractDocumentKeysFromArrayValue("not-in" /* Operator.NOT_IN */ , e); + } + matches(t) { + return !this.keys.some((e => e.isEqual(t.key))); + } +} + +function __PRIVATE_extractDocumentKeysFromArrayValue(t, e) { + return (e.arrayValue?.values || []).map((t => DocumentKey.fromName(t.referenceValue))); +} + +/** A Filter that implements the array-contains operator. */ class __PRIVATE_ArrayContainsFilter extends FieldFilter { + constructor(t, e) { + super(t, "array-contains" /* Operator.ARRAY_CONTAINS */ , e); + } + matches(t) { + const e = t.data.field(this.field); + return isArray(e) && __PRIVATE_arrayValueContains(e.arrayValue, this.value); + } +} + +/** A Filter that implements the IN operator. */ class __PRIVATE_InFilter extends FieldFilter { + constructor(t, e) { + super(t, "in" /* Operator.IN */ , e); + } + matches(t) { + const e = t.data.field(this.field); + return null !== e && __PRIVATE_arrayValueContains(this.value.arrayValue, e); + } +} + +/** A Filter that implements the not-in operator. */ class __PRIVATE_NotInFilter extends FieldFilter { + constructor(t, e) { + super(t, "not-in" /* Operator.NOT_IN */ , e); + } + matches(t) { + if (__PRIVATE_arrayValueContains(this.value.arrayValue, { + nullValue: "NULL_VALUE" + })) return !1; + const e = t.data.field(this.field); + return null !== e && void 0 === e.nullValue && !__PRIVATE_arrayValueContains(this.value.arrayValue, e); + } +} + +/** A Filter that implements the array-contains-any operator. */ class __PRIVATE_ArrayContainsAnyFilter extends FieldFilter { + constructor(t, e) { + super(t, "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ , e); + } + matches(t) { + const e = t.data.field(this.field); + return !(!isArray(e) || !e.arrayValue.values) && e.arrayValue.values.some((t => __PRIVATE_arrayValueContains(this.value.arrayValue, t))); + } +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An ordering on a field, in some Direction. Direction defaults to ASCENDING. + */ class OrderBy { + constructor(t, e = "asc" /* Direction.ASCENDING */) { + this.field = t, this.dir = e; + } +} + +function __PRIVATE_orderByEquals(t, e) { + return t.dir === e.dir && t.field.isEqual(e.field); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A version of a document in Firestore. This corresponds to the version + * timestamp, such as update_time or read_time. + */ class SnapshotVersion { + static fromTimestamp(t) { + return new SnapshotVersion(t); + } + static min() { + return new SnapshotVersion(new Timestamp(0, 0)); + } + static max() { + return new SnapshotVersion(new Timestamp(253402300799, 999999999)); + } + constructor(t) { + this.timestamp = t; + } + compareTo(t) { + return this.timestamp._compareTo(t.timestamp); + } + isEqual(t) { + return this.timestamp.isEqual(t.timestamp); + } + /** Returns a number representation of the version for use in spec tests. */ toMicroseconds() { + // Convert to microseconds. + return 1e6 * this.timestamp.seconds + this.timestamp.nanoseconds / 1e3; + } + toString() { + return "SnapshotVersion(" + this.timestamp.toString() + ")"; + } + toTimestamp() { + return this.timestamp; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// An immutable sorted map implementation, based on a Left-leaning Red-Black +// tree. +class SortedMap { + constructor(t, e) { + this.comparator = t, this.root = e || LLRBNode.EMPTY; + } + // Returns a copy of the map, with the specified key/value added or replaced. + insert(t, e) { + return new SortedMap(this.comparator, this.root.insert(t, e, this.comparator).copy(null, null, LLRBNode.BLACK, null, null)); + } + // Returns a copy of the map, with the specified key removed. + remove(t) { + return new SortedMap(this.comparator, this.root.remove(t, this.comparator).copy(null, null, LLRBNode.BLACK, null, null)); + } + // Returns the value of the node with the given key, or null. + get(t) { + let e = this.root; + for (;!e.isEmpty(); ) { + const r = this.comparator(t, e.key); + if (0 === r) return e.value; + r < 0 ? e = e.left : r > 0 && (e = e.right); + } + return null; + } + // Returns the index of the element in this sorted map, or -1 if it doesn't + // exist. + indexOf(t) { + // Number of nodes that were pruned when descending right + let e = 0, r = this.root; + for (;!r.isEmpty(); ) { + const n = this.comparator(t, r.key); + if (0 === n) return e + r.left.size; + n < 0 ? r = r.left : ( + // Count all nodes left of the node plus the node itself + e += r.left.size + 1, r = r.right); + } + // Node not found + return -1; + } + isEmpty() { + return this.root.isEmpty(); + } + // Returns the total number of nodes in the map. + get size() { + return this.root.size; + } + // Returns the minimum key in the map. + minKey() { + return this.root.minKey(); + } + // Returns the maximum key in the map. + maxKey() { + return this.root.maxKey(); + } + // Traverses the map in key order and calls the specified action function + // for each key/value pair. If action returns true, traversal is aborted. + // Returns the first truthy value returned by action, or the last falsey + // value returned by action. + inorderTraversal(t) { + return this.root.inorderTraversal(t); + } + forEach(t) { + this.inorderTraversal(((e, r) => (t(e, r), !1))); + } + toString() { + const t = []; + return this.inorderTraversal(((e, r) => (t.push(`${e}:${r}`), !1))), `{${t.join(", ")}}`; + } + // Traverses the map in reverse key order and calls the specified action + // function for each key/value pair. If action returns true, traversal is + // aborted. + // Returns the first truthy value returned by action, or the last falsey + // value returned by action. + reverseTraversal(t) { + return this.root.reverseTraversal(t); + } + // Returns an iterator over the SortedMap. + getIterator() { + return new SortedMapIterator(this.root, null, this.comparator, !1); + } + getIteratorFrom(t) { + return new SortedMapIterator(this.root, t, this.comparator, !1); + } + getReverseIterator() { + return new SortedMapIterator(this.root, null, this.comparator, !0); + } + getReverseIteratorFrom(t) { + return new SortedMapIterator(this.root, t, this.comparator, !0); + } +} + + // end SortedMap +// An iterator over an LLRBNode. +class SortedMapIterator { + constructor(t, e, r, n) { + this.isReverse = n, this.nodeStack = []; + let i = 1; + for (;!t.isEmpty(); ) if (i = e ? r(t.key, e) : 1, + // flip the comparison if we're going in reverse + e && n && (i *= -1), i < 0) + // This node is less than our start key. ignore it + t = this.isReverse ? t.left : t.right; else { + if (0 === i) { + // This node is exactly equal to our start key. Push it on the stack, + // but stop iterating; + this.nodeStack.push(t); + break; + } + // This node is greater than our start key, add it to the stack and move + // to the next one + this.nodeStack.push(t), t = this.isReverse ? t.right : t.left; + } + } + getNext() { + let t = this.nodeStack.pop(); + const e = { + key: t.key, + value: t.value + }; + if (this.isReverse) for (t = t.left; !t.isEmpty(); ) this.nodeStack.push(t), t = t.right; else for (t = t.right; !t.isEmpty(); ) this.nodeStack.push(t), + t = t.left; + return e; + } + hasNext() { + return this.nodeStack.length > 0; + } + peek() { + if (0 === this.nodeStack.length) return null; + const t = this.nodeStack[this.nodeStack.length - 1]; + return { + key: t.key, + value: t.value + }; + } +} + + // end SortedMapIterator +// Represents a node in a Left-leaning Red-Black tree. +class LLRBNode { + constructor(t, e, r, n, i) { + this.key = t, this.value = e, this.color = null != r ? r : LLRBNode.RED, this.left = null != n ? n : LLRBNode.EMPTY, + this.right = null != i ? i : LLRBNode.EMPTY, this.size = this.left.size + 1 + this.right.size; + } + // Returns a copy of the current node, optionally replacing pieces of it. + copy(t, e, r, n, i) { + return new LLRBNode(null != t ? t : this.key, null != e ? e : this.value, null != r ? r : this.color, null != n ? n : this.left, null != i ? i : this.right); + } + isEmpty() { + return !1; + } + // Traverses the tree in key order and calls the specified action function + // for each node. If action returns true, traversal is aborted. + // Returns the first truthy value returned by action, or the last falsey + // value returned by action. + inorderTraversal(t) { + return this.left.inorderTraversal(t) || t(this.key, this.value) || this.right.inorderTraversal(t); + } + // Traverses the tree in reverse key order and calls the specified action + // function for each node. If action returns true, traversal is aborted. + // Returns the first truthy value returned by action, or the last falsey + // value returned by action. + reverseTraversal(t) { + return this.right.reverseTraversal(t) || t(this.key, this.value) || this.left.reverseTraversal(t); + } + // Returns the minimum node in the tree. + min() { + return this.left.isEmpty() ? this : this.left.min(); + } + // Returns the maximum key in the tree. + minKey() { + return this.min().key; + } + // Returns the maximum key in the tree. + maxKey() { + return this.right.isEmpty() ? this.key : this.right.maxKey(); + } + // Returns new tree, with the key/value added. + insert(t, e, r) { + let n = this; + const i = r(t, n.key); + return n = i < 0 ? n.copy(null, null, null, n.left.insert(t, e, r), null) : 0 === i ? n.copy(null, e, null, null, null) : n.copy(null, null, null, null, n.right.insert(t, e, r)), + n.fixUp(); + } + removeMin() { + if (this.left.isEmpty()) return LLRBNode.EMPTY; + let t = this; + return t.left.isRed() || t.left.left.isRed() || (t = t.moveRedLeft()), t = t.copy(null, null, null, t.left.removeMin(), null), + t.fixUp(); + } + // Returns new tree, with the specified item removed. + remove(t, e) { + let r, n = this; + if (e(t, n.key) < 0) n.left.isEmpty() || n.left.isRed() || n.left.left.isRed() || (n = n.moveRedLeft()), + n = n.copy(null, null, null, n.left.remove(t, e), null); else { + if (n.left.isRed() && (n = n.rotateRight()), n.right.isEmpty() || n.right.isRed() || n.right.left.isRed() || (n = n.moveRedRight()), + 0 === e(t, n.key)) { + if (n.right.isEmpty()) return LLRBNode.EMPTY; + r = n.right.min(), n = n.copy(r.key, r.value, null, null, n.right.removeMin()); + } + n = n.copy(null, null, null, null, n.right.remove(t, e)); + } + return n.fixUp(); + } + isRed() { + return this.color; + } + // Returns new tree after performing any needed rotations. + fixUp() { + let t = this; + return t.right.isRed() && !t.left.isRed() && (t = t.rotateLeft()), t.left.isRed() && t.left.left.isRed() && (t = t.rotateRight()), + t.left.isRed() && t.right.isRed() && (t = t.colorFlip()), t; + } + moveRedLeft() { + let t = this.colorFlip(); + return t.right.left.isRed() && (t = t.copy(null, null, null, null, t.right.rotateRight()), + t = t.rotateLeft(), t = t.colorFlip()), t; + } + moveRedRight() { + let t = this.colorFlip(); + return t.left.left.isRed() && (t = t.rotateRight(), t = t.colorFlip()), t; + } + rotateLeft() { + const t = this.copy(null, null, LLRBNode.RED, null, this.right.left); + return this.right.copy(null, null, this.color, t, null); + } + rotateRight() { + const t = this.copy(null, null, LLRBNode.RED, this.left.right, null); + return this.left.copy(null, null, this.color, null, t); + } + colorFlip() { + const t = this.left.copy(null, null, !this.left.color, null, null), e = this.right.copy(null, null, !this.right.color, null, null); + return this.copy(null, null, !this.color, t, e); + } + // For testing. + checkMaxDepth() { + const t = this.check(); + return Math.pow(2, t) <= this.size + 1; + } + // In a balanced RB tree, the black-depth (number of black nodes) from root to + // leaves is equal on both sides. This function verifies that or asserts. + check() { + if (this.isRed() && this.left.isRed()) throw fail(43730, { + key: this.key, + value: this.value + }); + if (this.right.isRed()) throw fail(14113, { + key: this.key, + value: this.value + }); + const t = this.left.check(); + if (t !== this.right.check()) throw fail(27949); + return t + (this.isRed() ? 0 : 1); + } +} + + // end LLRBNode +// Empty node is shared between all LLRB trees. +// eslint-disable-next-line @typescript-eslint/no-explicit-any +LLRBNode.EMPTY = null, LLRBNode.RED = !0, LLRBNode.BLACK = !1; + +// end LLRBEmptyNode +LLRBNode.EMPTY = new +// Represents an empty node (a leaf node in the Red-Black Tree). +class LLRBEmptyNode { + constructor() { + this.size = 0; + } + get key() { + throw fail(57766); + } + get value() { + throw fail(16141); + } + get color() { + throw fail(16727); + } + get left() { + throw fail(29726); + } + get right() { + throw fail(36894); + } + // Returns a copy of the current node. + copy(t, e, r, n, i) { + return this; + } + // Returns a copy of the tree, with the specified key/value added. + insert(t, e, r) { + return new LLRBNode(t, e); + } + // Returns a copy of the tree, with the specified key removed. + remove(t, e) { + return this; + } + isEmpty() { + return !0; + } + inorderTraversal(t) { + return !1; + } + reverseTraversal(t) { + return !1; + } + minKey() { + return null; + } + maxKey() { + return null; + } + isRed() { + return !1; + } + // For testing. + checkMaxDepth() { + return !0; + } + check() { + return 0; + } +}; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * SortedSet is an immutable (copy-on-write) collection that holds elements + * in order specified by the provided comparator. + * + * NOTE: if provided comparator returns 0 for two elements, we consider them to + * be equal! + */ +class SortedSet { + constructor(t) { + this.comparator = t, this.data = new SortedMap(this.comparator); + } + has(t) { + return null !== this.data.get(t); + } + first() { + return this.data.minKey(); + } + last() { + return this.data.maxKey(); + } + get size() { + return this.data.size; + } + indexOf(t) { + return this.data.indexOf(t); + } + /** Iterates elements in order defined by "comparator" */ forEach(t) { + this.data.inorderTraversal(((e, r) => (t(e), !1))); + } + /** Iterates over `elem`s such that: range[0] <= elem < range[1]. */ forEachInRange(t, e) { + const r = this.data.getIteratorFrom(t[0]); + for (;r.hasNext(); ) { + const n = r.getNext(); + if (this.comparator(n.key, t[1]) >= 0) return; + e(n.key); + } + } + /** + * Iterates over `elem`s such that: start <= elem until false is returned. + */ forEachWhile(t, e) { + let r; + for (r = void 0 !== e ? this.data.getIteratorFrom(e) : this.data.getIterator(); r.hasNext(); ) { + if (!t(r.getNext().key)) return; + } + } + /** Finds the least element greater than or equal to `elem`. */ firstAfterOrEqual(t) { + const e = this.data.getIteratorFrom(t); + return e.hasNext() ? e.getNext().key : null; + } + getIterator() { + return new SortedSetIterator(this.data.getIterator()); + } + getIteratorFrom(t) { + return new SortedSetIterator(this.data.getIteratorFrom(t)); + } + /** Inserts or updates an element */ add(t) { + return this.copy(this.data.remove(t).insert(t, !0)); + } + /** Deletes an element */ delete(t) { + return this.has(t) ? this.copy(this.data.remove(t)) : this; + } + isEmpty() { + return this.data.isEmpty(); + } + unionWith(t) { + let e = this; + // Make sure `result` always refers to the larger one of the two sets. + return e.size < t.size && (e = t, t = this), t.forEach((t => { + e = e.add(t); + })), e; + } + isEqual(t) { + if (!(t instanceof SortedSet)) return !1; + if (this.size !== t.size) return !1; + const e = this.data.getIterator(), r = t.data.getIterator(); + for (;e.hasNext(); ) { + const t = e.getNext().key, n = r.getNext().key; + if (0 !== this.comparator(t, n)) return !1; + } + return !0; + } + toArray() { + const t = []; + return this.forEach((e => { + t.push(e); + })), t; + } + toString() { + const t = []; + return this.forEach((e => t.push(e))), "SortedSet(" + t.toString() + ")"; + } + copy(t) { + const e = new SortedSet(this.comparator); + return e.data = t, e; + } +} + +class SortedSetIterator { + constructor(t) { + this.iter = t; + } + getNext() { + return this.iter.getNext().key; + } + hasNext() { + return this.iter.hasNext(); + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Provides a set of fields that can be used to partially patch a document. + * FieldMask is used in conjunction with ObjectValue. + * Examples: + * foo - Overwrites foo entirely with the provided value. If foo is not + * present in the companion ObjectValue, the field is deleted. + * foo.bar - Overwrites only the field bar of the object foo. + * If foo is not an object, foo is replaced with an object + * containing foo + */ class FieldMask { + constructor(t) { + this.fields = t, + // TODO(dimond): validation of FieldMask + // Sort the field mask to support `FieldMask.isEqual()` and assert below. + t.sort(FieldPath$1.comparator); + } + static empty() { + return new FieldMask([]); + } + /** + * Returns a new FieldMask object that is the result of adding all the given + * fields paths to this field mask. + */ unionWith(t) { + let e = new SortedSet(FieldPath$1.comparator); + for (const t of this.fields) e = e.add(t); + for (const r of t) e = e.add(r); + return new FieldMask(e.toArray()); + } + /** + * Verifies that `fieldPath` is included by at least one field in this field + * mask. + * + * This is an O(n) operation, where `n` is the size of the field mask. + */ covers(t) { + for (const e of this.fields) if (e.isPrefixOf(t)) return !0; + return !1; + } + isEqual(t) { + return __PRIVATE_arrayEquals(this.fields, t.fields, ((t, e) => t.isEqual(e))); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An ObjectValue represents a MapValue in the Firestore Proto and offers the + * ability to add and remove fields (via the ObjectValueBuilder). + */ class ObjectValue { + constructor(t) { + this.value = t; + } + static empty() { + return new ObjectValue({ + mapValue: {} + }); + } + /** + * Returns the value at the given path or null. + * + * @param path - the path to search + * @returns The value at the path or null if the path is not set. + */ field(t) { + if (t.isEmpty()) return this.value; + { + let e = this.value; + for (let r = 0; r < t.length - 1; ++r) if (e = (e.mapValue.fields || {})[t.get(r)], + !__PRIVATE_isMapValue(e)) return null; + return e = (e.mapValue.fields || {})[t.lastSegment()], e || null; + } + } + /** + * Sets the field to the provided value. + * + * @param path - The field path to set. + * @param value - The value to set. + */ set(t, e) { + this.getFieldsMap(t.popLast())[t.lastSegment()] = __PRIVATE_deepClone(e); + } + /** + * Sets the provided fields to the provided values. + * + * @param data - A map of fields to values (or null for deletes). + */ setAll(t) { + let e = FieldPath$1.emptyPath(), r = {}, n = []; + t.forEach(((t, i) => { + if (!e.isImmediateParentOf(i)) { + // Insert the accumulated changes at this parent location + const t = this.getFieldsMap(e); + this.applyChanges(t, r, n), r = {}, n = [], e = i.popLast(); + } + t ? r[i.lastSegment()] = __PRIVATE_deepClone(t) : n.push(i.lastSegment()); + })); + const i = this.getFieldsMap(e); + this.applyChanges(i, r, n); + } + /** + * Removes the field at the specified path. If there is no field at the + * specified path, nothing is changed. + * + * @param path - The field path to remove. + */ delete(t) { + const e = this.field(t.popLast()); + __PRIVATE_isMapValue(e) && e.mapValue.fields && delete e.mapValue.fields[t.lastSegment()]; + } + isEqual(t) { + return __PRIVATE_valueEquals(this.value, t.value); + } + /** + * Returns the map that contains the leaf element of `path`. If the parent + * entry does not yet exist, or if it is not a map, a new map will be created. + */ getFieldsMap(t) { + let e = this.value; + e.mapValue.fields || (e.mapValue = { + fields: {} + }); + for (let r = 0; r < t.length; ++r) { + let n = e.mapValue.fields[t.get(r)]; + __PRIVATE_isMapValue(n) && n.mapValue.fields || (n = { + mapValue: { + fields: {} + } + }, e.mapValue.fields[t.get(r)] = n), e = n; + } + return e.mapValue.fields; + } + /** + * Modifies `fieldsMap` by adding, replacing or deleting the specified + * entries. + */ applyChanges(t, e, r) { + forEach(e, ((e, r) => t[e] = r)); + for (const e of r) delete t[e]; + } + clone() { + return new ObjectValue(__PRIVATE_deepClone(this.value)); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Represents a document in Firestore with a key, version, data and whether it + * has local mutations applied to it. + * + * Documents can transition between states via `convertToFoundDocument()`, + * `convertToNoDocument()` and `convertToUnknownDocument()`. If a document does + * not transition to one of these states even after all mutations have been + * applied, `isValidDocument()` returns false and the document should be removed + * from all views. + */ class MutableDocument { + constructor(t, e, r, n, i, s, o) { + this.key = t, this.documentType = e, this.version = r, this.readTime = n, this.createTime = i, + this.data = s, this.documentState = o; + } + /** + * Creates a document with no known version or data, but which can serve as + * base document for mutations. + */ static newInvalidDocument(t) { + return new MutableDocument(t, 0 /* DocumentType.INVALID */ , + /* version */ SnapshotVersion.min(), + /* readTime */ SnapshotVersion.min(), + /* createTime */ SnapshotVersion.min(), ObjectValue.empty(), 0 /* DocumentState.SYNCED */); + } + /** + * Creates a new document that is known to exist with the given data at the + * given version. + */ static newFoundDocument(t, e, r, n) { + return new MutableDocument(t, 1 /* DocumentType.FOUND_DOCUMENT */ , + /* version */ e, + /* readTime */ SnapshotVersion.min(), + /* createTime */ r, n, 0 /* DocumentState.SYNCED */); + } + /** Creates a new document that is known to not exist at the given version. */ static newNoDocument(t, e) { + return new MutableDocument(t, 2 /* DocumentType.NO_DOCUMENT */ , + /* version */ e, + /* readTime */ SnapshotVersion.min(), + /* createTime */ SnapshotVersion.min(), ObjectValue.empty(), 0 /* DocumentState.SYNCED */); + } + /** + * Creates a new document that is known to exist at the given version but + * whose data is not known (e.g. a document that was updated without a known + * base document). + */ static newUnknownDocument(t, e) { + return new MutableDocument(t, 3 /* DocumentType.UNKNOWN_DOCUMENT */ , + /* version */ e, + /* readTime */ SnapshotVersion.min(), + /* createTime */ SnapshotVersion.min(), ObjectValue.empty(), 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */); + } + /** + * Changes the document type to indicate that it exists and that its version + * and data are known. + */ convertToFoundDocument(t, e) { + // If a document is switching state from being an invalid or deleted + // document to a valid (FOUND_DOCUMENT) document, either due to receiving an + // update from Watch or due to applying a local set mutation on top + // of a deleted document, our best guess about its createTime would be the + // version at which the document transitioned to a FOUND_DOCUMENT. + return !this.createTime.isEqual(SnapshotVersion.min()) || 2 /* DocumentType.NO_DOCUMENT */ !== this.documentType && 0 /* DocumentType.INVALID */ !== this.documentType || (this.createTime = t), + this.version = t, this.documentType = 1 /* DocumentType.FOUND_DOCUMENT */ , this.data = e, + this.documentState = 0 /* DocumentState.SYNCED */ , this; + } + /** + * Changes the document type to indicate that it doesn't exist at the given + * version. + */ convertToNoDocument(t) { + return this.version = t, this.documentType = 2 /* DocumentType.NO_DOCUMENT */ , + this.data = ObjectValue.empty(), this.documentState = 0 /* DocumentState.SYNCED */ , + this; + } + /** + * Changes the document type to indicate that it exists at a given version but + * that its data is not known (e.g. a document that was updated without a known + * base document). + */ convertToUnknownDocument(t) { + return this.version = t, this.documentType = 3 /* DocumentType.UNKNOWN_DOCUMENT */ , + this.data = ObjectValue.empty(), this.documentState = 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */ , + this; + } + setHasCommittedMutations() { + return this.documentState = 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */ , this; + } + setHasLocalMutations() { + return this.documentState = 1 /* DocumentState.HAS_LOCAL_MUTATIONS */ , this.version = SnapshotVersion.min(), + this; + } + setReadTime(t) { + return this.readTime = t, this; + } + get hasLocalMutations() { + return 1 /* DocumentState.HAS_LOCAL_MUTATIONS */ === this.documentState; + } + get hasCommittedMutations() { + return 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */ === this.documentState; + } + get hasPendingWrites() { + return this.hasLocalMutations || this.hasCommittedMutations; + } + isValidDocument() { + return 0 /* DocumentType.INVALID */ !== this.documentType; + } + isFoundDocument() { + return 1 /* DocumentType.FOUND_DOCUMENT */ === this.documentType; + } + isNoDocument() { + return 2 /* DocumentType.NO_DOCUMENT */ === this.documentType; + } + isUnknownDocument() { + return 3 /* DocumentType.UNKNOWN_DOCUMENT */ === this.documentType; + } + isEqual(t) { + return t instanceof MutableDocument && this.key.isEqual(t.key) && this.version.isEqual(t.version) && this.documentType === t.documentType && this.documentState === t.documentState && this.data.isEqual(t.data); + } + mutableCopy() { + return new MutableDocument(this.key, this.documentType, this.version, this.readTime, this.createTime, this.data.clone(), this.documentState); + } + toString() { + return `Document(${this.key}, ${this.version}, ${JSON.stringify(this.data.value)}, {createTime: ${this.createTime}}), {documentType: ${this.documentType}}), {documentState: ${this.documentState}})`; + } +} + +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// Visible for testing +class __PRIVATE_TargetImpl { + constructor(t, e = null, r = [], n = [], i = null, s = null, o = null) { + this.path = t, this.collectionGroup = e, this.orderBy = r, this.filters = n, this.limit = i, + this.startAt = s, this.endAt = o, this.O = null; + } +} + +/** + * Initializes a Target with a path and optional additional query constraints. + * Path must currently be empty if this is a collection group query. + * + * NOTE: you should always construct `Target` from `Query.toTarget` instead of + * using this factory method, because `Query` provides an implicit `orderBy` + * property. + */ function __PRIVATE_newTarget(t, e = null, r = [], n = [], i = null, s = null, o = null) { + return new __PRIVATE_TargetImpl(t, e, r, n, i, s, o); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Query encapsulates all the query attributes we support in the SDK. It can + * be run against the LocalStore, as well as be converted to a `Target` to + * query the RemoteStore results. + * + * Visible for testing. + */ +class __PRIVATE_QueryImpl { + /** + * Initializes a Query with a path and optional additional query constraints. + * Path must currently be empty if this is a collection group query. + */ + constructor(t, e = null, r = [], n = [], i = null, s = "F" /* LimitType.First */ , o = null, a = null) { + this.path = t, this.collectionGroup = e, this.explicitOrderBy = r, this.filters = n, + this.limit = i, this.limitType = s, this.startAt = o, this.endAt = a, this.q = null, + // The corresponding `Target` of this `Query` instance, for use with + // non-aggregate queries. + this.B = null, + // The corresponding `Target` of this `Query` instance, for use with + // aggregate queries. Unlike targets for non-aggregate queries, + // aggregate query targets do not contain normalized order-bys, they only + // contain explicit order-bys. + this.$ = null, this.startAt, this.endAt; + } +} + +/** Creates a new Query for a query that matches all documents at `path` */ +/** + * Returns whether the query matches a collection group rather than a specific + * collection. + */ +function __PRIVATE_isCollectionGroupQuery(t) { + return null !== t.collectionGroup; +} + +/** + * Returns the normalized order-by constraint that is used to execute the Query, + * which can be different from the order-by constraints the user provided (e.g. + * the SDK and backend always orders by `__name__`). The normalized order-by + * includes implicit order-bys in addition to the explicit user provided + * order-bys. + */ function __PRIVATE_queryNormalizedOrderBy(t) { + const e = __PRIVATE_debugCast(t); + if (null === e.q) { + e.q = []; + const t = new Set; + // Any explicit order by fields should be added as is. + for (const r of e.explicitOrderBy) e.q.push(r), t.add(r.field.canonicalString()); + // The order of the implicit ordering always matches the last explicit order by. + const r = e.explicitOrderBy.length > 0 ? e.explicitOrderBy[e.explicitOrderBy.length - 1].dir : "asc" /* Direction.ASCENDING */ , n = + // Returns the sorted set of inequality filter fields used in this query. + function __PRIVATE_getInequalityFilterFields(t) { + let e = new SortedSet(FieldPath$1.comparator); + return t.filters.forEach((t => { + t.getFlattenedFilters().forEach((t => { + t.isInequality() && (e = e.add(t.field)); + })); + })), e; + } + /** + * Creates a new Query for a collection group query that matches all documents + * within the provided collection group. + */ (e); + // Any inequality fields not explicitly ordered should be implicitly ordered in a lexicographical + // order. When there are multiple inequality filters on the same field, the field should be added + // only once. + // Note: `SortedSet` sorts the key field before other fields. However, we want the key + // field to be sorted last. + n.forEach((n => { + t.has(n.canonicalString()) || n.isKeyField() || e.q.push(new OrderBy(n, r)); + })), + // Add the document key field to the last if it is not explicitly ordered. + t.has(FieldPath$1.keyField().canonicalString()) || e.q.push(new OrderBy(FieldPath$1.keyField(), r)); + } + return e.q; +} + +/** + * Converts this `Query` instance to its corresponding `Target` representation. + */ function __PRIVATE_queryToTarget(t) { + const e = __PRIVATE_debugCast(t); + return e.B || (e.B = __PRIVATE__queryToTarget(e, __PRIVATE_queryNormalizedOrderBy(t))), + e.B; +} + +/** + * Converts this `Query` instance to its corresponding `Target` representation, + * for use within an aggregate query. Unlike targets for non-aggregate queries, + * aggregate query targets do not contain normalized order-bys, they only + * contain explicit order-bys. + */ function __PRIVATE__queryToTarget(t, e) { + if ("F" /* LimitType.First */ === t.limitType) return __PRIVATE_newTarget(t.path, t.collectionGroup, e, t.filters, t.limit, t.startAt, t.endAt); + { + // Flip the orderBy directions since we want the last results + e = e.map((t => { + const e = "desc" /* Direction.DESCENDING */ === t.dir ? "asc" /* Direction.ASCENDING */ : "desc" /* Direction.DESCENDING */; + return new OrderBy(t.field, e); + })); + // We need to swap the cursors to match the now-flipped query ordering. + const r = t.endAt ? new Bound(t.endAt.position, t.endAt.inclusive) : null, n = t.startAt ? new Bound(t.startAt.position, t.startAt.inclusive) : null; + // Now return as a LimitType.First query. + return __PRIVATE_newTarget(t.path, t.collectionGroup, e, t.filters, t.limit, r, n); + } +} + +function __PRIVATE_queryWithAddedFilter(t, e) { + const r = t.filters.concat([ e ]); + return new __PRIVATE_QueryImpl(t.path, t.collectionGroup, t.explicitOrderBy.slice(), r, t.limit, t.limitType, t.startAt, t.endAt); +} + +function __PRIVATE_queryEquals(t, e) { + return function __PRIVATE_targetEquals(t, e) { + if (t.limit !== e.limit) return !1; + if (t.orderBy.length !== e.orderBy.length) return !1; + for (let r = 0; r < t.orderBy.length; r++) if (!__PRIVATE_orderByEquals(t.orderBy[r], e.orderBy[r])) return !1; + if (t.filters.length !== e.filters.length) return !1; + for (let r = 0; r < t.filters.length; r++) if (!__PRIVATE_filterEquals(t.filters[r], e.filters[r])) return !1; + return t.collectionGroup === e.collectionGroup && !!t.path.isEqual(e.path) && !!__PRIVATE_boundEquals(t.startAt, e.startAt) && __PRIVATE_boundEquals(t.endAt, e.endAt); + }(__PRIVATE_queryToTarget(t), __PRIVATE_queryToTarget(e)) && t.limitType === e.limitType; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Returns an DoubleValue for `value` that is encoded based the serializer's + * `useProto3Json` setting. + */ function __PRIVATE_toDouble(t, e) { + if (t.useProto3Json) { + if (isNaN(e)) return { + doubleValue: "NaN" + }; + if (e === 1 / 0) return { + doubleValue: "Infinity" + }; + if (e === -1 / 0) return { + doubleValue: "-Infinity" + }; + } + return { + doubleValue: __PRIVATE_isNegativeZero(e) ? "-0" : e + }; +} + +/** + * Returns an IntegerValue for `value`. + */ +/** + * Returns a value for a number that's appropriate to put into a proto. + * The return value is an IntegerValue if it can safely represent the value, + * otherwise a DoubleValue is returned. + */ +function toNumber(t, e) { + return function isSafeInteger(t) { + return "number" == typeof t && Number.isInteger(t) && !__PRIVATE_isNegativeZero(t) && t <= Number.MAX_SAFE_INTEGER && t >= Number.MIN_SAFE_INTEGER; + }(e) ? function __PRIVATE_toInteger(t) { + return { + integerValue: "" + t + }; + }(e) : __PRIVATE_toDouble(t, e); +} + +/** + * @license + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Used to represent a field transform on a mutation. */ class TransformOperation { + constructor() { + // Make sure that the structural type of `TransformOperation` is unique. + // See https://github.com/microsoft/TypeScript/issues/5451 + this._ = void 0; + } +} + +/** Transforms a value into a server-generated timestamp. */ class __PRIVATE_ServerTimestampTransform extends TransformOperation {} + +/** Transforms an array value via a union operation. */ class __PRIVATE_ArrayUnionTransformOperation extends TransformOperation { + constructor(t) { + super(), this.elements = t; + } +} + +/** Transforms an array value via a remove operation. */ class __PRIVATE_ArrayRemoveTransformOperation extends TransformOperation { + constructor(t) { + super(), this.elements = t; + } +} + +/** + * Implements the backend semantics for locally computed NUMERIC_ADD (increment) + * transforms. Converts all field values to integers or doubles, but unlike the + * backend does not cap integer values at 2^63. Instead, JavaScript number + * arithmetic is used and precision loss can occur for values greater than 2^53. + */ class __PRIVATE_NumericIncrementTransformOperation extends TransformOperation { + constructor(t, e) { + super(), this.serializer = t, this.k = e; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** A field path and the TransformOperation to perform upon it. */ class FieldTransform { + constructor(t, e) { + this.field = t, this.transform = e; + } +} + +/** + * Encodes a precondition for a mutation. This follows the model that the + * backend accepts with the special case of an explicit "empty" precondition + * (meaning no precondition). + */ class Precondition { + constructor(t, e) { + this.updateTime = t, this.exists = e; + } + /** Creates a new empty Precondition. */ static none() { + return new Precondition; + } + /** Creates a new Precondition with an exists flag. */ static exists(t) { + return new Precondition(void 0, t); + } + /** Creates a new Precondition based on a version a document exists at. */ static updateTime(t) { + return new Precondition(t); + } + /** Returns whether this Precondition is empty. */ get isNone() { + return void 0 === this.updateTime && void 0 === this.exists; + } + isEqual(t) { + return this.exists === t.exists && (this.updateTime ? !!t.updateTime && this.updateTime.isEqual(t.updateTime) : !t.updateTime); + } +} + +/** + * A mutation describes a self-contained change to a document. Mutations can + * create, replace, delete, and update subsets of documents. + * + * Mutations not only act on the value of the document but also its version. + * + * For local mutations (mutations that haven't been committed yet), we preserve + * the existing version for Set and Patch mutations. For Delete mutations, we + * reset the version to 0. + * + * Here's the expected transition table. + * + * MUTATION APPLIED TO RESULTS IN + * + * SetMutation Document(v3) Document(v3) + * SetMutation NoDocument(v3) Document(v0) + * SetMutation InvalidDocument(v0) Document(v0) + * PatchMutation Document(v3) Document(v3) + * PatchMutation NoDocument(v3) NoDocument(v3) + * PatchMutation InvalidDocument(v0) UnknownDocument(v3) + * DeleteMutation Document(v3) NoDocument(v0) + * DeleteMutation NoDocument(v3) NoDocument(v0) + * DeleteMutation InvalidDocument(v0) NoDocument(v0) + * + * For acknowledged mutations, we use the updateTime of the WriteResponse as + * the resulting version for Set and Patch mutations. As deletes have no + * explicit update time, we use the commitTime of the WriteResponse for + * Delete mutations. + * + * If a mutation is acknowledged by the backend but fails the precondition check + * locally, we transition to an `UnknownDocument` and rely on Watch to send us + * the updated version. + * + * Field transforms are used only with Patch and Set Mutations. We use the + * `updateTransforms` message to store transforms, rather than the `transforms`s + * messages. + * + * ## Subclassing Notes + * + * Every type of mutation needs to implement its own applyToRemoteDocument() and + * applyToLocalView() to implement the actual behavior of applying the mutation + * to some source document (see `setMutationApplyToRemoteDocument()` for an + * example). + */ class Mutation {} + +/** + * A mutation that creates or replaces the document at the given key with the + * object value contents. + */ class __PRIVATE_SetMutation extends Mutation { + constructor(t, e, r, n = []) { + super(), this.key = t, this.value = e, this.precondition = r, this.fieldTransforms = n, + this.type = 0 /* MutationType.Set */; + } + getFieldMask() { + return null; + } +} + +/** + * A mutation that modifies fields of the document at the given key with the + * given values. The values are applied through a field mask: + * + * * When a field is in both the mask and the values, the corresponding field + * is updated. + * * When a field is in neither the mask nor the values, the corresponding + * field is unmodified. + * * When a field is in the mask but not in the values, the corresponding field + * is deleted. + * * When a field is not in the mask but is in the values, the values map is + * ignored. + */ class __PRIVATE_PatchMutation extends Mutation { + constructor(t, e, r, n, i = []) { + super(), this.key = t, this.data = e, this.fieldMask = r, this.precondition = n, + this.fieldTransforms = i, this.type = 1 /* MutationType.Patch */; + } + getFieldMask() { + return this.fieldMask; + } +} + +/** A mutation that deletes the document at the given key. */ class __PRIVATE_DeleteMutation extends Mutation { + constructor(t, e) { + super(), this.key = t, this.precondition = e, this.type = 2 /* MutationType.Delete */ , + this.fieldTransforms = []; + } + getFieldMask() { + return null; + } +} + +/** + * A mutation that verifies the existence of the document at the given key with + * the provided precondition. + * + * The `verify` operation is only used in Transactions, and this class serves + * primarily to facilitate serialization into protos. + */ class __PRIVATE_VerifyMutation extends Mutation { + constructor(t, e) { + super(), this.key = t, this.precondition = e, this.type = 3 /* MutationType.Verify */ , + this.fieldTransforms = []; + } + getFieldMask() { + return null; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ const rt = (() => { + const t = { + asc: "ASCENDING", + desc: "DESCENDING" + }; + return t; +})(), nt = (() => { + const t = { + "<": "LESS_THAN", + "<=": "LESS_THAN_OR_EQUAL", + ">": "GREATER_THAN", + ">=": "GREATER_THAN_OR_EQUAL", + "==": "EQUAL", + "!=": "NOT_EQUAL", + "array-contains": "ARRAY_CONTAINS", + in: "IN", + "not-in": "NOT_IN", + "array-contains-any": "ARRAY_CONTAINS_ANY" + }; + return t; +})(), it = (() => { + const t = { + and: "AND", + or: "OR" + }; + return t; +})(); + +/** + * This class generates JsonObject values for the Datastore API suitable for + * sending to either GRPC stub methods or via the JSON/HTTP REST API. + * + * The serializer supports both Protobuf.js and Proto3 JSON formats. By + * setting `useProto3Json` to true, the serializer will use the Proto3 JSON + * format. + * + * For a description of the Proto3 JSON format check + * https://developers.google.com/protocol-buffers/docs/proto3#json + * + * TODO(klimt): We can remove the databaseId argument if we keep the full + * resource name in documents. + */ +class JsonProtoSerializer { + constructor(t, e) { + this.databaseId = t, this.useProto3Json = e; + } +} + +/** + * Returns a value for a number (or null) that's appropriate to put into + * a google.protobuf.Int32Value proto. + * DO NOT USE THIS FOR ANYTHING ELSE. + * This method cheats. It's typed as returning "number" because that's what + * our generated proto interfaces say Int32Value must be. But GRPC actually + * expects a { value: } struct. + */ +/** + * Returns a value for a Date that's appropriate to put into a proto. + */ +function toTimestamp(t, e) { + if (t.useProto3Json) { + return `${new Date(1e3 * e.seconds).toISOString().replace(/\.\d*/, "").replace("Z", "")}.${("000000000" + e.nanoseconds).slice(-9)}Z`; + } + return { + seconds: "" + e.seconds, + nanos: e.nanoseconds + }; +} + +/** + * Returns a Timestamp typed object given protobuf timestamp value. + */ +/** + * Returns a value for bytes that's appropriate to put in a proto. + * + * Visible for testing. + */ +function __PRIVATE_toBytes(t, e) { + return t.useProto3Json ? e.toBase64() : e.toUint8Array(); +} + +function __PRIVATE_toVersion(t, e) { + return toTimestamp(t, e.toTimestamp()); +} + +function __PRIVATE_fromVersion(t) { + return __PRIVATE_hardAssert(!!t, 49232), SnapshotVersion.fromTimestamp(function fromTimestamp(t) { + const e = __PRIVATE_normalizeTimestamp(t); + return new Timestamp(e.seconds, e.nanos); + }(t)); +} + +function __PRIVATE_toResourceName(t, e) { + return __PRIVATE_toResourcePath(t, e).canonicalString(); +} + +function __PRIVATE_toResourcePath(t, e) { + const r = function __PRIVATE_fullyQualifiedPrefixPath(t) { + return new ResourcePath([ "projects", t.projectId, "databases", t.database ]); + }(t).child("documents"); + return void 0 === e ? r : r.child(e); +} + +function __PRIVATE_toName(t, e) { + return __PRIVATE_toResourceName(t.databaseId, e.path); +} + +function fromName(t, e) { + const r = function __PRIVATE_fromResourceName(t) { + const e = ResourcePath.fromString(t); + return __PRIVATE_hardAssert(__PRIVATE_isValidResourceName(e), 10190, { + key: e.toString() + }), e; + }(e); + if (r.get(1) !== t.databaseId.projectId) throw new FirestoreError(y, "Tried to deserialize key from different project: " + r.get(1) + " vs " + t.databaseId.projectId); + if (r.get(3) !== t.databaseId.database) throw new FirestoreError(y, "Tried to deserialize key from different database: " + r.get(3) + " vs " + t.databaseId.database); + return new DocumentKey(function __PRIVATE_extractLocalPathFromResourceName(t) { + return __PRIVATE_hardAssert(t.length > 4 && "documents" === t.get(4), 29091, { + key: t.toString() + }), t.popFirst(5); + } + /** Creates a Document proto from key and fields (but no create/update time) */ (r)); +} + +function __PRIVATE_toMutationDocument(t, e, r) { + return { + name: __PRIVATE_toName(t, e), + fields: r.value.mapValue.fields + }; +} + +function __PRIVATE_fromBatchGetDocumentsResponse(t, e) { + return "found" in e ? function __PRIVATE_fromFound(t, e) { + __PRIVATE_hardAssert(!!e.found, 43571), e.found.name, e.found.updateTime; + const r = fromName(t, e.found.name), n = __PRIVATE_fromVersion(e.found.updateTime), i = e.found.createTime ? __PRIVATE_fromVersion(e.found.createTime) : SnapshotVersion.min(), s = new ObjectValue({ + mapValue: { + fields: e.found.fields + } + }); + return MutableDocument.newFoundDocument(r, n, i, s); + }(t, e) : "missing" in e ? function __PRIVATE_fromMissing(t, e) { + __PRIVATE_hardAssert(!!e.missing, 3894), __PRIVATE_hardAssert(!!e.readTime, 22933); + const r = fromName(t, e.missing), n = __PRIVATE_fromVersion(e.readTime); + return MutableDocument.newNoDocument(r, n); + }(t, e) : fail(7234, { + result: e + }); +} + +function toMutation(t, e) { + let r; + if (e instanceof __PRIVATE_SetMutation) r = { + update: __PRIVATE_toMutationDocument(t, e.key, e.value) + }; else if (e instanceof __PRIVATE_DeleteMutation) r = { + delete: __PRIVATE_toName(t, e.key) + }; else if (e instanceof __PRIVATE_PatchMutation) r = { + update: __PRIVATE_toMutationDocument(t, e.key, e.data), + updateMask: __PRIVATE_toDocumentMask(e.fieldMask) + }; else { + if (!(e instanceof __PRIVATE_VerifyMutation)) return fail(16599, { + L: e.type + }); + r = { + verify: __PRIVATE_toName(t, e.key) + }; + } + return e.fieldTransforms.length > 0 && (r.updateTransforms = e.fieldTransforms.map((t => function __PRIVATE_toFieldTransform(t, e) { + const r = e.transform; + if (r instanceof __PRIVATE_ServerTimestampTransform) return { + fieldPath: e.field.canonicalString(), + setToServerValue: "REQUEST_TIME" + }; + if (r instanceof __PRIVATE_ArrayUnionTransformOperation) return { + fieldPath: e.field.canonicalString(), + appendMissingElements: { + values: r.elements + } + }; + if (r instanceof __PRIVATE_ArrayRemoveTransformOperation) return { + fieldPath: e.field.canonicalString(), + removeAllFromArray: { + values: r.elements + } + }; + if (r instanceof __PRIVATE_NumericIncrementTransformOperation) return { + fieldPath: e.field.canonicalString(), + increment: r.k + }; + throw fail(20930, { + transform: e.transform + }); + }(0, t)))), e.precondition.isNone || (r.currentDocument = function __PRIVATE_toPrecondition(t, e) { + return void 0 !== e.updateTime ? { + updateTime: __PRIVATE_toVersion(t, e.updateTime) + } : void 0 !== e.exists ? { + exists: e.exists + } : fail(27497); + }(t, e.precondition)), r; +} + +function __PRIVATE_toQueryTarget(t, e) { + // Dissect the path into parent, collectionId, and optional key filter. + const r = { + structuredQuery: {} + }, n = e.path; + let i; + null !== e.collectionGroup ? (i = n, r.structuredQuery.from = [ { + collectionId: e.collectionGroup, + allDescendants: !0 + } ]) : (i = n.popLast(), r.structuredQuery.from = [ { + collectionId: n.lastSegment() + } ]), r.parent = function __PRIVATE_toQueryPath(t, e) { + return __PRIVATE_toResourceName(t.databaseId, e); + }(t, i); + const s = function __PRIVATE_toFilters(t) { + if (0 === t.length) return; + return __PRIVATE_toFilter(CompositeFilter.create(t, "and" /* CompositeOperator.AND */)); + }(e.filters); + s && (r.structuredQuery.where = s); + const o = function __PRIVATE_toOrder(t) { + if (0 === t.length) return; + return t.map((t => + // visible for testing + function __PRIVATE_toPropertyOrder(t) { + return { + field: __PRIVATE_toFieldPathReference(t.field), + direction: __PRIVATE_toDirection(t.dir) + }; + } + // visible for testing + (t))); + }(e.orderBy); + o && (r.structuredQuery.orderBy = o); + const a = function __PRIVATE_toInt32Proto(t, e) { + return t.useProto3Json || __PRIVATE_isNullOrUndefined(e) ? e : { + value: e + }; + }(t, e.limit); + return null !== a && (r.structuredQuery.limit = a), e.startAt && (r.structuredQuery.startAt = function __PRIVATE_toStartAtCursor(t) { + return { + before: t.inclusive, + values: t.position + }; + }(e.startAt)), e.endAt && (r.structuredQuery.endAt = function __PRIVATE_toEndAtCursor(t) { + return { + before: !t.inclusive, + values: t.position + }; + } + // visible for testing + (e.endAt)), { + M: r, + parent: i + }; +} + +function __PRIVATE_toDirection(t) { + return rt[t]; +} + +// visible for testing +function __PRIVATE_toOperatorName(t) { + return nt[t]; +} + +function __PRIVATE_toCompositeOperatorName(t) { + return it[t]; +} + +function __PRIVATE_toFieldPathReference(t) { + return { + fieldPath: t.canonicalString() + }; +} + +function __PRIVATE_toFilter(t) { + return t instanceof FieldFilter ? function __PRIVATE_toUnaryOrFieldFilter(t) { + if ("==" /* Operator.EQUAL */ === t.op) { + if (__PRIVATE_isNanValue(t.value)) return { + unaryFilter: { + field: __PRIVATE_toFieldPathReference(t.field), + op: "IS_NAN" + } + }; + if (__PRIVATE_isNullValue(t.value)) return { + unaryFilter: { + field: __PRIVATE_toFieldPathReference(t.field), + op: "IS_NULL" + } + }; + } else if ("!=" /* Operator.NOT_EQUAL */ === t.op) { + if (__PRIVATE_isNanValue(t.value)) return { + unaryFilter: { + field: __PRIVATE_toFieldPathReference(t.field), + op: "IS_NOT_NAN" + } + }; + if (__PRIVATE_isNullValue(t.value)) return { + unaryFilter: { + field: __PRIVATE_toFieldPathReference(t.field), + op: "IS_NOT_NULL" + } + }; + } + return { + fieldFilter: { + field: __PRIVATE_toFieldPathReference(t.field), + op: __PRIVATE_toOperatorName(t.op), + value: t.value + } + }; + }(t) : t instanceof CompositeFilter ? function __PRIVATE_toCompositeFilter(t) { + const e = t.getFilters().map((t => __PRIVATE_toFilter(t))); + if (1 === e.length) return e[0]; + return { + compositeFilter: { + op: __PRIVATE_toCompositeOperatorName(t.op), + filters: e + } + }; + }(t) : fail(54877, { + filter: t + }); +} + +function __PRIVATE_toDocumentMask(t) { + const e = []; + return t.fields.forEach((t => e.push(t.canonicalString()))), { + fieldPaths: e + }; +} + +function __PRIVATE_isValidResourceName(t) { + // Resource names have at least 4 components (project ID, database ID) + return t.length >= 4 && "projects" === t.get(0) && "databases" === t.get(2); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ function __PRIVATE_newSerializer(t) { + return new JsonProtoSerializer(t, /* useProto3Json= */ !0); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A helper for running delayed tasks following an exponential backoff curve + * between attempts. + * + * Each delay is made up of a "base" delay which follows the exponential + * backoff curve, and a +/- 50% "jitter" that is calculated and added to the + * base delay. This prevents clients from accidentally synchronizing their + * delays causing spikes of load to the backend. + */ +class __PRIVATE_ExponentialBackoff { + constructor( + /** + * The AsyncQueue to run backoff operations on. + */ + t, + /** + * The ID to use when scheduling backoff operations on the AsyncQueue. + */ + e, + /** + * The initial delay (used as the base delay on the first retry attempt). + * Note that jitter will still be applied, so the actual delay could be as + * little as 0.5*initialDelayMs. + */ + r = 1e3 + /** + * The multiplier to use to determine the extended base delay after each + * attempt. + */ , n = 1.5 + /** + * The maximum base delay after which no further backoff is performed. + * Note that jitter will still be applied, so the actual delay could be as + * much as 1.5*maxDelayMs. + */ , i = 6e4) { + this.U = t, this.timerId = e, this.j = r, this.W = n, this.K = i, this.G = 0, this.J = null, + /** The last backoff attempt, as epoch milliseconds. */ + this.H = Date.now(), this.reset(); + } + /** + * Resets the backoff delay. + * + * The very next backoffAndWait() will have no delay. If it is called again + * (i.e. due to an error), initialDelayMs (plus jitter) will be used, and + * subsequent ones will increase according to the backoffFactor. + */ reset() { + this.G = 0; + } + /** + * Resets the backoff delay to the maximum delay (e.g. for use after a + * RESOURCE_EXHAUSTED error). + */ Y() { + this.G = this.K; + } + /** + * Returns a promise that resolves after currentDelayMs, and increases the + * delay for any subsequent attempts. If there was a pending backoff operation + * already, it will be canceled. + */ Z(t) { + // Cancel any pending backoff operation. + this.cancel(); + // First schedule using the current base (which may be 0 and should be + // honored as such). + const e = Math.floor(this.G + this.X()), r = Math.max(0, Date.now() - this.H), n = Math.max(0, e - r); + // Guard against lastAttemptTime being in the future due to a clock change. + n > 0 && __PRIVATE_logDebug("ExponentialBackoff", `Backing off for ${n} ms (base delay: ${this.G} ms, delay with jitter: ${e} ms, last attempt: ${r} ms ago)`), + this.J = this.U.enqueueAfterDelay(this.timerId, n, (() => (this.H = Date.now(), + t()))), + // Apply backoff factor to determine next delay and ensure it is within + // bounds. + this.G *= this.W, this.G < this.j && (this.G = this.j), this.G > this.K && (this.G = this.K); + } + tt() { + null !== this.J && (this.J.skipDelay(), this.J = null); + } + cancel() { + null !== this.J && (this.J.cancel(), this.J = null); + } + /** Returns a random value in the range [-currentBaseMs/2, currentBaseMs/2] */ X() { + return (Math.random() - .5) * this.G; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Datastore and its related methods are a wrapper around the external Google + * Cloud Datastore grpc API, which provides an interface that is more convenient + * for the rest of the client SDK architecture to consume. + */ class Datastore {} + +/** + * An implementation of Datastore that exposes additional state for internal + * consumption. + */ class __PRIVATE_DatastoreImpl extends Datastore { + constructor(t, e, r, n) { + super(), this.authCredentials = t, this.appCheckCredentials = e, this.connection = r, + this.serializer = n, this.et = !1; + } + rt() { + if (this.et) throw new FirestoreError(S, "The client has already been terminated."); + } + /** Invokes the provided RPC with auth and AppCheck tokens. */ I(t, e, r, n) { + return this.rt(), Promise.all([ this.authCredentials.getToken(), this.appCheckCredentials.getToken() ]).then((([i, s]) => this.connection.I(t, __PRIVATE_toResourcePath(e, r), n, i, s))).catch((t => { + throw "FirebaseError" === t.name ? (t.code === D && (this.authCredentials.invalidateToken(), + this.appCheckCredentials.invalidateToken()), t) : new FirestoreError(p, t.toString()); + })); + } + /** Invokes the provided RPC with streamed results with auth and AppCheck tokens. */ D(t, e, r, n, i) { + return this.rt(), Promise.all([ this.authCredentials.getToken(), this.appCheckCredentials.getToken() ]).then((([s, o]) => this.connection.D(t, __PRIVATE_toResourcePath(e, r), n, s, o, i))).catch((t => { + throw "FirebaseError" === t.name ? (t.code === D && (this.authCredentials.invalidateToken(), + this.appCheckCredentials.invalidateToken()), t) : new FirestoreError(p, t.toString()); + })); + } + terminate() { + this.et = !0, this.connection.terminate(); + } +} + +// TODO(firestorexp): Make sure there is only one Datastore instance per +// firestore-exp client. +async function __PRIVATE_invokeCommitRpc(t, e) { + const r = __PRIVATE_debugCast(t), n = { + writes: e.map((t => toMutation(r.serializer, t))) + }; + await r.I("Commit", r.serializer.databaseId, ResourcePath.emptyPath(), n); +} + +async function __PRIVATE_invokeBatchGetDocumentsRpc(t, e) { + const r = __PRIVATE_debugCast(t), n = { + documents: e.map((t => __PRIVATE_toName(r.serializer, t))) + }, i = await r.D("BatchGetDocuments", r.serializer.databaseId, ResourcePath.emptyPath(), n, e.length), s = new Map; + i.forEach((t => { + const e = __PRIVATE_fromBatchGetDocumentsResponse(r.serializer, t); + s.set(e.key.toString(), e); + })); + const o = []; + return e.forEach((t => { + const e = s.get(t.toString()); + __PRIVATE_hardAssert(!!e, 55234, { + key: t + }), o.push(e); + })), o; +} + +async function __PRIVATE_invokeRunQueryRpc(t, e) { + const r = __PRIVATE_debugCast(t), {M: n, parent: i} = __PRIVATE_toQueryTarget(r.serializer, __PRIVATE_queryToTarget(e)); + return (await r.D("RunQuery", r.serializer.databaseId, i, { + structuredQuery: n.structuredQuery + })).filter((t => !!t.document)).map((t => function __PRIVATE_fromDocument(t, e, r) { + const n = fromName(t, e.name), i = __PRIVATE_fromVersion(e.updateTime), s = e.createTime ? __PRIVATE_fromVersion(e.createTime) : SnapshotVersion.min(), o = new ObjectValue({ + mapValue: { + fields: e.fields + } + }), a = MutableDocument.newFoundDocument(n, i, s, o); + return r && a.setHasCommittedMutations(), r ? a.setHasCommittedMutations() : a; + }(r.serializer, t.document, void 0))); +} + +async function __PRIVATE_invokeRunAggregationQueryRpc(t, e, r) { + const n = __PRIVATE_debugCast(t), {request: i, nt: s, parent: o} = function __PRIVATE_toRunAggregationQueryRequest(t, e, r, n) { + const {M: i, parent: s} = __PRIVATE_toQueryTarget(t, e), o = {}, a = []; + let u = 0; + return r.forEach((t => { + // Map all client-side aliases to a unique short-form + // alias. This avoids issues with client-side aliases that + // exceed the 1500-byte string size limit. + const e = n ? t.alias : "aggregate_" + u++; + o[e] = t.alias, "count" === t.aggregateType ? a.push({ + alias: e, + count: {} + }) : "avg" === t.aggregateType ? a.push({ + alias: e, + avg: { + field: __PRIVATE_toFieldPathReference(t.fieldPath) + } + }) : "sum" === t.aggregateType && a.push({ + alias: e, + sum: { + field: __PRIVATE_toFieldPathReference(t.fieldPath) + } + }); + })), { + request: { + structuredAggregationQuery: { + aggregations: a, + structuredQuery: i.structuredQuery + }, + parent: i.parent + }, + nt: o, + parent: s + }; + }(n.serializer, function __PRIVATE_queryToAggregateTarget(t) { + const e = __PRIVATE_debugCast(t); + return e.$ || ( + // Do not include implicit order-bys for aggregate queries. + e.$ = __PRIVATE__queryToTarget(e, t.explicitOrderBy)), e.$; + }(e), r); + n.connection.P || delete i.parent; + const a = (await n.D("RunAggregationQuery", n.serializer.databaseId, o, i, + /*expectedResponseCount=*/ 1)).filter((t => !!t.result)); + // Omit RunAggregationQueryResponse that only contain readTimes. + __PRIVATE_hardAssert(1 === a.length, 64727); + // Remap the short-form aliases that were sent to the server + // to the client-side aliases. Users will access the results + // using the client-side alias. + const u = a[0].result?.aggregateFields; + return Object.keys(u).reduce(((t, e) => (t[s[e]] = u[e], t)), {}); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ const st = "ComponentProvider", ot = new Map; + +/** + * An instance map that ensures only one Datastore exists per Firestore + * instance. + */ +/** + * Returns an initialized and started Datastore for the given Firestore + * instance. Callers must invoke removeComponents() when the Firestore + * instance is terminated. + */ +function __PRIVATE_getDatastore(t) { + if (t._terminated) throw new FirestoreError(S, "The client has already been terminated."); + if (!ot.has(t)) { + __PRIVATE_logDebug(st, "Initializing Datastore"); + const e = function __PRIVATE_newConnection(t) { + return new __PRIVATE_FetchConnection(t); + }(function __PRIVATE_makeDatabaseInfo(t, e, r, n) { + return new DatabaseInfo(t, e, r, n.host, n.ssl, n.experimentalForceLongPolling, n.experimentalAutoDetectLongPolling, __PRIVATE_cloneLongPollingOptions(n.experimentalLongPollingOptions), n.useFetchStreams, n.isUsingEmulator); + } + /** + * @license + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ (t._databaseId, t.app.options.appId || "", t._persistenceKey, t._freezeSettings())), r = __PRIVATE_newSerializer(t._databaseId), n = function __PRIVATE_newDatastore(t, e, r, n) { + return new __PRIVATE_DatastoreImpl(t, e, r, n); + }(t._authCredentials, t._appCheckCredentials, e, r); + ot.set(t, n); + } + return ot.get(t); +} + +/** + * Removes all components associated with the provided instance. Must be called + * when the `Firestore` instance is terminated. + */ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const at = 1048576, ut = "firestore.googleapis.com", _t = !0; + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// settings() defaults: +/** + * A concrete type describing all the values that can be applied via a + * user-supplied `FirestoreSettings` object. This is a separate type so that + * defaults can be supplied and the value can be checked for equality. + */ +class FirestoreSettingsImpl { + constructor(t) { + if (void 0 === t.host) { + if (void 0 !== t.ssl) throw new FirestoreError(y, "Can't provide ssl option if host option is not set"); + this.host = ut, this.ssl = _t; + } else this.host = t.host, this.ssl = t.ssl ?? _t; + if (this.isUsingEmulator = void 0 !== t.emulatorOptions, this.credentials = t.credentials, + this.ignoreUndefinedProperties = !!t.ignoreUndefinedProperties, this.localCache = t.localCache, + void 0 === t.cacheSizeBytes) this.cacheSizeBytes = 41943040; else { + if (-1 !== t.cacheSizeBytes && t.cacheSizeBytes < at) throw new FirestoreError(y, "cacheSizeBytes must be at least 1048576"); + this.cacheSizeBytes = t.cacheSizeBytes; + } + !function __PRIVATE_validateIsNotUsedTogether(t, e, r, n) { + if (!0 === e && !0 === n) throw new FirestoreError(y, `${t} and ${r} cannot be used together.`); + }("experimentalForceLongPolling", t.experimentalForceLongPolling, "experimentalAutoDetectLongPolling", t.experimentalAutoDetectLongPolling), + this.experimentalForceLongPolling = !!t.experimentalForceLongPolling, this.experimentalForceLongPolling ? this.experimentalAutoDetectLongPolling = !1 : void 0 === t.experimentalAutoDetectLongPolling ? this.experimentalAutoDetectLongPolling = true : + // For backwards compatibility, coerce the value to boolean even though + // the TypeScript compiler has narrowed the type to boolean already. + // noinspection PointlessBooleanExpressionJS + this.experimentalAutoDetectLongPolling = !!t.experimentalAutoDetectLongPolling, + this.experimentalLongPollingOptions = __PRIVATE_cloneLongPollingOptions(t.experimentalLongPollingOptions ?? {}), + function __PRIVATE_validateLongPollingOptions(t) { + if (void 0 !== t.timeoutSeconds) { + if (isNaN(t.timeoutSeconds)) throw new FirestoreError(y, `invalid long polling timeout: ${t.timeoutSeconds} (must not be NaN)`); + if (t.timeoutSeconds < 5) throw new FirestoreError(y, `invalid long polling timeout: ${t.timeoutSeconds} (minimum allowed value is 5)`); + if (t.timeoutSeconds > 30) throw new FirestoreError(y, `invalid long polling timeout: ${t.timeoutSeconds} (maximum allowed value is 30)`); + } + } + /** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + /** + * The Cloud Firestore service interface. + * + * Do not call this constructor directly. Instead, use {@link (getFirestore:1)}. + */ (this.experimentalLongPollingOptions), this.useFetchStreams = !!t.useFetchStreams; + } + isEqual(t) { + return this.host === t.host && this.ssl === t.ssl && this.credentials === t.credentials && this.cacheSizeBytes === t.cacheSizeBytes && this.experimentalForceLongPolling === t.experimentalForceLongPolling && this.experimentalAutoDetectLongPolling === t.experimentalAutoDetectLongPolling && function __PRIVATE_longPollingOptionsEqual(t, e) { + return t.timeoutSeconds === e.timeoutSeconds; + }(this.experimentalLongPollingOptions, t.experimentalLongPollingOptions) && this.ignoreUndefinedProperties === t.ignoreUndefinedProperties && this.useFetchStreams === t.useFetchStreams; + } +} + +class Firestore { + /** @hideconstructor */ + constructor(t, e, r, n) { + this._authCredentials = t, this._appCheckCredentials = e, this._databaseId = r, + this._app = n, + /** + * Whether it's a Firestore or Firestore Lite instance. + */ + this.type = "firestore-lite", this._persistenceKey = "(lite)", this._settings = new FirestoreSettingsImpl({}), + this._settingsFrozen = !1, this._emulatorOptions = {}, + // A task that is assigned when the terminate() is invoked and resolved when + // all components have shut down. Otherwise, Firestore is not terminated, + // which can mean either the FirestoreClient is in the process of starting, + // or restarting. + this._terminateTask = "notTerminated"; + } + /** + * The {@link @firebase/app#FirebaseApp} associated with this `Firestore` service + * instance. + */ get app() { + if (!this._app) throw new FirestoreError(S, "Firestore was not initialized using the Firebase SDK. 'app' is not available"); + return this._app; + } + get _initialized() { + return this._settingsFrozen; + } + get _terminated() { + return "notTerminated" !== this._terminateTask; + } + _setSettings(t) { + if (this._settingsFrozen) throw new FirestoreError(S, "Firestore has already been started and its settings can no longer be changed. You can only modify settings before calling any other methods on a Firestore object."); + this._settings = new FirestoreSettingsImpl(t), this._emulatorOptions = t.emulatorOptions || {}, + void 0 !== t.credentials && (this._authCredentials = function __PRIVATE_makeAuthCredentialsProvider(t) { + if (!t) return new __PRIVATE_EmptyAuthCredentialsProvider; + switch (t.type) { + case "firstParty": + return new __PRIVATE_FirstPartyAuthCredentialsProvider(t.sessionIndex || "0", t.iamToken || null, t.authTokenFactory || null); + + case "provider": + return t.client; + + default: + throw new FirestoreError(y, "makeAuthCredentialsProvider failed due to invalid credential type"); + } + }(t.credentials)); + } + _getSettings() { + return this._settings; + } + _getEmulatorOptions() { + return this._emulatorOptions; + } + _freezeSettings() { + return this._settingsFrozen = !0, this._settings; + } + _delete() { + // The `_terminateTask` must be assigned future that completes when + // terminate is complete. The existence of this future puts SDK in state + // that will not accept further API interaction. + return "notTerminated" === this._terminateTask && (this._terminateTask = this._terminate()), + this._terminateTask; + } + async _restart() { + // The `_terminateTask` must equal 'notTerminated' after restart to + // signal that client is in a state that accepts API calls. + "notTerminated" === this._terminateTask ? await this._terminate() : this._terminateTask = "notTerminated"; + } + /** Returns a JSON-serializable representation of this `Firestore` instance. */ toJSON() { + return { + app: this._app, + databaseId: this._databaseId, + settings: this._settings + }; + } + /** + * Terminates all components used by this client. Subclasses can override + * this method to clean up their own dependencies, but must also call this + * method. + * + * Only ever called once. + */ _terminate() { + return function __PRIVATE_removeComponents(t) { + const e = ot.get(t); + e && (__PRIVATE_logDebug(st, "Removing Datastore"), ot.delete(t), e.terminate()); + }(this), Promise.resolve(); + } +} + +function initializeFirestore(t, e, r) { + r || (r = Q); + const n = _getProvider(t, "firestore/lite"); + if (n.isInitialized(r)) throw new FirestoreError(S, "Firestore can only be initialized once per app."); + return n.initialize({ + options: e, + instanceIdentifier: r + }); +} + +function getFirestore(t, r) { + const n = "object" == typeof t ? t : getApp(), i = "string" == typeof t ? t : r || "(default)", s = _getProvider(n, "firestore/lite").getImmediate({ + identifier: i + }); + if (!s._initialized) { + const t = getDefaultEmulatorHostnameAndPort("firestore"); + t && connectFirestoreEmulator(s, ...t); + } + return s; +} + +/** + * Modify this instance to communicate with the Cloud Firestore emulator. + * + * Note: This must be called before this instance has been used to do any + * operations. + * + * @param firestore - The `Firestore` instance to configure to connect to the + * emulator. + * @param host - the emulator host (ex: localhost). + * @param port - the emulator port (ex: 9000). + * @param options.mockUserToken - the mock auth token to use for unit testing + * Security Rules. + */ function connectFirestoreEmulator(t, e, r, n = {}) { + t = __PRIVATE_cast(t, Firestore); + const i = isCloudWorkstation(e), s = t._getSettings(), o = { + ...s, + emulatorOptions: t._getEmulatorOptions() + }, a = `${e}:${r}`; + i && (pingServer(`https://${a}`), updateEmulatorBanner("Firestore", !0)), s.host !== ut && s.host !== a && __PRIVATE_logWarn("Host has been set in both settings() and connectFirestoreEmulator(), emulator host will be used."); + const u = { + ...s, + host: a, + ssl: i, + emulatorOptions: n + }; + // No-op if the new configuration matches the current configuration. This supports SSR + // enviornments which might call `connectFirestoreEmulator` multiple times as a standard practice. + if (!deepEqual(u, o) && (t._setSettings(u), n.mockUserToken)) { + let e, r; + if ("string" == typeof n.mockUserToken) e = n.mockUserToken, r = User.MOCK_USER; else { + // Let createMockUserToken validate first (catches common mistakes like + // invalid field "uid" and missing field "sub" / "user_id".) + e = createMockUserToken(n.mockUserToken, t._app?.options.projectId); + const i = n.mockUserToken.sub || n.mockUserToken.user_id; + if (!i) throw new FirestoreError(y, "mockUserToken must contain 'sub' or 'user_id' field!"); + r = new User(i); + } + t._authCredentials = new __PRIVATE_EmulatorAuthCredentialsProvider(new __PRIVATE_OAuthToken(e, r)); + } +} + +/** + * Terminates the provided `Firestore` instance. + * + * After calling `terminate()` only the `clearIndexedDbPersistence()` functions + * may be used. Any other function will throw a `FirestoreError`. Termination + * does not cancel any pending writes, and any promises that are awaiting a + * response from the server will not be resolved. + * + * To restart after termination, create a new instance of `Firestore` with + * {@link (getFirestore:1)}. + * + * Note: Under normal circumstances, calling `terminate()` is not required. This + * function is useful only when you want to force this instance to release all of + * its resources or in combination with {@link clearIndexedDbPersistence} to + * ensure that all local state is destroyed between test runs. + * + * @param firestore - The `Firestore` instance to terminate. + * @returns A `Promise` that is resolved when the instance has been successfully + * terminated. + */ function terminate(t) { + return t = __PRIVATE_cast(t, Firestore), _removeServiceInstance(t.app, "firestore/lite"), t._delete(); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Represents an aggregation that can be performed by Firestore. + */ +// eslint-disable-next-line @typescript-eslint/no-unused-vars +class AggregateField { + /** + * Create a new AggregateField + * @param aggregateType Specifies the type of aggregation operation to perform. + * @param _internalFieldPath Optionally specifies the field that is aggregated. + * @internal + */ + constructor(t = "count", e) { + this._internalFieldPath = e, + /** A type string to uniquely identify instances of this class. */ + this.type = "AggregateField", this.aggregateType = t; + } +} + +/** + * The results of executing an aggregation query. + */ class AggregateQuerySnapshot { + /** @hideconstructor */ + constructor(t, e, r) { + this._userDataWriter = e, this._data = r, + /** A type string to uniquely identify instances of this class. */ + this.type = "AggregateQuerySnapshot", this.query = t; + } + /** + * Returns the results of the aggregations performed over the underlying + * query. + * + * The keys of the returned object will be the same as those of the + * `AggregateSpec` object specified to the aggregation method, and the values + * will be the corresponding aggregation result. + * + * @returns The results of the aggregations performed over the underlying + * query. + */ data() { + return this._userDataWriter.convertObjectMap(this._data); + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A `Query` refers to a query which you can read or listen to. You can also + * construct refined `Query` objects by adding filters and ordering. + */ class Query { + // This is the lite version of the Query class in the main SDK. + /** @hideconstructor protected */ + constructor(t, + /** + * If provided, the `FirestoreDataConverter` associated with this instance. + */ + e, r) { + this.converter = e, this._query = r, + /** The type of this Firestore reference. */ + this.type = "query", this.firestore = t; + } + withConverter(t) { + return new Query(this.firestore, t, this._query); + } +} + +/** + * A `DocumentReference` refers to a document location in a Firestore database + * and can be used to write, read, or listen to the location. The document at + * the referenced location may or may not exist. + */ class DocumentReference { + /** @hideconstructor */ + constructor(t, + /** + * If provided, the `FirestoreDataConverter` associated with this instance. + */ + e, r) { + this.converter = e, this._key = r, + /** The type of this Firestore reference. */ + this.type = "document", this.firestore = t; + } + get _path() { + return this._key.path; + } + /** + * The document's identifier within its collection. + */ get id() { + return this._key.path.lastSegment(); + } + /** + * A string representing the path of the referenced document (relative + * to the root of the database). + */ get path() { + return this._key.path.canonicalString(); + } + /** + * The collection this `DocumentReference` belongs to. + */ get parent() { + return new CollectionReference(this.firestore, this.converter, this._key.path.popLast()); + } + withConverter(t) { + return new DocumentReference(this.firestore, t, this._key); + } + /** + * Returns a JSON-serializable representation of this `DocumentReference` instance. + * + * @returns a JSON representation of this object. + */ toJSON() { + return { + type: DocumentReference._jsonSchemaVersion, + referencePath: this._key.toString() + }; + } + static fromJSON(t, e, r) { + if (__PRIVATE_validateJSON(e, DocumentReference._jsonSchema)) return new DocumentReference(t, r || null, new DocumentKey(ResourcePath.fromString(e.referencePath))); + } +} + +DocumentReference._jsonSchemaVersion = "firestore/documentReference/1.0", DocumentReference._jsonSchema = { + type: property("string", DocumentReference._jsonSchemaVersion), + referencePath: property("string") +}; + +/** + * A `CollectionReference` object can be used for adding documents, getting + * document references, and querying for documents (using {@link (query:1)}). + */ +class CollectionReference extends Query { + /** @hideconstructor */ + constructor(t, e, r) { + super(t, e, function __PRIVATE_newQueryForPath(t) { + return new __PRIVATE_QueryImpl(t); + }(r)), this._path = r, + /** The type of this Firestore reference. */ + this.type = "collection"; + } + /** The collection's identifier. */ get id() { + return this._query.path.lastSegment(); + } + /** + * A string representing the path of the referenced collection (relative + * to the root of the database). + */ get path() { + return this._query.path.canonicalString(); + } + /** + * A reference to the containing `DocumentReference` if this is a + * subcollection. If this isn't a subcollection, the reference is null. + */ get parent() { + const t = this._path.popLast(); + return t.isEmpty() ? null : new DocumentReference(this.firestore, + /* converter= */ null, new DocumentKey(t)); + } + withConverter(t) { + return new CollectionReference(this.firestore, t, this._path); + } +} + +function collection(t, e, ...r) { + if (t = getModularInstance(t), __PRIVATE_validateNonEmptyArgument("collection", "path", e), t instanceof Firestore) { + const n = ResourcePath.fromString(e, ...r); + return __PRIVATE_validateCollectionPath(n), new CollectionReference(t, /* converter= */ null, n); + } + { + if (!(t instanceof DocumentReference || t instanceof CollectionReference)) throw new FirestoreError(y, "Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore"); + const n = t._path.child(ResourcePath.fromString(e, ...r)); + return __PRIVATE_validateCollectionPath(n), new CollectionReference(t.firestore, + /* converter= */ null, n); + } +} + +// TODO(firestorelite): Consider using ErrorFactory - +// https://github.com/firebase/firebase-js-sdk/blob/0131e1f/packages/util/src/errors.ts#L106 +/** + * Creates and returns a new `Query` instance that includes all documents in the + * database that are contained in a collection or subcollection with the + * given `collectionId`. + * + * @param firestore - A reference to the root `Firestore` instance. + * @param collectionId - Identifies the collections to query over. Every + * collection or subcollection with this ID as the last segment of its path + * will be included. Cannot contain a slash. + * @returns The created `Query`. + */ function collectionGroup(t, e) { + if (t = __PRIVATE_cast(t, Firestore), __PRIVATE_validateNonEmptyArgument("collectionGroup", "collection id", e), + e.indexOf("/") >= 0) throw new FirestoreError(y, `Invalid collection ID '${e}' passed to function collectionGroup(). Collection IDs must not contain '/'.`); + return new Query(t, + /* converter= */ null, function __PRIVATE_newQueryForCollectionGroup(t) { + return new __PRIVATE_QueryImpl(ResourcePath.emptyPath(), t); + }(e)); +} + +function doc(t, e, ...r) { + if (t = getModularInstance(t), + // We allow omission of 'pathString' but explicitly prohibit passing in both + // 'undefined' and 'null'. + 1 === arguments.length && (e = __PRIVATE_AutoId.newId()), __PRIVATE_validateNonEmptyArgument("doc", "path", e), + t instanceof Firestore) { + const n = ResourcePath.fromString(e, ...r); + return __PRIVATE_validateDocumentPath(n), new DocumentReference(t, + /* converter= */ null, new DocumentKey(n)); + } + { + if (!(t instanceof DocumentReference || t instanceof CollectionReference)) throw new FirestoreError(y, "Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore"); + const n = t._path.child(ResourcePath.fromString(e, ...r)); + return __PRIVATE_validateDocumentPath(n), new DocumentReference(t.firestore, t instanceof CollectionReference ? t.converter : null, new DocumentKey(n)); + } +} + +/** + * Returns true if the provided references are equal. + * + * @param left - A reference to compare. + * @param right - A reference to compare. + * @returns true if the references point to the same location in the same + * Firestore database. + */ function refEqual(t, e) { + return t = getModularInstance(t), e = getModularInstance(e), (t instanceof DocumentReference || t instanceof CollectionReference) && (e instanceof DocumentReference || e instanceof CollectionReference) && (t.firestore === e.firestore && t.path === e.path && t.converter === e.converter); +} + +/** + * Returns true if the provided queries point to the same collection and apply + * the same constraints. + * + * @param left - A `Query` to compare. + * @param right - A `Query` to compare. + * @returns true if the references point to the same location in the same + * Firestore database. + */ function queryEqual(t, e) { + return t = getModularInstance(t), e = getModularInstance(e), t instanceof Query && e instanceof Query && (t.firestore === e.firestore && __PRIVATE_queryEquals(t._query, e._query) && t.converter === e.converter); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An immutable object representing an array of bytes. + */ class Bytes { + /** @hideconstructor */ + constructor(t) { + this._byteString = t; + } + /** + * Creates a new `Bytes` object from the given Base64 string, converting it to + * bytes. + * + * @param base64 - The Base64 string used to create the `Bytes` object. + */ static fromBase64String(t) { + try { + return new Bytes(ByteString.fromBase64String(t)); + } catch (t) { + throw new FirestoreError(y, "Failed to construct data from Base64 string: " + t); + } + } + /** + * Creates a new `Bytes` object from the given Uint8Array. + * + * @param array - The Uint8Array used to create the `Bytes` object. + */ static fromUint8Array(t) { + return new Bytes(ByteString.fromUint8Array(t)); + } + /** + * Returns the underlying bytes as a Base64-encoded string. + * + * @returns The Base64-encoded string created from the `Bytes` object. + */ toBase64() { + return this._byteString.toBase64(); + } + /** + * Returns the underlying bytes in a new `Uint8Array`. + * + * @returns The Uint8Array created from the `Bytes` object. + */ toUint8Array() { + return this._byteString.toUint8Array(); + } + /** + * Returns a string representation of the `Bytes` object. + * + * @returns A string representation of the `Bytes` object. + */ toString() { + return "Bytes(base64: " + this.toBase64() + ")"; + } + /** + * Returns true if this `Bytes` object is equal to the provided one. + * + * @param other - The `Bytes` object to compare against. + * @returns true if this `Bytes` object is equal to the provided one. + */ isEqual(t) { + return this._byteString.isEqual(t._byteString); + } + /** + * Returns a JSON-serializable representation of this `Bytes` instance. + * + * @returns a JSON representation of this object. + */ toJSON() { + return { + type: Bytes._jsonSchemaVersion, + bytes: this.toBase64() + }; + } + /** + * Builds a `Bytes` instance from a JSON object created by {@link Bytes.toJSON}. + * + * @param json a JSON object represention of a `Bytes` instance + * @returns an instance of {@link Bytes} if the JSON object could be parsed. Throws a + * {@link FirestoreError} if an error occurs. + */ static fromJSON(t) { + if (__PRIVATE_validateJSON(t, Bytes._jsonSchema)) return Bytes.fromBase64String(t.bytes); + } +} + +Bytes._jsonSchemaVersion = "firestore/bytes/1.0", Bytes._jsonSchema = { + type: property("string", Bytes._jsonSchemaVersion), + bytes: property("string") +}; + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A `FieldPath` refers to a field in a document. The path may consist of a + * single field name (referring to a top-level field in the document), or a + * list of field names (referring to a nested field in the document). + * + * Create a `FieldPath` by providing field names. If more than one field + * name is provided, the path will point to a nested field in a document. + */ +class FieldPath { + /** + * Creates a `FieldPath` from the provided field names. If more than one field + * name is provided, the path will point to a nested field in a document. + * + * @param fieldNames - A list of field names. + */ + constructor(...t) { + for (let e = 0; e < t.length; ++e) if (0 === t[e].length) throw new FirestoreError(y, "Invalid field name at argument $(i + 1). Field names must not be empty."); + this._internalPath = new FieldPath$1(t); + } + /** + * Returns true if this `FieldPath` is equal to the provided one. + * + * @param other - The `FieldPath` to compare against. + * @returns true if this `FieldPath` is equal to the provided one. + */ isEqual(t) { + return this._internalPath.isEqual(t._internalPath); + } +} + +/** + * Returns a special sentinel `FieldPath` to refer to the ID of a document. + * It can be used in queries to sort or filter by the document ID. + */ function documentId() { + return new FieldPath(M); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Sentinel values that can be used when writing document fields with `set()` + * or `update()`. + */ class FieldValue { + /** + * @param _methodName - The public API endpoint that returns this class. + * @hideconstructor + */ + constructor(t) { + this._methodName = t; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An immutable object representing a geographic location in Firestore. The + * location is represented as latitude/longitude pair. + * + * Latitude values are in the range of [-90, 90]. + * Longitude values are in the range of [-180, 180]. + */ class GeoPoint { + /** + * Creates a new immutable `GeoPoint` object with the provided latitude and + * longitude values. + * @param latitude - The latitude as number between -90 and 90. + * @param longitude - The longitude as number between -180 and 180. + */ + constructor(t, e) { + if (!isFinite(t) || t < -90 || t > 90) throw new FirestoreError(y, "Latitude must be a number between -90 and 90, but was: " + t); + if (!isFinite(e) || e < -180 || e > 180) throw new FirestoreError(y, "Longitude must be a number between -180 and 180, but was: " + e); + this._lat = t, this._long = e; + } + /** + * The latitude of this `GeoPoint` instance. + */ get latitude() { + return this._lat; + } + /** + * The longitude of this `GeoPoint` instance. + */ get longitude() { + return this._long; + } + /** + * Returns true if this `GeoPoint` is equal to the provided one. + * + * @param other - The `GeoPoint` to compare against. + * @returns true if this `GeoPoint` is equal to the provided one. + */ isEqual(t) { + return this._lat === t._lat && this._long === t._long; + } + /** + * Actually private to JS consumers of our API, so this function is prefixed + * with an underscore. + */ _compareTo(t) { + return __PRIVATE_primitiveComparator(this._lat, t._lat) || __PRIVATE_primitiveComparator(this._long, t._long); + } + /** + * Returns a JSON-serializable representation of this `GeoPoint` instance. + * + * @returns a JSON representation of this object. + */ toJSON() { + return { + latitude: this._lat, + longitude: this._long, + type: GeoPoint._jsonSchemaVersion + }; + } + /** + * Builds a `GeoPoint` instance from a JSON object created by {@link GeoPoint.toJSON}. + * + * @param json a JSON object represention of a `GeoPoint` instance + * @returns an instance of {@link GeoPoint} if the JSON object could be parsed. Throws a + * {@link FirestoreError} if an error occurs. + */ static fromJSON(t) { + if (__PRIVATE_validateJSON(t, GeoPoint._jsonSchema)) return new GeoPoint(t.latitude, t.longitude); + } +} + +GeoPoint._jsonSchemaVersion = "firestore/geoPoint/1.0", GeoPoint._jsonSchema = { + type: property("string", GeoPoint._jsonSchemaVersion), + latitude: property("number"), + longitude: property("number") +}; + +/** + * @license + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Represents a vector type in Firestore documents. + * Create an instance with {@link vector}. + * + * @class VectorValue + */ +class VectorValue { + /** + * @private + * @internal + */ + constructor(t) { + // Making a copy of the parameter. + this._values = (t || []).map((t => t)); + } + /** + * Returns a copy of the raw number array form of the vector. + */ toArray() { + return this._values.map((t => t)); + } + /** + * Returns `true` if the two `VectorValue` values have the same raw number arrays, returns `false` otherwise. + */ isEqual(t) { + /** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + /** + * Verifies equality for an array of primitives. + * + * @private + * @internal + * @param left Array of primitives. + * @param right Array of primitives. + * @return True if arrays are equal. + */ + return function __PRIVATE_isPrimitiveArrayEqual(t, e) { + if (t.length !== e.length) return !1; + for (let r = 0; r < t.length; ++r) if (t[r] !== e[r]) return !1; + return !0; + }(this._values, t._values); + } + /** + * Returns a JSON-serializable representation of this `VectorValue` instance. + * + * @returns a JSON representation of this object. + */ toJSON() { + return { + type: VectorValue._jsonSchemaVersion, + vectorValues: this._values + }; + } + /** + * Builds a `VectorValue` instance from a JSON object created by {@link VectorValue.toJSON}. + * + * @param json a JSON object represention of a `VectorValue` instance. + * @returns an instance of {@link VectorValue} if the JSON object could be parsed. Throws a + * {@link FirestoreError} if an error occurs. + */ static fromJSON(t) { + if (__PRIVATE_validateJSON(t, VectorValue._jsonSchema)) { + if (Array.isArray(t.vectorValues) && t.vectorValues.every((t => "number" == typeof t))) return new VectorValue(t.vectorValues); + throw new FirestoreError(y, "Expected 'vectorValues' field to be a number array"); + } + } +} + +VectorValue._jsonSchemaVersion = "firestore/vectorValue/1.0", VectorValue._jsonSchema = { + type: property("string", VectorValue._jsonSchemaVersion), + vectorValues: property("object") +}; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const ct = /^__.*__$/; + +/** The result of parsing document data (e.g. for a setData call). */ class ParsedSetData { + constructor(t, e, r) { + this.data = t, this.fieldMask = e, this.fieldTransforms = r; + } + toMutation(t, e) { + return null !== this.fieldMask ? new __PRIVATE_PatchMutation(t, this.data, this.fieldMask, e, this.fieldTransforms) : new __PRIVATE_SetMutation(t, this.data, e, this.fieldTransforms); + } +} + +/** The result of parsing "update" data (i.e. for an updateData call). */ class ParsedUpdateData { + constructor(t, + // The fieldMask does not include document transforms. + e, r) { + this.data = t, this.fieldMask = e, this.fieldTransforms = r; + } + toMutation(t, e) { + return new __PRIVATE_PatchMutation(t, this.data, this.fieldMask, e, this.fieldTransforms); + } +} + +function __PRIVATE_isWrite(t) { + switch (t) { + case 0 /* UserDataSource.Set */ : + // fall through + case 2 /* UserDataSource.MergeSet */ : + // fall through + case 1 /* UserDataSource.Update */ : + return !0; + + case 3 /* UserDataSource.Argument */ : + case 4 /* UserDataSource.ArrayArgument */ : + return !1; + + default: + throw fail(40011, { + it: t + }); + } +} + +/** A "context" object passed around while parsing user data. */ class __PRIVATE_ParseContextImpl { + /** + * Initializes a ParseContext with the given source and path. + * + * @param settings - The settings for the parser. + * @param databaseId - The database ID of the Firestore instance. + * @param serializer - The serializer to use to generate the Value proto. + * @param ignoreUndefinedProperties - Whether to ignore undefined properties + * rather than throw. + * @param fieldTransforms - A mutable list of field transforms encountered + * while parsing the data. + * @param fieldMask - A mutable list of field paths encountered while parsing + * the data. + * + * TODO(b/34871131): We don't support array paths right now, so path can be + * null to indicate the context represents any location within an array (in + * which case certain features will not work and errors will be somewhat + * compromised). + */ + constructor(t, e, r, n, i, s) { + this.settings = t, this.databaseId = e, this.serializer = r, this.ignoreUndefinedProperties = n, + // Minor hack: If fieldTransforms is undefined, we assume this is an + // external call and we need to validate the entire path. + void 0 === i && this.st(), this.fieldTransforms = i || [], this.fieldMask = s || []; + } + get path() { + return this.settings.path; + } + get it() { + return this.settings.it; + } + /** Returns a new context with the specified settings overwritten. */ ot(t) { + return new __PRIVATE_ParseContextImpl({ + ...this.settings, + ...t + }, this.databaseId, this.serializer, this.ignoreUndefinedProperties, this.fieldTransforms, this.fieldMask); + } + ut(t) { + const e = this.path?.child(t), r = this.ot({ + path: e, + _t: !1 + }); + return r.ct(t), r; + } + lt(t) { + const e = this.path?.child(t), r = this.ot({ + path: e, + _t: !1 + }); + return r.st(), r; + } + ht(t) { + // TODO(b/34871131): We don't support array paths right now; so make path + // undefined. + return this.ot({ + path: void 0, + _t: !0 + }); + } + ft(t) { + return __PRIVATE_createError(t, this.settings.methodName, this.settings.dt || !1, this.path, this.settings.Et); + } + /** Returns 'true' if 'fieldPath' was traversed when creating this context. */ contains(t) { + return void 0 !== this.fieldMask.find((e => t.isPrefixOf(e))) || void 0 !== this.fieldTransforms.find((e => t.isPrefixOf(e.field))); + } + st() { + // TODO(b/34871131): Remove null check once we have proper paths for fields + // within arrays. + if (this.path) for (let t = 0; t < this.path.length; t++) this.ct(this.path.get(t)); + } + ct(t) { + if (0 === t.length) throw this.ft("Document fields must not be empty"); + if (__PRIVATE_isWrite(this.it) && ct.test(t)) throw this.ft('Document fields cannot begin and end with "__"'); + } +} + +/** + * Helper for parsing raw user input (provided via the API) into internal model + * classes. + */ class __PRIVATE_UserDataReader { + constructor(t, e, r) { + this.databaseId = t, this.ignoreUndefinedProperties = e, this.serializer = r || __PRIVATE_newSerializer(t); + } + /** Creates a new top-level parse context. */ Tt(t, e, r, n = !1) { + return new __PRIVATE_ParseContextImpl({ + it: t, + methodName: e, + Et: r, + path: FieldPath$1.emptyPath(), + _t: !1, + dt: n + }, this.databaseId, this.serializer, this.ignoreUndefinedProperties); + } +} + +function __PRIVATE_newUserDataReader(t) { + const e = t._freezeSettings(), r = __PRIVATE_newSerializer(t._databaseId); + return new __PRIVATE_UserDataReader(t._databaseId, !!e.ignoreUndefinedProperties, r); +} + +/** Parse document data from a set() call. */ function __PRIVATE_parseSetData(t, e, r, n, i, s = {}) { + const o = t.Tt(s.merge || s.mergeFields ? 2 /* UserDataSource.MergeSet */ : 0 /* UserDataSource.Set */ , e, r, i); + __PRIVATE_validatePlainObject("Data must be an object, but it was:", o, n); + const a = __PRIVATE_parseObject(n, o); + let u, _; + if (s.merge) u = new FieldMask(o.fieldMask), _ = o.fieldTransforms; else if (s.mergeFields) { + const t = []; + for (const n of s.mergeFields) { + const i = __PRIVATE_fieldPathFromArgument$1(e, n, r); + if (!o.contains(i)) throw new FirestoreError(y, `Field '${i}' is specified in your field mask but missing from your input data.`); + __PRIVATE_fieldMaskContains(t, i) || t.push(i); + } + u = new FieldMask(t), _ = o.fieldTransforms.filter((t => u.covers(t.field))); + } else u = null, _ = o.fieldTransforms; + return new ParsedSetData(new ObjectValue(a), u, _); +} + +class __PRIVATE_DeleteFieldValueImpl extends FieldValue { + _toFieldTransform(t) { + if (2 /* UserDataSource.MergeSet */ !== t.it) throw 1 /* UserDataSource.Update */ === t.it ? t.ft(`${this._methodName}() can only appear at the top level of your update data`) : t.ft(`${this._methodName}() cannot be used with set() unless you pass {merge:true}`); + // No transform to add for a delete, but we need to add it to our + // fieldMask so it gets deleted. + return t.fieldMask.push(t.path), null; + } + isEqual(t) { + return t instanceof __PRIVATE_DeleteFieldValueImpl; + } +} + +/** + * Creates a child context for parsing SerializableFieldValues. + * + * This is different than calling `ParseContext.contextWith` because it keeps + * the fieldTransforms and fieldMask separate. + * + * The created context has its `dataSource` set to `UserDataSource.Argument`. + * Although these values are used with writes, any elements in these FieldValues + * are not considered writes since they cannot contain any FieldValue sentinels, + * etc. + * + * @param fieldValue - The sentinel FieldValue for which to create a child + * context. + * @param context - The parent context. + * @param arrayElement - Whether or not the FieldValue has an array. + */ function __PRIVATE_createSentinelChildContext(t, e, r) { + return new __PRIVATE_ParseContextImpl({ + it: 3 /* UserDataSource.Argument */ , + Et: e.settings.Et, + methodName: t._methodName, + _t: r + }, e.databaseId, e.serializer, e.ignoreUndefinedProperties); +} + +class __PRIVATE_ServerTimestampFieldValueImpl extends FieldValue { + _toFieldTransform(t) { + return new FieldTransform(t.path, new __PRIVATE_ServerTimestampTransform); + } + isEqual(t) { + return t instanceof __PRIVATE_ServerTimestampFieldValueImpl; + } +} + +class __PRIVATE_ArrayUnionFieldValueImpl extends FieldValue { + constructor(t, e) { + super(t), this.Pt = e; + } + _toFieldTransform(t) { + const e = __PRIVATE_createSentinelChildContext(this, t, + /*array=*/ !0), r = this.Pt.map((t => __PRIVATE_parseData(t, e))), n = new __PRIVATE_ArrayUnionTransformOperation(r); + return new FieldTransform(t.path, n); + } + isEqual(t) { + return t instanceof __PRIVATE_ArrayUnionFieldValueImpl && deepEqual(this.Pt, t.Pt); + } +} + +class __PRIVATE_ArrayRemoveFieldValueImpl extends FieldValue { + constructor(t, e) { + super(t), this.Pt = e; + } + _toFieldTransform(t) { + const e = __PRIVATE_createSentinelChildContext(this, t, + /*array=*/ !0), r = this.Pt.map((t => __PRIVATE_parseData(t, e))), n = new __PRIVATE_ArrayRemoveTransformOperation(r); + return new FieldTransform(t.path, n); + } + isEqual(t) { + return t instanceof __PRIVATE_ArrayRemoveFieldValueImpl && deepEqual(this.Pt, t.Pt); + } +} + +class __PRIVATE_NumericIncrementFieldValueImpl extends FieldValue { + constructor(t, e) { + super(t), this.At = e; + } + _toFieldTransform(t) { + const e = new __PRIVATE_NumericIncrementTransformOperation(t.serializer, toNumber(t.serializer, this.At)); + return new FieldTransform(t.path, e); + } + isEqual(t) { + return t instanceof __PRIVATE_NumericIncrementFieldValueImpl && this.At === t.At; + } +} + +/** Parse update data from an update() call. */ function __PRIVATE_parseUpdateData(t, e, r, n) { + const i = t.Tt(1 /* UserDataSource.Update */ , e, r); + __PRIVATE_validatePlainObject("Data must be an object, but it was:", i, n); + const s = [], o = ObjectValue.empty(); + forEach(n, ((t, n) => { + const a = __PRIVATE_fieldPathFromDotSeparatedString(e, t, r); + // For Compat types, we have to "extract" the underlying types before + // performing validation. + n = getModularInstance(n); + const u = i.lt(a); + if (n instanceof __PRIVATE_DeleteFieldValueImpl) + // Add it to the field mask, but don't add anything to updateData. + s.push(a); else { + const t = __PRIVATE_parseData(n, u); + null != t && (s.push(a), o.set(a, t)); + } + })); + const a = new FieldMask(s); + return new ParsedUpdateData(o, a, i.fieldTransforms); +} + +/** Parse update data from a list of field/value arguments. */ function __PRIVATE_parseUpdateVarargs(t, e, r, n, i, s) { + const o = t.Tt(1 /* UserDataSource.Update */ , e, r), a = [ __PRIVATE_fieldPathFromArgument$1(e, n, r) ], u = [ i ]; + if (s.length % 2 != 0) throw new FirestoreError(y, `Function ${e}() needs to be called with an even number of arguments that alternate between field names and values.`); + for (let t = 0; t < s.length; t += 2) a.push(__PRIVATE_fieldPathFromArgument$1(e, s[t])), + u.push(s[t + 1]); + const _ = [], c = ObjectValue.empty(); + // We iterate in reverse order to pick the last value for a field if the + // user specified the field multiple times. + for (let t = a.length - 1; t >= 0; --t) if (!__PRIVATE_fieldMaskContains(_, a[t])) { + const e = a[t]; + let r = u[t]; + // For Compat types, we have to "extract" the underlying types before + // performing validation. + r = getModularInstance(r); + const n = o.lt(e); + if (r instanceof __PRIVATE_DeleteFieldValueImpl) + // Add it to the field mask, but don't add anything to updateData. + _.push(e); else { + const t = __PRIVATE_parseData(r, n); + null != t && (_.push(e), c.set(e, t)); + } + } + const l = new FieldMask(_); + return new ParsedUpdateData(c, l, o.fieldTransforms); +} + +/** + * Parse a "query value" (e.g. value in a where filter or a value in a cursor + * bound). + * + * @param allowArrays - Whether the query value is an array that may directly + * contain additional arrays (e.g. the operand of an `in` query). + */ function __PRIVATE_parseQueryValue(t, e, r, n = !1) { + return __PRIVATE_parseData(r, t.Tt(n ? 4 /* UserDataSource.ArrayArgument */ : 3 /* UserDataSource.Argument */ , e)); +} + +/** + * Parses user data to Protobuf Values. + * + * @param input - Data to be parsed. + * @param context - A context object representing the current path being parsed, + * the source of the data being parsed, etc. + * @returns The parsed value, or null if the value was a FieldValue sentinel + * that should not be included in the resulting parsed data. + */ function __PRIVATE_parseData(t, e) { + if (__PRIVATE_looksLikeJsonObject( + // Unwrap the API type from the Compat SDK. This will return the API type + // from firestore-exp. + t = getModularInstance(t))) return __PRIVATE_validatePlainObject("Unsupported field value:", e, t), + __PRIVATE_parseObject(t, e); + if (t instanceof FieldValue) + // FieldValues usually parse into transforms (except deleteField()) + // in which case we do not want to include this field in our parsed data + // (as doing so will overwrite the field directly prior to the transform + // trying to transform it). So we don't add this location to + // context.fieldMask and we return null as our parsing result. + /** + * "Parses" the provided FieldValueImpl, adding any necessary transforms to + * context.fieldTransforms. + */ + return function __PRIVATE_parseSentinelFieldValue(t, e) { + // Sentinels are only supported with writes, and not within arrays. + if (!__PRIVATE_isWrite(e.it)) throw e.ft(`${t._methodName}() can only be used with update() and set()`); + if (!e.path) throw e.ft(`${t._methodName}() is not currently supported inside arrays`); + const r = t._toFieldTransform(e); + r && e.fieldTransforms.push(r); + } + /** + * Helper to parse a scalar value (i.e. not an Object, Array, or FieldValue) + * + * @returns The parsed value + */ (t, e), null; + if (void 0 === t && e.ignoreUndefinedProperties) + // If the input is undefined it can never participate in the fieldMask, so + // don't handle this below. If `ignoreUndefinedProperties` is false, + // `parseScalarValue` will reject an undefined value. + return null; + if ( + // If context.path is null we are inside an array and we don't support + // field mask paths more granular than the top-level array. + e.path && e.fieldMask.push(e.path), t instanceof Array) { + // TODO(b/34871131): Include the path containing the array in the error + // message. + // In the case of IN queries, the parsed data is an array (representing + // the set of values to be included for the IN query) that may directly + // contain additional arrays (each representing an individual field + // value), so we disable this validation. + if (e.settings._t && 4 /* UserDataSource.ArrayArgument */ !== e.it) throw e.ft("Nested arrays are not supported"); + return function __PRIVATE_parseArray(t, e) { + const r = []; + let n = 0; + for (const i of t) { + let t = __PRIVATE_parseData(i, e.ht(n)); + null == t && ( + // Just include nulls in the array for fields being replaced with a + // sentinel. + t = { + nullValue: "NULL_VALUE" + }), r.push(t), n++; + } + return { + arrayValue: { + values: r + } + }; + }(t, e); + } + return function __PRIVATE_parseScalarValue(t, e) { + if (null === (t = getModularInstance(t))) return { + nullValue: "NULL_VALUE" + }; + if ("number" == typeof t) return toNumber(e.serializer, t); + if ("boolean" == typeof t) return { + booleanValue: t + }; + if ("string" == typeof t) return { + stringValue: t + }; + if (t instanceof Date) { + const r = Timestamp.fromDate(t); + return { + timestampValue: toTimestamp(e.serializer, r) + }; + } + if (t instanceof Timestamp) { + // Firestore backend truncates precision down to microseconds. To ensure + // offline mode works the same with regards to truncation, perform the + // truncation immediately without waiting for the backend to do that. + const r = new Timestamp(t.seconds, 1e3 * Math.floor(t.nanoseconds / 1e3)); + return { + timestampValue: toTimestamp(e.serializer, r) + }; + } + if (t instanceof GeoPoint) return { + geoPointValue: { + latitude: t.latitude, + longitude: t.longitude + } + }; + if (t instanceof Bytes) return { + bytesValue: __PRIVATE_toBytes(e.serializer, t._byteString) + }; + if (t instanceof DocumentReference) { + const r = e.databaseId, n = t.firestore._databaseId; + if (!n.isEqual(r)) throw e.ft(`Document reference is for database ${n.projectId}/${n.database} but should be for database ${r.projectId}/${r.database}`); + return { + referenceValue: __PRIVATE_toResourceName(t.firestore._databaseId || e.databaseId, t._key.path) + }; + } + if (t instanceof VectorValue) + /** + * Creates a new VectorValue proto value (using the internal format). + */ + return function __PRIVATE_parseVectorValue(t, e) { + const r = { + fields: { + [Y]: { + stringValue: tt + }, + [et]: { + arrayValue: { + values: t.toArray().map((t => { + if ("number" != typeof t) throw e.ft("VectorValues must only contain numeric values."); + return __PRIVATE_toDouble(e.serializer, t); + })) + } + } + } + }; + return { + mapValue: r + }; + } + /** + * Checks whether an object looks like a JSON object that should be converted + * into a struct. Normal class/prototype instances are considered to look like + * JSON objects since they should be converted to a struct value. Arrays, Dates, + * GeoPoints, etc. are not considered to look like JSON objects since they map + * to specific FieldValue types other than ObjectValue. + */ (t, e); + throw e.ft(`Unsupported field value: ${__PRIVATE_valueDescription(t)}`); + }(t, e); +} + +function __PRIVATE_parseObject(t, e) { + const r = {}; + return !function isEmpty(t) { + for (const e in t) if (Object.prototype.hasOwnProperty.call(t, e)) return !1; + return !0; + }(t) ? forEach(t, ((t, n) => { + const i = __PRIVATE_parseData(n, e.ut(t)); + null != i && (r[t] = i); + })) : + // If we encounter an empty object, we explicitly add it to the update + // mask to ensure that the server creates a map entry. + e.path && e.path.length > 0 && e.fieldMask.push(e.path), { + mapValue: { + fields: r + } + }; +} + +function __PRIVATE_looksLikeJsonObject(t) { + return !("object" != typeof t || null === t || t instanceof Array || t instanceof Date || t instanceof Timestamp || t instanceof GeoPoint || t instanceof Bytes || t instanceof DocumentReference || t instanceof FieldValue || t instanceof VectorValue); +} + +function __PRIVATE_validatePlainObject(t, e, r) { + if (!__PRIVATE_looksLikeJsonObject(r) || !__PRIVATE_isPlainObject(r)) { + const n = __PRIVATE_valueDescription(r); + throw "an object" === n ? e.ft(t + " a custom object") : e.ft(t + " " + n); + } +} + +/** + * Helper that calls fromDotSeparatedString() but wraps any error thrown. + */ function __PRIVATE_fieldPathFromArgument$1(t, e, r) { + if (( + // If required, replace the FieldPath Compat class with the firestore-exp + // FieldPath. + e = getModularInstance(e)) instanceof FieldPath) return e._internalPath; + if ("string" == typeof e) return __PRIVATE_fieldPathFromDotSeparatedString(t, e); + throw __PRIVATE_createError("Field path arguments must be of type string or ", t, + /* hasConverter= */ !1, + /* path= */ void 0, r); +} + +/** + * Matches any characters in a field path string that are reserved. + */ const lt = new RegExp("[~\\*/\\[\\]]"); + +/** + * Wraps fromDotSeparatedString with an error message about the method that + * was thrown. + * @param methodName - The publicly visible method name + * @param path - The dot-separated string form of a field path which will be + * split on dots. + * @param targetDoc - The document against which the field path will be + * evaluated. + */ function __PRIVATE_fieldPathFromDotSeparatedString(t, e, r) { + if (e.search(lt) >= 0) throw __PRIVATE_createError(`Invalid field path (${e}). Paths must not contain '~', '*', '/', '[', or ']'`, t, + /* hasConverter= */ !1, + /* path= */ void 0, r); + try { + return new FieldPath(...e.split("."))._internalPath; + } catch (n) { + throw __PRIVATE_createError(`Invalid field path (${e}). Paths must not be empty, begin with '.', end with '.', or contain '..'`, t, + /* hasConverter= */ !1, + /* path= */ void 0, r); + } +} + +function __PRIVATE_createError(t, e, r, n, i) { + const s = n && !n.isEmpty(), o = void 0 !== i; + let a = `Function ${e}() called with invalid data`; + r && (a += " (via `toFirestore()`)"), a += ". "; + let u = ""; + return (s || o) && (u += " (found", s && (u += ` in field ${n}`), o && (u += ` in document ${i}`), + u += ")"), new FirestoreError(y, a + t + u); +} + +/** Checks `haystack` if FieldPath `needle` is present. Runs in O(n). */ function __PRIVATE_fieldMaskContains(t, e) { + return t.some((t => t.isEqual(e))); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A `DocumentSnapshot` contains data read from a document in your Firestore + * database. The data can be extracted with `.data()` or `.get()` to + * get a specific field. + * + * For a `DocumentSnapshot` that points to a non-existing document, any data + * access will return 'undefined'. You can use the `exists()` method to + * explicitly verify a document's existence. + */ class DocumentSnapshot { + // Note: This class is stripped down version of the DocumentSnapshot in + // the legacy SDK. The changes are: + // - No support for SnapshotMetadata. + // - No support for SnapshotOptions. + /** @hideconstructor protected */ + constructor(t, e, r, n, i) { + this._firestore = t, this._userDataWriter = e, this._key = r, this._document = n, + this._converter = i; + } + /** Property of the `DocumentSnapshot` that provides the document's ID. */ get id() { + return this._key.path.lastSegment(); + } + /** + * The `DocumentReference` for the document included in the `DocumentSnapshot`. + */ get ref() { + return new DocumentReference(this._firestore, this._converter, this._key); + } + /** + * Signals whether or not the document at the snapshot's location exists. + * + * @returns true if the document exists. + */ exists() { + return null !== this._document; + } + /** + * Retrieves all fields in the document as an `Object`. Returns `undefined` if + * the document doesn't exist. + * + * @returns An `Object` containing all fields in the document or `undefined` + * if the document doesn't exist. + */ data() { + if (this._document) { + if (this._converter) { + // We only want to use the converter and create a new DocumentSnapshot + // if a converter has been provided. + const t = new QueryDocumentSnapshot(this._firestore, this._userDataWriter, this._key, this._document, + /* converter= */ null); + return this._converter.fromFirestore(t); + } + return this._userDataWriter.convertValue(this._document.data.value); + } + } + /** + * Retrieves the field specified by `fieldPath`. Returns `undefined` if the + * document or field doesn't exist. + * + * @param fieldPath - The path (for example 'foo' or 'foo.bar') to a specific + * field. + * @returns The data at the specified field location or undefined if no such + * field exists in the document. + */ + // We are using `any` here to avoid an explicit cast by our users. + // eslint-disable-next-line @typescript-eslint/no-explicit-any + get(t) { + if (this._document) { + const e = this._document.data.field(__PRIVATE_fieldPathFromArgument("DocumentSnapshot.get", t)); + if (null !== e) return this._userDataWriter.convertValue(e); + } + } +} + +/** + * A `QueryDocumentSnapshot` contains data read from a document in your + * Firestore database as part of a query. The document is guaranteed to exist + * and its data can be extracted with `.data()` or `.get()` to get a + * specific field. + * + * A `QueryDocumentSnapshot` offers the same API surface as a + * `DocumentSnapshot`. Since query results contain only existing documents, the + * `exists` property will always be true and `data()` will never return + * 'undefined'. + */ class QueryDocumentSnapshot extends DocumentSnapshot { + /** + * Retrieves all fields in the document as an `Object`. + * + * @override + * @returns An `Object` containing all fields in the document. + */ + data() { + return super.data(); + } +} + +/** + * A `QuerySnapshot` contains zero or more `DocumentSnapshot` objects + * representing the results of a query. The documents can be accessed as an + * array via the `docs` property or enumerated using the `forEach` method. The + * number of documents can be determined via the `empty` and `size` + * properties. + */ class QuerySnapshot { + /** @hideconstructor */ + constructor(t, e) { + this._docs = e, this.query = t; + } + /** An array of all the documents in the `QuerySnapshot`. */ get docs() { + return [ ...this._docs ]; + } + /** The number of documents in the `QuerySnapshot`. */ get size() { + return this.docs.length; + } + /** True if there are no documents in the `QuerySnapshot`. */ get empty() { + return 0 === this.docs.length; + } + /** + * Enumerates all of the documents in the `QuerySnapshot`. + * + * @param callback - A callback to be called with a `QueryDocumentSnapshot` for + * each document in the snapshot. + * @param thisArg - The `this` binding for the callback. + */ forEach(t, e) { + this._docs.forEach(t, e); + } +} + +/** + * Returns true if the provided snapshots are equal. + * + * @param left - A snapshot to compare. + * @param right - A snapshot to compare. + * @returns true if the snapshots are equal. + */ function snapshotEqual(t, e) { + return t = getModularInstance(t), e = getModularInstance(e), t instanceof DocumentSnapshot && e instanceof DocumentSnapshot ? t._firestore === e._firestore && t._key.isEqual(e._key) && (null === t._document ? null === e._document : t._document.isEqual(e._document)) && t._converter === e._converter : t instanceof QuerySnapshot && e instanceof QuerySnapshot && (queryEqual(t.query, e.query) && __PRIVATE_arrayEquals(t.docs, e.docs, snapshotEqual)); +} + +/** + * Helper that calls `fromDotSeparatedString()` but wraps any error thrown. + */ function __PRIVATE_fieldPathFromArgument(t, e) { + return "string" == typeof e ? __PRIVATE_fieldPathFromDotSeparatedString(t, e) : e instanceof FieldPath ? e._internalPath : e._delegate._internalPath; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An `AppliableConstraint` is an abstraction of a constraint that can be applied + * to a Firestore query. + */ +class AppliableConstraint {} + +/** + * A `QueryConstraint` is used to narrow the set of documents returned by a + * Firestore query. `QueryConstraint`s are created by invoking {@link where}, + * {@link orderBy}, {@link (startAt:1)}, {@link (startAfter:1)}, {@link + * (endBefore:1)}, {@link (endAt:1)}, {@link limit}, {@link limitToLast} and + * can then be passed to {@link (query:1)} to create a new query instance that + * also contains this `QueryConstraint`. + */ class QueryConstraint extends AppliableConstraint {} + +function query(t, e, ...r) { + let n = []; + e instanceof AppliableConstraint && n.push(e), n = n.concat(r), function __PRIVATE_validateQueryConstraintArray(t) { + const e = t.filter((t => t instanceof QueryCompositeFilterConstraint)).length, r = t.filter((t => t instanceof QueryFieldFilterConstraint)).length; + if (e > 1 || e > 0 && r > 0) throw new FirestoreError(y, "InvalidQuery. When using composite filters, you cannot use more than one filter at the top level. Consider nesting the multiple filters within an `and(...)` statement. For example: change `query(query, where(...), or(...))` to `query(query, and(where(...), or(...)))`."); + } + /** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + /** + * Converts Firestore's internal types to the JavaScript types that we expose + * to the user. + * + * @internal + */ (n); + for (const e of n) t = e._apply(t); + return t; +} + +/** + * A `QueryFieldFilterConstraint` is used to narrow the set of documents returned by + * a Firestore query by filtering on one or more document fields. + * `QueryFieldFilterConstraint`s are created by invoking {@link where} and can then + * be passed to {@link (query:1)} to create a new query instance that also contains + * this `QueryFieldFilterConstraint`. + */ class QueryFieldFilterConstraint extends QueryConstraint { + /** + * @internal + */ + constructor(t, e, r) { + super(), this._field = t, this._op = e, this._value = r, + /** The type of this query constraint */ + this.type = "where"; + } + static _create(t, e, r) { + return new QueryFieldFilterConstraint(t, e, r); + } + _apply(t) { + const e = this._parse(t); + return __PRIVATE_validateNewFieldFilter(t._query, e), new Query(t.firestore, t.converter, __PRIVATE_queryWithAddedFilter(t._query, e)); + } + _parse(t) { + const e = __PRIVATE_newUserDataReader(t.firestore), r = function __PRIVATE_newQueryFilter(t, e, r, n, i, s, o) { + let a; + if (i.isKeyField()) { + if ("array-contains" /* Operator.ARRAY_CONTAINS */ === s || "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ === s) throw new FirestoreError(y, `Invalid Query. You can't perform '${s}' queries on documentId().`); + if ("in" /* Operator.IN */ === s || "not-in" /* Operator.NOT_IN */ === s) { + __PRIVATE_validateDisjunctiveFilterElements(o, s); + const e = []; + for (const r of o) e.push(__PRIVATE_parseDocumentIdValue(n, t, r)); + a = { + arrayValue: { + values: e + } + }; + } else a = __PRIVATE_parseDocumentIdValue(n, t, o); + } else "in" /* Operator.IN */ !== s && "not-in" /* Operator.NOT_IN */ !== s && "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ !== s || __PRIVATE_validateDisjunctiveFilterElements(o, s), + a = __PRIVATE_parseQueryValue(r, e, o, + /* allowArrays= */ "in" /* Operator.IN */ === s || "not-in" /* Operator.NOT_IN */ === s); + const u = FieldFilter.create(i, s, a); + return u; + }(t._query, "where", e, t.firestore._databaseId, this._field, this._op, this._value); + return r; + } +} + +/** + * Creates a {@link QueryFieldFilterConstraint} that enforces that documents + * must contain the specified field and that the value should satisfy the + * relation constraint provided. + * + * @param fieldPath - The path to compare + * @param opStr - The operation string (e.g "<", "<=", "==", "<", + * "<=", "!="). + * @param value - The value for comparison + * @returns The created {@link QueryFieldFilterConstraint}. + */ function where(t, e, r) { + const n = e, i = __PRIVATE_fieldPathFromArgument("where", t); + return QueryFieldFilterConstraint._create(i, n, r); +} + +/** + * A `QueryCompositeFilterConstraint` is used to narrow the set of documents + * returned by a Firestore query by performing the logical OR or AND of multiple + * {@link QueryFieldFilterConstraint}s or {@link QueryCompositeFilterConstraint}s. + * `QueryCompositeFilterConstraint`s are created by invoking {@link or} or + * {@link and} and can then be passed to {@link (query:1)} to create a new query + * instance that also contains the `QueryCompositeFilterConstraint`. + */ class QueryCompositeFilterConstraint extends AppliableConstraint { + /** + * @internal + */ + constructor( + /** The type of this query constraint */ + t, e) { + super(), this.type = t, this._queryConstraints = e; + } + static _create(t, e) { + return new QueryCompositeFilterConstraint(t, e); + } + _parse(t) { + const e = this._queryConstraints.map((e => e._parse(t))).filter((t => t.getFilters().length > 0)); + return 1 === e.length ? e[0] : CompositeFilter.create(e, this._getOperator()); + } + _apply(t) { + const e = this._parse(t); + return 0 === e.getFilters().length ? t : (function __PRIVATE_validateNewFilter(t, e) { + let r = t; + const n = e.getFlattenedFilters(); + for (const t of n) __PRIVATE_validateNewFieldFilter(r, t), r = __PRIVATE_queryWithAddedFilter(r, t); + } + // Checks if any of the provided filter operators are included in the given list of filters and + // returns the first one that is, or null if none are. + (t._query, e), new Query(t.firestore, t.converter, __PRIVATE_queryWithAddedFilter(t._query, e))); + } + _getQueryConstraints() { + return this._queryConstraints; + } + _getOperator() { + return "and" === this.type ? "and" /* CompositeOperator.AND */ : "or" /* CompositeOperator.OR */; + } +} + +/** + * Creates a new {@link QueryCompositeFilterConstraint} that is a disjunction of + * the given filter constraints. A disjunction filter includes a document if it + * satisfies any of the given filters. + * + * @param queryConstraints - Optional. The list of + * {@link QueryFilterConstraint}s to perform a disjunction for. These must be + * created with calls to {@link where}, {@link or}, or {@link and}. + * @returns The newly created {@link QueryCompositeFilterConstraint}. + */ function or(...t) { + // Only support QueryFilterConstraints + return t.forEach((t => __PRIVATE_validateQueryFilterConstraint("or", t))), QueryCompositeFilterConstraint._create("or" /* CompositeOperator.OR */ , t); +} + +/** + * Creates a new {@link QueryCompositeFilterConstraint} that is a conjunction of + * the given filter constraints. A conjunction filter includes a document if it + * satisfies all of the given filters. + * + * @param queryConstraints - Optional. The list of + * {@link QueryFilterConstraint}s to perform a conjunction for. These must be + * created with calls to {@link where}, {@link or}, or {@link and}. + * @returns The newly created {@link QueryCompositeFilterConstraint}. + */ function and(...t) { + // Only support QueryFilterConstraints + return t.forEach((t => __PRIVATE_validateQueryFilterConstraint("and", t))), QueryCompositeFilterConstraint._create("and" /* CompositeOperator.AND */ , t); +} + +/** + * A `QueryOrderByConstraint` is used to sort the set of documents returned by a + * Firestore query. `QueryOrderByConstraint`s are created by invoking + * {@link orderBy} and can then be passed to {@link (query:1)} to create a new query + * instance that also contains this `QueryOrderByConstraint`. + * + * Note: Documents that do not contain the orderBy field will not be present in + * the query result. + */ class QueryOrderByConstraint extends QueryConstraint { + /** + * @internal + */ + constructor(t, e) { + super(), this._field = t, this._direction = e, + /** The type of this query constraint */ + this.type = "orderBy"; + } + static _create(t, e) { + return new QueryOrderByConstraint(t, e); + } + _apply(t) { + const e = function __PRIVATE_newQueryOrderBy(t, e, r) { + if (null !== t.startAt) throw new FirestoreError(y, "Invalid query. You must not call startAt() or startAfter() before calling orderBy()."); + if (null !== t.endAt) throw new FirestoreError(y, "Invalid query. You must not call endAt() or endBefore() before calling orderBy()."); + const n = new OrderBy(e, r); + return n; + } + /** + * Create a `Bound` from a query and a document. + * + * Note that the `Bound` will always include the key of the document + * and so only the provided document will compare equal to the returned + * position. + * + * Will throw if the document does not contain all fields of the order by + * of the query or if any of the fields in the order by are an uncommitted + * server timestamp. + */ (t._query, this._field, this._direction); + return new Query(t.firestore, t.converter, function __PRIVATE_queryWithAddedOrderBy(t, e) { + // TODO(dimond): validate that orderBy does not list the same key twice. + const r = t.explicitOrderBy.concat([ e ]); + return new __PRIVATE_QueryImpl(t.path, t.collectionGroup, r, t.filters.slice(), t.limit, t.limitType, t.startAt, t.endAt); + }(t._query, e)); + } +} + +/** + * Creates a {@link QueryOrderByConstraint} that sorts the query result by the + * specified field, optionally in descending order instead of ascending. + * + * Note: Documents that do not contain the specified field will not be present + * in the query result. + * + * @param fieldPath - The field to sort by. + * @param directionStr - Optional direction to sort by ('asc' or 'desc'). If + * not specified, order will be ascending. + * @returns The created {@link QueryOrderByConstraint}. + */ function orderBy(t, e = "asc") { + const r = e, n = __PRIVATE_fieldPathFromArgument("orderBy", t); + return QueryOrderByConstraint._create(n, r); +} + +/** + * A `QueryLimitConstraint` is used to limit the number of documents returned by + * a Firestore query. + * `QueryLimitConstraint`s are created by invoking {@link limit} or + * {@link limitToLast} and can then be passed to {@link (query:1)} to create a new + * query instance that also contains this `QueryLimitConstraint`. + */ class QueryLimitConstraint extends QueryConstraint { + /** + * @internal + */ + constructor( + /** The type of this query constraint */ + t, e, r) { + super(), this.type = t, this._limit = e, this._limitType = r; + } + static _create(t, e, r) { + return new QueryLimitConstraint(t, e, r); + } + _apply(t) { + return new Query(t.firestore, t.converter, function __PRIVATE_queryWithLimit(t, e, r) { + return new __PRIVATE_QueryImpl(t.path, t.collectionGroup, t.explicitOrderBy.slice(), t.filters.slice(), e, r, t.startAt, t.endAt); + }(t._query, this._limit, this._limitType)); + } +} + +/** + * Creates a {@link QueryLimitConstraint} that only returns the first matching + * documents. + * + * @param limit - The maximum number of items to return. + * @returns The created {@link QueryLimitConstraint}. + */ function limit(t) { + return __PRIVATE_validatePositiveNumber("limit", t), QueryLimitConstraint._create("limit", t, "F" /* LimitType.First */); +} + +/** + * Creates a {@link QueryLimitConstraint} that only returns the last matching + * documents. + * + * You must specify at least one `orderBy` clause for `limitToLast` queries, + * otherwise an exception will be thrown during execution. + * + * @param limit - The maximum number of items to return. + * @returns The created {@link QueryLimitConstraint}. + */ function limitToLast(t) { + return __PRIVATE_validatePositiveNumber("limitToLast", t), QueryLimitConstraint._create("limitToLast", t, "L" /* LimitType.Last */); +} + +/** + * A `QueryStartAtConstraint` is used to exclude documents from the start of a + * result set returned by a Firestore query. + * `QueryStartAtConstraint`s are created by invoking {@link (startAt:1)} or + * {@link (startAfter:1)} and can then be passed to {@link (query:1)} to create a + * new query instance that also contains this `QueryStartAtConstraint`. + */ class QueryStartAtConstraint extends QueryConstraint { + /** + * @internal + */ + constructor( + /** The type of this query constraint */ + t, e, r) { + super(), this.type = t, this._docOrFields = e, this._inclusive = r; + } + static _create(t, e, r) { + return new QueryStartAtConstraint(t, e, r); + } + _apply(t) { + const e = __PRIVATE_newQueryBoundFromDocOrFields(t, this.type, this._docOrFields, this._inclusive); + return new Query(t.firestore, t.converter, function __PRIVATE_queryWithStartAt(t, e) { + return new __PRIVATE_QueryImpl(t.path, t.collectionGroup, t.explicitOrderBy.slice(), t.filters.slice(), t.limit, t.limitType, e, t.endAt); + }(t._query, e)); + } +} + +function startAt(...t) { + return QueryStartAtConstraint._create("startAt", t, + /*inclusive=*/ !0); +} + +function startAfter(...t) { + return QueryStartAtConstraint._create("startAfter", t, + /*inclusive=*/ !1); +} + +/** + * A `QueryEndAtConstraint` is used to exclude documents from the end of a + * result set returned by a Firestore query. + * `QueryEndAtConstraint`s are created by invoking {@link (endAt:1)} or + * {@link (endBefore:1)} and can then be passed to {@link (query:1)} to create a new + * query instance that also contains this `QueryEndAtConstraint`. + */ class QueryEndAtConstraint extends QueryConstraint { + /** + * @internal + */ + constructor( + /** The type of this query constraint */ + t, e, r) { + super(), this.type = t, this._docOrFields = e, this._inclusive = r; + } + static _create(t, e, r) { + return new QueryEndAtConstraint(t, e, r); + } + _apply(t) { + const e = __PRIVATE_newQueryBoundFromDocOrFields(t, this.type, this._docOrFields, this._inclusive); + return new Query(t.firestore, t.converter, function __PRIVATE_queryWithEndAt(t, e) { + return new __PRIVATE_QueryImpl(t.path, t.collectionGroup, t.explicitOrderBy.slice(), t.filters.slice(), t.limit, t.limitType, t.startAt, e); + }(t._query, e)); + } +} + +function endBefore(...t) { + return QueryEndAtConstraint._create("endBefore", t, + /*inclusive=*/ !1); +} + +function endAt(...t) { + return QueryEndAtConstraint._create("endAt", t, + /*inclusive=*/ !0); +} + +/** Helper function to create a bound from a document or fields */ function __PRIVATE_newQueryBoundFromDocOrFields(t, e, r, n) { + if (r[0] = getModularInstance(r[0]), r[0] instanceof DocumentSnapshot) return function __PRIVATE_newQueryBoundFromDocument(t, e, r, n, i) { + if (!n) throw new FirestoreError(w, `Can't use a DocumentSnapshot that doesn't exist for ${r}().`); + const s = []; + // Because people expect to continue/end a query at the exact document + // provided, we need to use the implicit sort order rather than the explicit + // sort order, because it's guaranteed to contain the document key. That way + // the position becomes unambiguous and the query continues/ends exactly at + // the provided document. Without the key (by using the explicit sort + // orders), multiple documents could match the position, yielding duplicate + // results. + for (const r of __PRIVATE_queryNormalizedOrderBy(t)) if (r.field.isKeyField()) s.push(__PRIVATE_refValue(e, n.key)); else { + const t = n.data.field(r.field); + if (__PRIVATE_isServerTimestamp(t)) throw new FirestoreError(y, 'Invalid query. You are trying to start or end a query using a document for which the field "' + r.field + '" is an uncommitted server timestamp. (Since the value of this field is unknown, you cannot start/end a query with it.)'); + if (null === t) { + const t = r.field.canonicalString(); + throw new FirestoreError(y, `Invalid query. You are trying to start or end a query using a document for which the field '${t}' (used as the orderBy) does not exist.`); + } + s.push(t); + } + return new Bound(s, i); + } + /** + * Converts a list of field values to a `Bound` for the given query. + */ (t._query, t.firestore._databaseId, e, r[0]._document, n); + { + const i = __PRIVATE_newUserDataReader(t.firestore); + return function __PRIVATE_newQueryBoundFromFields(t, e, r, n, i, s) { + // Use explicit order by's because it has to match the query the user made + const o = t.explicitOrderBy; + if (i.length > o.length) throw new FirestoreError(y, `Too many arguments provided to ${n}(). The number of arguments must be less than or equal to the number of orderBy() clauses`); + const a = []; + for (let s = 0; s < i.length; s++) { + const u = i[s]; + if (o[s].field.isKeyField()) { + if ("string" != typeof u) throw new FirestoreError(y, `Invalid query. Expected a string for document ID in ${n}(), but got a ${typeof u}`); + if (!__PRIVATE_isCollectionGroupQuery(t) && -1 !== u.indexOf("/")) throw new FirestoreError(y, `Invalid query. When querying a collection and ordering by documentId(), the value passed to ${n}() must be a plain document ID, but '${u}' contains a slash.`); + const r = t.path.child(ResourcePath.fromString(u)); + if (!DocumentKey.isDocumentKey(r)) throw new FirestoreError(y, `Invalid query. When querying a collection group and ordering by documentId(), the value passed to ${n}() must result in a valid document path, but '${r}' is not because it contains an odd number of segments.`); + const i = new DocumentKey(r); + a.push(__PRIVATE_refValue(e, i)); + } else { + const t = __PRIVATE_parseQueryValue(r, n, u); + a.push(t); + } + } + return new Bound(a, s); + } + /** + * Parses the given `documentIdValue` into a `ReferenceValue`, throwing + * appropriate errors if the value is anything other than a `DocumentReference` + * or `string`, or if the string is malformed. + */ (t._query, t.firestore._databaseId, i, e, r, n); + } +} + +function __PRIVATE_parseDocumentIdValue(t, e, r) { + if ("string" == typeof (r = getModularInstance(r))) { + if ("" === r) throw new FirestoreError(y, "Invalid query. When querying with documentId(), you must provide a valid document ID, but it was an empty string."); + if (!__PRIVATE_isCollectionGroupQuery(e) && -1 !== r.indexOf("/")) throw new FirestoreError(y, `Invalid query. When querying a collection by documentId(), you must provide a plain document ID, but '${r}' contains a '/' character.`); + const n = e.path.child(ResourcePath.fromString(r)); + if (!DocumentKey.isDocumentKey(n)) throw new FirestoreError(y, `Invalid query. When querying a collection group by documentId(), the value provided must result in a valid document path, but '${n}' is not because it has an odd number of segments (${n.length}).`); + return __PRIVATE_refValue(t, new DocumentKey(n)); + } + if (r instanceof DocumentReference) return __PRIVATE_refValue(t, r._key); + throw new FirestoreError(y, `Invalid query. When querying with documentId(), you must provide a valid string or a DocumentReference, but it was: ${__PRIVATE_valueDescription(r)}.`); +} + +/** + * Validates that the value passed into a disjunctive filter satisfies all + * array requirements. + */ function __PRIVATE_validateDisjunctiveFilterElements(t, e) { + if (!Array.isArray(t) || 0 === t.length) throw new FirestoreError(y, `Invalid Query. A non-empty array is required for '${e.toString()}' filters.`); +} + +/** + * Given an operator, returns the set of operators that cannot be used with it. + * + * This is not a comprehensive check, and this function should be removed in the + * long term. Validations should occur in the Firestore backend. + * + * Operators in a query must adhere to the following set of rules: + * 1. Only one inequality per query. + * 2. `NOT_IN` cannot be used with array, disjunctive, or `NOT_EQUAL` operators. + */ function __PRIVATE_validateNewFieldFilter(t, e) { + const r = function __PRIVATE_findOpInsideFilters(t, e) { + for (const r of t) for (const t of r.getFlattenedFilters()) if (e.indexOf(t.op) >= 0) return t.op; + return null; + }(t.filters, function __PRIVATE_conflictingOps(t) { + switch (t) { + case "!=" /* Operator.NOT_EQUAL */ : + return [ "!=" /* Operator.NOT_EQUAL */ , "not-in" /* Operator.NOT_IN */ ]; + + case "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ : + case "in" /* Operator.IN */ : + return [ "not-in" /* Operator.NOT_IN */ ]; + + case "not-in" /* Operator.NOT_IN */ : + return [ "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ , "in" /* Operator.IN */ , "not-in" /* Operator.NOT_IN */ , "!=" /* Operator.NOT_EQUAL */ ]; + + default: + return []; + } + }(e.op)); + if (null !== r) + // Special case when it's a duplicate op to give a slightly clearer error message. + throw r === e.op ? new FirestoreError(y, `Invalid query. You cannot use more than one '${e.op.toString()}' filter.`) : new FirestoreError(y, `Invalid query. You cannot use '${e.op.toString()}' filters with '${r.toString()}' filters.`); +} + +function __PRIVATE_validateQueryFilterConstraint(t, e) { + if (!(e instanceof QueryFieldFilterConstraint || e instanceof QueryCompositeFilterConstraint)) throw new FirestoreError(y, `Function ${t}() requires AppliableConstraints created with a call to 'where(...)', 'or(...)', or 'and(...)'.`); +} + +class AbstractUserDataWriter { + convertValue(t, e = "none") { + switch (__PRIVATE_typeOrder(t)) { + case 0 /* TypeOrder.NullValue */ : + return null; + + case 1 /* TypeOrder.BooleanValue */ : + return t.booleanValue; + + case 2 /* TypeOrder.NumberValue */ : + return __PRIVATE_normalizeNumber(t.integerValue || t.doubleValue); + + case 3 /* TypeOrder.TimestampValue */ : + return this.convertTimestamp(t.timestampValue); + + case 4 /* TypeOrder.ServerTimestampValue */ : + return this.convertServerTimestamp(t, e); + + case 5 /* TypeOrder.StringValue */ : + return t.stringValue; + + case 6 /* TypeOrder.BlobValue */ : + return this.convertBytes(__PRIVATE_normalizeByteString(t.bytesValue)); + + case 7 /* TypeOrder.RefValue */ : + return this.convertReference(t.referenceValue); + + case 8 /* TypeOrder.GeoPointValue */ : + return this.convertGeoPoint(t.geoPointValue); + + case 9 /* TypeOrder.ArrayValue */ : + return this.convertArray(t.arrayValue, e); + + case 11 /* TypeOrder.ObjectValue */ : + return this.convertObject(t.mapValue, e); + + case 10 /* TypeOrder.VectorValue */ : + return this.convertVectorValue(t.mapValue); + + default: + throw fail(62114, { + value: t + }); + } + } + convertObject(t, e) { + return this.convertObjectMap(t.fields, e); + } + /** + * @internal + */ convertObjectMap(t, e = "none") { + const r = {}; + return forEach(t, ((t, n) => { + r[t] = this.convertValue(n, e); + })), r; + } + /** + * @internal + */ convertVectorValue(t) { + const e = t.fields?.[et].arrayValue?.values?.map((t => __PRIVATE_normalizeNumber(t.doubleValue))); + return new VectorValue(e); + } + convertGeoPoint(t) { + return new GeoPoint(__PRIVATE_normalizeNumber(t.latitude), __PRIVATE_normalizeNumber(t.longitude)); + } + convertArray(t, e) { + return (t.values || []).map((t => this.convertValue(t, e))); + } + convertServerTimestamp(t, e) { + switch (e) { + case "previous": + const r = __PRIVATE_getPreviousValue(t); + return null == r ? null : this.convertValue(r, e); + + case "estimate": + return this.convertTimestamp(__PRIVATE_getLocalWriteTime(t)); + + default: + return null; + } + } + convertTimestamp(t) { + const e = __PRIVATE_normalizeTimestamp(t); + return new Timestamp(e.seconds, e.nanos); + } + convertDocumentKey(t, e) { + const r = ResourcePath.fromString(t); + __PRIVATE_hardAssert(__PRIVATE_isValidResourceName(r), 9688, { + name: t + }); + const n = new DatabaseId(r.get(1), r.get(3)), i = new DocumentKey(r.popFirst(5)); + return n.isEqual(e) || + // TODO(b/64130202): Somehow support foreign references. + __PRIVATE_logError(`Document ${i} contains a document reference within a different database (${n.projectId}/${n.database}) which is not supported. It will be treated as a reference in the current database (${e.projectId}/${e.database}) instead.`), + i; + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Converts custom model object of type T into `DocumentData` by applying the + * converter if it exists. + * + * This function is used when converting user objects to `DocumentData` + * because we want to provide the user with a more specific error message if + * their `set()` or fails due to invalid data originating from a `toFirestore()` + * call. + */ function __PRIVATE_applyFirestoreDataConverter(t, e, r) { + let n; + // Cast to `any` in order to satisfy the union type constraint on + // toFirestore(). + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return n = t ? r && (r.merge || r.mergeFields) ? t.toFirestore(e, r) : t.toFirestore(e) : e, + n; +} + +class __PRIVATE_LiteUserDataWriter extends AbstractUserDataWriter { + constructor(t) { + super(), this.firestore = t; + } + convertBytes(t) { + return new Bytes(t); + } + convertReference(t) { + const e = this.convertDocumentKey(t, this.firestore._databaseId); + return new DocumentReference(this.firestore, /* converter= */ null, e); + } +} + +/** + * Reads the document referred to by the specified document reference. + * + * All documents are directly fetched from the server, even if the document was + * previously read or modified. Recent modifications are only reflected in the + * retrieved `DocumentSnapshot` if they have already been applied by the + * backend. If the client is offline, the read fails. If you like to use + * caching or see local modifications, please use the full Firestore SDK. + * + * @param reference - The reference of the document to fetch. + * @returns A Promise resolved with a `DocumentSnapshot` containing the current + * document contents. + */ function getDoc(t) { + const e = __PRIVATE_getDatastore((t = __PRIVATE_cast(t, DocumentReference)).firestore), r = new __PRIVATE_LiteUserDataWriter(t.firestore); + return __PRIVATE_invokeBatchGetDocumentsRpc(e, [ t._key ]).then((e => { + __PRIVATE_hardAssert(1 === e.length, 15618); + const n = e[0]; + return new DocumentSnapshot(t.firestore, r, t._key, n.isFoundDocument() ? n : null, t.converter); + })); +} + +/** + * Executes the query and returns the results as a {@link QuerySnapshot}. + * + * All queries are executed directly by the server, even if the query was + * previously executed. Recent modifications are only reflected in the retrieved + * results if they have already been applied by the backend. If the client is + * offline, the operation fails. To see previously cached result and local + * modifications, use the full Firestore SDK. + * + * @param query - The `Query` to execute. + * @returns A Promise that will be resolved with the results of the query. + */ function getDocs(t) { + (function __PRIVATE_validateHasExplicitOrderByForLimitToLast(t) { + if ("L" /* LimitType.Last */ === t.limitType && 0 === t.explicitOrderBy.length) throw new FirestoreError(O, "limitToLast() queries require specifying at least one orderBy() clause"); + })((t = __PRIVATE_cast(t, Query))._query); + const e = __PRIVATE_getDatastore(t.firestore), r = new __PRIVATE_LiteUserDataWriter(t.firestore); + return __PRIVATE_invokeRunQueryRpc(e, t._query).then((e => { + const n = e.map((e => new QueryDocumentSnapshot(t.firestore, r, e.key, e, t.converter))); + return "L" /* LimitType.Last */ === t._query.limitType && + // Limit to last queries reverse the orderBy constraint that was + // specified by the user. As such, we need to reverse the order of the + // results to return the documents in the expected order. + n.reverse(), new QuerySnapshot(t, n); + })); +} + +function setDoc(t, e, r) { + const n = __PRIVATE_applyFirestoreDataConverter((t = __PRIVATE_cast(t, DocumentReference)).converter, e, r), i = __PRIVATE_parseSetData(__PRIVATE_newUserDataReader(t.firestore), "setDoc", t._key, n, null !== t.converter, r); + return __PRIVATE_invokeCommitRpc(__PRIVATE_getDatastore(t.firestore), [ i.toMutation(t._key, Precondition.none()) ]); +} + +function updateDoc(t, e, r, ...n) { + const i = __PRIVATE_newUserDataReader((t = __PRIVATE_cast(t, DocumentReference)).firestore); + // For Compat types, we have to "extract" the underlying types before + // performing validation. + let s; + s = "string" == typeof (e = getModularInstance(e)) || e instanceof FieldPath ? __PRIVATE_parseUpdateVarargs(i, "updateDoc", t._key, e, r, n) : __PRIVATE_parseUpdateData(i, "updateDoc", t._key, e); + return __PRIVATE_invokeCommitRpc(__PRIVATE_getDatastore(t.firestore), [ s.toMutation(t._key, Precondition.exists(!0)) ]); +} + +/** + * Deletes the document referred to by the specified `DocumentReference`. + * + * The deletion will only be reflected in document reads that occur after the + * returned promise resolves. If the client is offline, the + * delete fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @param reference - A reference to the document to delete. + * @returns A `Promise` resolved once the document has been successfully + * deleted from the backend. + */ function deleteDoc(t) { + return __PRIVATE_invokeCommitRpc(__PRIVATE_getDatastore((t = __PRIVATE_cast(t, DocumentReference)).firestore), [ new __PRIVATE_DeleteMutation(t._key, Precondition.none()) ]); +} + +/** + * Add a new document to specified `CollectionReference` with the given data, + * assigning it a document ID automatically. + * + * The result of this write will only be reflected in document reads that occur + * after the returned promise resolves. If the client is offline, the + * write fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @param reference - A reference to the collection to add this document to. + * @param data - An Object containing the data for the new document. + * @throws Error - If the provided input is not a valid Firestore document. + * @returns A `Promise` resolved with a `DocumentReference` pointing to the + * newly created document after it has been written to the backend. + */ function addDoc(t, e) { + const r = doc(t = __PRIVATE_cast(t, CollectionReference)), n = __PRIVATE_applyFirestoreDataConverter(t.converter, e), i = __PRIVATE_parseSetData(__PRIVATE_newUserDataReader(t.firestore), "addDoc", r._key, n, null !== r.converter, {}); + return __PRIVATE_invokeCommitRpc(__PRIVATE_getDatastore(t.firestore), [ i.toMutation(r._key, Precondition.exists(!1)) ]).then((() => r)); +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Calculates the number of documents in the result set of the given query + * without actually downloading the documents. + * + * Using this function to count the documents is efficient because only the + * final count, not the documents' data, is downloaded. This function can + * count the documents in cases where the result set is prohibitively large to + * download entirely (thousands of documents). + * + * @param query The query whose result set size is calculated. + * @returns A Promise that will be resolved with the count; the count can be + * retrieved from `snapshot.data().count`, where `snapshot` is the + * `AggregateQuerySnapshot` to which the returned Promise resolves. + */ function getCount(t) { + return getAggregate(t, { + count: count() + }); +} + +/** + * Calculates the specified aggregations over the documents in the result + * set of the given query without actually downloading the documents. + * + * Using this function to perform aggregations is efficient because only the + * final aggregation values, not the documents' data, are downloaded. This + * function can perform aggregations of the documents in cases where the result + * set is prohibitively large to download entirely (thousands of documents). + * + * @param query The query whose result set is aggregated over. + * @param aggregateSpec An `AggregateSpec` object that specifies the aggregates + * to perform over the result set. The AggregateSpec specifies aliases for each + * aggregate, which can be used to retrieve the aggregate result. + * @example + * ```typescript + * const aggregateSnapshot = await getAggregate(query, { + * countOfDocs: count(), + * totalHours: sum('hours'), + * averageScore: average('score') + * }); + * + * const countOfDocs: number = aggregateSnapshot.data().countOfDocs; + * const totalHours: number = aggregateSnapshot.data().totalHours; + * const averageScore: number | null = aggregateSnapshot.data().averageScore; + * ``` + */ function getAggregate(t, e) { + const r = __PRIVATE_cast(t.firestore, Firestore), n = __PRIVATE_getDatastore(r), i = function __PRIVATE_mapToArray(t, e) { + const r = []; + for (const n in t) Object.prototype.hasOwnProperty.call(t, n) && r.push(e(t[n], n, t)); + return r; + }(e, ((t, e) => new __PRIVATE_AggregateImpl(e, t.aggregateType, t._internalFieldPath))); + // Run the aggregation and convert the results + return __PRIVATE_invokeRunAggregationQueryRpc(n, t._query, i).then((e => function __PRIVATE_convertToAggregateQuerySnapshot(t, e, r) { + const n = new __PRIVATE_LiteUserDataWriter(t), i = new AggregateQuerySnapshot(e, n, r); + return i; + } + /** + * Create an AggregateField object that can be used to compute the sum of + * a specified field over a range of documents in the result set of a query. + * @param field Specifies the field to sum across the result set. + */ (r, t, e))); +} + +function sum(t) { + return new AggregateField("sum", __PRIVATE_fieldPathFromArgument$1("sum", t)); +} + +/** + * Create an AggregateField object that can be used to compute the average of + * a specified field over a range of documents in the result set of a query. + * @param field Specifies the field to average across the result set. + */ function average(t) { + return new AggregateField("avg", __PRIVATE_fieldPathFromArgument$1("average", t)); +} + +/** + * Create an AggregateField object that can be used to compute the count of + * documents in the result set of a query. + */ function count() { + return new AggregateField("count"); +} + +/** + * Compares two 'AggregateField` instances for equality. + * + * @param left Compare this AggregateField to the `right`. + * @param right Compare this AggregateField to the `left`. + */ function aggregateFieldEqual(t, e) { + return t instanceof AggregateField && e instanceof AggregateField && t.aggregateType === e.aggregateType && t._internalFieldPath?.canonicalString() === e._internalFieldPath?.canonicalString(); +} + +/** + * Compares two `AggregateQuerySnapshot` instances for equality. + * + * Two `AggregateQuerySnapshot` instances are considered "equal" if they have + * underlying queries that compare equal, and the same data. + * + * @param left - The first `AggregateQuerySnapshot` to compare. + * @param right - The second `AggregateQuerySnapshot` to compare. + * + * @returns `true` if the objects are "equal", as defined above, or `false` + * otherwise. + */ function aggregateQuerySnapshotEqual(t, e) { + return queryEqual(t.query, e.query) && deepEqual(t.data(), e.data()); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Returns a sentinel for use with {@link @firebase/firestore/lite#(updateDoc:1)} or + * {@link @firebase/firestore/lite#(setDoc:1)} with `{merge: true}` to mark a field for deletion. + */ function deleteField() { + return new __PRIVATE_DeleteFieldValueImpl("deleteField"); +} + +/** + * Returns a sentinel used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link @firebase/firestore/lite#(updateDoc:1)} to + * include a server-generated timestamp in the written data. + */ function serverTimestamp() { + return new __PRIVATE_ServerTimestampFieldValueImpl("serverTimestamp"); +} + +/** + * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link + * @firebase/firestore/lite#(updateDoc:1)} that tells the server to union the given elements with any array + * value that already exists on the server. Each specified element that doesn't + * already exist in the array will be added to the end. If the field being + * modified is not already an array it will be overwritten with an array + * containing exactly the specified elements. + * + * @param elements - The elements to union into the array. + * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or + * `updateDoc()`. + */ function arrayUnion(...t) { + // NOTE: We don't actually parse the data until it's used in set() or + // update() since we'd need the Firestore instance to do this. + return new __PRIVATE_ArrayUnionFieldValueImpl("arrayUnion", t); +} + +/** + * Returns a special value that can be used with {@link (setDoc:1)} or {@link + * updateDoc:1} that tells the server to remove the given elements from any + * array value that already exists on the server. All instances of each element + * specified will be removed from the array. If the field being modified is not + * already an array it will be overwritten with an empty array. + * + * @param elements - The elements to remove from the array. + * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or + * `updateDoc()` + */ function arrayRemove(...t) { + // NOTE: We don't actually parse the data until it's used in set() or + // update() since we'd need the Firestore instance to do this. + return new __PRIVATE_ArrayRemoveFieldValueImpl("arrayRemove", t); +} + +/** + * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link + * @firebase/firestore/lite#(updateDoc:1)} that tells the server to increment the field's current value by + * the given value. + * + * If either the operand or the current field value uses floating point + * precision, all arithmetic follows IEEE 754 semantics. If both values are + * integers, values outside of JavaScript's safe number range + * (`Number.MIN_SAFE_INTEGER` to `Number.MAX_SAFE_INTEGER`) are also subject to + * precision loss. Furthermore, once processed by the Firestore backend, all + * integer operations are capped between -2^63 and 2^63-1. + * + * If the current field value is not of type `number`, or if the field does not + * yet exist, the transformation sets the field to the given value. + * + * @param n - The value to increment by. + * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or + * `updateDoc()` + */ function increment(t) { + return new __PRIVATE_NumericIncrementFieldValueImpl("increment", t); +} + +/** + * Creates a new `VectorValue` constructed with a copy of the given array of numbers. + * + * @param values - Create a `VectorValue` instance with a copy of this array of numbers. + * + * @returns A new `VectorValue` constructed with a copy of the given array of numbers. + */ function vector(t) { + return new VectorValue(t); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A write batch, used to perform multiple writes as a single atomic unit. + * + * A `WriteBatch` object can be acquired by calling {@link writeBatch}. It + * provides methods for adding writes to the write batch. None of the writes + * will be committed (or visible locally) until {@link WriteBatch.commit} is + * called. + */ class WriteBatch { + /** @hideconstructor */ + constructor(t, e) { + this._firestore = t, this._commitHandler = e, this._mutations = [], this._committed = !1, + this._dataReader = __PRIVATE_newUserDataReader(t); + } + set(t, e, r) { + this._verifyNotCommitted(); + const n = __PRIVATE_validateReference(t, this._firestore), i = __PRIVATE_applyFirestoreDataConverter(n.converter, e, r), s = __PRIVATE_parseSetData(this._dataReader, "WriteBatch.set", n._key, i, null !== n.converter, r); + return this._mutations.push(s.toMutation(n._key, Precondition.none())), this; + } + update(t, e, r, ...n) { + this._verifyNotCommitted(); + const i = __PRIVATE_validateReference(t, this._firestore); + // For Compat types, we have to "extract" the underlying types before + // performing validation. + let s; + return s = "string" == typeof (e = getModularInstance(e)) || e instanceof FieldPath ? __PRIVATE_parseUpdateVarargs(this._dataReader, "WriteBatch.update", i._key, e, r, n) : __PRIVATE_parseUpdateData(this._dataReader, "WriteBatch.update", i._key, e), + this._mutations.push(s.toMutation(i._key, Precondition.exists(!0))), this; + } + /** + * Deletes the document referred to by the provided {@link DocumentReference}. + * + * @param documentRef - A reference to the document to be deleted. + * @returns This `WriteBatch` instance. Used for chaining method calls. + */ delete(t) { + this._verifyNotCommitted(); + const e = __PRIVATE_validateReference(t, this._firestore); + return this._mutations = this._mutations.concat(new __PRIVATE_DeleteMutation(e._key, Precondition.none())), + this; + } + /** + * Commits all of the writes in this write batch as a single atomic unit. + * + * The result of these writes will only be reflected in document reads that + * occur after the returned promise resolves. If the client is offline, the + * write fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @returns A `Promise` resolved once all of the writes in the batch have been + * successfully written to the backend as an atomic unit (note that it won't + * resolve while you're offline). + */ commit() { + return this._verifyNotCommitted(), this._committed = !0, this._mutations.length > 0 ? this._commitHandler(this._mutations) : Promise.resolve(); + } + _verifyNotCommitted() { + if (this._committed) throw new FirestoreError(S, "A write batch can no longer be used after commit() has been called."); + } +} + +function __PRIVATE_validateReference(t, e) { + if ((t = getModularInstance(t)).firestore !== e) throw new FirestoreError(y, "Provided document reference is from a different Firestore instance."); + return t; +} + +/** + * Creates a write batch, used for performing multiple writes as a single + * atomic operation. The maximum number of writes allowed in a single WriteBatch + * is 500. + * + * The result of these writes will only be reflected in document reads that + * occur after the returned promise resolves. If the client is offline, the + * write fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @returns A `WriteBatch` that can be used to atomically execute multiple + * writes. + */ function writeBatch(t) { + const e = __PRIVATE_getDatastore(t = __PRIVATE_cast(t, Firestore)); + return new WriteBatch(t, (t => __PRIVATE_invokeCommitRpc(e, t))); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Internal transaction object responsible for accumulating the mutations to + * perform and the base versions for any documents read. + */ class Transaction$1 { + constructor(t) { + this.datastore = t, + // The version of each document that was read during this transaction. + this.readVersions = new Map, this.mutations = [], this.committed = !1, + /** + * A deferred usage error that occurred previously in this transaction that + * will cause the transaction to fail once it actually commits. + */ + this.lastTransactionError = null, + /** + * Set of documents that have been written in the transaction. + * + * When there's more than one write to the same key in a transaction, any + * writes after the first are handled differently. + */ + this.writtenDocs = new Set; + } + async lookup(t) { + if (this.ensureCommitNotCalled(), this.mutations.length > 0) throw this.lastTransactionError = new FirestoreError(y, "Firestore transactions require all reads to be executed before all writes."), + this.lastTransactionError; + const e = await __PRIVATE_invokeBatchGetDocumentsRpc(this.datastore, t); + return e.forEach((t => this.recordVersion(t))), e; + } + set(t, e) { + this.write(e.toMutation(t, this.precondition(t))), this.writtenDocs.add(t.toString()); + } + update(t, e) { + try { + this.write(e.toMutation(t, this.preconditionForUpdate(t))); + } catch (t) { + this.lastTransactionError = t; + } + this.writtenDocs.add(t.toString()); + } + delete(t) { + this.write(new __PRIVATE_DeleteMutation(t, this.precondition(t))), this.writtenDocs.add(t.toString()); + } + async commit() { + if (this.ensureCommitNotCalled(), this.lastTransactionError) throw this.lastTransactionError; + const t = this.readVersions; + // For each mutation, note that the doc was written. + this.mutations.forEach((e => { + t.delete(e.key.toString()); + })), + // For each document that was read but not written to, we want to perform + // a `verify` operation. + t.forEach(((t, e) => { + const r = DocumentKey.fromPath(e); + this.mutations.push(new __PRIVATE_VerifyMutation(r, this.precondition(r))); + })), await __PRIVATE_invokeCommitRpc(this.datastore, this.mutations), this.committed = !0; + } + recordVersion(t) { + let e; + if (t.isFoundDocument()) e = t.version; else { + if (!t.isNoDocument()) throw fail(50498, { + Rt: t.constructor.name + }); + // Represent a deleted doc using SnapshotVersion.min(). + e = SnapshotVersion.min(); + } + const r = this.readVersions.get(t.key.toString()); + if (r) { + if (!e.isEqual(r)) + // This transaction will fail no matter what. + throw new FirestoreError(C, "Document version changed between two reads."); + } else this.readVersions.set(t.key.toString(), e); + } + /** + * Returns the version of this document when it was read in this transaction, + * as a precondition, or no precondition if it was not read. + */ precondition(t) { + const e = this.readVersions.get(t.toString()); + return !this.writtenDocs.has(t.toString()) && e ? e.isEqual(SnapshotVersion.min()) ? Precondition.exists(!1) : Precondition.updateTime(e) : Precondition.none(); + } + /** + * Returns the precondition for a document if the operation is an update. + */ preconditionForUpdate(t) { + const e = this.readVersions.get(t.toString()); + // The first time a document is written, we want to take into account the + // read time and existence + if (!this.writtenDocs.has(t.toString()) && e) { + if (e.isEqual(SnapshotVersion.min())) + // The document doesn't exist, so fail the transaction. + // This has to be validated locally because you can't send a + // precondition that a document does not exist without changing the + // semantics of the backend write to be an insert. This is the reverse + // of what we want, since we want to assert that the document doesn't + // exist but then send the update and have it fail. Since we can't + // express that to the backend, we have to validate locally. + // Note: this can change once we can send separate verify writes in the + // transaction. + throw new FirestoreError(y, "Can't update a document that doesn't exist."); + // Document exists, base precondition on document update time. + return Precondition.updateTime(e); + } + // Document was not read, so we just use the preconditions for a blind + // update. + return Precondition.exists(!0); + } + write(t) { + this.ensureCommitNotCalled(), this.mutations.push(t); + } + ensureCommitNotCalled() {} +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ const ht = { + maxAttempts: 5 +}; + +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * TransactionRunner encapsulates the logic needed to run and retry transactions + * with backoff. + */ +class __PRIVATE_TransactionRunner { + constructor(t, e, r, n, i) { + this.asyncQueue = t, this.datastore = e, this.options = r, this.updateFunction = n, + this.deferred = i, this.Vt = r.maxAttempts, this.It = new __PRIVATE_ExponentialBackoff(this.asyncQueue, "transaction_retry" /* TimerId.TransactionRetry */); + } + /** Runs the transaction and sets the result on deferred. */ yt() { + this.Vt -= 1, this.gt(); + } + gt() { + this.It.Z((async () => { + const t = new Transaction$1(this.datastore), e = this.wt(t); + e && e.then((e => { + this.asyncQueue.enqueueAndForget((() => t.commit().then((() => { + this.deferred.resolve(e); + })).catch((t => { + this.Ft(t); + })))); + })).catch((t => { + this.Ft(t); + })); + })); + } + wt(t) { + try { + const e = this.updateFunction(t); + return !__PRIVATE_isNullOrUndefined(e) && e.catch && e.then ? e : (this.deferred.reject(Error("Transaction callback must return a Promise")), + null); + } catch (t) { + // Do not retry errors thrown by user provided updateFunction. + return this.deferred.reject(t), null; + } + } + Ft(t) { + this.Vt > 0 && this.vt(t) ? (this.Vt -= 1, this.asyncQueue.enqueueAndForget((() => (this.gt(), + Promise.resolve())))) : this.deferred.reject(t); + } + vt(t) { + if ("FirebaseError" === t?.name) { + // In transactions, the backend will fail outdated reads with FAILED_PRECONDITION and + // non-matching document versions with ABORTED. These errors should be retried. + const e = t.code; + return "aborted" === e || "failed-precondition" === e || "already-exists" === e || ! + /** + * Determines whether an error code represents a permanent error when received + * in response to a non-write operation. + * + * See isPermanentWriteError for classifying write errors. + */ + function __PRIVATE_isPermanentError(t) { + switch (t) { + case V: + return fail(64938); + + case I: + case p: + case g: + case b: + case q: + case B: + // Unauthenticated means something went wrong with our token and we need + // to retry with new credentials which will happen automatically. + case D: + return !1; + + case y: + case w: + case F: + case v: + case S: + // Aborted might be retried in some scenarios, but that is dependent on + // the context and should handled individually by the calling code. + // See https://cloud.google.com/apis/design/errors. + case C: + case N: + case O: + case $: + return !0; + + default: + return fail(15467, { + code: t + }); + } + }(e); + } + return !1; + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** The Platform's 'document' implementation or null if not available. */ function getDocument() { + // `document` is not always available, e.g. in ReactNative and WebWorkers. + // eslint-disable-next-line no-restricted-globals + return "undefined" != typeof document ? document : null; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Represents an operation scheduled to be run in the future on an AsyncQueue. + * + * It is created via DelayedOperation.createAndSchedule(). + * + * Supports cancellation (via cancel()) and early execution (via skipDelay()). + * + * Note: We implement `PromiseLike` instead of `Promise`, as the `Promise` type + * in newer versions of TypeScript defines `finally`, which is not available in + * IE. + */ class DelayedOperation { + constructor(t, e, r, n, i) { + this.asyncQueue = t, this.timerId = e, this.targetTimeMs = r, this.op = n, this.removalCallback = i, + this.deferred = new __PRIVATE_Deferred, this.then = this.deferred.promise.then.bind(this.deferred.promise), + // It's normal for the deferred promise to be canceled (due to cancellation) + // and so we attach a dummy catch callback to avoid + // 'UnhandledPromiseRejectionWarning' log spam. + this.deferred.promise.catch((t => {})); + } + get promise() { + return this.deferred.promise; + } + /** + * Creates and returns a DelayedOperation that has been scheduled to be + * executed on the provided asyncQueue after the provided delayMs. + * + * @param asyncQueue - The queue to schedule the operation on. + * @param id - A Timer ID identifying the type of operation this is. + * @param delayMs - The delay (ms) before the operation should be scheduled. + * @param op - The operation to run. + * @param removalCallback - A callback to be called synchronously once the + * operation is executed or canceled, notifying the AsyncQueue to remove it + * from its delayedOperations list. + * PORTING NOTE: This exists to prevent making removeDelayedOperation() and + * the DelayedOperation class public. + */ static createAndSchedule(t, e, r, n, i) { + const s = Date.now() + r, o = new DelayedOperation(t, e, s, n, i); + return o.start(r), o; + } + /** + * Starts the timer. This is called immediately after construction by + * createAndSchedule(). + */ start(t) { + this.timerHandle = setTimeout((() => this.handleDelayElapsed()), t); + } + /** + * Queues the operation to run immediately (if it hasn't already been run or + * canceled). + */ skipDelay() { + return this.handleDelayElapsed(); + } + /** + * Cancels the operation if it hasn't already been executed or canceled. The + * promise will be rejected. + * + * As long as the operation has not yet been run, calling cancel() provides a + * guarantee that the operation will not be run. + */ cancel(t) { + null !== this.timerHandle && (this.clearTimeout(), this.deferred.reject(new FirestoreError(I, "Operation cancelled" + (t ? ": " + t : "")))); + } + handleDelayElapsed() { + this.asyncQueue.enqueueAndForget((() => null !== this.timerHandle ? (this.clearTimeout(), + this.op().then((t => this.deferred.resolve(t)))) : Promise.resolve())); + } + clearTimeout() { + null !== this.timerHandle && (this.removalCallback(this), clearTimeout(this.timerHandle), + this.timerHandle = null); + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ const ft = "AsyncQueue"; + +class __PRIVATE_AsyncQueueImpl { + constructor(t = Promise.resolve()) { + // A list of retryable operations. Retryable operations are run in order and + // retried with backoff. + this.Dt = [], + // Is this AsyncQueue being shut down? Once it is set to true, it will not + // be changed again. + this.bt = !1, + // Operations scheduled to be queued in the future. Operations are + // automatically removed after they are run or canceled. + this.St = [], + // visible for testing + this.Ct = null, + // Flag set while there's an outstanding AsyncQueue operation, used for + // assertion sanity-checks. + this.Nt = !1, + // Enabled during shutdown on Safari to prevent future access to IndexedDB. + this.Ot = !1, + // List of TimerIds to fast-forward delays for. + this.qt = [], + // Backoff timer used to schedule retries for retryable operations + this.It = new __PRIVATE_ExponentialBackoff(this, "async_queue_retry" /* TimerId.AsyncQueueRetry */), + // Visibility handler that triggers an immediate retry of all retryable + // operations. Meant to speed up recovery when we regain file system access + // after page comes into foreground. + this.Bt = () => { + const t = getDocument(); + t && __PRIVATE_logDebug(ft, "Visibility state changed to " + t.visibilityState), + this.It.tt(); + }, this.$t = t; + const e = getDocument(); + e && "function" == typeof e.addEventListener && e.addEventListener("visibilitychange", this.Bt); + } + get isShuttingDown() { + return this.bt; + } + /** + * Adds a new operation to the queue without waiting for it to complete (i.e. + * we ignore the Promise result). + */ enqueueAndForget(t) { + // eslint-disable-next-line @typescript-eslint/no-floating-promises + this.enqueue(t); + } + enqueueAndForgetEvenWhileRestricted(t) { + this.Qt(), + // eslint-disable-next-line @typescript-eslint/no-floating-promises + this.kt(t); + } + enterRestrictedMode(t) { + if (!this.bt) { + this.bt = !0, this.Ot = t || !1; + const e = getDocument(); + e && "function" == typeof e.removeEventListener && e.removeEventListener("visibilitychange", this.Bt); + } + } + enqueue(t) { + if (this.Qt(), this.bt) + // Return a Promise which never resolves. + return new Promise((() => {})); + // Create a deferred Promise that we can return to the callee. This + // allows us to return a "hanging Promise" only to the callee and still + // advance the queue even when the operation is not run. + const e = new __PRIVATE_Deferred; + return this.kt((() => this.bt && this.Ot ? Promise.resolve() : (t().then(e.resolve, e.reject), + e.promise))).then((() => e.promise)); + } + enqueueRetryable(t) { + this.enqueueAndForget((() => (this.Dt.push(t), this.Lt()))); + } + /** + * Runs the next operation from the retryable queue. If the operation fails, + * reschedules with backoff. + */ async Lt() { + if (0 !== this.Dt.length) { + try { + await this.Dt[0](), this.Dt.shift(), this.It.reset(); + } catch (t) { + if (! + /** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + /** Verifies whether `e` is an IndexedDbTransactionError. */ + function __PRIVATE_isIndexedDbTransactionError(t) { + // Use name equality, as instanceof checks on errors don't work with errors + // that wrap other errors. + return "IndexedDbTransactionError" === t.name; + }(t)) throw t; + // Failure will be handled by AsyncQueue + __PRIVATE_logDebug(ft, "Operation failed with retryable error: " + t); + } + this.Dt.length > 0 && + // If there are additional operations, we re-schedule `retryNextOp()`. + // This is necessary to run retryable operations that failed during + // their initial attempt since we don't know whether they are already + // enqueued. If, for example, `op1`, `op2`, `op3` are enqueued and `op1` + // needs to be re-run, we will run `op1`, `op1`, `op2` using the + // already enqueued calls to `retryNextOp()`. `op3()` will then run in the + // call scheduled here. + // Since `backoffAndRun()` cancels an existing backoff and schedules a + // new backoff on every call, there is only ever a single additional + // operation in the queue. + this.It.Z((() => this.Lt())); + } + } + kt(t) { + const e = this.$t.then((() => (this.Nt = !0, t().catch((t => { + this.Ct = t, this.Nt = !1; + // Re-throw the error so that this.tail becomes a rejected Promise and + // all further attempts to chain (via .then) will just short-circuit + // and return the rejected Promise. + throw __PRIVATE_logError("INTERNAL UNHANDLED ERROR: ", __PRIVATE_getMessageOrStack(t)), + t; + })).then((t => (this.Nt = !1, t)))))); + return this.$t = e, e; + } + enqueueAfterDelay(t, e, r) { + this.Qt(), + // Fast-forward delays for timerIds that have been overridden. + this.qt.indexOf(t) > -1 && (e = 0); + const n = DelayedOperation.createAndSchedule(this, t, e, r, (t => this.Mt(t))); + return this.St.push(n), n; + } + Qt() { + this.Ct && fail(47125, { + xt: __PRIVATE_getMessageOrStack(this.Ct) + }); + } + verifyOperationInProgress() {} + /** + * Waits until all currently queued tasks are finished executing. Delayed + * operations are not run. + */ async Ut() { + // Operations in the queue prior to draining may have enqueued additional + // operations. Keep draining the queue until the tail is no longer advanced, + // which indicates that no more new operations were enqueued and that all + // operations were executed. + let t; + do { + t = this.$t, await t; + } while (t !== this.$t); + } + /** + * For Tests: Determine if a delayed operation with a particular TimerId + * exists. + */ jt(t) { + for (const e of this.St) if (e.timerId === t) return !0; + return !1; + } + /** + * For Tests: Runs some or all delayed operations early. + * + * @param lastTimerId - Delayed operations up to and including this TimerId + * will be drained. Pass TimerId.All to run all delayed operations. + * @returns a Promise that resolves once all operations have been run. + */ zt(t) { + // Note that draining may generate more delayed ops, so we do that first. + return this.Ut().then((() => { + // Run ops in the same order they'd run if they ran naturally. + /* eslint-disable-next-line @typescript-eslint/no-floating-promises */ + this.St.sort(((t, e) => t.targetTimeMs - e.targetTimeMs)); + for (const e of this.St) if (e.skipDelay(), "all" /* TimerId.All */ !== t && e.timerId === t) break; + return this.Ut(); + })); + } + /** + * For Tests: Skip all subsequent delays for a timer id. + */ Wt(t) { + this.qt.push(t); + } + /** Called once a DelayedOperation is run or canceled. */ Mt(t) { + // NOTE: indexOf / slice are O(n), but delayedOperations is expected to be small. + const e = this.St.indexOf(t); + /* eslint-disable-next-line @typescript-eslint/no-floating-promises */ this.St.splice(e, 1); + } +} + +/** + * Chrome includes Error.message in Error.stack. Other browsers do not. + * This returns expected output of message + stack when available. + * @param error - Error or FirestoreError + */ +function __PRIVATE_getMessageOrStack(t) { + let e = t.message || ""; + return t.stack && (e = t.stack.includes(t.message) ? t.stack : t.message + "\n" + t.stack), + e; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// TODO(mrschmidt) Consider using `BaseTransaction` as the base class in the +// legacy SDK. +/** + * A reference to a transaction. + * + * The `Transaction` object passed to a transaction's `updateFunction` provides + * the methods to read and write data within the transaction context. See + * {@link runTransaction}. + */ class Transaction { + /** @hideconstructor */ + constructor(t, e) { + this._firestore = t, this._transaction = e, this._dataReader = __PRIVATE_newUserDataReader(t); + } + /** + * Reads the document referenced by the provided {@link DocumentReference}. + * + * @param documentRef - A reference to the document to be read. + * @returns A `DocumentSnapshot` with the read data. + */ get(t) { + const e = __PRIVATE_validateReference(t, this._firestore), r = new __PRIVATE_LiteUserDataWriter(this._firestore); + return this._transaction.lookup([ e._key ]).then((t => { + if (!t || 1 !== t.length) return fail(24041); + const n = t[0]; + if (n.isFoundDocument()) return new DocumentSnapshot(this._firestore, r, n.key, n, e.converter); + if (n.isNoDocument()) return new DocumentSnapshot(this._firestore, r, e._key, null, e.converter); + throw fail(18433, { + doc: n + }); + })); + } + set(t, e, r) { + const n = __PRIVATE_validateReference(t, this._firestore), i = __PRIVATE_applyFirestoreDataConverter(n.converter, e, r), s = __PRIVATE_parseSetData(this._dataReader, "Transaction.set", n._key, i, null !== n.converter, r); + return this._transaction.set(n._key, s), this; + } + update(t, e, r, ...n) { + const i = __PRIVATE_validateReference(t, this._firestore); + // For Compat types, we have to "extract" the underlying types before + // performing validation. + let s; + return s = "string" == typeof (e = getModularInstance(e)) || e instanceof FieldPath ? __PRIVATE_parseUpdateVarargs(this._dataReader, "Transaction.update", i._key, e, r, n) : __PRIVATE_parseUpdateData(this._dataReader, "Transaction.update", i._key, e), + this._transaction.update(i._key, s), this; + } + /** + * Deletes the document referred to by the provided {@link DocumentReference}. + * + * @param documentRef - A reference to the document to be deleted. + * @returns This `Transaction` instance. Used for chaining method calls. + */ delete(t) { + const e = __PRIVATE_validateReference(t, this._firestore); + return this._transaction.delete(e._key), this; + } +} + +/** + * Executes the given `updateFunction` and then attempts to commit the changes + * applied within the transaction. If any document read within the transaction + * has changed, Cloud Firestore retries the `updateFunction`. If it fails to + * commit after 5 attempts, the transaction fails. + * + * The maximum number of writes allowed in a single transaction is 500. + * + * @param firestore - A reference to the Firestore database to run this + * transaction against. + * @param updateFunction - The function to execute within the transaction + * context. + * @param options - An options object to configure maximum number of attempts to + * commit. + * @returns If the transaction completed successfully or was explicitly aborted + * (the `updateFunction` returned a failed promise), the promise returned by the + * `updateFunction `is returned here. Otherwise, if the transaction failed, a + * rejected promise with the corresponding failure error is returned. + */ function runTransaction(t, e, r) { + const n = __PRIVATE_getDatastore(t = __PRIVATE_cast(t, Firestore)), i = { + ...ht, + ...r + }; + !function __PRIVATE_validateTransactionOptions(t) { + if (t.maxAttempts < 1) throw new FirestoreError(y, "Max attempts must be at least 1"); + }(i); + const s = new __PRIVATE_Deferred; + return new __PRIVATE_TransactionRunner(function __PRIVATE_newAsyncQueue() { + return new __PRIVATE_AsyncQueueImpl; + }(), n, i, (r => e(new Transaction(t, r))), s).yt(), s.promise; +} + +/** + * Firestore Lite + * + * @remarks Firestore Lite is a small online-only SDK that allows read + * and write access to your Firestore database. All operations connect + * directly to the backend, and `onSnapshot()` APIs are not supported. + * @packageDocumentation + */ !function __PRIVATE_registerFirestore() { + !function __PRIVATE_setSDKVersion(t) { + A = t; + }(`${SDK_VERSION}_lite`), _registerComponent(new Component("firestore/lite", ((t, {instanceIdentifier: e, options: r}) => { + const n = t.getProvider("app").getImmediate(), i = new Firestore(new __PRIVATE_LiteAuthCredentialsProvider(t.getProvider("auth-internal")), new __PRIVATE_LiteAppCheckTokenProvider(n, t.getProvider("app-check-internal")), function __PRIVATE_databaseIdFromApp(t, e) { + if (!Object.prototype.hasOwnProperty.apply(t.options, [ "projectId" ])) throw new FirestoreError(y, '"projectId" not provided in firebase.initializeApp.'); + return new DatabaseId(t.options.projectId, e); + }(n, e), n); + return r && i._setSettings(r), i; + }), "PUBLIC").setMultipleInstances(!0)), + // RUNTIME_ENV and BUILD_TARGET are replaced by real values during the compilation + registerVersion("firestore-lite", P, ""), registerVersion("firestore-lite", P, "esm2020"); +}(); + +export { AggregateField, AggregateQuerySnapshot, Bytes, CollectionReference, DocumentReference, DocumentSnapshot, FieldPath, FieldValue, Firestore, FirestoreError, GeoPoint, Query, QueryCompositeFilterConstraint, QueryConstraint, QueryDocumentSnapshot, QueryEndAtConstraint, QueryFieldFilterConstraint, QueryLimitConstraint, QueryOrderByConstraint, QuerySnapshot, QueryStartAtConstraint, Timestamp, Transaction, VectorValue, WriteBatch, addDoc, aggregateFieldEqual, aggregateQuerySnapshotEqual, and, arrayRemove, arrayUnion, average, collection, collectionGroup, connectFirestoreEmulator, count, deleteDoc, deleteField, doc, documentId, endAt, endBefore, getAggregate, getCount, getDoc, getDocs, getFirestore, increment, initializeFirestore, limit, limitToLast, or, orderBy, query, queryEqual, refEqual, runTransaction, serverTimestamp, setDoc, setLogLevel, snapshotEqual, startAfter, startAt, sum, terminate, updateDoc, vector, where, writeBatch }; +//# sourceMappingURL=index.browser.esm.js.map diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/index.browser.esm.js.map b/frontend-old/node_modules/@firebase/firestore/dist/lite/index.browser.esm.js.map new file mode 100644 index 0000000..be96617 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/index.browser.esm.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.browser.esm.js","sources":["../../src/auth/user.ts","../../src/core/version.ts","../../src/util/log.ts","../../src/platform/browser/format_json.ts","../../src/util/assert.ts","../../src/util/error.ts","../../src/util/promise.ts","../../src/api/credentials.ts","../../src/core/database_info.ts","../../src/platform/browser/random_bytes.ts","../../src/util/misc.ts","../../src/model/path.ts","../../src/model/document_key.ts","../../src/util/input_validation.ts","../../src/api/long_polling_options.ts","../../src/util/debug_uid.ts","../../src/util/types.ts","../../src/remote/rest_connection.ts","../../src/remote/rpc_error.ts","../../src/platform/browser_lite/fetch_connection.ts","../../src/core/aggregate.ts","../../src/util/obj.ts","../../src/util/base64_decode_error.ts","../../src/util/byte_string.ts","../../src/platform/browser/base64.ts","../../src/model/normalize.ts","../../src/util/json_validation.ts","../../src/lite-api/timestamp.ts","../../src/model/server_timestamps.ts","../../src/model/values.ts","../../src/core/bound.ts","../../src/core/filter.ts","../../src/core/order_by.ts","../../src/core/snapshot_version.ts","../../src/util/sorted_map.ts","../../src/util/sorted_set.ts","../../src/model/field_mask.ts","../../src/model/object_value.ts","../../src/model/document.ts","../../src/core/target.ts","../../src/core/query.ts","../../src/remote/number_serializer.ts","../../src/model/transform_operation.ts","../../src/model/mutation.ts","../../src/remote/serializer.ts","../../src/platform/browser/serializer.ts","../../src/remote/backoff.ts","../../src/remote/datastore.ts","../../src/lite-api/components.ts","../../src/platform/browser_lite/connection.ts","../../src/local/lru_garbage_collector_impl.ts","../../src/lite-api/settings.ts","../../src/local/lru_garbage_collector.ts","../../src/lite-api/database.ts","../../src/lite-api/aggregate_types.ts","../../src/lite-api/reference.ts","../../src/lite-api/bytes.ts","../../src/lite-api/field_path.ts","../../src/lite-api/field_value.ts","../../src/lite-api/geo_point.ts","../../src/lite-api/vector_value.ts","../../src/util/array.ts","../../src/lite-api/user_data_reader.ts","../../src/lite-api/snapshot.ts","../../src/lite-api/query.ts","../../src/lite-api/user_data_writer.ts","../../src/lite-api/reference_impl.ts","../../src/lite-api/aggregate.ts","../../src/lite-api/field_value_impl.ts","../../src/lite-api/write_batch.ts","../../src/core/transaction.ts","../../src/core/transaction_options.ts","../../src/core/transaction_runner.ts","../../src/platform/browser/dom.ts","../../src/util/async_queue.ts","../../src/util/async_queue_impl.ts","../../src/local/simple_db.ts","../../src/lite-api/transaction.ts","../../lite/register.ts","../../lite/index.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Simple wrapper around a nullable UID. Mostly exists to make code more\n * readable.\n */\nexport class User {\n /** A user with a null UID. */\n static readonly UNAUTHENTICATED = new User(null);\n\n // TODO(mikelehen): Look into getting a proper uid-equivalent for\n // non-FirebaseAuth providers.\n static readonly GOOGLE_CREDENTIALS = new User('google-credentials-uid');\n static readonly FIRST_PARTY = new User('first-party-uid');\n static readonly MOCK_USER = new User('mock-user');\n\n constructor(readonly uid: string | null) {}\n\n isAuthenticated(): boolean {\n return this.uid != null;\n }\n\n /**\n * Returns a key representing this user, suitable for inclusion in a\n * dictionary.\n */\n toKey(): string {\n if (this.isAuthenticated()) {\n return 'uid:' + this.uid;\n } else {\n return 'anonymous-user';\n }\n }\n\n isEqual(otherUser: User): boolean {\n return otherUser.uid === this.uid;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** The semver (www.semver.org) version of the SDK. */\nimport { version } from '../../../firebase/package.json';\nexport let SDK_VERSION = version;\nexport function setSDKVersion(version: string): void {\n SDK_VERSION = version;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Logger, LogLevel, LogLevelString } from '@firebase/logger';\n\nimport { SDK_VERSION } from '../core/version';\nimport { formatJSON } from '../platform/format_json';\n\nexport { LogLevel, LogLevelString };\n\nconst logClient = new Logger('@firebase/firestore');\n\n// Helper methods are needed because variables can't be exported as read/write\nexport function getLogLevel(): LogLevel {\n return logClient.logLevel;\n}\n\n/**\n * Sets the verbosity of Cloud Firestore logs (debug, error, or silent).\n *\n * @param logLevel - The verbosity you set for activity and error logging. Can\n * be any of the following values:\n *\n *
    \n *
  • `debug` for the most verbose logging level, primarily for\n * debugging.
  • \n *
  • `error` to log errors only.
  • \n *
  • `silent` to turn off logging.
  • \n *
\n */\nexport function setLogLevel(logLevel: LogLevelString): void {\n logClient.setLogLevel(logLevel);\n}\n\nexport function logDebug(msg: string, ...obj: unknown[]): void {\n if (logClient.logLevel <= LogLevel.DEBUG) {\n const args = obj.map(argToString);\n logClient.debug(`Firestore (${SDK_VERSION}): ${msg}`, ...args);\n }\n}\n\nexport function logError(msg: string, ...obj: unknown[]): void {\n if (logClient.logLevel <= LogLevel.ERROR) {\n const args = obj.map(argToString);\n logClient.error(`Firestore (${SDK_VERSION}): ${msg}`, ...args);\n }\n}\n\n/**\n * @internal\n */\nexport function logWarn(msg: string, ...obj: unknown[]): void {\n if (logClient.logLevel <= LogLevel.WARN) {\n const args = obj.map(argToString);\n logClient.warn(`Firestore (${SDK_VERSION}): ${msg}`, ...args);\n }\n}\n\n/**\n * Converts an additional log parameter to a string representation.\n */\nfunction argToString(obj: unknown): string | unknown {\n if (typeof obj === 'string') {\n return obj;\n } else {\n try {\n return formatJSON(obj);\n } catch (e) {\n // Converting to JSON failed, just log the object directly\n return obj;\n }\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** Formats an object as a JSON string, suitable for logging. */\nexport function formatJSON(value: unknown): string {\n return JSON.stringify(value);\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SDK_VERSION } from '../core/version';\n\nimport { logError } from './log';\n\n/**\n * Unconditionally fails, throwing an Error with the given message.\n * Messages are stripped in production builds.\n *\n * Returns `never` and can be used in expressions:\n * @example\n * let futureVar = fail('not implemented yet');\n *\n * @param code generate a new unique value with `yarn assertion-id:generate`\n * Search for an existing value using `yarn assertion-id:find X`\n */\nexport function fail(\n code: number,\n message: string,\n context?: Record\n): never;\n\n/**\n * Unconditionally fails, throwing an Error with the given message.\n * Messages are stripped in production builds.\n *\n * Returns `never` and can be used in expressions:\n * @example\n * let futureVar = fail('not implemented yet');\n *\n * @param id generate a new unique value with `yarn assertion-id:generate`\n * Search for an existing value using `yarn assertion-id:find X`\n */\nexport function fail(id: number, context?: Record): never;\n\nexport function fail(\n id: number,\n messageOrContext?: string | Record,\n context?: Record\n): never {\n let message = 'Unexpected state';\n if (typeof messageOrContext === 'string') {\n message = messageOrContext;\n } else {\n context = messageOrContext;\n }\n _fail(id, message, context);\n}\n\nfunction _fail(\n id: number,\n failure: string,\n context?: Record\n): never {\n // Log the failure in addition to throw an exception, just in case the\n // exception is swallowed.\n let message = `FIRESTORE (${SDK_VERSION}) INTERNAL ASSERTION FAILED: ${failure} (ID: ${id.toString(\n 16\n )})`;\n if (context !== undefined) {\n try {\n const stringContext = JSON.stringify(context);\n message += ' CONTEXT: ' + stringContext;\n } catch (e) {\n message += ' CONTEXT: ' + context;\n }\n }\n logError(message);\n\n // NOTE: We don't use FirestoreError here because these are internal failures\n // that cannot be handled by the user. (Also it would create a circular\n // dependency between the error and assert modules which doesn't work.)\n throw new Error(message);\n}\n\n/**\n * Fails if the given assertion condition is false, throwing an Error with the\n * given message if it did.\n *\n * Messages are stripped in production builds.\n *\n * @param id generate a new unique value with `yarn assertion-idgenerate`.\n * Search for an existing value using `yarn assertion-id:find X`\n */\nexport function hardAssert(\n assertion: boolean,\n id: number,\n message: string,\n context?: Record\n): asserts assertion;\n\n/**\n * Fails if the given assertion condition is false, throwing an Error with the\n * given message if it did.\n *\n * Messages are stripped in production builds.\n *\n * @param id generate a new unique value with `yarn assertion-id:generate`.\n * Search for an existing value using `yarn assertion-id:find X`\n */\nexport function hardAssert(\n assertion: boolean,\n id: number,\n context?: Record\n): asserts assertion;\n\nexport function hardAssert(\n assertion: boolean,\n id: number,\n messageOrContext?: string | Record,\n context?: Record\n): asserts assertion {\n let message = 'Unexpected state';\n if (typeof messageOrContext === 'string') {\n message = messageOrContext;\n } else {\n context = messageOrContext;\n }\n\n if (!assertion) {\n _fail(id, message, context);\n }\n}\n\n/**\n * Fails if the given assertion condition is false, throwing an Error with the\n * given message if it did.\n *\n * The code of callsites invoking this function are stripped out in production\n * builds. Any side-effects of code within the debugAssert() invocation will not\n * happen in this case.\n *\n * @internal\n */\nexport function debugAssert(\n assertion: boolean,\n message: string\n): asserts assertion {\n if (!assertion) {\n fail(0xdeb6, message);\n }\n}\n\n/**\n * Casts `obj` to `T`. In non-production builds, verifies that `obj` is an\n * instance of `T` before casting.\n */\nexport function debugCast(\n obj: object,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n constructor: { new (...args: any[]): T }\n): T | never {\n debugAssert(\n obj instanceof constructor,\n `Expected type '${constructor.name}', but was '${obj.constructor.name}'`\n );\n return obj as T;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseError } from '@firebase/util';\n\n/**\n * The set of Firestore status codes. The codes are the same at the ones\n * exposed by gRPC here:\n * https://github.com/grpc/grpc/blob/master/doc/statuscodes.md\n *\n * Possible values:\n * - 'cancelled': The operation was cancelled (typically by the caller).\n * - 'unknown': Unknown error or an error from a different error domain.\n * - 'invalid-argument': Client specified an invalid argument. Note that this\n * differs from 'failed-precondition'. 'invalid-argument' indicates\n * arguments that are problematic regardless of the state of the system\n * (e.g. an invalid field name).\n * - 'deadline-exceeded': Deadline expired before operation could complete.\n * For operations that change the state of the system, this error may be\n * returned even if the operation has completed successfully. For example,\n * a successful response from a server could have been delayed long enough\n * for the deadline to expire.\n * - 'not-found': Some requested document was not found.\n * - 'already-exists': Some document that we attempted to create already\n * exists.\n * - 'permission-denied': The caller does not have permission to execute the\n * specified operation.\n * - 'resource-exhausted': Some resource has been exhausted, perhaps a\n * per-user quota, or perhaps the entire file system is out of space.\n * - 'failed-precondition': Operation was rejected because the system is not\n * in a state required for the operation's execution.\n * - 'aborted': The operation was aborted, typically due to a concurrency\n * issue like transaction aborts, etc.\n * - 'out-of-range': Operation was attempted past the valid range.\n * - 'unimplemented': Operation is not implemented or not supported/enabled.\n * - 'internal': Internal errors. Means some invariants expected by\n * underlying system has been broken. If you see one of these errors,\n * something is very broken.\n * - 'unavailable': The service is currently unavailable. This is most likely\n * a transient condition and may be corrected by retrying with a backoff.\n * - 'data-loss': Unrecoverable data loss or corruption.\n * - 'unauthenticated': The request does not have valid authentication\n * credentials for the operation.\n */\nexport type FirestoreErrorCode =\n | 'cancelled'\n | 'unknown'\n | 'invalid-argument'\n | 'deadline-exceeded'\n | 'not-found'\n | 'already-exists'\n | 'permission-denied'\n | 'resource-exhausted'\n | 'failed-precondition'\n | 'aborted'\n | 'out-of-range'\n | 'unimplemented'\n | 'internal'\n | 'unavailable'\n | 'data-loss'\n | 'unauthenticated';\n\n/**\n * Error Codes describing the different ways Firestore can fail. These come\n * directly from GRPC.\n */\nexport type Code = FirestoreErrorCode;\n\nexport const Code = {\n // Causes are copied from:\n // https://github.com/grpc/grpc/blob/bceec94ea4fc5f0085d81235d8e1c06798dc341a/include/grpc%2B%2B/impl/codegen/status_code_enum.h\n /** Not an error; returned on success. */\n OK: 'ok' as FirestoreErrorCode,\n\n /** The operation was cancelled (typically by the caller). */\n CANCELLED: 'cancelled' as FirestoreErrorCode,\n\n /** Unknown error or an error from a different error domain. */\n UNKNOWN: 'unknown' as FirestoreErrorCode,\n\n /**\n * Client specified an invalid argument. Note that this differs from\n * FAILED_PRECONDITION. INVALID_ARGUMENT indicates arguments that are\n * problematic regardless of the state of the system (e.g., a malformed file\n * name).\n */\n INVALID_ARGUMENT: 'invalid-argument' as FirestoreErrorCode,\n\n /**\n * Deadline expired before operation could complete. For operations that\n * change the state of the system, this error may be returned even if the\n * operation has completed successfully. For example, a successful response\n * from a server could have been delayed long enough for the deadline to\n * expire.\n */\n DEADLINE_EXCEEDED: 'deadline-exceeded' as FirestoreErrorCode,\n\n /** Some requested entity (e.g., file or directory) was not found. */\n NOT_FOUND: 'not-found' as FirestoreErrorCode,\n\n /**\n * Some entity that we attempted to create (e.g., file or directory) already\n * exists.\n */\n ALREADY_EXISTS: 'already-exists' as FirestoreErrorCode,\n\n /**\n * The caller does not have permission to execute the specified operation.\n * PERMISSION_DENIED must not be used for rejections caused by exhausting\n * some resource (use RESOURCE_EXHAUSTED instead for those errors).\n * PERMISSION_DENIED must not be used if the caller cannot be identified\n * (use UNAUTHENTICATED instead for those errors).\n */\n PERMISSION_DENIED: 'permission-denied' as FirestoreErrorCode,\n\n /**\n * The request does not have valid authentication credentials for the\n * operation.\n */\n UNAUTHENTICATED: 'unauthenticated' as FirestoreErrorCode,\n\n /**\n * Some resource has been exhausted, perhaps a per-user quota, or perhaps the\n * entire file system is out of space.\n */\n RESOURCE_EXHAUSTED: 'resource-exhausted' as FirestoreErrorCode,\n\n /**\n * Operation was rejected because the system is not in a state required for\n * the operation's execution. For example, directory to be deleted may be\n * non-empty, an rmdir operation is applied to a non-directory, etc.\n *\n * A litmus test that may help a service implementor in deciding\n * between FAILED_PRECONDITION, ABORTED, and UNAVAILABLE:\n * (a) Use UNAVAILABLE if the client can retry just the failing call.\n * (b) Use ABORTED if the client should retry at a higher-level\n * (e.g., restarting a read-modify-write sequence).\n * (c) Use FAILED_PRECONDITION if the client should not retry until\n * the system state has been explicitly fixed. E.g., if an \"rmdir\"\n * fails because the directory is non-empty, FAILED_PRECONDITION\n * should be returned since the client should not retry unless\n * they have first fixed up the directory by deleting files from it.\n * (d) Use FAILED_PRECONDITION if the client performs conditional\n * REST Get/Update/Delete on a resource and the resource on the\n * server does not match the condition. E.g., conflicting\n * read-modify-write on the same resource.\n */\n FAILED_PRECONDITION: 'failed-precondition' as FirestoreErrorCode,\n\n /**\n * The operation was aborted, typically due to a concurrency issue like\n * sequencer check failures, transaction aborts, etc.\n *\n * See litmus test above for deciding between FAILED_PRECONDITION, ABORTED,\n * and UNAVAILABLE.\n */\n ABORTED: 'aborted' as FirestoreErrorCode,\n\n /**\n * Operation was attempted past the valid range. E.g., seeking or reading\n * past end of file.\n *\n * Unlike INVALID_ARGUMENT, this error indicates a problem that may be fixed\n * if the system state changes. For example, a 32-bit file system will\n * generate INVALID_ARGUMENT if asked to read at an offset that is not in the\n * range [0,2^32-1], but it will generate OUT_OF_RANGE if asked to read from\n * an offset past the current file size.\n *\n * There is a fair bit of overlap between FAILED_PRECONDITION and\n * OUT_OF_RANGE. We recommend using OUT_OF_RANGE (the more specific error)\n * when it applies so that callers who are iterating through a space can\n * easily look for an OUT_OF_RANGE error to detect when they are done.\n */\n OUT_OF_RANGE: 'out-of-range' as FirestoreErrorCode,\n\n /** Operation is not implemented or not supported/enabled in this service. */\n UNIMPLEMENTED: 'unimplemented' as FirestoreErrorCode,\n\n /**\n * Internal errors. Means some invariants expected by underlying System has\n * been broken. If you see one of these errors, Something is very broken.\n */\n INTERNAL: 'internal' as FirestoreErrorCode,\n\n /**\n * The service is currently unavailable. This is a most likely a transient\n * condition and may be corrected by retrying with a backoff.\n *\n * See litmus test above for deciding between FAILED_PRECONDITION, ABORTED,\n * and UNAVAILABLE.\n */\n UNAVAILABLE: 'unavailable' as FirestoreErrorCode,\n\n /** Unrecoverable data loss or corruption. */\n DATA_LOSS: 'data-loss' as FirestoreErrorCode\n};\n\n/** An error returned by a Firestore operation. */\nexport class FirestoreError extends FirebaseError {\n /** The stack of the error. */\n readonly stack?: string;\n\n /** @hideconstructor */\n constructor(\n /**\n * The backend error code associated with this error.\n */\n readonly code: FirestoreErrorCode,\n /**\n * A custom error description.\n */\n readonly message: string\n ) {\n super(code, message);\n\n // HACK: We write a toString property directly because Error is not a real\n // class and so inheritance does not work correctly. We could alternatively\n // do the same \"back-door inheritance\" trick that FirebaseError does.\n this.toString = () => `${this.name}: [code=${this.code}]: ${this.message}`;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport interface Resolver {\n (value: R | Promise): void;\n}\n\nexport interface Rejecter {\n (reason?: Error): void;\n}\n\nexport class Deferred {\n promise: Promise;\n // Assigned synchronously in constructor by Promise constructor callback.\n resolve!: Resolver;\n reject!: Rejecter;\n\n constructor() {\n this.promise = new Promise((resolve: Resolver, reject: Rejecter) => {\n this.resolve = resolve;\n this.reject = reject;\n });\n }\n}\n\n/**\n * Takes an array of values and a function from a value to a Promise. The function is run on each\n * value sequentially, waiting for the previous promise to resolve before starting the next one.\n * The returned promise resolves once the function has been run on all values.\n */\nexport function sequence(\n values: T[],\n fn: (value: T) => Promise\n): Promise {\n let p = Promise.resolve();\n for (const value of values) {\n p = p.then(() => fn(value));\n }\n return p;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseApp, _isFirebaseServerApp } from '@firebase/app';\nimport {\n AppCheckInternalComponentName,\n AppCheckTokenListener,\n AppCheckTokenResult,\n FirebaseAppCheckInternal\n} from '@firebase/app-check-interop-types';\nimport {\n FirebaseAuthInternal,\n FirebaseAuthInternalName\n} from '@firebase/auth-interop-types';\nimport { Provider } from '@firebase/component';\n\nimport { User } from '../auth/user';\nimport { debugAssert, hardAssert } from '../util/assert';\nimport { AsyncQueue } from '../util/async_queue';\nimport { Code, FirestoreError } from '../util/error';\nimport { logDebug } from '../util/log';\nimport { Deferred } from '../util/promise';\n\n// TODO(mikelehen): This should be split into multiple files and probably\n// moved to an auth/ folder to match other platforms.\n\n/**\n * @internal\n */\nexport type AuthTokenFactory = () => string;\n\n/**\n * @internal\n */\nexport interface FirstPartyCredentialsSettings {\n // These are external types. Prevent minification.\n ['type']: 'firstParty';\n ['sessionIndex']: string;\n ['iamToken']: string | null;\n ['authTokenFactory']: AuthTokenFactory | null;\n}\n\nexport interface ProviderCredentialsSettings {\n // These are external types. Prevent minification.\n ['type']: 'provider';\n ['client']: CredentialsProvider;\n}\n\n/** Settings for private credentials */\nexport type CredentialsSettings =\n | FirstPartyCredentialsSettings\n | ProviderCredentialsSettings;\n\nexport type TokenType = 'OAuth' | 'FirstParty' | 'AppCheck';\nexport interface Token {\n /** Type of token. */\n type: TokenType;\n\n /**\n * The user with which the token is associated (used for persisting user\n * state on disk, etc.).\n * This will be null for Tokens of the type 'AppCheck'.\n */\n user?: User;\n\n /** Header values to set for this token */\n headers: Map;\n}\n\nexport class OAuthToken implements Token {\n type = 'OAuth' as TokenType;\n headers = new Map();\n\n constructor(value: string, public user: User) {\n this.headers.set('Authorization', `Bearer ${value}`);\n }\n}\n\n/**\n * A Listener for credential change events. The listener should fetch a new\n * token and may need to invalidate other state if the current user has also\n * changed.\n */\nexport type CredentialChangeListener = (credential: T) => Promise;\n\n/**\n * Provides methods for getting the uid and token for the current user and\n * listening for changes.\n */\nexport interface CredentialsProvider {\n /**\n * Starts the credentials provider and specifies a listener to be notified of\n * credential changes (sign-in / sign-out, token changes). It is immediately\n * called once with the initial user.\n *\n * The change listener is invoked on the provided AsyncQueue.\n */\n start(\n asyncQueue: AsyncQueue,\n changeListener: CredentialChangeListener\n ): void;\n\n /** Requests a token for the current user. */\n getToken(): Promise;\n\n /**\n * Marks the last retrieved token as invalid, making the next GetToken request\n * force-refresh the token.\n */\n invalidateToken(): void;\n\n shutdown(): void;\n}\n\n/**\n * A CredentialsProvider that always yields an empty token.\n * @internal\n */\nexport class EmptyAuthCredentialsProvider implements CredentialsProvider {\n getToken(): Promise {\n return Promise.resolve(null);\n }\n\n invalidateToken(): void {}\n\n start(\n asyncQueue: AsyncQueue,\n changeListener: CredentialChangeListener\n ): void {\n // Fire with initial user.\n asyncQueue.enqueueRetryable(() => changeListener(User.UNAUTHENTICATED));\n }\n\n shutdown(): void {}\n}\n\n/**\n * A CredentialsProvider that always returns a constant token. Used for\n * emulator token mocking.\n */\nexport class EmulatorAuthCredentialsProvider\n implements CredentialsProvider\n{\n constructor(private token: Token) {}\n\n /**\n * Stores the listener registered with setChangeListener()\n * This isn't actually necessary since the UID never changes, but we use this\n * to verify the listen contract is adhered to in tests.\n */\n private changeListener: CredentialChangeListener | null = null;\n\n getToken(): Promise {\n return Promise.resolve(this.token);\n }\n\n invalidateToken(): void {}\n\n start(\n asyncQueue: AsyncQueue,\n changeListener: CredentialChangeListener\n ): void {\n debugAssert(\n !this.changeListener,\n 'Can only call setChangeListener() once.'\n );\n this.changeListener = changeListener;\n // Fire with initial user.\n asyncQueue.enqueueRetryable(() => changeListener(this.token.user!));\n }\n\n shutdown(): void {\n this.changeListener = null;\n }\n}\n\n/** Credential provider for the Lite SDK. */\nexport class LiteAuthCredentialsProvider implements CredentialsProvider {\n private auth: FirebaseAuthInternal | null = null;\n\n constructor(authProvider: Provider) {\n authProvider.onInit(auth => {\n this.auth = auth;\n });\n }\n\n getToken(): Promise {\n if (!this.auth) {\n return Promise.resolve(null);\n }\n\n return this.auth.getToken().then(tokenData => {\n if (tokenData) {\n hardAssert(\n typeof tokenData.accessToken === 'string',\n 0xa539,\n 'Invalid tokenData returned from getToken()',\n { tokenData }\n );\n return new OAuthToken(\n tokenData.accessToken,\n new User(this.auth!.getUid())\n );\n } else {\n return null;\n }\n });\n }\n\n invalidateToken(): void {}\n\n start(\n asyncQueue: AsyncQueue,\n changeListener: CredentialChangeListener\n ): void {}\n\n shutdown(): void {}\n}\n\nexport class FirebaseAuthCredentialsProvider\n implements CredentialsProvider\n{\n /**\n * The auth token listener registered with FirebaseApp, retained here so we\n * can unregister it.\n */\n private tokenListener: (() => void) | undefined;\n\n /** Tracks the current User. */\n private currentUser: User = User.UNAUTHENTICATED;\n\n /**\n * Counter used to detect if the token changed while a getToken request was\n * outstanding.\n */\n private tokenCounter = 0;\n\n private forceRefresh = false;\n\n private auth: FirebaseAuthInternal | null = null;\n\n constructor(private authProvider: Provider) {}\n\n start(\n asyncQueue: AsyncQueue,\n changeListener: CredentialChangeListener\n ): void {\n hardAssert(\n this.tokenListener === undefined,\n 0xa540,\n 'Token listener already added'\n );\n let lastTokenId = this.tokenCounter;\n\n // A change listener that prevents double-firing for the same token change.\n const guardedChangeListener: (user: User) => Promise = user => {\n if (this.tokenCounter !== lastTokenId) {\n lastTokenId = this.tokenCounter;\n return changeListener(user);\n } else {\n return Promise.resolve();\n }\n };\n\n // A promise that can be waited on to block on the next token change.\n // This promise is re-created after each change.\n let nextToken = new Deferred();\n\n this.tokenListener = () => {\n this.tokenCounter++;\n this.currentUser = this.getUser();\n nextToken.resolve();\n nextToken = new Deferred();\n asyncQueue.enqueueRetryable(() =>\n guardedChangeListener(this.currentUser)\n );\n };\n\n const awaitNextToken: () => void = () => {\n const currentTokenAttempt = nextToken;\n asyncQueue.enqueueRetryable(async () => {\n await currentTokenAttempt.promise;\n await guardedChangeListener(this.currentUser);\n });\n };\n\n const registerAuth = (auth: FirebaseAuthInternal): void => {\n logDebug('FirebaseAuthCredentialsProvider', 'Auth detected');\n this.auth = auth;\n if (this.tokenListener) {\n this.auth.addAuthTokenListener(this.tokenListener);\n awaitNextToken();\n }\n };\n\n this.authProvider.onInit(auth => registerAuth(auth));\n\n // Our users can initialize Auth right after Firestore, so we give it\n // a chance to register itself with the component framework before we\n // determine whether to start up in unauthenticated mode.\n setTimeout(() => {\n if (!this.auth) {\n const auth = this.authProvider.getImmediate({ optional: true });\n if (auth) {\n registerAuth(auth);\n } else {\n // If auth is still not available, proceed with `null` user\n logDebug('FirebaseAuthCredentialsProvider', 'Auth not yet detected');\n nextToken.resolve();\n nextToken = new Deferred();\n }\n }\n }, 0);\n\n awaitNextToken();\n }\n\n getToken(): Promise {\n debugAssert(\n this.tokenListener != null,\n 'FirebaseAuthCredentialsProvider not started.'\n );\n\n // Take note of the current value of the tokenCounter so that this method\n // can fail (with an ABORTED error) if there is a token change while the\n // request is outstanding.\n const initialTokenCounter = this.tokenCounter;\n const forceRefresh = this.forceRefresh;\n this.forceRefresh = false;\n\n if (!this.auth) {\n return Promise.resolve(null);\n }\n\n return this.auth.getToken(forceRefresh).then(tokenData => {\n // Cancel the request since the token changed while the request was\n // outstanding so the response is potentially for a previous user (which\n // user, we can't be sure).\n if (this.tokenCounter !== initialTokenCounter) {\n logDebug(\n 'FirebaseAuthCredentialsProvider',\n 'getToken aborted due to token change.'\n );\n return this.getToken();\n } else {\n if (tokenData) {\n hardAssert(\n typeof tokenData.accessToken === 'string',\n 0x7c5d,\n 'Invalid tokenData returned from getToken()',\n { tokenData }\n );\n return new OAuthToken(tokenData.accessToken, this.currentUser);\n } else {\n return null;\n }\n }\n });\n }\n\n invalidateToken(): void {\n this.forceRefresh = true;\n }\n\n shutdown(): void {\n if (this.auth && this.tokenListener) {\n this.auth.removeAuthTokenListener(this.tokenListener);\n }\n this.tokenListener = undefined;\n }\n\n // Auth.getUid() can return null even with a user logged in. It is because\n // getUid() is synchronous, but the auth code populating Uid is asynchronous.\n // This method should only be called in the AuthTokenListener callback\n // to guarantee to get the actual user.\n private getUser(): User {\n const currentUid = this.auth && this.auth.getUid();\n hardAssert(\n currentUid === null || typeof currentUid === 'string',\n 0x0807,\n 'Received invalid UID',\n { currentUid }\n );\n return new User(currentUid);\n }\n}\n\n/*\n * FirstPartyToken provides a fresh token each time its value\n * is requested, because if the token is too old, requests will be rejected.\n * Technically this may no longer be necessary since the SDK should gracefully\n * recover from unauthenticated errors (see b/33147818 for context), but it's\n * safer to keep the implementation as-is.\n */\nexport class FirstPartyToken implements Token {\n type = 'FirstParty' as TokenType;\n user = User.FIRST_PARTY;\n private _headers = new Map();\n\n constructor(\n private readonly sessionIndex: string,\n private readonly iamToken: string | null,\n private readonly authTokenFactory: AuthTokenFactory | null\n ) {}\n\n /**\n * Gets an authorization token, using a provided factory function, or return\n * null.\n */\n private getAuthToken(): string | null {\n if (this.authTokenFactory) {\n return this.authTokenFactory();\n } else {\n return null;\n }\n }\n\n get headers(): Map {\n this._headers.set('X-Goog-AuthUser', this.sessionIndex);\n // Use array notation to prevent minification\n const authHeaderTokenValue = this.getAuthToken();\n if (authHeaderTokenValue) {\n this._headers.set('Authorization', authHeaderTokenValue);\n }\n if (this.iamToken) {\n this._headers.set('X-Goog-Iam-Authorization-Token', this.iamToken);\n }\n\n return this._headers;\n }\n}\n\n/*\n * Provides user credentials required for the Firestore JavaScript SDK\n * to authenticate the user, using technique that is only available\n * to applications hosted by Google.\n */\nexport class FirstPartyAuthCredentialsProvider\n implements CredentialsProvider\n{\n constructor(\n private sessionIndex: string,\n private iamToken: string | null,\n private authTokenFactory: AuthTokenFactory | null\n ) {}\n\n getToken(): Promise {\n return Promise.resolve(\n new FirstPartyToken(\n this.sessionIndex,\n this.iamToken,\n this.authTokenFactory\n )\n );\n }\n\n start(\n asyncQueue: AsyncQueue,\n changeListener: CredentialChangeListener\n ): void {\n // Fire with initial uid.\n asyncQueue.enqueueRetryable(() => changeListener(User.FIRST_PARTY));\n }\n\n shutdown(): void {}\n\n invalidateToken(): void {}\n}\n\nexport class AppCheckToken implements Token {\n type = 'AppCheck' as TokenType;\n headers = new Map();\n\n constructor(private value: string) {\n if (value && value.length > 0) {\n this.headers.set('x-firebase-appcheck', this.value);\n }\n }\n}\n\nexport class FirebaseAppCheckTokenProvider\n implements CredentialsProvider\n{\n /**\n * The AppCheck token listener registered with FirebaseApp, retained here so\n * we can unregister it.\n */\n private tokenListener: AppCheckTokenListener | undefined;\n private forceRefresh = false;\n private appCheck: FirebaseAppCheckInternal | null = null;\n private latestAppCheckToken: string | null = null;\n private serverAppAppCheckToken: string | null = null;\n\n constructor(\n app: FirebaseApp,\n private appCheckProvider: Provider\n ) {\n if (_isFirebaseServerApp(app) && app.settings.appCheckToken) {\n this.serverAppAppCheckToken = app.settings.appCheckToken;\n }\n }\n\n start(\n asyncQueue: AsyncQueue,\n changeListener: CredentialChangeListener\n ): void {\n hardAssert(\n this.tokenListener === undefined,\n 0x0db8,\n 'Token listener already added'\n );\n\n const onTokenChanged: (\n tokenResult: AppCheckTokenResult\n ) => Promise = tokenResult => {\n if (tokenResult.error != null) {\n logDebug(\n 'FirebaseAppCheckTokenProvider',\n `Error getting App Check token; using placeholder token instead. Error: ${tokenResult.error.message}`\n );\n }\n const tokenUpdated = tokenResult.token !== this.latestAppCheckToken;\n this.latestAppCheckToken = tokenResult.token;\n logDebug(\n 'FirebaseAppCheckTokenProvider',\n `Received ${tokenUpdated ? 'new' : 'existing'} token.`\n );\n return tokenUpdated\n ? changeListener(tokenResult.token)\n : Promise.resolve();\n };\n\n this.tokenListener = (tokenResult: AppCheckTokenResult) => {\n asyncQueue.enqueueRetryable(() => onTokenChanged(tokenResult));\n };\n\n const registerAppCheck = (appCheck: FirebaseAppCheckInternal): void => {\n logDebug('FirebaseAppCheckTokenProvider', 'AppCheck detected');\n this.appCheck = appCheck;\n if (this.tokenListener) {\n this.appCheck.addTokenListener(this.tokenListener);\n }\n };\n\n this.appCheckProvider.onInit(appCheck => registerAppCheck(appCheck));\n\n // Our users can initialize AppCheck after Firestore, so we give it\n // a chance to register itself with the component framework.\n setTimeout(() => {\n if (!this.appCheck) {\n const appCheck = this.appCheckProvider.getImmediate({ optional: true });\n if (appCheck) {\n registerAppCheck(appCheck);\n } else {\n // If AppCheck is still not available, proceed without it.\n logDebug(\n 'FirebaseAppCheckTokenProvider',\n 'AppCheck not yet detected'\n );\n }\n }\n }, 0);\n }\n\n getToken(): Promise {\n if (this.serverAppAppCheckToken) {\n return Promise.resolve(new AppCheckToken(this.serverAppAppCheckToken));\n }\n debugAssert(\n this.tokenListener != null,\n 'FirebaseAppCheckTokenProvider not started.'\n );\n\n const forceRefresh = this.forceRefresh;\n this.forceRefresh = false;\n\n if (!this.appCheck) {\n return Promise.resolve(null);\n }\n\n return this.appCheck.getToken(forceRefresh).then(tokenResult => {\n if (tokenResult) {\n hardAssert(\n typeof tokenResult.token === 'string',\n 0xae0e,\n 'Invalid tokenResult returned from getToken()',\n { tokenResult }\n );\n this.latestAppCheckToken = tokenResult.token;\n return new AppCheckToken(tokenResult.token);\n } else {\n return null;\n }\n });\n }\n\n invalidateToken(): void {\n this.forceRefresh = true;\n }\n\n shutdown(): void {\n if (this.appCheck && this.tokenListener) {\n this.appCheck.removeTokenListener(this.tokenListener);\n }\n this.tokenListener = undefined;\n }\n}\n\n/**\n * An AppCheck token provider that always yields an empty token.\n * @internal\n */\nexport class EmptyAppCheckTokenProvider implements CredentialsProvider {\n getToken(): Promise {\n return Promise.resolve(new AppCheckToken(''));\n }\n\n invalidateToken(): void {}\n\n start(\n asyncQueue: AsyncQueue,\n changeListener: CredentialChangeListener\n ): void {}\n\n shutdown(): void {}\n}\n\n/** AppCheck token provider for the Lite SDK. */\nexport class LiteAppCheckTokenProvider implements CredentialsProvider {\n private appCheck: FirebaseAppCheckInternal | null = null;\n private serverAppAppCheckToken: string | null = null;\n\n constructor(\n app: FirebaseApp,\n private appCheckProvider: Provider\n ) {\n if (_isFirebaseServerApp(app) && app.settings.appCheckToken) {\n this.serverAppAppCheckToken = app.settings.appCheckToken;\n }\n appCheckProvider.onInit(appCheck => {\n this.appCheck = appCheck;\n });\n }\n\n getToken(): Promise {\n if (this.serverAppAppCheckToken) {\n return Promise.resolve(new AppCheckToken(this.serverAppAppCheckToken));\n }\n\n if (!this.appCheck) {\n return Promise.resolve(null);\n }\n\n return this.appCheck.getToken().then(tokenResult => {\n if (tokenResult) {\n hardAssert(\n typeof tokenResult.token === 'string',\n 0x0d8e,\n 'Invalid tokenResult returned from getToken()',\n { tokenResult }\n );\n return new AppCheckToken(tokenResult.token);\n } else {\n return null;\n }\n });\n }\n\n invalidateToken(): void {}\n\n start(\n asyncQueue: AsyncQueue,\n changeListener: CredentialChangeListener\n ): void {}\n\n shutdown(): void {}\n}\n\n/**\n * Builds a CredentialsProvider depending on the type of\n * the credentials passed in.\n */\nexport function makeAuthCredentialsProvider(\n credentials?: CredentialsSettings\n): CredentialsProvider {\n if (!credentials) {\n return new EmptyAuthCredentialsProvider();\n }\n switch (credentials['type']) {\n case 'firstParty':\n return new FirstPartyAuthCredentialsProvider(\n credentials['sessionIndex'] || '0',\n credentials['iamToken'] || null,\n credentials['authTokenFactory'] || null\n );\n\n case 'provider':\n return credentials['client'];\n\n default:\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'makeAuthCredentialsProvider failed due to invalid credential type'\n );\n }\n}\n","import { FirebaseApp } from '@firebase/app';\n\nimport { ExperimentalLongPollingOptions } from '../api/long_polling_options';\nimport { Code, FirestoreError } from '../util/error';\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport class DatabaseInfo {\n /**\n * Constructs a DatabaseInfo using the provided host, databaseId and\n * persistenceKey.\n *\n * @param databaseId - The database to use.\n * @param appId - The Firebase App Id.\n * @param persistenceKey - A unique identifier for this Firestore's local\n * storage (used in conjunction with the databaseId).\n * @param host - The Firestore backend host to connect to.\n * @param ssl - Whether to use SSL when connecting.\n * @param forceLongPolling - Whether to use the forceLongPolling option\n * when using WebChannel as the network transport.\n * @param autoDetectLongPolling - Whether to use the detectBufferingProxy\n * option when using WebChannel as the network transport.\n * @param longPollingOptions Options that configure long-polling.\n * @param useFetchStreams Whether to use the Fetch API instead of\n * XMLHTTPRequest\n */\n constructor(\n readonly databaseId: DatabaseId,\n readonly appId: string,\n readonly persistenceKey: string,\n readonly host: string,\n readonly ssl: boolean,\n readonly forceLongPolling: boolean,\n readonly autoDetectLongPolling: boolean,\n readonly longPollingOptions: ExperimentalLongPollingOptions,\n readonly useFetchStreams: boolean,\n readonly isUsingEmulator: boolean\n ) {}\n}\n\n/** The default database name for a project. */\nexport const DEFAULT_DATABASE_NAME = '(default)';\n\n/**\n * Represents the database ID a Firestore client is associated with.\n * @internal\n */\nexport class DatabaseId {\n readonly database: string;\n constructor(readonly projectId: string, database?: string) {\n this.database = database ? database : DEFAULT_DATABASE_NAME;\n }\n\n static empty(): DatabaseId {\n return new DatabaseId('', '');\n }\n\n get isDefaultDatabase(): boolean {\n return this.database === DEFAULT_DATABASE_NAME;\n }\n\n isEqual(other: {}): boolean {\n return (\n other instanceof DatabaseId &&\n other.projectId === this.projectId &&\n other.database === this.database\n );\n }\n}\n\nexport function databaseIdFromApp(\n app: FirebaseApp,\n database?: string\n): DatabaseId {\n if (!Object.prototype.hasOwnProperty.apply(app.options, ['projectId'])) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n '\"projectId\" not provided in firebase.initializeApp.'\n );\n }\n\n return new DatabaseId(app.options.projectId!, database);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { debugAssert } from '../../util/assert';\n\n/**\n * Generates `nBytes` of random bytes.\n *\n * If `nBytes < 0` , an error will be thrown.\n */\nexport function randomBytes(nBytes: number): Uint8Array {\n debugAssert(nBytes >= 0, `Expecting non-negative nBytes, got: ${nBytes}`);\n\n // Polyfills for IE and WebWorker by using `self` and `msCrypto` when `crypto` is not available.\n const crypto =\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n typeof self !== 'undefined' && (self.crypto || (self as any)['msCrypto']);\n const bytes = new Uint8Array(nBytes);\n if (crypto && typeof crypto.getRandomValues === 'function') {\n crypto.getRandomValues(bytes);\n } else {\n // Falls back to Math.random\n for (let i = 0; i < nBytes; i++) {\n bytes[i] = Math.floor(Math.random() * 256);\n }\n }\n return bytes;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { randomBytes } from '../platform/random_bytes';\n\nimport { debugAssert } from './assert';\n\nexport type EventHandler = (value: E) => void;\nexport interface Indexable {\n [k: string]: unknown;\n}\n\n/**\n * A utility class for generating unique alphanumeric IDs of a specified length.\n *\n * @internal\n * Exported internally for testing purposes.\n */\nexport class AutoId {\n static newId(): string {\n // Alphanumeric characters\n const chars =\n 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';\n // The largest byte value that is a multiple of `char.length`.\n const maxMultiple = Math.floor(256 / chars.length) * chars.length;\n debugAssert(\n 0 < maxMultiple && maxMultiple < 256,\n `Expect maxMultiple to be (0, 256), but got ${maxMultiple}`\n );\n\n let autoId = '';\n const targetLength = 20;\n while (autoId.length < targetLength) {\n const bytes = randomBytes(40);\n for (let i = 0; i < bytes.length; ++i) {\n // Only accept values that are [0, maxMultiple), this ensures they can\n // be evenly mapped to indices of `chars` via a modulo operation.\n if (autoId.length < targetLength && bytes[i] < maxMultiple) {\n autoId += chars.charAt(bytes[i] % chars.length);\n }\n }\n }\n debugAssert(autoId.length === targetLength, 'Invalid auto ID: ' + autoId);\n\n return autoId;\n }\n}\n\nexport function primitiveComparator(left: T, right: T): number {\n if (left < right) {\n return -1;\n }\n if (left > right) {\n return 1;\n }\n return 0;\n}\n\nexport interface Equatable {\n isEqual(other: T): boolean;\n}\n\n/** Compare strings in UTF-8 encoded byte order */\nexport function compareUtf8Strings(left: string, right: string): number {\n // Find the first differing character (a.k.a. \"UTF-16 code unit\") in the two strings and,\n // if found, use that character to determine the relative ordering of the two strings as a\n // whole. Comparing UTF-16 strings in UTF-8 byte order can be done simply and efficiently by\n // comparing the UTF-16 code units (chars). This serendipitously works because of the way UTF-8\n // and UTF-16 happen to represent Unicode code points.\n //\n // After finding the first pair of differing characters, there are two cases:\n //\n // Case 1: Both characters are non-surrogates (code points less than or equal to 0xFFFF) or\n // both are surrogates from a surrogate pair (that collectively represent code points greater\n // than 0xFFFF). In this case their numeric order as UTF-16 code units is the same as the\n // lexicographical order of their corresponding UTF-8 byte sequences. A direct comparison is\n // sufficient.\n //\n // Case 2: One character is a surrogate and the other is not. In this case the surrogate-\n // containing string is always ordered after the non-surrogate. This is because surrogates are\n // used to represent code points greater than 0xFFFF which have 4-byte UTF-8 representations\n // and are lexicographically greater than the 1, 2, or 3-byte representations of code points\n // less than or equal to 0xFFFF.\n //\n // An example of why Case 2 is required is comparing the following two Unicode code points:\n //\n // |-----------------------|------------|---------------------|-----------------|\n // | Name | Code Point | UTF-8 Encoding | UTF-16 Encoding |\n // |-----------------------|------------|---------------------|-----------------|\n // | Replacement Character | U+FFFD | 0xEF 0xBF 0xBD | 0xFFFD |\n // | Grinning Face | U+1F600 | 0xF0 0x9F 0x98 0x80 | 0xD83D 0xDE00 |\n // |-----------------------|------------|---------------------|-----------------|\n //\n // A lexicographical comparison of the UTF-8 encodings of these code points would order\n // \"Replacement Character\" _before_ \"Grinning Face\" because 0xEF is less than 0xF0. However, a\n // direct comparison of the UTF-16 code units, as would be done in case 1, would erroneously\n // produce the _opposite_ ordering, because 0xFFFD is _greater than_ 0xD83D. As it turns out,\n // this relative ordering holds for all comparisons of UTF-16 code points requiring a surrogate\n // pair with those that do not.\n const length = Math.min(left.length, right.length);\n for (let i = 0; i < length; i++) {\n const leftChar = left.charAt(i);\n const rightChar = right.charAt(i);\n if (leftChar !== rightChar) {\n return isSurrogate(leftChar) === isSurrogate(rightChar)\n ? primitiveComparator(leftChar, rightChar)\n : isSurrogate(leftChar)\n ? 1\n : -1;\n }\n }\n\n // Use the lengths of the strings to determine the overall comparison result since either the\n // strings were equal or one is a prefix of the other.\n return primitiveComparator(left.length, right.length);\n}\n\nconst MIN_SURROGATE = 0xd800;\nconst MAX_SURROGATE = 0xdfff;\n\nexport function isSurrogate(s: string): boolean {\n debugAssert(s.length === 1, `s.length == ${s.length}, but expected 1`);\n const c = s.charCodeAt(0);\n return c >= MIN_SURROGATE && c <= MAX_SURROGATE;\n}\n\nexport interface Iterable {\n forEach: (cb: (v: V) => void) => void;\n}\n\n/** Helper to compare arrays using isEqual(). */\nexport function arrayEquals(\n left: T[],\n right: T[],\n comparator: (l: T, r: T) => boolean\n): boolean {\n if (left.length !== right.length) {\n return false;\n }\n return left.every((value, index) => comparator(value, right[index]));\n}\n/**\n * Returns the immediate lexicographically-following string. This is useful to\n * construct an inclusive range for indexeddb iterators.\n */\nexport function immediateSuccessor(s: string): string {\n // Return the input string, with an additional NUL byte appended.\n return s + '\\0';\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Integer } from '@firebase/webchannel-wrapper/bloom-blob';\n\nimport { debugAssert, fail } from '../util/assert';\nimport { Code, FirestoreError } from '../util/error';\nimport { compareUtf8Strings, primitiveComparator } from '../util/misc';\n\nexport const DOCUMENT_KEY_NAME = '__name__';\n\n/**\n * Path represents an ordered sequence of string segments.\n */\nabstract class BasePath> {\n private segments: string[];\n private offset: number;\n private len: number;\n\n constructor(segments: string[], offset?: number, length?: number) {\n if (offset === undefined) {\n offset = 0;\n } else if (offset > segments.length) {\n fail(0x027d, 'offset out of range', {\n offset,\n range: segments.length\n });\n }\n\n if (length === undefined) {\n length = segments.length - offset;\n } else if (length > segments.length - offset) {\n fail(0x06d2, 'length out of range', {\n length,\n range: segments.length - offset\n });\n }\n this.segments = segments;\n this.offset = offset;\n this.len = length;\n }\n\n /**\n * Abstract constructor method to construct an instance of B with the given\n * parameters.\n */\n protected abstract construct(\n segments: string[],\n offset?: number,\n length?: number\n ): B;\n\n /**\n * Returns a String representation.\n *\n * Implementing classes are required to provide deterministic implementations as\n * the String representation is used to obtain canonical Query IDs.\n */\n abstract toString(): string;\n\n get length(): number {\n return this.len;\n }\n\n isEqual(other: B): boolean {\n return BasePath.comparator(this, other) === 0;\n }\n\n child(nameOrPath: string | B): B {\n const segments = this.segments.slice(this.offset, this.limit());\n if (nameOrPath instanceof BasePath) {\n nameOrPath.forEach(segment => {\n segments.push(segment);\n });\n } else {\n segments.push(nameOrPath);\n }\n return this.construct(segments);\n }\n\n /** The index of one past the last segment of the path. */\n private limit(): number {\n return this.offset + this.length;\n }\n\n popFirst(size?: number): B {\n size = size === undefined ? 1 : size;\n debugAssert(\n this.length >= size,\n \"Can't call popFirst() with less segments\"\n );\n return this.construct(\n this.segments,\n this.offset + size,\n this.length - size\n );\n }\n\n popLast(): B {\n debugAssert(!this.isEmpty(), \"Can't call popLast() on empty path\");\n return this.construct(this.segments, this.offset, this.length - 1);\n }\n\n firstSegment(): string {\n debugAssert(!this.isEmpty(), \"Can't call firstSegment() on empty path\");\n return this.segments[this.offset];\n }\n\n lastSegment(): string {\n debugAssert(!this.isEmpty(), \"Can't call lastSegment() on empty path\");\n return this.get(this.length - 1);\n }\n\n get(index: number): string {\n debugAssert(index < this.length, 'Index out of range');\n return this.segments[this.offset + index];\n }\n\n isEmpty(): boolean {\n return this.length === 0;\n }\n\n isPrefixOf(other: this): boolean {\n if (other.length < this.length) {\n return false;\n }\n\n for (let i = 0; i < this.length; i++) {\n if (this.get(i) !== other.get(i)) {\n return false;\n }\n }\n\n return true;\n }\n\n isImmediateParentOf(potentialChild: this): boolean {\n if (this.length + 1 !== potentialChild.length) {\n return false;\n }\n\n for (let i = 0; i < this.length; i++) {\n if (this.get(i) !== potentialChild.get(i)) {\n return false;\n }\n }\n\n return true;\n }\n\n forEach(fn: (segment: string) => void): void {\n for (let i = this.offset, end = this.limit(); i < end; i++) {\n fn(this.segments[i]);\n }\n }\n\n toArray(): string[] {\n return this.segments.slice(this.offset, this.limit());\n }\n\n /**\n * Compare 2 paths segment by segment, prioritizing numeric IDs\n * (e.g., \"__id123__\") in numeric ascending order, followed by string\n * segments in lexicographical order.\n */\n static comparator>(\n p1: BasePath,\n p2: BasePath\n ): number {\n const len = Math.min(p1.length, p2.length);\n for (let i = 0; i < len; i++) {\n const comparison = BasePath.compareSegments(p1.get(i), p2.get(i));\n if (comparison !== 0) {\n return comparison;\n }\n }\n return primitiveComparator(p1.length, p2.length);\n }\n\n private static compareSegments(lhs: string, rhs: string): number {\n const isLhsNumeric = BasePath.isNumericId(lhs);\n const isRhsNumeric = BasePath.isNumericId(rhs);\n\n if (isLhsNumeric && !isRhsNumeric) {\n // Only lhs is numeric\n return -1;\n } else if (!isLhsNumeric && isRhsNumeric) {\n // Only rhs is numeric\n return 1;\n } else if (isLhsNumeric && isRhsNumeric) {\n // both numeric\n return BasePath.extractNumericId(lhs).compare(\n BasePath.extractNumericId(rhs)\n );\n } else {\n // both non-numeric\n return compareUtf8Strings(lhs, rhs);\n }\n }\n\n // Checks if a segment is a numeric ID (starts with \"__id\" and ends with \"__\").\n private static isNumericId(segment: string): boolean {\n return segment.startsWith('__id') && segment.endsWith('__');\n }\n\n private static extractNumericId(segment: string): Integer {\n return Integer.fromString(segment.substring(4, segment.length - 2));\n }\n}\n\n/**\n * A slash-separated path for navigating resources (documents and collections)\n * within Firestore.\n *\n * @internal\n */\nexport class ResourcePath extends BasePath {\n protected construct(\n segments: string[],\n offset?: number,\n length?: number\n ): ResourcePath {\n return new ResourcePath(segments, offset, length);\n }\n\n canonicalString(): string {\n // NOTE: The client is ignorant of any path segments containing escape\n // sequences (e.g. __id123__) and just passes them through raw (they exist\n // for legacy reasons and should not be used frequently).\n\n return this.toArray().join('/');\n }\n\n toString(): string {\n return this.canonicalString();\n }\n\n /**\n * Returns a string representation of this path\n * where each path segment has been encoded with\n * `encodeURIComponent`.\n */\n toUriEncodedString(): string {\n return this.toArray().map(encodeURIComponent).join('/');\n }\n\n /**\n * Creates a resource path from the given slash-delimited string. If multiple\n * arguments are provided, all components are combined. Leading and trailing\n * slashes from all components are ignored.\n */\n static fromString(...pathComponents: string[]): ResourcePath {\n // NOTE: The client is ignorant of any path segments containing escape\n // sequences (e.g. __id123__) and just passes them through raw (they exist\n // for legacy reasons and should not be used frequently).\n\n const segments: string[] = [];\n for (const path of pathComponents) {\n if (path.indexOf('//') >= 0) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid segment (${path}). Paths must not contain // in them.`\n );\n }\n // Strip leading and trailing slashed.\n segments.push(...path.split('/').filter(segment => segment.length > 0));\n }\n\n return new ResourcePath(segments);\n }\n\n static emptyPath(): ResourcePath {\n return new ResourcePath([]);\n }\n}\n\nconst identifierRegExp = /^[_a-zA-Z][_a-zA-Z0-9]*$/;\n\n/**\n * A dot-separated path for navigating sub-objects within a document.\n * @internal\n */\nexport class FieldPath extends BasePath {\n protected construct(\n segments: string[],\n offset?: number,\n length?: number\n ): FieldPath {\n return new FieldPath(segments, offset, length);\n }\n\n /**\n * Returns true if the string could be used as a segment in a field path\n * without escaping.\n */\n private static isValidIdentifier(segment: string): boolean {\n return identifierRegExp.test(segment);\n }\n\n canonicalString(): string {\n return this.toArray()\n .map(str => {\n str = str.replace(/\\\\/g, '\\\\\\\\').replace(/`/g, '\\\\`');\n if (!FieldPath.isValidIdentifier(str)) {\n str = '`' + str + '`';\n }\n return str;\n })\n .join('.');\n }\n\n toString(): string {\n return this.canonicalString();\n }\n\n /**\n * Returns true if this field references the key of a document.\n */\n isKeyField(): boolean {\n return this.length === 1 && this.get(0) === DOCUMENT_KEY_NAME;\n }\n\n /**\n * The field designating the key of a document.\n */\n static keyField(): FieldPath {\n return new FieldPath([DOCUMENT_KEY_NAME]);\n }\n\n /**\n * Parses a field string from the given server-formatted string.\n *\n * - Splitting the empty string is not allowed (for now at least).\n * - Empty segments within the string (e.g. if there are two consecutive\n * separators) are not allowed.\n *\n * TODO(b/37244157): we should make this more strict. Right now, it allows\n * non-identifier path components, even if they aren't escaped.\n */\n static fromServerFormat(path: string): FieldPath {\n const segments: string[] = [];\n let current = '';\n let i = 0;\n\n const addCurrentSegment = (): void => {\n if (current.length === 0) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid field path (${path}). Paths must not be empty, begin ` +\n `with '.', end with '.', or contain '..'`\n );\n }\n segments.push(current);\n current = '';\n };\n\n let inBackticks = false;\n\n while (i < path.length) {\n const c = path[i];\n if (c === '\\\\') {\n if (i + 1 === path.length) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Path has trailing escape character: ' + path\n );\n }\n const next = path[i + 1];\n if (!(next === '\\\\' || next === '.' || next === '`')) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Path has invalid escape sequence: ' + path\n );\n }\n current += next;\n i += 2;\n } else if (c === '`') {\n inBackticks = !inBackticks;\n i++;\n } else if (c === '.' && !inBackticks) {\n addCurrentSegment();\n i++;\n } else {\n current += c;\n i++;\n }\n }\n addCurrentSegment();\n\n if (inBackticks) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Unterminated ` in path: ' + path\n );\n }\n\n return new FieldPath(segments);\n }\n\n static emptyPath(): FieldPath {\n return new FieldPath([]);\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { debugAssert } from '../util/assert';\n\nimport { ResourcePath } from './path';\n\n/**\n * @internal\n */\nexport class DocumentKey {\n constructor(readonly path: ResourcePath) {\n debugAssert(\n DocumentKey.isDocumentKey(path),\n 'Invalid DocumentKey with an odd number of segments: ' +\n path.toArray().join('/')\n );\n }\n\n static fromPath(path: string): DocumentKey {\n return new DocumentKey(ResourcePath.fromString(path));\n }\n\n static fromName(name: string): DocumentKey {\n return new DocumentKey(ResourcePath.fromString(name).popFirst(5));\n }\n\n static empty(): DocumentKey {\n return new DocumentKey(ResourcePath.emptyPath());\n }\n\n get collectionGroup(): string {\n debugAssert(\n !this.path.isEmpty(),\n 'Cannot get collection group for empty key'\n );\n return this.path.popLast().lastSegment();\n }\n\n /** Returns true if the document is in the specified collectionId. */\n hasCollectionId(collectionId: string): boolean {\n return (\n this.path.length >= 2 &&\n this.path.get(this.path.length - 2) === collectionId\n );\n }\n\n /** Returns the collection group (i.e. the name of the parent collection) for this key. */\n getCollectionGroup(): string {\n debugAssert(\n !this.path.isEmpty(),\n 'Cannot get collection group for empty key'\n );\n return this.path.get(this.path.length - 2);\n }\n\n /** Returns the fully qualified path to the parent collection. */\n getCollectionPath(): ResourcePath {\n return this.path.popLast();\n }\n\n isEqual(other: DocumentKey | null): boolean {\n return (\n other !== null && ResourcePath.comparator(this.path, other.path) === 0\n );\n }\n\n toString(): string {\n return this.path.toString();\n }\n\n static comparator(k1: DocumentKey, k2: DocumentKey): number {\n return ResourcePath.comparator(k1.path, k2.path);\n }\n\n static isDocumentKey(path: ResourcePath): boolean {\n return path.length % 2 === 0;\n }\n\n /**\n * Creates and returns a new document key with the given segments.\n *\n * @param segments - The segments of the path to the document\n * @returns A new instance of DocumentKey\n */\n static fromSegments(segments: string[]): DocumentKey {\n return new DocumentKey(new ResourcePath(segments.slice()));\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DocumentKey } from '../model/document_key';\nimport { ResourcePath } from '../model/path';\n\nimport { fail } from './assert';\nimport { Code, FirestoreError } from './error';\n\n/** Types accepted by validateType() and related methods for validation. */\nexport type ValidationType =\n | 'undefined'\n | 'object'\n | 'function'\n | 'boolean'\n | 'number'\n | 'string'\n | 'non-empty string';\n\nexport function validateNonEmptyArgument(\n functionName: string,\n argumentName: string,\n argument?: string\n): asserts argument is string {\n if (!argument) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Function ${functionName}() cannot be called with an empty ${argumentName}.`\n );\n }\n}\n\n/**\n * Validates that two boolean options are not set at the same time.\n * @internal\n */\nexport function validateIsNotUsedTogether(\n optionName1: string,\n argument1: boolean | undefined,\n optionName2: string,\n argument2: boolean | undefined\n): void {\n if (argument1 === true && argument2 === true) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `${optionName1} and ${optionName2} cannot be used together.`\n );\n }\n}\n\n/**\n * Validates that `path` refers to a document (indicated by the fact it contains\n * an even numbers of segments).\n */\nexport function validateDocumentPath(path: ResourcePath): void {\n if (!DocumentKey.isDocumentKey(path)) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid document reference. Document references must have an even number of segments, but ${path} has ${path.length}.`\n );\n }\n}\n\n/**\n * Validates that `path` refers to a collection (indicated by the fact it\n * contains an odd numbers of segments).\n */\nexport function validateCollectionPath(path: ResourcePath): void {\n if (DocumentKey.isDocumentKey(path)) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid collection reference. Collection references must have an odd number of segments, but ${path} has ${path.length}.`\n );\n }\n}\n\n/**\n * Returns true if it's a non-null object without a custom prototype\n * (i.e. excludes Array, Date, etc.).\n */\nexport function isPlainObject(input: unknown): boolean {\n return (\n typeof input === 'object' &&\n input !== null &&\n (Object.getPrototypeOf(input) === Object.prototype ||\n Object.getPrototypeOf(input) === null)\n );\n}\n\n/** Returns a string describing the type / value of the provided input. */\nexport function valueDescription(input: unknown): string {\n if (input === undefined) {\n return 'undefined';\n } else if (input === null) {\n return 'null';\n } else if (typeof input === 'string') {\n if (input.length > 20) {\n input = `${input.substring(0, 20)}...`;\n }\n return JSON.stringify(input);\n } else if (typeof input === 'number' || typeof input === 'boolean') {\n return '' + input;\n } else if (typeof input === 'object') {\n if (input instanceof Array) {\n return 'an array';\n } else {\n const customObjectName = tryGetCustomObjectType(input!);\n if (customObjectName) {\n return `a custom ${customObjectName} object`;\n } else {\n return 'an object';\n }\n }\n } else if (typeof input === 'function') {\n return 'a function';\n } else {\n return fail(0x3029, 'Unknown wrong type', { type: typeof input });\n }\n}\n\n/** try to get the constructor name for an object. */\nexport function tryGetCustomObjectType(input: object): string | null {\n if (input.constructor) {\n return input.constructor.name;\n }\n return null;\n}\n\n/**\n * Casts `obj` to `T`, optionally unwrapping Compat types to expose the\n * underlying instance. Throws if `obj` is not an instance of `T`.\n *\n * This cast is used in the Lite and Full SDK to verify instance types for\n * arguments passed to the public API.\n * @internal\n */\nexport function cast(\n obj: object,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n constructor: { new (...args: any[]): T }\n): T | never {\n if ('_delegate' in obj) {\n // Unwrap Compat types\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n obj = (obj as any)._delegate;\n }\n\n if (!(obj instanceof constructor)) {\n if (constructor.name === obj.constructor.name) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Type does not match the expected instance. Did you pass a ' +\n `reference from a different Firestore SDK?`\n );\n } else {\n const description = valueDescription(obj);\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Expected type '${constructor.name}', but it was: ${description}`\n );\n }\n }\n return obj as T;\n}\n\nexport function validatePositiveNumber(functionName: string, n: number): void {\n if (n <= 0) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Function ${functionName}() requires a positive number, but it was: ${n}.`\n );\n }\n}\n","/**\n * @license\n * Copyright 2023 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Options that configure the SDK’s underlying network transport (WebChannel)\n * when long-polling is used.\n *\n * Note: This interface is \"experimental\" and is subject to change.\n *\n * See `FirestoreSettings.experimentalAutoDetectLongPolling`,\n * `FirestoreSettings.experimentalForceLongPolling`, and\n * `FirestoreSettings.experimentalLongPollingOptions`.\n */\nexport interface ExperimentalLongPollingOptions {\n /**\n * The desired maximum timeout interval, in seconds, to complete a\n * long-polling GET response. Valid values are between 5 and 30, inclusive.\n * Floating point values are allowed and will be rounded to the nearest\n * millisecond.\n *\n * By default, when long-polling is used the \"hanging GET\" request sent by\n * the client times out after 30 seconds. To request a different timeout\n * from the server, set this setting with the desired timeout.\n *\n * Changing the default timeout may be useful, for example, if the buffering\n * proxy that necessitated enabling long-polling in the first place has a\n * shorter timeout for hanging GET requests, in which case setting the\n * long-polling timeout to a shorter value, such as 25 seconds, may fix\n * prematurely-closed hanging GET requests.\n * For example, see https://github.com/firebase/firebase-js-sdk/issues/6987.\n */\n timeoutSeconds?: number;\n}\n\n/**\n * Compares two `ExperimentalLongPollingOptions` objects for equality.\n */\nexport function longPollingOptionsEqual(\n options1: ExperimentalLongPollingOptions,\n options2: ExperimentalLongPollingOptions\n): boolean {\n return options1.timeoutSeconds === options2.timeoutSeconds;\n}\n\n/**\n * Creates and returns a new `ExperimentalLongPollingOptions` with the same\n * option values as the given instance.\n */\nexport function cloneLongPollingOptions(\n options: ExperimentalLongPollingOptions\n): ExperimentalLongPollingOptions {\n const clone: ExperimentalLongPollingOptions = {};\n\n if (options.timeoutSeconds !== undefined) {\n clone.timeoutSeconds = options.timeoutSeconds;\n }\n\n return clone;\n}\n","/**\n * @license\n * Copyright 2023 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * The value returned from the most recent invocation of\n * `generateUniqueDebugId()`, or null if it has never been invoked.\n */\nlet lastUniqueDebugId: number | null = null;\n\n/**\n * Generates and returns an initial value for `lastUniqueDebugId`.\n *\n * The returned value is randomly selected from a range of integers that are\n * represented as 8 hexadecimal digits. This means that (within reason) any\n * numbers generated by incrementing the returned number by 1 will also be\n * represented by 8 hexadecimal digits. This leads to all \"IDs\" having the same\n * length when converted to a hexadecimal string, making reading logs containing\n * these IDs easier to follow. And since the return value is randomly selected\n * it will help to differentiate between logs from different executions.\n */\nfunction generateInitialUniqueDebugId(): number {\n const minResult = 0x10000000;\n const maxResult = 0x90000000;\n const resultRange = maxResult - minResult;\n const resultOffset = Math.round(resultRange * Math.random());\n return minResult + resultOffset;\n}\n\n/**\n * Generates and returns a unique ID as a hexadecimal string.\n *\n * The returned ID is intended to be used in debug logging messages to help\n * correlate log messages that may be spatially separated in the logs, but\n * logically related. For example, a network connection could include the same\n * \"debug ID\" string in all of its log messages to help trace a specific\n * connection over time.\n *\n * @return the 10-character generated ID (e.g. \"0xa1b2c3d4\").\n */\nexport function generateUniqueDebugId(): string {\n if (lastUniqueDebugId === null) {\n lastUniqueDebugId = generateInitialUniqueDebugId();\n } else {\n lastUniqueDebugId++;\n }\n return '0x' + lastUniqueDebugId.toString(16);\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** Sentinel value that sorts before any Mutation Batch ID. */\nexport const BATCHID_UNKNOWN = -1;\n\n// An Object whose keys and values are strings.\nexport interface StringMap {\n [key: string]: string;\n}\n\n/**\n * Returns whether a variable is either undefined or null.\n */\nexport function isNullOrUndefined(value: unknown): value is null | undefined {\n return value === null || value === undefined;\n}\n\n/** Returns whether the value represents -0. */\nexport function isNegativeZero(value: number): boolean {\n // Detect if the value is -0.0. Based on polyfill from\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is\n return value === 0 && 1 / value === 1 / -0;\n}\n\n/**\n * Returns whether a value is an integer and in the safe integer range\n * @param value - The value to test for being an integer and in the safe range\n */\nexport function isSafeInteger(value: unknown): boolean {\n return (\n typeof value === 'number' &&\n Number.isInteger(value) &&\n !isNegativeZero(value) &&\n value <= Number.MAX_SAFE_INTEGER &&\n value >= Number.MIN_SAFE_INTEGER\n );\n}\n\n/** The subset of the browser's Window interface used by the SDK. */\nexport interface WindowLike {\n readonly localStorage: Storage;\n readonly indexedDB: IDBFactory | null;\n addEventListener(type: string, listener: EventListener): void;\n removeEventListener(type: string, listener: EventListener): void;\n}\n\n/** The subset of the browser's Document interface used by the SDK. */\nexport interface DocumentLike {\n readonly visibilityState: DocumentVisibilityState;\n addEventListener(type: string, listener: EventListener): void;\n removeEventListener(type: string, listener: EventListener): void;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isCloudWorkstation } from '@firebase/util';\n\nimport { SDK_VERSION } from '../../src/core/version';\nimport { Token } from '../api/credentials';\nimport {\n DatabaseId,\n DatabaseInfo,\n DEFAULT_DATABASE_NAME\n} from '../core/database_info';\nimport { ResourcePath } from '../model/path';\nimport { debugAssert } from '../util/assert';\nimport { generateUniqueDebugId } from '../util/debug_uid';\nimport { FirestoreError } from '../util/error';\nimport { logDebug, logWarn } from '../util/log';\nimport { StringMap } from '../util/types';\n\nimport { Connection, Stream } from './connection';\n\nconst LOG_TAG = 'RestConnection';\n\n/**\n * Maps RPC names to the corresponding REST endpoint name.\n *\n * We use array notation to avoid mangling.\n */\nconst RPC_NAME_URL_MAPPING: StringMap = {};\n\nRPC_NAME_URL_MAPPING['BatchGetDocuments'] = 'batchGet';\nRPC_NAME_URL_MAPPING['Commit'] = 'commit';\nRPC_NAME_URL_MAPPING['RunQuery'] = 'runQuery';\nRPC_NAME_URL_MAPPING['RunAggregationQuery'] = 'runAggregationQuery';\n\nconst RPC_URL_VERSION = 'v1';\n\n// SDK_VERSION is updated to different value at runtime depending on the entry point,\n// so we need to get its value when we need it in a function.\nfunction getGoogApiClientValue(): string {\n return 'gl-js/ fire/' + SDK_VERSION;\n}\n/**\n * Base class for all Rest-based connections to the backend (WebChannel and\n * HTTP).\n */\nexport abstract class RestConnection implements Connection {\n protected readonly databaseId: DatabaseId;\n protected readonly baseUrl: string;\n private readonly databasePath: string;\n private readonly requestParams: string;\n\n get shouldResourcePathBeIncludedInRequest(): boolean {\n // Both `invokeRPC()` and `invokeStreamingRPC()` use their `path` arguments to determine\n // where to run the query, and expect the `request` to NOT specify the \"path\".\n return false;\n }\n\n constructor(private readonly databaseInfo: DatabaseInfo) {\n this.databaseId = databaseInfo.databaseId;\n const proto = databaseInfo.ssl ? 'https' : 'http';\n const projectId = encodeURIComponent(this.databaseId.projectId);\n const databaseId = encodeURIComponent(this.databaseId.database);\n this.baseUrl = proto + '://' + databaseInfo.host;\n this.databasePath = `projects/${projectId}/databases/${databaseId}`;\n this.requestParams =\n this.databaseId.database === DEFAULT_DATABASE_NAME\n ? `project_id=${projectId}`\n : `project_id=${projectId}&database_id=${databaseId}`;\n }\n\n invokeRPC(\n rpcName: string,\n path: ResourcePath,\n req: Req,\n authToken: Token | null,\n appCheckToken: Token | null\n ): Promise {\n const streamId = generateUniqueDebugId();\n const url = this.makeUrl(rpcName, path.toUriEncodedString());\n logDebug(LOG_TAG, `Sending RPC '${rpcName}' ${streamId}:`, url, req);\n\n const headers: StringMap = {\n 'google-cloud-resource-prefix': this.databasePath,\n 'x-goog-request-params': this.requestParams\n };\n this.modifyHeadersForRequest(headers, authToken, appCheckToken);\n\n const { host } = new URL(url);\n const forwardCredentials = isCloudWorkstation(host);\n return this.performRPCRequest(\n rpcName,\n url,\n headers,\n req,\n forwardCredentials\n ).then(\n response => {\n logDebug(LOG_TAG, `Received RPC '${rpcName}' ${streamId}: `, response);\n return response;\n },\n (err: FirestoreError) => {\n logWarn(\n LOG_TAG,\n `RPC '${rpcName}' ${streamId} failed with error: `,\n err,\n 'url: ',\n url,\n 'request:',\n req\n );\n throw err;\n }\n );\n }\n\n invokeStreamingRPC(\n rpcName: string,\n path: ResourcePath,\n request: Req,\n authToken: Token | null,\n appCheckToken: Token | null,\n expectedResponseCount?: number\n ): Promise {\n // The REST API automatically aggregates all of the streamed results, so we\n // can just use the normal invoke() method.\n return this.invokeRPC(\n rpcName,\n path,\n request,\n authToken,\n appCheckToken\n );\n }\n\n abstract openStream(\n rpcName: string,\n authToken: Token | null,\n appCheckToken: Token | null\n ): Stream;\n\n /**\n * Modifies the headers for a request, adding any authorization token if\n * present and any additional headers for the request.\n */\n protected modifyHeadersForRequest(\n headers: StringMap,\n authToken: Token | null,\n appCheckToken: Token | null\n ): void {\n headers['X-Goog-Api-Client'] = getGoogApiClientValue();\n\n // Content-Type: text/plain will avoid preflight requests which might\n // mess with CORS and redirects by proxies. If we add custom headers\n // we will need to change this code to potentially use the $httpOverwrite\n // parameter supported by ESF to avoid triggering preflight requests.\n headers['Content-Type'] = 'text/plain';\n\n if (this.databaseInfo.appId) {\n headers['X-Firebase-GMPID'] = this.databaseInfo.appId;\n }\n\n if (authToken) {\n authToken.headers.forEach((value, key) => (headers[key] = value));\n }\n if (appCheckToken) {\n appCheckToken.headers.forEach((value, key) => (headers[key] = value));\n }\n }\n\n /**\n * Performs an RPC request using an implementation specific networking layer.\n */\n protected abstract performRPCRequest(\n rpcName: string,\n url: string,\n headers: StringMap,\n body: Req,\n _forwardCredentials: boolean\n ): Promise;\n\n private makeUrl(rpcName: string, path: string): string {\n const urlRpcName = RPC_NAME_URL_MAPPING[rpcName];\n debugAssert(\n urlRpcName !== undefined,\n 'Unknown REST mapping for: ' + rpcName\n );\n return `${this.baseUrl}/${RPC_URL_VERSION}/${path}:${urlRpcName}`;\n }\n\n /**\n * Closes and cleans up any resources associated with the connection. This\n * implementation is a no-op because there are no resources associated\n * with the RestConnection that need to be cleaned up.\n */\n terminate(): void {\n // No-op\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { fail } from '../util/assert';\nimport { Code } from '../util/error';\nimport { logError } from '../util/log';\n\n/**\n * Error Codes describing the different ways GRPC can fail. These are copied\n * directly from GRPC's sources here:\n *\n * https://github.com/grpc/grpc/blob/bceec94ea4fc5f0085d81235d8e1c06798dc341a/include/grpc%2B%2B/impl/codegen/status_code_enum.h\n *\n * Important! The names of these identifiers matter because the string forms\n * are used for reverse lookups from the webchannel stream. Do NOT change the\n * names of these identifiers or change this into a const enum.\n */\nenum RpcCode {\n OK = 0,\n CANCELLED = 1,\n UNKNOWN = 2,\n INVALID_ARGUMENT = 3,\n DEADLINE_EXCEEDED = 4,\n NOT_FOUND = 5,\n ALREADY_EXISTS = 6,\n PERMISSION_DENIED = 7,\n UNAUTHENTICATED = 16,\n RESOURCE_EXHAUSTED = 8,\n FAILED_PRECONDITION = 9,\n ABORTED = 10,\n OUT_OF_RANGE = 11,\n UNIMPLEMENTED = 12,\n INTERNAL = 13,\n UNAVAILABLE = 14,\n DATA_LOSS = 15\n}\n\n/**\n * Determines whether an error code represents a permanent error when received\n * in response to a non-write operation.\n *\n * See isPermanentWriteError for classifying write errors.\n */\nexport function isPermanentError(code: Code): boolean {\n switch (code) {\n case Code.OK:\n return fail(0xfdaa, 'Treated status OK as error');\n case Code.CANCELLED:\n case Code.UNKNOWN:\n case Code.DEADLINE_EXCEEDED:\n case Code.RESOURCE_EXHAUSTED:\n case Code.INTERNAL:\n case Code.UNAVAILABLE:\n // Unauthenticated means something went wrong with our token and we need\n // to retry with new credentials which will happen automatically.\n case Code.UNAUTHENTICATED:\n return false;\n case Code.INVALID_ARGUMENT:\n case Code.NOT_FOUND:\n case Code.ALREADY_EXISTS:\n case Code.PERMISSION_DENIED:\n case Code.FAILED_PRECONDITION:\n // Aborted might be retried in some scenarios, but that is dependent on\n // the context and should handled individually by the calling code.\n // See https://cloud.google.com/apis/design/errors.\n case Code.ABORTED:\n case Code.OUT_OF_RANGE:\n case Code.UNIMPLEMENTED:\n case Code.DATA_LOSS:\n return true;\n default:\n return fail(0x3c6b, 'Unknown status code', { code });\n }\n}\n\n/**\n * Determines whether an error code represents a permanent error when received\n * in response to a write operation.\n *\n * Write operations must be handled specially because as of b/119437764, ABORTED\n * errors on the write stream should be retried too (even though ABORTED errors\n * are not generally retryable).\n *\n * Note that during the initial handshake on the write stream an ABORTED error\n * signals that we should discard our stream token (i.e. it is permanent). This\n * means a handshake error should be classified with isPermanentError, above.\n */\nexport function isPermanentWriteError(code: Code): boolean {\n return isPermanentError(code) && code !== Code.ABORTED;\n}\n\n/**\n * Maps an error Code from a GRPC status identifier like 'NOT_FOUND'.\n *\n * @returns The Code equivalent to the given status string or undefined if\n * there is no match.\n */\nexport function mapCodeFromRpcStatus(status: string): Code | undefined {\n // lookup by string\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const code: RpcCode = RpcCode[status as any] as any;\n if (code === undefined) {\n return undefined;\n }\n\n return mapCodeFromRpcCode(code);\n}\n\n/**\n * Maps an error Code from GRPC status code number, like 0, 1, or 14. These\n * are not the same as HTTP status codes.\n *\n * @returns The Code equivalent to the given GRPC status code. Fails if there\n * is no match.\n */\nexport function mapCodeFromRpcCode(code: number | undefined): Code {\n if (code === undefined) {\n // This shouldn't normally happen, but in certain error cases (like trying\n // to send invalid proto messages) we may get an error with no GRPC code.\n logError('GRPC error has no .code');\n return Code.UNKNOWN;\n }\n\n switch (code) {\n case RpcCode.OK:\n return Code.OK;\n case RpcCode.CANCELLED:\n return Code.CANCELLED;\n case RpcCode.UNKNOWN:\n return Code.UNKNOWN;\n case RpcCode.DEADLINE_EXCEEDED:\n return Code.DEADLINE_EXCEEDED;\n case RpcCode.RESOURCE_EXHAUSTED:\n return Code.RESOURCE_EXHAUSTED;\n case RpcCode.INTERNAL:\n return Code.INTERNAL;\n case RpcCode.UNAVAILABLE:\n return Code.UNAVAILABLE;\n case RpcCode.UNAUTHENTICATED:\n return Code.UNAUTHENTICATED;\n case RpcCode.INVALID_ARGUMENT:\n return Code.INVALID_ARGUMENT;\n case RpcCode.NOT_FOUND:\n return Code.NOT_FOUND;\n case RpcCode.ALREADY_EXISTS:\n return Code.ALREADY_EXISTS;\n case RpcCode.PERMISSION_DENIED:\n return Code.PERMISSION_DENIED;\n case RpcCode.FAILED_PRECONDITION:\n return Code.FAILED_PRECONDITION;\n case RpcCode.ABORTED:\n return Code.ABORTED;\n case RpcCode.OUT_OF_RANGE:\n return Code.OUT_OF_RANGE;\n case RpcCode.UNIMPLEMENTED:\n return Code.UNIMPLEMENTED;\n case RpcCode.DATA_LOSS:\n return Code.DATA_LOSS;\n default:\n return fail(0x999b, 'Unknown status code', { code });\n }\n}\n\n/**\n * Maps an RPC code from a Code. This is the reverse operation from\n * mapCodeFromRpcCode and should really only be used in tests.\n */\nexport function mapRpcCodeFromCode(code: Code | undefined): number {\n if (code === undefined) {\n return RpcCode.OK;\n }\n\n switch (code) {\n case Code.OK:\n return RpcCode.OK;\n case Code.CANCELLED:\n return RpcCode.CANCELLED;\n case Code.UNKNOWN:\n return RpcCode.UNKNOWN;\n case Code.DEADLINE_EXCEEDED:\n return RpcCode.DEADLINE_EXCEEDED;\n case Code.RESOURCE_EXHAUSTED:\n return RpcCode.RESOURCE_EXHAUSTED;\n case Code.INTERNAL:\n return RpcCode.INTERNAL;\n case Code.UNAVAILABLE:\n return RpcCode.UNAVAILABLE;\n case Code.UNAUTHENTICATED:\n return RpcCode.UNAUTHENTICATED;\n case Code.INVALID_ARGUMENT:\n return RpcCode.INVALID_ARGUMENT;\n case Code.NOT_FOUND:\n return RpcCode.NOT_FOUND;\n case Code.ALREADY_EXISTS:\n return RpcCode.ALREADY_EXISTS;\n case Code.PERMISSION_DENIED:\n return RpcCode.PERMISSION_DENIED;\n case Code.FAILED_PRECONDITION:\n return RpcCode.FAILED_PRECONDITION;\n case Code.ABORTED:\n return RpcCode.ABORTED;\n case Code.OUT_OF_RANGE:\n return RpcCode.OUT_OF_RANGE;\n case Code.UNIMPLEMENTED:\n return RpcCode.UNIMPLEMENTED;\n case Code.DATA_LOSS:\n return RpcCode.DATA_LOSS;\n default:\n return fail(0x3019, 'Unknown status code', { code });\n }\n}\n\n/**\n * Converts an HTTP Status Code to the equivalent error code.\n *\n * @param status - An HTTP Status Code, like 200, 404, 503, etc.\n * @returns The equivalent Code. Unknown status codes are mapped to\n * Code.UNKNOWN.\n */\nexport function mapCodeFromHttpStatus(status?: number): Code {\n if (status === undefined) {\n logError('RPC_ERROR', 'HTTP error has no status');\n return Code.UNKNOWN;\n }\n\n // The canonical error codes for Google APIs [1] specify mapping onto HTTP\n // status codes but the mapping is not bijective. In each case of ambiguity\n // this function chooses a primary error.\n //\n // [1]\n // https://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto\n switch (status) {\n case 200: // OK\n return Code.OK;\n\n case 400: // Bad Request\n return Code.FAILED_PRECONDITION;\n // Other possibilities based on the forward mapping\n // return Code.INVALID_ARGUMENT;\n // return Code.OUT_OF_RANGE;\n\n case 401: // Unauthorized\n return Code.UNAUTHENTICATED;\n\n case 403: // Forbidden\n return Code.PERMISSION_DENIED;\n\n case 404: // Not Found\n return Code.NOT_FOUND;\n\n case 409: // Conflict\n return Code.ABORTED;\n // Other possibilities:\n // return Code.ALREADY_EXISTS;\n\n case 416: // Range Not Satisfiable\n return Code.OUT_OF_RANGE;\n\n case 429: // Too Many Requests\n return Code.RESOURCE_EXHAUSTED;\n\n case 499: // Client Closed Request\n return Code.CANCELLED;\n\n case 500: // Internal Server Error\n return Code.UNKNOWN;\n // Other possibilities:\n // return Code.INTERNAL;\n // return Code.DATA_LOSS;\n\n case 501: // Unimplemented\n return Code.UNIMPLEMENTED;\n\n case 503: // Service Unavailable\n return Code.UNAVAILABLE;\n\n case 504: // Gateway Timeout\n return Code.DEADLINE_EXCEEDED;\n\n default:\n if (status >= 200 && status < 300) {\n return Code.OK;\n }\n if (status >= 400 && status < 500) {\n return Code.FAILED_PRECONDITION;\n }\n if (status >= 500 && status < 600) {\n return Code.INTERNAL;\n }\n return Code.UNKNOWN;\n }\n}\n\n/**\n * Converts an HTTP response's error status to the equivalent error code.\n *\n * @param status - An HTTP error response status (\"FAILED_PRECONDITION\",\n * \"UNKNOWN\", etc.)\n * @returns The equivalent Code. Non-matching responses are mapped to\n * Code.UNKNOWN.\n */\nexport function mapCodeFromHttpResponseErrorStatus(status: string): Code {\n const serverError = status.toLowerCase().replace(/_/g, '-');\n return Object.values(Code).indexOf(serverError as Code) >= 0\n ? (serverError as Code)\n : Code.UNKNOWN;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Token } from '../../api/credentials';\nimport { Stream } from '../../remote/connection';\nimport { RestConnection } from '../../remote/rest_connection';\nimport { mapCodeFromHttpStatus } from '../../remote/rpc_error';\nimport { FirestoreError } from '../../util/error';\nimport { StringMap } from '../../util/types';\n\n/**\n * A Rest-based connection that relies on the native HTTP stack\n * (e.g. `fetch` or a polyfill).\n */\nexport class FetchConnection extends RestConnection {\n openStream(\n rpcName: string,\n token: Token | null\n ): Stream {\n throw new Error('Not supported by FetchConnection');\n }\n\n protected async performRPCRequest(\n rpcName: string,\n url: string,\n headers: StringMap,\n body: Req,\n forwardCredentials: boolean\n ): Promise {\n const requestJson = JSON.stringify(body);\n let response: Response;\n\n try {\n const fetchArgs: RequestInit = {\n method: 'POST',\n headers,\n body: requestJson\n };\n if (forwardCredentials) {\n fetchArgs.credentials = 'include';\n }\n response = await fetch(url, fetchArgs);\n } catch (e) {\n const err = e as { status: number | undefined; statusText: string };\n throw new FirestoreError(\n mapCodeFromHttpStatus(err.status),\n 'Request failed with error: ' + err.statusText\n );\n }\n\n if (!response.ok) {\n let errorResponse = await response.json();\n if (Array.isArray(errorResponse)) {\n errorResponse = errorResponse[0];\n }\n const errorMessage = errorResponse?.error?.message;\n throw new FirestoreError(\n mapCodeFromHttpStatus(response.status),\n `Request failed with error: ${errorMessage ?? response.statusText}`\n );\n }\n\n return response.json();\n }\n}\n","/**\n * @license\n * Copyright 2023 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FieldPath } from '../model/path';\n\n/**\n * Union type representing the aggregate type to be performed.\n */\nexport type AggregateType = 'count' | 'avg' | 'sum';\n\n/**\n * Represents an Aggregate to be performed over a query result set.\n */\nexport interface Aggregate {\n readonly fieldPath?: FieldPath;\n readonly alias: string;\n readonly aggregateType: AggregateType;\n}\n\n/**\n * Concrete implementation of the Aggregate type.\n */\nexport class AggregateImpl implements Aggregate {\n constructor(\n readonly alias: string,\n readonly aggregateType: AggregateType,\n readonly fieldPath?: FieldPath\n ) {}\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { debugAssert } from './assert';\n\nexport interface Dict {\n [stringKey: string]: V;\n}\n\nexport function objectSize(obj: object): number {\n let count = 0;\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n count++;\n }\n }\n return count;\n}\n\nexport function forEach(\n obj: Dict | undefined,\n fn: (key: string, val: V) => void\n): void {\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n fn(key, obj[key]);\n }\n }\n}\n\nexport function mapToArray(\n obj: Dict,\n fn: (element: V, key: string, obj: Dict) => R\n): R[] {\n const result: R[] = [];\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n result.push(fn(obj[key], key, obj));\n }\n }\n return result;\n}\n\nexport function isEmpty(obj: Dict): boolean {\n debugAssert(\n obj != null && typeof obj === 'object',\n 'isEmpty() expects object parameter.'\n );\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n return false;\n }\n }\n return true;\n}\n","/**\n * @license\n * Copyright 2023 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * An error encountered while decoding base64 string.\n */\nexport class Base64DecodeError extends Error {\n readonly name = 'Base64DecodeError';\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { decodeBase64, encodeBase64 } from '../platform/base64';\n\nimport { primitiveComparator } from './misc';\n\n/**\n * Immutable class that represents a \"proto\" byte string.\n *\n * Proto byte strings can either be Base64-encoded strings or Uint8Arrays when\n * sent on the wire. This class abstracts away this differentiation by holding\n * the proto byte string in a common class that must be converted into a string\n * before being sent as a proto.\n * @internal\n */\nexport class ByteString {\n static readonly EMPTY_BYTE_STRING = new ByteString('');\n\n private constructor(private readonly binaryString: string) {}\n\n static fromBase64String(base64: string): ByteString {\n const binaryString = decodeBase64(base64);\n return new ByteString(binaryString);\n }\n\n static fromUint8Array(array: Uint8Array): ByteString {\n // TODO(indexing); Remove the copy of the byte string here as this method\n // is frequently called during indexing.\n const binaryString = binaryStringFromUint8Array(array);\n return new ByteString(binaryString);\n }\n\n [Symbol.iterator](): Iterator {\n let i = 0;\n return {\n next: () => {\n if (i < this.binaryString.length) {\n return { value: this.binaryString.charCodeAt(i++), done: false };\n } else {\n return { value: undefined, done: true };\n }\n }\n };\n }\n\n toBase64(): string {\n return encodeBase64(this.binaryString);\n }\n\n toUint8Array(): Uint8Array {\n return uint8ArrayFromBinaryString(this.binaryString);\n }\n\n approximateByteSize(): number {\n return this.binaryString.length * 2;\n }\n\n compareTo(other: ByteString): number {\n return primitiveComparator(this.binaryString, other.binaryString);\n }\n\n isEqual(other: ByteString): boolean {\n return this.binaryString === other.binaryString;\n }\n}\n\n/**\n * Helper function to convert an Uint8array to a binary string.\n */\nexport function binaryStringFromUint8Array(array: Uint8Array): string {\n let binaryString = '';\n for (let i = 0; i < array.length; ++i) {\n binaryString += String.fromCharCode(array[i]);\n }\n return binaryString;\n}\n\n/**\n * Helper function to convert a binary string to an Uint8Array.\n */\nexport function uint8ArrayFromBinaryString(binaryString: string): Uint8Array {\n const buffer = new Uint8Array(binaryString.length);\n for (let i = 0; i < binaryString.length; i++) {\n buffer[i] = binaryString.charCodeAt(i);\n }\n return buffer;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Base64DecodeError } from '../../util/base64_decode_error';\n\n/** Converts a Base64 encoded string to a binary string. */\nexport function decodeBase64(encoded: string): string {\n try {\n return atob(encoded);\n } catch (e) {\n // Check that `DOMException` is defined before using it to avoid\n // \"ReferenceError: Property 'DOMException' doesn't exist\" in react-native.\n // (https://github.com/firebase/firebase-js-sdk/issues/7115)\n if (typeof DOMException !== 'undefined' && e instanceof DOMException) {\n throw new Base64DecodeError('Invalid base64 string: ' + e);\n } else {\n throw e;\n }\n }\n}\n\n/** Converts a binary string to a Base64 encoded string. */\nexport function encodeBase64(raw: string): string {\n return btoa(raw);\n}\n\n/** True if and only if the Base64 conversion functions are available. */\nexport function isBase64Available(): boolean {\n return typeof atob !== 'undefined';\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Timestamp } from '../protos/firestore_proto_api';\nimport { hardAssert } from '../util/assert';\nimport { ByteString } from '../util/byte_string';\n\n// A RegExp matching ISO 8601 UTC timestamps with optional fraction.\nconst ISO_TIMESTAMP_REG_EXP = new RegExp(\n /^\\d{4}-\\d\\d-\\d\\dT\\d\\d:\\d\\d:\\d\\d(?:\\.(\\d+))?Z$/\n);\n\n/**\n * Converts the possible Proto values for a timestamp value into a \"seconds and\n * nanos\" representation.\n */\nexport function normalizeTimestamp(date: Timestamp): {\n seconds: number;\n nanos: number;\n} {\n hardAssert(!!date, 0x986a, 'Cannot normalize null or undefined timestamp.');\n\n // The json interface (for the browser) will return an iso timestamp string,\n // while the proto js library (for node) will return a\n // google.protobuf.Timestamp instance.\n if (typeof date === 'string') {\n // The date string can have higher precision (nanos) than the Date class\n // (millis), so we do some custom parsing here.\n\n // Parse the nanos right out of the string.\n let nanos = 0;\n const fraction = ISO_TIMESTAMP_REG_EXP.exec(date);\n hardAssert(!!fraction, 0xb5de, 'invalid timestamp', {\n timestamp: date\n });\n if (fraction[1]) {\n // Pad the fraction out to 9 digits (nanos).\n let nanoStr = fraction[1];\n nanoStr = (nanoStr + '000000000').substr(0, 9);\n nanos = Number(nanoStr);\n }\n\n // Parse the date to get the seconds.\n const parsedDate = new Date(date);\n const seconds = Math.floor(parsedDate.getTime() / 1000);\n\n return { seconds, nanos };\n } else {\n // TODO(b/37282237): Use strings for Proto3 timestamps\n // assert(!this.options.useProto3Json,\n // 'The timestamp instance format requires Proto JS.');\n const seconds = normalizeNumber(date.seconds);\n const nanos = normalizeNumber(date.nanos);\n return { seconds, nanos };\n }\n}\n\n/**\n * Converts the possible Proto types for numbers into a JavaScript number.\n * Returns 0 if the value is not numeric.\n */\nexport function normalizeNumber(value: number | string | undefined): number {\n // TODO(bjornick): Handle int64 greater than 53 bits.\n if (typeof value === 'number') {\n return value;\n } else if (typeof value === 'string') {\n return Number(value);\n } else {\n return 0;\n }\n}\n\n/** Converts the possible Proto types for Blobs into a ByteString. */\nexport function normalizeByteString(blob: string | Uint8Array): ByteString {\n if (typeof blob === 'string') {\n return ByteString.fromBase64String(blob);\n } else {\n return ByteString.fromUint8Array(blob);\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isPlainObject } from '../util/input_validation';\n\nimport { Code, FirestoreError } from './error';\n\n/**\n * A list of data types Firestore objects may serialize in their toJSON implemenetations.\n * @private\n * @internal\n */\nexport type JsonTypeDesc =\n | 'object'\n | 'string'\n | 'number'\n | 'boolean'\n | 'null'\n | 'undefined';\n\n/**\n * An association of JsonTypeDesc values to their native types.\n * @private\n * @internal\n */\nexport type TSType = T extends 'object'\n ? object\n : T extends 'string'\n ? string\n : T extends 'number'\n ? number\n : T extends 'boolean'\n ? boolean\n : T extends 'null'\n ? null\n : T extends 'undefined'\n ? undefined\n : never;\n\n/**\n * The representation of a JSON object property name and its type value.\n * @private\n * @internal\n */\nexport interface Property {\n value?: TSType;\n typeString: JsonTypeDesc;\n}\n\n/**\n * A type Firestore data types may use to define the fields used in their JSON serialization.\n * @private\n * @internal\n */\nexport interface JsonSchema {\n [key: string]: Property;\n}\n\n/**\n * Associates the JSON property type to the native type and sets them to be Required.\n * @private\n * @internal\n */\nexport type Json = {\n [K in keyof T]: Required['value'];\n};\n\n/**\n * Helper function to define a JSON schema {@link Property}.\n * @private\n * @internal\n */\nexport function property(\n typeString: T,\n optionalValue?: TSType\n): Property {\n const result: Property = {\n typeString\n };\n if (optionalValue) {\n result.value = optionalValue;\n }\n return result;\n}\n\n/**\n * Validates the JSON object based on the provided schema, and narrows the type to the provided\n * JSON schema.\n * @private\n * @internal\n *\n * @param json A JSON object to validate.\n * @param scheme a {@link JsonSchema} that defines the properties to validate.\n * @returns true if the JSON schema exists within the object. Throws a FirestoreError otherwise.\n */\nexport function validateJSON(\n json: object,\n schema: S\n): json is Json {\n if (!isPlainObject(json)) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'JSON must be an object');\n }\n let error: string | undefined = undefined;\n for (const key in schema) {\n if (schema[key]) {\n const typeString = schema[key].typeString;\n const value: { value: unknown } | undefined =\n 'value' in schema[key] ? { value: schema[key].value } : undefined;\n if (!(key in json)) {\n error = `JSON missing required field: '${key}'`;\n break;\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const fieldValue = (json as any)[key];\n if (typeString && typeof fieldValue !== typeString) {\n error = `JSON field '${key}' must be a ${typeString}.`;\n break;\n } else if (value !== undefined && fieldValue !== value.value) {\n error = `Expected '${key}' field to equal '${value.value}'`;\n break;\n }\n }\n }\n if (error) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, error);\n }\n return true;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Code, FirestoreError } from '../util/error';\n// API extractor fails importing 'property' unless we also explicitly import 'Property'.\n// eslint-disable-next-line @typescript-eslint/no-unused-vars, unused-imports/no-unused-imports-ts\nimport { Property, property, validateJSON } from '../util/json_validation';\nimport { primitiveComparator } from '../util/misc';\n\n// The earliest date supported by Firestore timestamps (0001-01-01T00:00:00Z).\nconst MIN_SECONDS = -62135596800;\n\n// Number of nanoseconds in a millisecond.\nconst MS_TO_NANOS = 1e6;\n\n/**\n * A `Timestamp` represents a point in time independent of any time zone or\n * calendar, represented as seconds and fractions of seconds at nanosecond\n * resolution in UTC Epoch time.\n *\n * It is encoded using the Proleptic Gregorian Calendar which extends the\n * Gregorian calendar backwards to year one. It is encoded assuming all minutes\n * are 60 seconds long, i.e. leap seconds are \"smeared\" so that no leap second\n * table is needed for interpretation. Range is from 0001-01-01T00:00:00Z to\n * 9999-12-31T23:59:59.999999999Z.\n *\n * For examples and further specifications, refer to the\n * {@link https://github.com/google/protobuf/blob/master/src/google/protobuf/timestamp.proto | Timestamp definition}.\n */\nexport class Timestamp {\n /**\n * Creates a new timestamp with the current date, with millisecond precision.\n *\n * @returns a new timestamp representing the current date.\n */\n static now(): Timestamp {\n return Timestamp.fromMillis(Date.now());\n }\n\n /**\n * Creates a new timestamp from the given date.\n *\n * @param date - The date to initialize the `Timestamp` from.\n * @returns A new `Timestamp` representing the same point in time as the given\n * date.\n */\n static fromDate(date: Date): Timestamp {\n return Timestamp.fromMillis(date.getTime());\n }\n\n /**\n * Creates a new timestamp from the given number of milliseconds.\n *\n * @param milliseconds - Number of milliseconds since Unix epoch\n * 1970-01-01T00:00:00Z.\n * @returns A new `Timestamp` representing the same point in time as the given\n * number of milliseconds.\n */\n static fromMillis(milliseconds: number): Timestamp {\n const seconds = Math.floor(milliseconds / 1000);\n const nanos = Math.floor((milliseconds - seconds * 1000) * MS_TO_NANOS);\n return new Timestamp(seconds, nanos);\n }\n\n /**\n * Creates a new timestamp.\n *\n * @param seconds - The number of seconds of UTC time since Unix epoch\n * 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to\n * 9999-12-31T23:59:59Z inclusive.\n * @param nanoseconds - The non-negative fractions of a second at nanosecond\n * resolution. Negative second values with fractions must still have\n * non-negative nanoseconds values that count forward in time. Must be\n * from 0 to 999,999,999 inclusive.\n */\n constructor(\n /**\n * The number of seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z.\n */\n readonly seconds: number,\n /**\n * The fractions of a second at nanosecond resolution.*\n */\n readonly nanoseconds: number\n ) {\n if (nanoseconds < 0) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Timestamp nanoseconds out of range: ' + nanoseconds\n );\n }\n if (nanoseconds >= 1e9) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Timestamp nanoseconds out of range: ' + nanoseconds\n );\n }\n if (seconds < MIN_SECONDS) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Timestamp seconds out of range: ' + seconds\n );\n }\n // This will break in the year 10,000.\n if (seconds >= 253402300800) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Timestamp seconds out of range: ' + seconds\n );\n }\n }\n\n /**\n * Converts a `Timestamp` to a JavaScript `Date` object. This conversion\n * causes a loss of precision since `Date` objects only support millisecond\n * precision.\n *\n * @returns JavaScript `Date` object representing the same point in time as\n * this `Timestamp`, with millisecond precision.\n */\n toDate(): Date {\n return new Date(this.toMillis());\n }\n\n /**\n * Converts a `Timestamp` to a numeric timestamp (in milliseconds since\n * epoch). This operation causes a loss of precision.\n *\n * @returns The point in time corresponding to this timestamp, represented as\n * the number of milliseconds since Unix epoch 1970-01-01T00:00:00Z.\n */\n toMillis(): number {\n return this.seconds * 1000 + this.nanoseconds / MS_TO_NANOS;\n }\n\n _compareTo(other: Timestamp): number {\n if (this.seconds === other.seconds) {\n return primitiveComparator(this.nanoseconds, other.nanoseconds);\n }\n return primitiveComparator(this.seconds, other.seconds);\n }\n\n /**\n * Returns true if this `Timestamp` is equal to the provided one.\n *\n * @param other - The `Timestamp` to compare against.\n * @returns true if this `Timestamp` is equal to the provided one.\n */\n isEqual(other: Timestamp): boolean {\n return (\n other.seconds === this.seconds && other.nanoseconds === this.nanoseconds\n );\n }\n\n /** Returns a textual representation of this `Timestamp`. */\n toString(): string {\n return (\n 'Timestamp(seconds=' +\n this.seconds +\n ', nanoseconds=' +\n this.nanoseconds +\n ')'\n );\n }\n\n static _jsonSchemaVersion: string = 'firestore/timestamp/1.0';\n static _jsonSchema = {\n type: property('string', Timestamp._jsonSchemaVersion),\n seconds: property('number'),\n nanoseconds: property('number')\n };\n\n /**\n * Returns a JSON-serializable representation of this `Timestamp`.\n */\n toJSON(): { seconds: number; nanoseconds: number; type: string } {\n return {\n type: Timestamp._jsonSchemaVersion,\n seconds: this.seconds,\n nanoseconds: this.nanoseconds\n };\n }\n\n /**\n * Builds a `Timestamp` instance from a JSON object created by {@link Timestamp.toJSON}.\n */\n static fromJSON(json: object): Timestamp {\n if (validateJSON(json, Timestamp._jsonSchema)) {\n return new Timestamp(json.seconds, json.nanoseconds);\n }\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Unexpected error creating Timestamp from JSON.'\n );\n }\n\n /**\n * Converts this object to a primitive string, which allows `Timestamp` objects\n * to be compared using the `>`, `<=`, `>=` and `>` operators.\n */\n valueOf(): string {\n // This method returns a string of the form . where\n // is translated to have a non-negative value and both \n // and are left-padded with zeroes to be a consistent length.\n // Strings with this format then have a lexicographical ordering that matches\n // the expected ordering. The translation is done to avoid having\n // a leading negative sign (i.e. a leading '-' character) in its string\n // representation, which would affect its lexicographical ordering.\n const adjustedSeconds = this.seconds - MIN_SECONDS;\n // Note: Up to 12 decimal digits are required to represent all valid\n // 'seconds' values.\n const formattedSeconds = String(adjustedSeconds).padStart(12, '0');\n const formattedNanoseconds = String(this.nanoseconds).padStart(9, '0');\n return formattedSeconds + '.' + formattedNanoseconds;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Timestamp } from '../lite-api/timestamp';\nimport {\n Value as ProtoValue,\n MapValue as ProtoMapValue\n} from '../protos/firestore_proto_api';\n\nimport { normalizeTimestamp } from './normalize';\n\n/**\n * Represents a locally-applied ServerTimestamp.\n *\n * Server Timestamps are backed by MapValues that contain an internal field\n * `__type__` with a value of `server_timestamp`. The previous value and local\n * write time are stored in its `__previous_value__` and `__local_write_time__`\n * fields respectively.\n *\n * Notes:\n * - ServerTimestampValue instances are created as the result of applying a\n * transform. They can only exist in the local view of a document. Therefore\n * they do not need to be parsed or serialized.\n * - When evaluated locally (e.g. for snapshot.data()), they by default\n * evaluate to `null`. This behavior can be configured by passing custom\n * FieldValueOptions to value().\n * - With respect to other ServerTimestampValues, they sort by their\n * localWriteTime.\n */\n\nconst SERVER_TIMESTAMP_SENTINEL = 'server_timestamp';\nconst TYPE_KEY = '__type__';\nconst PREVIOUS_VALUE_KEY = '__previous_value__';\nconst LOCAL_WRITE_TIME_KEY = '__local_write_time__';\n\nexport function isServerTimestamp(value: ProtoValue | null): boolean {\n const type = (value?.mapValue?.fields || {})[TYPE_KEY]?.stringValue;\n return type === SERVER_TIMESTAMP_SENTINEL;\n}\n\n/**\n * Creates a new ServerTimestamp proto value (using the internal format).\n */\nexport function serverTimestamp(\n localWriteTime: Timestamp,\n previousValue: ProtoValue | null\n): ProtoValue {\n const mapValue: ProtoMapValue = {\n fields: {\n [TYPE_KEY]: {\n stringValue: SERVER_TIMESTAMP_SENTINEL\n },\n [LOCAL_WRITE_TIME_KEY]: {\n timestampValue: {\n seconds: localWriteTime.seconds,\n nanos: localWriteTime.nanoseconds\n }\n }\n }\n };\n\n // We should avoid storing deeply nested server timestamp map values\n // because we never use the intermediate \"previous values\".\n // For example:\n // previous: 42L, add: t1, result: t1 -> 42L\n // previous: t1, add: t2, result: t2 -> 42L (NOT t2 -> t1 -> 42L)\n // previous: t2, add: t3, result: t3 -> 42L (NOT t3 -> t2 -> t1 -> 42L)\n // `getPreviousValue` recursively traverses server timestamps to find the\n // least recent Value.\n if (previousValue && isServerTimestamp(previousValue)) {\n previousValue = getPreviousValue(previousValue);\n }\n if (previousValue) {\n mapValue.fields![PREVIOUS_VALUE_KEY] = previousValue;\n }\n\n return { mapValue };\n}\n\n/**\n * Returns the value of the field before this ServerTimestamp was set.\n *\n * Preserving the previous values allows the user to display the last resoled\n * value until the backend responds with the timestamp.\n */\nexport function getPreviousValue(value: ProtoValue): ProtoValue | null {\n const previousValue = value.mapValue!.fields![PREVIOUS_VALUE_KEY];\n\n if (isServerTimestamp(previousValue)) {\n return getPreviousValue(previousValue);\n }\n return previousValue;\n}\n\n/**\n * Returns the local time at which this timestamp was first set.\n */\nexport function getLocalWriteTime(value: ProtoValue): Timestamp {\n const localWriteTime = normalizeTimestamp(\n value.mapValue!.fields![LOCAL_WRITE_TIME_KEY].timestampValue!\n );\n return new Timestamp(localWriteTime.seconds, localWriteTime.nanos);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DatabaseId } from '../core/database_info';\nimport {\n ArrayValue,\n LatLng,\n MapValue,\n Timestamp,\n Value as ProtoValue,\n Value\n} from '../protos/firestore_proto_api';\nimport { fail } from '../util/assert';\nimport {\n arrayEquals,\n compareUtf8Strings,\n primitiveComparator\n} from '../util/misc';\nimport { forEach, objectSize } from '../util/obj';\nimport { isNegativeZero } from '../util/types';\n\nimport { DocumentKey } from './document_key';\nimport {\n normalizeByteString,\n normalizeNumber,\n normalizeTimestamp\n} from './normalize';\nimport {\n getLocalWriteTime,\n getPreviousValue,\n isServerTimestamp\n} from './server_timestamps';\nimport { TypeOrder } from './type_order';\n\nexport const TYPE_KEY = '__type__';\nconst MAX_VALUE_TYPE = '__max__';\nexport const MAX_VALUE: Value = {\n mapValue: {\n fields: {\n '__type__': { stringValue: MAX_VALUE_TYPE }\n }\n }\n};\n\nexport const VECTOR_VALUE_SENTINEL = '__vector__';\nexport const VECTOR_MAP_VECTORS_KEY = 'value';\n\nexport const MIN_VALUE: Value = {\n nullValue: 'NULL_VALUE'\n};\n\n/** Extracts the backend's type order for the provided value. */\nexport function typeOrder(value: Value): TypeOrder {\n if ('nullValue' in value) {\n return TypeOrder.NullValue;\n } else if ('booleanValue' in value) {\n return TypeOrder.BooleanValue;\n } else if ('integerValue' in value || 'doubleValue' in value) {\n return TypeOrder.NumberValue;\n } else if ('timestampValue' in value) {\n return TypeOrder.TimestampValue;\n } else if ('stringValue' in value) {\n return TypeOrder.StringValue;\n } else if ('bytesValue' in value) {\n return TypeOrder.BlobValue;\n } else if ('referenceValue' in value) {\n return TypeOrder.RefValue;\n } else if ('geoPointValue' in value) {\n return TypeOrder.GeoPointValue;\n } else if ('arrayValue' in value) {\n return TypeOrder.ArrayValue;\n } else if ('mapValue' in value) {\n if (isServerTimestamp(value)) {\n return TypeOrder.ServerTimestampValue;\n } else if (isMaxValue(value)) {\n return TypeOrder.MaxValue;\n } else if (isVectorValue(value)) {\n return TypeOrder.VectorValue;\n }\n return TypeOrder.ObjectValue;\n } else {\n return fail(0x6e87, 'Invalid value type', { value });\n }\n}\n\n/** Tests `left` and `right` for equality based on the backend semantics. */\nexport function valueEquals(left: Value, right: Value): boolean {\n if (left === right) {\n return true;\n }\n\n const leftType = typeOrder(left);\n const rightType = typeOrder(right);\n if (leftType !== rightType) {\n return false;\n }\n\n switch (leftType) {\n case TypeOrder.NullValue:\n return true;\n case TypeOrder.BooleanValue:\n return left.booleanValue === right.booleanValue;\n case TypeOrder.ServerTimestampValue:\n return getLocalWriteTime(left).isEqual(getLocalWriteTime(right));\n case TypeOrder.TimestampValue:\n return timestampEquals(left, right);\n case TypeOrder.StringValue:\n return left.stringValue === right.stringValue;\n case TypeOrder.BlobValue:\n return blobEquals(left, right);\n case TypeOrder.RefValue:\n return left.referenceValue === right.referenceValue;\n case TypeOrder.GeoPointValue:\n return geoPointEquals(left, right);\n case TypeOrder.NumberValue:\n return numberEquals(left, right);\n case TypeOrder.ArrayValue:\n return arrayEquals(\n left.arrayValue!.values || [],\n right.arrayValue!.values || [],\n valueEquals\n );\n case TypeOrder.VectorValue:\n case TypeOrder.ObjectValue:\n return objectEquals(left, right);\n case TypeOrder.MaxValue:\n return true;\n default:\n return fail(0xcbf8, 'Unexpected value type', { left });\n }\n}\n\nfunction timestampEquals(left: Value, right: Value): boolean {\n if (\n typeof left.timestampValue === 'string' &&\n typeof right.timestampValue === 'string' &&\n left.timestampValue.length === right.timestampValue.length\n ) {\n // Use string equality for ISO 8601 timestamps\n return left.timestampValue === right.timestampValue;\n }\n\n const leftTimestamp = normalizeTimestamp(left.timestampValue!);\n const rightTimestamp = normalizeTimestamp(right.timestampValue!);\n return (\n leftTimestamp.seconds === rightTimestamp.seconds &&\n leftTimestamp.nanos === rightTimestamp.nanos\n );\n}\n\nfunction geoPointEquals(left: Value, right: Value): boolean {\n return (\n normalizeNumber(left.geoPointValue!.latitude) ===\n normalizeNumber(right.geoPointValue!.latitude) &&\n normalizeNumber(left.geoPointValue!.longitude) ===\n normalizeNumber(right.geoPointValue!.longitude)\n );\n}\n\nfunction blobEquals(left: Value, right: Value): boolean {\n return normalizeByteString(left.bytesValue!).isEqual(\n normalizeByteString(right.bytesValue!)\n );\n}\n\nexport function numberEquals(left: Value, right: Value): boolean {\n if ('integerValue' in left && 'integerValue' in right) {\n return (\n normalizeNumber(left.integerValue) === normalizeNumber(right.integerValue)\n );\n } else if ('doubleValue' in left && 'doubleValue' in right) {\n const n1 = normalizeNumber(left.doubleValue!);\n const n2 = normalizeNumber(right.doubleValue!);\n\n if (n1 === n2) {\n return isNegativeZero(n1) === isNegativeZero(n2);\n } else {\n return isNaN(n1) && isNaN(n2);\n }\n }\n\n return false;\n}\n\nfunction objectEquals(left: Value, right: Value): boolean {\n const leftMap = left.mapValue!.fields || {};\n const rightMap = right.mapValue!.fields || {};\n\n if (objectSize(leftMap) !== objectSize(rightMap)) {\n return false;\n }\n\n for (const key in leftMap) {\n if (leftMap.hasOwnProperty(key)) {\n if (\n rightMap[key] === undefined ||\n !valueEquals(leftMap[key], rightMap[key])\n ) {\n return false;\n }\n }\n }\n return true;\n}\n\n/** Returns true if the ArrayValue contains the specified element. */\nexport function arrayValueContains(\n haystack: ArrayValue,\n needle: Value\n): boolean {\n return (\n (haystack.values || []).find(v => valueEquals(v, needle)) !== undefined\n );\n}\n\nexport function valueCompare(left: Value, right: Value): number {\n if (left === right) {\n return 0;\n }\n\n const leftType = typeOrder(left);\n const rightType = typeOrder(right);\n\n if (leftType !== rightType) {\n return primitiveComparator(leftType, rightType);\n }\n\n switch (leftType) {\n case TypeOrder.NullValue:\n case TypeOrder.MaxValue:\n return 0;\n case TypeOrder.BooleanValue:\n return primitiveComparator(left.booleanValue!, right.booleanValue!);\n case TypeOrder.NumberValue:\n return compareNumbers(left, right);\n case TypeOrder.TimestampValue:\n return compareTimestamps(left.timestampValue!, right.timestampValue!);\n case TypeOrder.ServerTimestampValue:\n return compareTimestamps(\n getLocalWriteTime(left),\n getLocalWriteTime(right)\n );\n case TypeOrder.StringValue:\n return compareUtf8Strings(left.stringValue!, right.stringValue!);\n case TypeOrder.BlobValue:\n return compareBlobs(left.bytesValue!, right.bytesValue!);\n case TypeOrder.RefValue:\n return compareReferences(left.referenceValue!, right.referenceValue!);\n case TypeOrder.GeoPointValue:\n return compareGeoPoints(left.geoPointValue!, right.geoPointValue!);\n case TypeOrder.ArrayValue:\n return compareArrays(left.arrayValue!, right.arrayValue!);\n case TypeOrder.VectorValue:\n return compareVectors(left.mapValue!, right.mapValue!);\n case TypeOrder.ObjectValue:\n return compareMaps(left.mapValue!, right.mapValue!);\n default:\n throw fail(0x5ae0, 'Invalid value type', { leftType });\n }\n}\n\nfunction compareNumbers(left: Value, right: Value): number {\n const leftNumber = normalizeNumber(left.integerValue || left.doubleValue);\n const rightNumber = normalizeNumber(right.integerValue || right.doubleValue);\n\n if (leftNumber < rightNumber) {\n return -1;\n } else if (leftNumber > rightNumber) {\n return 1;\n } else if (leftNumber === rightNumber) {\n return 0;\n } else {\n // one or both are NaN.\n if (isNaN(leftNumber)) {\n return isNaN(rightNumber) ? 0 : -1;\n } else {\n return 1;\n }\n }\n}\n\nfunction compareTimestamps(left: Timestamp, right: Timestamp): number {\n if (\n typeof left === 'string' &&\n typeof right === 'string' &&\n left.length === right.length\n ) {\n return primitiveComparator(left, right);\n }\n\n const leftTimestamp = normalizeTimestamp(left);\n const rightTimestamp = normalizeTimestamp(right);\n\n const comparison = primitiveComparator(\n leftTimestamp.seconds,\n rightTimestamp.seconds\n );\n if (comparison !== 0) {\n return comparison;\n }\n return primitiveComparator(leftTimestamp.nanos, rightTimestamp.nanos);\n}\n\nfunction compareReferences(leftPath: string, rightPath: string): number {\n const leftSegments = leftPath.split('/');\n const rightSegments = rightPath.split('/');\n for (let i = 0; i < leftSegments.length && i < rightSegments.length; i++) {\n const comparison = primitiveComparator(leftSegments[i], rightSegments[i]);\n if (comparison !== 0) {\n return comparison;\n }\n }\n return primitiveComparator(leftSegments.length, rightSegments.length);\n}\n\nfunction compareGeoPoints(left: LatLng, right: LatLng): number {\n const comparison = primitiveComparator(\n normalizeNumber(left.latitude),\n normalizeNumber(right.latitude)\n );\n if (comparison !== 0) {\n return comparison;\n }\n return primitiveComparator(\n normalizeNumber(left.longitude),\n normalizeNumber(right.longitude)\n );\n}\n\nfunction compareBlobs(\n left: string | Uint8Array,\n right: string | Uint8Array\n): number {\n const leftBytes = normalizeByteString(left);\n const rightBytes = normalizeByteString(right);\n return leftBytes.compareTo(rightBytes);\n}\n\nfunction compareArrays(left: ArrayValue, right: ArrayValue): number {\n const leftArray = left.values || [];\n const rightArray = right.values || [];\n\n for (let i = 0; i < leftArray.length && i < rightArray.length; ++i) {\n const compare = valueCompare(leftArray[i], rightArray[i]);\n if (compare) {\n return compare;\n }\n }\n return primitiveComparator(leftArray.length, rightArray.length);\n}\n\nfunction compareVectors(left: MapValue, right: MapValue): number {\n const leftMap = left.fields || {};\n const rightMap = right.fields || {};\n\n // The vector is a map, but only vector value is compared.\n const leftArrayValue = leftMap[VECTOR_MAP_VECTORS_KEY]?.arrayValue;\n const rightArrayValue = rightMap[VECTOR_MAP_VECTORS_KEY]?.arrayValue;\n\n const lengthCompare = primitiveComparator(\n leftArrayValue?.values?.length || 0,\n rightArrayValue?.values?.length || 0\n );\n if (lengthCompare !== 0) {\n return lengthCompare;\n }\n\n return compareArrays(leftArrayValue!, rightArrayValue!);\n}\n\nfunction compareMaps(left: MapValue, right: MapValue): number {\n if (left === MAX_VALUE.mapValue && right === MAX_VALUE.mapValue) {\n return 0;\n } else if (left === MAX_VALUE.mapValue) {\n return 1;\n } else if (right === MAX_VALUE.mapValue) {\n return -1;\n }\n\n const leftMap = left.fields || {};\n const leftKeys = Object.keys(leftMap);\n const rightMap = right.fields || {};\n const rightKeys = Object.keys(rightMap);\n\n // Even though MapValues are likely sorted correctly based on their insertion\n // order (e.g. when received from the backend), local modifications can bring\n // elements out of order. We need to re-sort the elements to ensure that\n // canonical IDs are independent of insertion order.\n leftKeys.sort();\n rightKeys.sort();\n\n for (let i = 0; i < leftKeys.length && i < rightKeys.length; ++i) {\n const keyCompare = compareUtf8Strings(leftKeys[i], rightKeys[i]);\n if (keyCompare !== 0) {\n return keyCompare;\n }\n const compare = valueCompare(leftMap[leftKeys[i]], rightMap[rightKeys[i]]);\n if (compare !== 0) {\n return compare;\n }\n }\n\n return primitiveComparator(leftKeys.length, rightKeys.length);\n}\n\n/**\n * Generates the canonical ID for the provided field value (as used in Target\n * serialization).\n */\nexport function canonicalId(value: Value): string {\n return canonifyValue(value);\n}\n\nfunction canonifyValue(value: Value): string {\n if ('nullValue' in value) {\n return 'null';\n } else if ('booleanValue' in value) {\n return '' + value.booleanValue!;\n } else if ('integerValue' in value) {\n return '' + value.integerValue!;\n } else if ('doubleValue' in value) {\n return '' + value.doubleValue!;\n } else if ('timestampValue' in value) {\n return canonifyTimestamp(value.timestampValue!);\n } else if ('stringValue' in value) {\n return value.stringValue!;\n } else if ('bytesValue' in value) {\n return canonifyByteString(value.bytesValue!);\n } else if ('referenceValue' in value) {\n return canonifyReference(value.referenceValue!);\n } else if ('geoPointValue' in value) {\n return canonifyGeoPoint(value.geoPointValue!);\n } else if ('arrayValue' in value) {\n return canonifyArray(value.arrayValue!);\n } else if ('mapValue' in value) {\n return canonifyMap(value.mapValue!);\n } else {\n return fail(0xee4d, 'Invalid value type', { value });\n }\n}\n\nfunction canonifyByteString(byteString: string | Uint8Array): string {\n return normalizeByteString(byteString).toBase64();\n}\n\nfunction canonifyTimestamp(timestamp: Timestamp): string {\n const normalizedTimestamp = normalizeTimestamp(timestamp);\n return `time(${normalizedTimestamp.seconds},${normalizedTimestamp.nanos})`;\n}\n\nfunction canonifyGeoPoint(geoPoint: LatLng): string {\n return `geo(${geoPoint.latitude},${geoPoint.longitude})`;\n}\n\nfunction canonifyReference(referenceValue: string): string {\n return DocumentKey.fromName(referenceValue).toString();\n}\n\nfunction canonifyMap(mapValue: MapValue): string {\n // Iteration order in JavaScript is not guaranteed. To ensure that we generate\n // matching canonical IDs for identical maps, we need to sort the keys.\n const sortedKeys = Object.keys(mapValue.fields || {}).sort();\n\n let result = '{';\n let first = true;\n for (const key of sortedKeys) {\n if (!first) {\n result += ',';\n } else {\n first = false;\n }\n result += `${key}:${canonifyValue(mapValue.fields![key])}`;\n }\n return result + '}';\n}\n\nfunction canonifyArray(arrayValue: ArrayValue): string {\n let result = '[';\n let first = true;\n for (const value of arrayValue.values || []) {\n if (!first) {\n result += ',';\n } else {\n first = false;\n }\n result += canonifyValue(value);\n }\n return result + ']';\n}\n\n/**\n * Returns an approximate (and wildly inaccurate) in-memory size for the field\n * value.\n *\n * The memory size takes into account only the actual user data as it resides\n * in memory and ignores object overhead.\n */\nexport function estimateByteSize(value: Value): number {\n switch (typeOrder(value)) {\n case TypeOrder.NullValue:\n return 4;\n case TypeOrder.BooleanValue:\n return 4;\n case TypeOrder.NumberValue:\n return 8;\n case TypeOrder.TimestampValue:\n // Timestamps are made up of two distinct numbers (seconds + nanoseconds)\n return 16;\n case TypeOrder.ServerTimestampValue:\n const previousValue = getPreviousValue(value);\n return previousValue ? 16 + estimateByteSize(previousValue) : 16;\n case TypeOrder.StringValue:\n // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures:\n // \"JavaScript's String type is [...] a set of elements of 16-bit unsigned\n // integer values\"\n return value.stringValue!.length * 2;\n case TypeOrder.BlobValue:\n return normalizeByteString(value.bytesValue!).approximateByteSize();\n case TypeOrder.RefValue:\n return value.referenceValue!.length;\n case TypeOrder.GeoPointValue:\n // GeoPoints are made up of two distinct numbers (latitude + longitude)\n return 16;\n case TypeOrder.ArrayValue:\n return estimateArrayByteSize(value.arrayValue!);\n case TypeOrder.VectorValue:\n case TypeOrder.ObjectValue:\n return estimateMapByteSize(value.mapValue!);\n default:\n throw fail(0x34ae, 'Invalid value type', { value });\n }\n}\n\nfunction estimateMapByteSize(mapValue: MapValue): number {\n let size = 0;\n forEach(mapValue.fields, (key, val) => {\n size += key.length + estimateByteSize(val);\n });\n return size;\n}\n\nfunction estimateArrayByteSize(arrayValue: ArrayValue): number {\n return (arrayValue.values || []).reduce(\n (previousSize, value) => previousSize + estimateByteSize(value),\n 0\n );\n}\n\n/** Returns a reference value for the provided database and key. */\nexport function refValue(databaseId: DatabaseId, key: DocumentKey): Value {\n return {\n referenceValue: `projects/${databaseId.projectId}/databases/${\n databaseId.database\n }/documents/${key.path.canonicalString()}`\n };\n}\n\n/** Returns true if `value` is an IntegerValue . */\nexport function isInteger(\n value?: Value | null\n): value is { integerValue: string | number } {\n return !!value && 'integerValue' in value;\n}\n\n/** Returns true if `value` is a DoubleValue. */\nexport function isDouble(\n value?: Value | null\n): value is { doubleValue: string | number } {\n return !!value && 'doubleValue' in value;\n}\n\n/** Returns true if `value` is either an IntegerValue or a DoubleValue. */\nexport function isNumber(value?: Value | null): boolean {\n return isInteger(value) || isDouble(value);\n}\n\n/** Returns true if `value` is an ArrayValue. */\nexport function isArray(\n value?: Value | null\n): value is { arrayValue: ArrayValue } {\n return !!value && 'arrayValue' in value;\n}\n\n/** Returns true if `value` is a ReferenceValue. */\nexport function isReferenceValue(\n value?: Value | null\n): value is { referenceValue: string } {\n return !!value && 'referenceValue' in value;\n}\n\n/** Returns true if `value` is a NullValue. */\nexport function isNullValue(\n value?: Value | null\n): value is { nullValue: 'NULL_VALUE' } {\n return !!value && 'nullValue' in value;\n}\n\n/** Returns true if `value` is NaN. */\nexport function isNanValue(\n value?: Value | null\n): value is { doubleValue: 'NaN' | number } {\n return !!value && 'doubleValue' in value && isNaN(Number(value.doubleValue));\n}\n\n/** Returns true if `value` is a MapValue. */\nexport function isMapValue(\n value?: Value | null\n): value is { mapValue: MapValue } {\n return !!value && 'mapValue' in value;\n}\n\n/** Returns true if `value` is a VetorValue. */\nexport function isVectorValue(value: ProtoValue | null): boolean {\n const type = (value?.mapValue?.fields || {})[TYPE_KEY]?.stringValue;\n return type === VECTOR_VALUE_SENTINEL;\n}\n\n/** Creates a deep copy of `source`. */\nexport function deepClone(source: Value): Value {\n if (source.geoPointValue) {\n return { geoPointValue: { ...source.geoPointValue } };\n } else if (\n source.timestampValue &&\n typeof source.timestampValue === 'object'\n ) {\n return { timestampValue: { ...source.timestampValue } };\n } else if (source.mapValue) {\n const target: Value = { mapValue: { fields: {} } };\n forEach(\n source.mapValue.fields,\n (key, val) => (target.mapValue!.fields![key] = deepClone(val))\n );\n return target;\n } else if (source.arrayValue) {\n const target: Value = { arrayValue: { values: [] } };\n for (let i = 0; i < (source.arrayValue.values || []).length; ++i) {\n target.arrayValue!.values![i] = deepClone(source.arrayValue.values![i]);\n }\n return target;\n } else {\n return { ...source };\n }\n}\n\n/** Returns true if the Value represents the canonical {@link #MAX_VALUE} . */\nexport function isMaxValue(value: Value): boolean {\n return (\n (((value.mapValue || {}).fields || {})['__type__'] || {}).stringValue ===\n MAX_VALUE_TYPE\n );\n}\n\nexport const MIN_VECTOR_VALUE = {\n mapValue: {\n fields: {\n [TYPE_KEY]: { stringValue: VECTOR_VALUE_SENTINEL },\n [VECTOR_MAP_VECTORS_KEY]: {\n arrayValue: {}\n }\n }\n }\n};\n\n/** Returns the lowest value for the given value type (inclusive). */\nexport function valuesGetLowerBound(value: Value): Value {\n if ('nullValue' in value) {\n return MIN_VALUE;\n } else if ('booleanValue' in value) {\n return { booleanValue: false };\n } else if ('integerValue' in value || 'doubleValue' in value) {\n return { doubleValue: NaN };\n } else if ('timestampValue' in value) {\n return { timestampValue: { seconds: Number.MIN_SAFE_INTEGER } };\n } else if ('stringValue' in value) {\n return { stringValue: '' };\n } else if ('bytesValue' in value) {\n return { bytesValue: '' };\n } else if ('referenceValue' in value) {\n return refValue(DatabaseId.empty(), DocumentKey.empty());\n } else if ('geoPointValue' in value) {\n return { geoPointValue: { latitude: -90, longitude: -180 } };\n } else if ('arrayValue' in value) {\n return { arrayValue: {} };\n } else if ('mapValue' in value) {\n if (isVectorValue(value)) {\n return MIN_VECTOR_VALUE;\n }\n return { mapValue: {} };\n } else {\n return fail(0x8c66, 'Invalid value type', { value });\n }\n}\n\n/** Returns the largest value for the given value type (exclusive). */\nexport function valuesGetUpperBound(value: Value): Value {\n if ('nullValue' in value) {\n return { booleanValue: false };\n } else if ('booleanValue' in value) {\n return { doubleValue: NaN };\n } else if ('integerValue' in value || 'doubleValue' in value) {\n return { timestampValue: { seconds: Number.MIN_SAFE_INTEGER } };\n } else if ('timestampValue' in value) {\n return { stringValue: '' };\n } else if ('stringValue' in value) {\n return { bytesValue: '' };\n } else if ('bytesValue' in value) {\n return refValue(DatabaseId.empty(), DocumentKey.empty());\n } else if ('referenceValue' in value) {\n return { geoPointValue: { latitude: -90, longitude: -180 } };\n } else if ('geoPointValue' in value) {\n return { arrayValue: {} };\n } else if ('arrayValue' in value) {\n return MIN_VECTOR_VALUE;\n } else if ('mapValue' in value) {\n if (isVectorValue(value)) {\n return { mapValue: {} };\n }\n return MAX_VALUE;\n } else {\n return fail(0xf207, 'Invalid value type', { value });\n }\n}\n\nexport function lowerBoundCompare(\n left: { value: Value; inclusive: boolean },\n right: { value: Value; inclusive: boolean }\n): number {\n const cmp = valueCompare(left.value, right.value);\n if (cmp !== 0) {\n return cmp;\n }\n\n if (left.inclusive && !right.inclusive) {\n return -1;\n } else if (!left.inclusive && right.inclusive) {\n return 1;\n }\n\n return 0;\n}\n\nexport function upperBoundCompare(\n left: { value: Value; inclusive: boolean },\n right: { value: Value; inclusive: boolean }\n): number {\n const cmp = valueCompare(left.value, right.value);\n if (cmp !== 0) {\n return cmp;\n }\n\n if (left.inclusive && !right.inclusive) {\n return 1;\n } else if (!left.inclusive && right.inclusive) {\n return -1;\n }\n\n return 0;\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { isReferenceValue, valueCompare, valueEquals } from '../model/values';\nimport { Value as ProtoValue } from '../protos/firestore_proto_api';\nimport { debugAssert } from '../util/assert';\n\nimport { Direction, OrderBy } from './order_by';\n\n/**\n * Represents a bound of a query.\n *\n * The bound is specified with the given components representing a position and\n * whether it's just before or just after the position (relative to whatever the\n * query order is).\n *\n * The position represents a logical index position for a query. It's a prefix\n * of values for the (potentially implicit) order by clauses of a query.\n *\n * Bound provides a function to determine whether a document comes before or\n * after a bound. This is influenced by whether the position is just before or\n * just after the provided values.\n */\nexport class Bound {\n constructor(readonly position: ProtoValue[], readonly inclusive: boolean) {}\n}\n\nfunction boundCompareToDocument(\n bound: Bound,\n orderBy: OrderBy[],\n doc: Document\n): number {\n debugAssert(\n bound.position.length <= orderBy.length,\n \"Bound has more components than query's orderBy\"\n );\n let comparison = 0;\n for (let i = 0; i < bound.position.length; i++) {\n const orderByComponent = orderBy[i];\n const component = bound.position[i];\n if (orderByComponent.field.isKeyField()) {\n debugAssert(\n isReferenceValue(component),\n 'Bound has a non-key value where the key path is being used.'\n );\n comparison = DocumentKey.comparator(\n DocumentKey.fromName(component.referenceValue),\n doc.key\n );\n } else {\n const docValue = doc.data.field(orderByComponent.field);\n debugAssert(\n docValue !== null,\n 'Field should exist since document matched the orderBy already.'\n );\n comparison = valueCompare(component, docValue);\n }\n if (orderByComponent.dir === Direction.DESCENDING) {\n comparison = comparison * -1;\n }\n if (comparison !== 0) {\n break;\n }\n }\n return comparison;\n}\n\n/**\n * Returns true if a document sorts after a bound using the provided sort\n * order.\n */\nexport function boundSortsAfterDocument(\n bound: Bound,\n orderBy: OrderBy[],\n doc: Document\n): boolean {\n const comparison = boundCompareToDocument(bound, orderBy, doc);\n return bound.inclusive ? comparison >= 0 : comparison > 0;\n}\n\n/**\n * Returns true if a document sorts before a bound using the provided sort\n * order.\n */\nexport function boundSortsBeforeDocument(\n bound: Bound,\n orderBy: OrderBy[],\n doc: Document\n): boolean {\n const comparison = boundCompareToDocument(bound, orderBy, doc);\n return bound.inclusive ? comparison <= 0 : comparison < 0;\n}\n\nexport function boundEquals(left: Bound | null, right: Bound | null): boolean {\n if (left === null) {\n return right === null;\n } else if (right === null) {\n return false;\n }\n\n if (\n left.inclusive !== right.inclusive ||\n left.position.length !== right.position.length\n ) {\n return false;\n }\n for (let i = 0; i < left.position.length; i++) {\n const leftPosition = left.position[i];\n const rightPosition = right.position[i];\n if (!valueEquals(leftPosition, rightPosition)) {\n return false;\n }\n }\n return true;\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { FieldPath } from '../model/path';\nimport {\n arrayValueContains,\n canonicalId,\n isArray,\n isReferenceValue,\n typeOrder,\n valueCompare,\n valueEquals\n} from '../model/values';\nimport { Value as ProtoValue } from '../protos/firestore_proto_api';\nimport { debugAssert, fail } from '../util/assert';\n\n// The operator of a FieldFilter\nexport const enum Operator {\n LESS_THAN = '<',\n LESS_THAN_OR_EQUAL = '<=',\n EQUAL = '==',\n NOT_EQUAL = '!=',\n GREATER_THAN = '>',\n GREATER_THAN_OR_EQUAL = '>=',\n ARRAY_CONTAINS = 'array-contains',\n IN = 'in',\n NOT_IN = 'not-in',\n ARRAY_CONTAINS_ANY = 'array-contains-any'\n}\n\n// The operator of a CompositeFilter\nexport const enum CompositeOperator {\n OR = 'or',\n AND = 'and'\n}\n\nexport abstract class Filter {\n abstract matches(doc: Document): boolean;\n\n abstract getFlattenedFilters(): readonly FieldFilter[];\n\n abstract getFilters(): Filter[];\n}\n\nexport class FieldFilter extends Filter {\n protected constructor(\n public readonly field: FieldPath,\n public readonly op: Operator,\n public readonly value: ProtoValue\n ) {\n super();\n }\n\n /**\n * Creates a filter based on the provided arguments.\n */\n static create(\n field: FieldPath,\n op: Operator,\n value: ProtoValue\n ): FieldFilter {\n if (field.isKeyField()) {\n if (op === Operator.IN || op === Operator.NOT_IN) {\n return this.createKeyFieldInFilter(field, op, value);\n } else {\n debugAssert(\n isReferenceValue(value),\n 'Comparing on key, but filter value not a RefValue'\n );\n debugAssert(\n op !== Operator.ARRAY_CONTAINS && op !== Operator.ARRAY_CONTAINS_ANY,\n `'${op.toString()}' queries don't make sense on document keys.`\n );\n return new KeyFieldFilter(field, op, value);\n }\n } else if (op === Operator.ARRAY_CONTAINS) {\n return new ArrayContainsFilter(field, value);\n } else if (op === Operator.IN) {\n debugAssert(\n isArray(value),\n 'IN filter has invalid value: ' + value.toString()\n );\n return new InFilter(field, value);\n } else if (op === Operator.NOT_IN) {\n debugAssert(\n isArray(value),\n 'NOT_IN filter has invalid value: ' + value.toString()\n );\n return new NotInFilter(field, value);\n } else if (op === Operator.ARRAY_CONTAINS_ANY) {\n debugAssert(\n isArray(value),\n 'ARRAY_CONTAINS_ANY filter has invalid value: ' + value.toString()\n );\n return new ArrayContainsAnyFilter(field, value);\n } else {\n return new FieldFilter(field, op, value);\n }\n }\n\n private static createKeyFieldInFilter(\n field: FieldPath,\n op: Operator.IN | Operator.NOT_IN,\n value: ProtoValue\n ): FieldFilter {\n debugAssert(\n isArray(value),\n `Comparing on key with ${op.toString()}` +\n ', but filter value not an ArrayValue'\n );\n debugAssert(\n (value.arrayValue.values || []).every(elem => isReferenceValue(elem)),\n `Comparing on key with ${op.toString()}` +\n ', but an array value was not a RefValue'\n );\n\n return op === Operator.IN\n ? new KeyFieldInFilter(field, value)\n : new KeyFieldNotInFilter(field, value);\n }\n\n matches(doc: Document): boolean {\n const other = doc.data.field(this.field);\n // Types do not have to match in NOT_EQUAL filters.\n if (this.op === Operator.NOT_EQUAL) {\n return (\n other !== null &&\n other.nullValue === undefined &&\n this.matchesComparison(valueCompare(other!, this.value))\n );\n }\n\n // Only compare types with matching backend order (such as double and int).\n return (\n other !== null &&\n typeOrder(this.value) === typeOrder(other) &&\n this.matchesComparison(valueCompare(other, this.value))\n );\n }\n\n protected matchesComparison(comparison: number): boolean {\n switch (this.op) {\n case Operator.LESS_THAN:\n return comparison < 0;\n case Operator.LESS_THAN_OR_EQUAL:\n return comparison <= 0;\n case Operator.EQUAL:\n return comparison === 0;\n case Operator.NOT_EQUAL:\n return comparison !== 0;\n case Operator.GREATER_THAN:\n return comparison > 0;\n case Operator.GREATER_THAN_OR_EQUAL:\n return comparison >= 0;\n default:\n return fail(0xb8a2, 'Unknown FieldFilter operator', {\n operator: this.op\n });\n }\n }\n\n isInequality(): boolean {\n return (\n [\n Operator.LESS_THAN,\n Operator.LESS_THAN_OR_EQUAL,\n Operator.GREATER_THAN,\n Operator.GREATER_THAN_OR_EQUAL,\n Operator.NOT_EQUAL,\n Operator.NOT_IN\n ].indexOf(this.op) >= 0\n );\n }\n\n getFlattenedFilters(): readonly FieldFilter[] {\n return [this];\n }\n\n getFilters(): Filter[] {\n return [this];\n }\n}\n\nexport class CompositeFilter extends Filter {\n private memoizedFlattenedFilters: FieldFilter[] | null = null;\n\n protected constructor(\n public readonly filters: readonly Filter[],\n public readonly op: CompositeOperator\n ) {\n super();\n }\n\n /**\n * Creates a filter based on the provided arguments.\n */\n static create(filters: Filter[], op: CompositeOperator): CompositeFilter {\n return new CompositeFilter(filters, op);\n }\n\n matches(doc: Document): boolean {\n if (compositeFilterIsConjunction(this)) {\n // For conjunctions, all filters must match, so return false if any filter doesn't match.\n return this.filters.find(filter => !filter.matches(doc)) === undefined;\n } else {\n // For disjunctions, at least one filter should match.\n return this.filters.find(filter => filter.matches(doc)) !== undefined;\n }\n }\n\n getFlattenedFilters(): readonly FieldFilter[] {\n if (this.memoizedFlattenedFilters !== null) {\n return this.memoizedFlattenedFilters;\n }\n\n this.memoizedFlattenedFilters = this.filters.reduce((result, subfilter) => {\n return result.concat(subfilter.getFlattenedFilters());\n }, [] as FieldFilter[]);\n\n return this.memoizedFlattenedFilters;\n }\n\n // Returns a mutable copy of `this.filters`\n getFilters(): Filter[] {\n return Object.assign([], this.filters);\n }\n}\n\nexport function compositeFilterIsConjunction(\n compositeFilter: CompositeFilter\n): boolean {\n return compositeFilter.op === CompositeOperator.AND;\n}\n\nexport function compositeFilterIsDisjunction(\n compositeFilter: CompositeFilter\n): boolean {\n return compositeFilter.op === CompositeOperator.OR;\n}\n\n/**\n * Returns true if this filter is a conjunction of field filters only. Returns false otherwise.\n */\nexport function compositeFilterIsFlatConjunction(\n compositeFilter: CompositeFilter\n): boolean {\n return (\n compositeFilterIsFlat(compositeFilter) &&\n compositeFilterIsConjunction(compositeFilter)\n );\n}\n\n/**\n * Returns true if this filter does not contain any composite filters. Returns false otherwise.\n */\nexport function compositeFilterIsFlat(\n compositeFilter: CompositeFilter\n): boolean {\n for (const filter of compositeFilter.filters) {\n if (filter instanceof CompositeFilter) {\n return false;\n }\n }\n return true;\n}\n\nexport function canonifyFilter(filter: Filter): string {\n debugAssert(\n filter instanceof FieldFilter || filter instanceof CompositeFilter,\n 'canonifyFilter() only supports FieldFilters and CompositeFilters'\n );\n\n if (filter instanceof FieldFilter) {\n // TODO(b/29183165): Technically, this won't be unique if two values have\n // the same description, such as the int 3 and the string \"3\". So we should\n // add the types in here somehow, too.\n return (\n filter.field.canonicalString() +\n filter.op.toString() +\n canonicalId(filter.value)\n );\n } else if (compositeFilterIsFlatConjunction(filter)) {\n // Older SDK versions use an implicit AND operation between their filters.\n // In the new SDK versions, the developer may use an explicit AND filter.\n // To stay consistent with the old usages, we add a special case to ensure\n // the canonical ID for these two are the same. For example:\n // `col.whereEquals(\"a\", 1).whereEquals(\"b\", 2)` should have the same\n // canonical ID as `col.where(and(equals(\"a\",1), equals(\"b\",2)))`.\n return filter.filters.map(filter => canonifyFilter(filter)).join(',');\n } else {\n // filter instanceof CompositeFilter\n const canonicalIdsString = filter.filters\n .map(filter => canonifyFilter(filter))\n .join(',');\n return `${filter.op}(${canonicalIdsString})`;\n }\n}\n\nexport function filterEquals(f1: Filter, f2: Filter): boolean {\n if (f1 instanceof FieldFilter) {\n return fieldFilterEquals(f1, f2);\n } else if (f1 instanceof CompositeFilter) {\n return compositeFilterEquals(f1, f2);\n } else {\n fail(0x4bef, 'Only FieldFilters and CompositeFilters can be compared');\n }\n}\n\nexport function fieldFilterEquals(f1: FieldFilter, f2: Filter): boolean {\n return (\n f2 instanceof FieldFilter &&\n f1.op === f2.op &&\n f1.field.isEqual(f2.field) &&\n valueEquals(f1.value, f2.value)\n );\n}\n\nexport function compositeFilterEquals(\n f1: CompositeFilter,\n f2: Filter\n): boolean {\n if (\n f2 instanceof CompositeFilter &&\n f1.op === f2.op &&\n f1.filters.length === f2.filters.length\n ) {\n const subFiltersMatch: boolean = f1.filters.reduce(\n (result: boolean, f1Filter: Filter, index: number): boolean =>\n result && filterEquals(f1Filter, f2.filters[index]),\n true\n );\n\n return subFiltersMatch;\n }\n\n return false;\n}\n\n/**\n * Returns a new composite filter that contains all filter from\n * `compositeFilter` plus all the given filters in `otherFilters`.\n */\nexport function compositeFilterWithAddedFilters(\n compositeFilter: CompositeFilter,\n otherFilters: Filter[]\n): CompositeFilter {\n const mergedFilters = compositeFilter.filters.concat(otherFilters);\n return CompositeFilter.create(mergedFilters, compositeFilter.op);\n}\n\n/** Returns a debug description for `filter`. */\nexport function stringifyFilter(filter: Filter): string {\n debugAssert(\n filter instanceof FieldFilter || filter instanceof CompositeFilter,\n 'stringifyFilter() only supports FieldFilters and CompositeFilters'\n );\n if (filter instanceof FieldFilter) {\n return stringifyFieldFilter(filter);\n } else if (filter instanceof CompositeFilter) {\n return stringifyCompositeFilter(filter);\n } else {\n return 'Filter';\n }\n}\n\nexport function stringifyCompositeFilter(filter: CompositeFilter): string {\n return (\n filter.op.toString() +\n ` {` +\n filter.getFilters().map(stringifyFilter).join(' ,') +\n '}'\n );\n}\n\nexport function stringifyFieldFilter(filter: FieldFilter): string {\n return `${filter.field.canonicalString()} ${filter.op} ${canonicalId(\n filter.value\n )}`;\n}\n\n/** Filter that matches on key fields (i.e. '__name__'). */\nexport class KeyFieldFilter extends FieldFilter {\n private readonly key: DocumentKey;\n\n constructor(field: FieldPath, op: Operator, value: ProtoValue) {\n super(field, op, value);\n debugAssert(\n isReferenceValue(value),\n 'KeyFieldFilter expects a ReferenceValue'\n );\n this.key = DocumentKey.fromName(value.referenceValue);\n }\n\n matches(doc: Document): boolean {\n const comparison = DocumentKey.comparator(doc.key, this.key);\n return this.matchesComparison(comparison);\n }\n}\n\n/** Filter that matches on key fields within an array. */\nexport class KeyFieldInFilter extends FieldFilter {\n private readonly keys: DocumentKey[];\n\n constructor(field: FieldPath, value: ProtoValue) {\n super(field, Operator.IN, value);\n this.keys = extractDocumentKeysFromArrayValue(Operator.IN, value);\n }\n\n matches(doc: Document): boolean {\n return this.keys.some(key => key.isEqual(doc.key));\n }\n}\n\n/** Filter that matches on key fields not present within an array. */\nexport class KeyFieldNotInFilter extends FieldFilter {\n private readonly keys: DocumentKey[];\n\n constructor(field: FieldPath, value: ProtoValue) {\n super(field, Operator.NOT_IN, value);\n this.keys = extractDocumentKeysFromArrayValue(Operator.NOT_IN, value);\n }\n\n matches(doc: Document): boolean {\n return !this.keys.some(key => key.isEqual(doc.key));\n }\n}\n\nfunction extractDocumentKeysFromArrayValue(\n op: Operator.IN | Operator.NOT_IN,\n value: ProtoValue\n): DocumentKey[] {\n debugAssert(\n isArray(value),\n 'KeyFieldInFilter/KeyFieldNotInFilter expects an ArrayValue'\n );\n return (value.arrayValue?.values || []).map(v => {\n debugAssert(\n isReferenceValue(v),\n `Comparing on key with ${op.toString()}, but an array value was not ` +\n `a ReferenceValue`\n );\n return DocumentKey.fromName(v.referenceValue);\n });\n}\n\n/** A Filter that implements the array-contains operator. */\nexport class ArrayContainsFilter extends FieldFilter {\n constructor(field: FieldPath, value: ProtoValue) {\n super(field, Operator.ARRAY_CONTAINS, value);\n }\n\n matches(doc: Document): boolean {\n const other = doc.data.field(this.field);\n return isArray(other) && arrayValueContains(other.arrayValue, this.value);\n }\n}\n\n/** A Filter that implements the IN operator. */\nexport class InFilter extends FieldFilter {\n constructor(field: FieldPath, value: ProtoValue) {\n super(field, Operator.IN, value);\n debugAssert(isArray(value), 'InFilter expects an ArrayValue');\n }\n\n matches(doc: Document): boolean {\n const other = doc.data.field(this.field);\n return other !== null && arrayValueContains(this.value.arrayValue!, other);\n }\n}\n\n/** A Filter that implements the not-in operator. */\nexport class NotInFilter extends FieldFilter {\n constructor(field: FieldPath, value: ProtoValue) {\n super(field, Operator.NOT_IN, value);\n debugAssert(isArray(value), 'NotInFilter expects an ArrayValue');\n }\n\n matches(doc: Document): boolean {\n if (\n arrayValueContains(this.value.arrayValue!, { nullValue: 'NULL_VALUE' })\n ) {\n return false;\n }\n const other = doc.data.field(this.field);\n return (\n other !== null &&\n other.nullValue === undefined &&\n !arrayValueContains(this.value.arrayValue!, other)\n );\n }\n}\n\n/** A Filter that implements the array-contains-any operator. */\nexport class ArrayContainsAnyFilter extends FieldFilter {\n constructor(field: FieldPath, value: ProtoValue) {\n super(field, Operator.ARRAY_CONTAINS_ANY, value);\n debugAssert(isArray(value), 'ArrayContainsAnyFilter expects an ArrayValue');\n }\n\n matches(doc: Document): boolean {\n const other = doc.data.field(this.field);\n if (!isArray(other) || !other.arrayValue.values) {\n return false;\n }\n return other.arrayValue.values.some(val =>\n arrayValueContains(this.value.arrayValue!, val)\n );\n }\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FieldPath } from '../model/path';\n\n/**\n * The direction of sorting in an order by.\n */\nexport const enum Direction {\n ASCENDING = 'asc',\n DESCENDING = 'desc'\n}\n\n/**\n * An ordering on a field, in some Direction. Direction defaults to ASCENDING.\n */\nexport class OrderBy {\n constructor(\n readonly field: FieldPath,\n readonly dir: Direction = Direction.ASCENDING\n ) {}\n}\n\nexport function canonifyOrderBy(orderBy: OrderBy): string {\n // TODO(b/29183165): Make this collision robust.\n return orderBy.field.canonicalString() + orderBy.dir;\n}\n\nexport function stringifyOrderBy(orderBy: OrderBy): string {\n return `${orderBy.field.canonicalString()} (${orderBy.dir})`;\n}\n\nexport function orderByEquals(left: OrderBy, right: OrderBy): boolean {\n return left.dir === right.dir && left.field.isEqual(right.field);\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Timestamp } from '../lite-api/timestamp';\n\n/**\n * A version of a document in Firestore. This corresponds to the version\n * timestamp, such as update_time or read_time.\n */\nexport class SnapshotVersion {\n static fromTimestamp(value: Timestamp): SnapshotVersion {\n return new SnapshotVersion(value);\n }\n\n static min(): SnapshotVersion {\n return new SnapshotVersion(new Timestamp(0, 0));\n }\n\n static max(): SnapshotVersion {\n return new SnapshotVersion(new Timestamp(253402300799, 1e9 - 1));\n }\n\n private constructor(private timestamp: Timestamp) {}\n\n compareTo(other: SnapshotVersion): number {\n return this.timestamp._compareTo(other.timestamp);\n }\n\n isEqual(other: SnapshotVersion): boolean {\n return this.timestamp.isEqual(other.timestamp);\n }\n\n /** Returns a number representation of the version for use in spec tests. */\n toMicroseconds(): number {\n // Convert to microseconds.\n return this.timestamp.seconds * 1e6 + this.timestamp.nanoseconds / 1000;\n }\n\n toString(): string {\n return 'SnapshotVersion(' + this.timestamp.toString() + ')';\n }\n\n toTimestamp(): Timestamp {\n return this.timestamp;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { debugAssert, fail } from './assert';\n\n/*\n * Implementation of an immutable SortedMap using a Left-leaning\n * Red-Black Tree, adapted from the implementation in Mugs\n * (http://mads379.github.com/mugs/) by Mads Hartmann Jensen\n * (mads379@gmail.com).\n *\n * Original paper on Left-leaning Red-Black Trees:\n * http://www.cs.princeton.edu/~rs/talks/LLRB/LLRB.pdf\n *\n * Invariant 1: No red node has a red child\n * Invariant 2: Every leaf path has the same number of black nodes\n * Invariant 3: Only the left child can be red (left leaning)\n */\n\nexport type Comparator = (key1: K, key2: K) => number;\n\nexport interface Entry {\n key: K;\n value: V;\n}\n\n// An immutable sorted map implementation, based on a Left-leaning Red-Black\n// tree.\nexport class SortedMap {\n // visible for testing\n root: LLRBNode | LLRBEmptyNode;\n\n constructor(\n public comparator: Comparator,\n root?: LLRBNode | LLRBEmptyNode\n ) {\n this.root = root ? root : LLRBNode.EMPTY;\n }\n\n // Returns a copy of the map, with the specified key/value added or replaced.\n insert(key: K, value: V): SortedMap {\n return new SortedMap(\n this.comparator,\n this.root\n .insert(key, value, this.comparator)\n .copy(null, null, LLRBNode.BLACK, null, null)\n );\n }\n\n // Returns a copy of the map, with the specified key removed.\n remove(key: K): SortedMap {\n return new SortedMap(\n this.comparator,\n this.root\n .remove(key, this.comparator)\n .copy(null, null, LLRBNode.BLACK, null, null)\n );\n }\n\n // Returns the value of the node with the given key, or null.\n get(key: K): V | null {\n let node = this.root;\n while (!node.isEmpty()) {\n const cmp = this.comparator(key, node.key);\n if (cmp === 0) {\n return node.value;\n } else if (cmp < 0) {\n node = node.left;\n } else if (cmp > 0) {\n node = node.right;\n }\n }\n return null;\n }\n\n // Returns the index of the element in this sorted map, or -1 if it doesn't\n // exist.\n indexOf(key: K): number {\n // Number of nodes that were pruned when descending right\n let prunedNodes = 0;\n let node = this.root;\n while (!node.isEmpty()) {\n const cmp = this.comparator(key, node.key);\n if (cmp === 0) {\n return prunedNodes + node.left.size;\n } else if (cmp < 0) {\n node = node.left;\n } else {\n // Count all nodes left of the node plus the node itself\n prunedNodes += node.left.size + 1;\n node = node.right;\n }\n }\n // Node not found\n return -1;\n }\n\n isEmpty(): boolean {\n return this.root.isEmpty();\n }\n\n // Returns the total number of nodes in the map.\n get size(): number {\n return this.root.size;\n }\n\n // Returns the minimum key in the map.\n minKey(): K | null {\n return this.root.minKey();\n }\n\n // Returns the maximum key in the map.\n maxKey(): K | null {\n return this.root.maxKey();\n }\n\n // Traverses the map in key order and calls the specified action function\n // for each key/value pair. If action returns true, traversal is aborted.\n // Returns the first truthy value returned by action, or the last falsey\n // value returned by action.\n inorderTraversal(action: (k: K, v: V) => T): T {\n return (this.root as LLRBNode).inorderTraversal(action);\n }\n\n forEach(fn: (k: K, v: V) => void): void {\n this.inorderTraversal((k, v) => {\n fn(k, v);\n return false;\n });\n }\n\n toString(): string {\n const descriptions: string[] = [];\n this.inorderTraversal((k, v) => {\n descriptions.push(`${k}:${v}`);\n return false;\n });\n return `{${descriptions.join(', ')}}`;\n }\n\n // Traverses the map in reverse key order and calls the specified action\n // function for each key/value pair. If action returns true, traversal is\n // aborted.\n // Returns the first truthy value returned by action, or the last falsey\n // value returned by action.\n reverseTraversal(action: (k: K, v: V) => T): T {\n return (this.root as LLRBNode).reverseTraversal(action);\n }\n\n // Returns an iterator over the SortedMap.\n getIterator(): SortedMapIterator {\n return new SortedMapIterator(this.root, null, this.comparator, false);\n }\n\n getIteratorFrom(key: K): SortedMapIterator {\n return new SortedMapIterator(this.root, key, this.comparator, false);\n }\n\n getReverseIterator(): SortedMapIterator {\n return new SortedMapIterator(this.root, null, this.comparator, true);\n }\n\n getReverseIteratorFrom(key: K): SortedMapIterator {\n return new SortedMapIterator(this.root, key, this.comparator, true);\n }\n} // end SortedMap\n\n// An iterator over an LLRBNode.\nexport class SortedMapIterator {\n private isReverse: boolean;\n private nodeStack: Array | LLRBEmptyNode>;\n\n constructor(\n node: LLRBNode | LLRBEmptyNode,\n startKey: K | null,\n comparator: Comparator,\n isReverse: boolean\n ) {\n this.isReverse = isReverse;\n this.nodeStack = [];\n\n let cmp = 1;\n while (!node.isEmpty()) {\n cmp = startKey ? comparator(node.key, startKey) : 1;\n // flip the comparison if we're going in reverse\n if (startKey && isReverse) {\n cmp *= -1;\n }\n\n if (cmp < 0) {\n // This node is less than our start key. ignore it\n if (this.isReverse) {\n node = node.left;\n } else {\n node = node.right;\n }\n } else if (cmp === 0) {\n // This node is exactly equal to our start key. Push it on the stack,\n // but stop iterating;\n this.nodeStack.push(node);\n break;\n } else {\n // This node is greater than our start key, add it to the stack and move\n // to the next one\n this.nodeStack.push(node);\n if (this.isReverse) {\n node = node.right;\n } else {\n node = node.left;\n }\n }\n }\n }\n\n getNext(): Entry {\n debugAssert(\n this.nodeStack.length > 0,\n 'getNext() called on iterator when hasNext() is false.'\n );\n\n let node = this.nodeStack.pop()!;\n const result = { key: node.key, value: node.value };\n\n if (this.isReverse) {\n node = node.left;\n while (!node.isEmpty()) {\n this.nodeStack.push(node);\n node = node.right;\n }\n } else {\n node = node.right;\n while (!node.isEmpty()) {\n this.nodeStack.push(node);\n node = node.left;\n }\n }\n\n return result;\n }\n\n hasNext(): boolean {\n return this.nodeStack.length > 0;\n }\n\n peek(): Entry | null {\n if (this.nodeStack.length === 0) {\n return null;\n }\n\n const node = this.nodeStack[this.nodeStack.length - 1];\n return { key: node.key, value: node.value };\n }\n} // end SortedMapIterator\n\n// Represents a node in a Left-leaning Red-Black tree.\nexport class LLRBNode {\n readonly color: boolean;\n readonly left: LLRBNode | LLRBEmptyNode;\n readonly right: LLRBNode | LLRBEmptyNode;\n readonly size: number;\n\n // Empty node is shared between all LLRB trees.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n static EMPTY: LLRBEmptyNode = null as any;\n\n static RED = true;\n static BLACK = false;\n\n constructor(\n public key: K,\n public value: V,\n color?: boolean,\n left?: LLRBNode | LLRBEmptyNode,\n right?: LLRBNode | LLRBEmptyNode\n ) {\n this.color = color != null ? color : LLRBNode.RED;\n this.left = left != null ? left : LLRBNode.EMPTY;\n this.right = right != null ? right : LLRBNode.EMPTY;\n this.size = this.left.size + 1 + this.right.size;\n }\n\n // Returns a copy of the current node, optionally replacing pieces of it.\n copy(\n key: K | null,\n value: V | null,\n color: boolean | null,\n left: LLRBNode | LLRBEmptyNode | null,\n right: LLRBNode | LLRBEmptyNode | null\n ): LLRBNode {\n return new LLRBNode(\n key != null ? key : this.key,\n value != null ? value : this.value,\n color != null ? color : this.color,\n left != null ? left : this.left,\n right != null ? right : this.right\n );\n }\n\n isEmpty(): boolean {\n return false;\n }\n\n // Traverses the tree in key order and calls the specified action function\n // for each node. If action returns true, traversal is aborted.\n // Returns the first truthy value returned by action, or the last falsey\n // value returned by action.\n inorderTraversal(action: (k: K, v: V) => T): T {\n return (\n (this.left as LLRBNode).inorderTraversal(action) ||\n action(this.key, this.value) ||\n (this.right as LLRBNode).inorderTraversal(action)\n );\n }\n\n // Traverses the tree in reverse key order and calls the specified action\n // function for each node. If action returns true, traversal is aborted.\n // Returns the first truthy value returned by action, or the last falsey\n // value returned by action.\n reverseTraversal(action: (k: K, v: V) => T): T {\n return (\n (this.right as LLRBNode).reverseTraversal(action) ||\n action(this.key, this.value) ||\n (this.left as LLRBNode).reverseTraversal(action)\n );\n }\n\n // Returns the minimum node in the tree.\n private min(): LLRBNode {\n if (this.left.isEmpty()) {\n return this;\n } else {\n return (this.left as LLRBNode).min();\n }\n }\n\n // Returns the maximum key in the tree.\n minKey(): K | null {\n return this.min().key;\n }\n\n // Returns the maximum key in the tree.\n maxKey(): K | null {\n if (this.right.isEmpty()) {\n return this.key;\n } else {\n return this.right.maxKey();\n }\n }\n\n // Returns new tree, with the key/value added.\n insert(key: K, value: V, comparator: Comparator): LLRBNode {\n let n: LLRBNode = this;\n const cmp = comparator(key, n.key);\n if (cmp < 0) {\n n = n.copy(null, null, null, n.left.insert(key, value, comparator), null);\n } else if (cmp === 0) {\n n = n.copy(null, value, null, null, null);\n } else {\n n = n.copy(\n null,\n null,\n null,\n null,\n n.right.insert(key, value, comparator)\n );\n }\n return n.fixUp();\n }\n\n private removeMin(): LLRBNode | LLRBEmptyNode {\n if (this.left.isEmpty()) {\n return LLRBNode.EMPTY;\n }\n let n: LLRBNode = this;\n if (!n.left.isRed() && !n.left.left.isRed()) {\n n = n.moveRedLeft();\n }\n n = n.copy(null, null, null, (n.left as LLRBNode).removeMin(), null);\n return n.fixUp();\n }\n\n // Returns new tree, with the specified item removed.\n remove(\n key: K,\n comparator: Comparator\n ): LLRBNode | LLRBEmptyNode {\n let smallest: LLRBNode;\n let n: LLRBNode = this;\n if (comparator(key, n.key) < 0) {\n if (!n.left.isEmpty() && !n.left.isRed() && !n.left.left.isRed()) {\n n = n.moveRedLeft();\n }\n n = n.copy(null, null, null, n.left.remove(key, comparator), null);\n } else {\n if (n.left.isRed()) {\n n = n.rotateRight();\n }\n if (!n.right.isEmpty() && !n.right.isRed() && !n.right.left.isRed()) {\n n = n.moveRedRight();\n }\n if (comparator(key, n.key) === 0) {\n if (n.right.isEmpty()) {\n return LLRBNode.EMPTY;\n } else {\n smallest = (n.right as LLRBNode).min();\n n = n.copy(\n smallest.key,\n smallest.value,\n null,\n null,\n (n.right as LLRBNode).removeMin()\n );\n }\n }\n n = n.copy(null, null, null, null, n.right.remove(key, comparator));\n }\n return n.fixUp();\n }\n\n isRed(): boolean {\n return this.color;\n }\n\n // Returns new tree after performing any needed rotations.\n private fixUp(): LLRBNode {\n let n: LLRBNode = this;\n if (n.right.isRed() && !n.left.isRed()) {\n n = n.rotateLeft();\n }\n if (n.left.isRed() && n.left.left.isRed()) {\n n = n.rotateRight();\n }\n if (n.left.isRed() && n.right.isRed()) {\n n = n.colorFlip();\n }\n return n;\n }\n\n private moveRedLeft(): LLRBNode {\n let n = this.colorFlip();\n if (n.right.left.isRed()) {\n n = n.copy(\n null,\n null,\n null,\n null,\n (n.right as LLRBNode).rotateRight()\n );\n n = n.rotateLeft();\n n = n.colorFlip();\n }\n return n;\n }\n\n private moveRedRight(): LLRBNode {\n let n = this.colorFlip();\n if (n.left.left.isRed()) {\n n = n.rotateRight();\n n = n.colorFlip();\n }\n return n;\n }\n\n private rotateLeft(): LLRBNode {\n const nl = this.copy(null, null, LLRBNode.RED, null, this.right.left);\n return (this.right as LLRBNode).copy(\n null,\n null,\n this.color,\n nl,\n null\n );\n }\n\n private rotateRight(): LLRBNode {\n const nr = this.copy(null, null, LLRBNode.RED, this.left.right, null);\n return (this.left as LLRBNode).copy(null, null, this.color, null, nr);\n }\n\n private colorFlip(): LLRBNode {\n const left = this.left.copy(null, null, !this.left.color, null, null);\n const right = this.right.copy(null, null, !this.right.color, null, null);\n return this.copy(null, null, !this.color, left, right);\n }\n\n // For testing.\n checkMaxDepth(): boolean {\n const blackDepth = this.check();\n if (Math.pow(2.0, blackDepth) <= this.size + 1) {\n return true;\n } else {\n return false;\n }\n }\n\n // In a balanced RB tree, the black-depth (number of black nodes) from root to\n // leaves is equal on both sides. This function verifies that or asserts.\n protected check(): number {\n if (this.isRed() && this.left.isRed()) {\n throw fail(0xaad2, 'Red node has red child', {\n key: this.key,\n value: this.value\n });\n }\n if (this.right.isRed()) {\n throw fail(0x3721, 'Right child of (`key`, `value`) is red', {\n key: this.key,\n value: this.value\n });\n }\n const blackDepth = (this.left as LLRBNode).check();\n if (blackDepth !== (this.right as LLRBNode).check()) {\n throw fail(0x6d2d, 'Black depths differ');\n } else {\n return blackDepth + (this.isRed() ? 0 : 1);\n }\n }\n} // end LLRBNode\n\n// Represents an empty node (a leaf node in the Red-Black Tree).\nexport class LLRBEmptyNode {\n get key(): never {\n throw fail(0xe1a6, 'LLRBEmptyNode has no key.');\n }\n get value(): never {\n throw fail(0x3f0d, 'LLRBEmptyNode has no value.');\n }\n get color(): never {\n throw fail(0x4157, 'LLRBEmptyNode has no color.');\n }\n get left(): never {\n throw fail(0x741e, 'LLRBEmptyNode has no left child.');\n }\n get right(): never {\n throw fail(0x901e, 'LLRBEmptyNode has no right child.');\n }\n size = 0;\n\n // Returns a copy of the current node.\n copy(\n key: K | null,\n value: V | null,\n color: boolean | null,\n left: LLRBNode | LLRBEmptyNode | null,\n right: LLRBNode | LLRBEmptyNode | null\n ): LLRBEmptyNode {\n return this;\n }\n\n // Returns a copy of the tree, with the specified key/value added.\n insert(key: K, value: V, comparator: Comparator): LLRBNode {\n return new LLRBNode(key, value);\n }\n\n // Returns a copy of the tree, with the specified key removed.\n remove(key: K, comparator: Comparator): LLRBEmptyNode {\n return this;\n }\n\n isEmpty(): boolean {\n return true;\n }\n\n inorderTraversal(action: (k: K, v: V) => boolean): boolean {\n return false;\n }\n\n reverseTraversal(action: (k: K, v: V) => boolean): boolean {\n return false;\n }\n\n minKey(): K | null {\n return null;\n }\n\n maxKey(): K | null {\n return null;\n }\n\n isRed(): boolean {\n return false;\n }\n\n // For testing.\n checkMaxDepth(): boolean {\n return true;\n }\n\n protected check(): 0 {\n return 0;\n }\n} // end LLRBEmptyNode\n\nLLRBNode.EMPTY = new LLRBEmptyNode();\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SortedMap, SortedMapIterator } from './sorted_map';\n\n/**\n * SortedSet is an immutable (copy-on-write) collection that holds elements\n * in order specified by the provided comparator.\n *\n * NOTE: if provided comparator returns 0 for two elements, we consider them to\n * be equal!\n */\nexport class SortedSet {\n private data: SortedMap;\n\n constructor(private comparator: (left: T, right: T) => number) {\n this.data = new SortedMap(this.comparator);\n }\n\n has(elem: T): boolean {\n return this.data.get(elem) !== null;\n }\n\n first(): T | null {\n return this.data.minKey();\n }\n\n last(): T | null {\n return this.data.maxKey();\n }\n\n get size(): number {\n return this.data.size;\n }\n\n indexOf(elem: T): number {\n return this.data.indexOf(elem);\n }\n\n /** Iterates elements in order defined by \"comparator\" */\n forEach(cb: (elem: T) => void): void {\n this.data.inorderTraversal((k: T, v: boolean) => {\n cb(k);\n return false;\n });\n }\n\n /** Iterates over `elem`s such that: range[0] <= elem < range[1]. */\n forEachInRange(range: [T, T], cb: (elem: T) => void): void {\n const iter = this.data.getIteratorFrom(range[0]);\n while (iter.hasNext()) {\n const elem = iter.getNext();\n if (this.comparator(elem.key, range[1]) >= 0) {\n return;\n }\n cb(elem.key);\n }\n }\n\n /**\n * Iterates over `elem`s such that: start <= elem until false is returned.\n */\n forEachWhile(cb: (elem: T) => boolean, start?: T): void {\n let iter: SortedMapIterator;\n if (start !== undefined) {\n iter = this.data.getIteratorFrom(start);\n } else {\n iter = this.data.getIterator();\n }\n while (iter.hasNext()) {\n const elem = iter.getNext();\n const result = cb(elem.key);\n if (!result) {\n return;\n }\n }\n }\n\n /** Finds the least element greater than or equal to `elem`. */\n firstAfterOrEqual(elem: T): T | null {\n const iter = this.data.getIteratorFrom(elem);\n return iter.hasNext() ? iter.getNext().key : null;\n }\n\n getIterator(): SortedSetIterator {\n return new SortedSetIterator(this.data.getIterator());\n }\n\n getIteratorFrom(key: T): SortedSetIterator {\n return new SortedSetIterator(this.data.getIteratorFrom(key));\n }\n\n /** Inserts or updates an element */\n add(elem: T): SortedSet {\n return this.copy(this.data.remove(elem).insert(elem, true));\n }\n\n /** Deletes an element */\n delete(elem: T): SortedSet {\n if (!this.has(elem)) {\n return this;\n }\n return this.copy(this.data.remove(elem));\n }\n\n isEmpty(): boolean {\n return this.data.isEmpty();\n }\n\n unionWith(other: SortedSet): SortedSet {\n let result: SortedSet = this;\n\n // Make sure `result` always refers to the larger one of the two sets.\n if (result.size < other.size) {\n result = other;\n other = this;\n }\n\n other.forEach(elem => {\n result = result.add(elem);\n });\n return result;\n }\n\n isEqual(other: SortedSet): boolean {\n if (!(other instanceof SortedSet)) {\n return false;\n }\n if (this.size !== other.size) {\n return false;\n }\n\n const thisIt = this.data.getIterator();\n const otherIt = other.data.getIterator();\n while (thisIt.hasNext()) {\n const thisElem = thisIt.getNext().key;\n const otherElem = otherIt.getNext().key;\n if (this.comparator(thisElem, otherElem) !== 0) {\n return false;\n }\n }\n return true;\n }\n\n toArray(): T[] {\n const res: T[] = [];\n this.forEach(targetId => {\n res.push(targetId);\n });\n return res;\n }\n\n toString(): string {\n const result: T[] = [];\n this.forEach(elem => result.push(elem));\n return 'SortedSet(' + result.toString() + ')';\n }\n\n private copy(data: SortedMap): SortedSet {\n const result = new SortedSet(this.comparator);\n result.data = data;\n return result;\n }\n}\n\nexport class SortedSetIterator {\n constructor(private iter: SortedMapIterator) {}\n\n getNext(): T {\n return this.iter.getNext().key;\n }\n\n hasNext(): boolean {\n return this.iter.hasNext();\n }\n}\n\n/**\n * Compares two sorted sets for equality using their natural ordering. The\n * method computes the intersection and invokes `onAdd` for every element that\n * is in `after` but not `before`. `onRemove` is invoked for every element in\n * `before` but missing from `after`.\n *\n * The method creates a copy of both `before` and `after` and runs in O(n log\n * n), where n is the size of the two lists.\n *\n * @param before - The elements that exist in the original set.\n * @param after - The elements to diff against the original set.\n * @param comparator - The comparator for the elements in before and after.\n * @param onAdd - A function to invoke for every element that is part of `\n * after` but not `before`.\n * @param onRemove - A function to invoke for every element that is part of\n * `before` but not `after`.\n */\nexport function diffSortedSets(\n before: SortedSet,\n after: SortedSet,\n comparator: (l: T, r: T) => number,\n onAdd: (entry: T) => void,\n onRemove: (entry: T) => void\n): void {\n const beforeIt = before.getIterator();\n const afterIt = after.getIterator();\n\n let beforeValue = advanceIterator(beforeIt);\n let afterValue = advanceIterator(afterIt);\n\n // Walk through the two sets at the same time, using the ordering defined by\n // `comparator`.\n while (beforeValue || afterValue) {\n let added = false;\n let removed = false;\n\n if (beforeValue && afterValue) {\n const cmp = comparator(beforeValue, afterValue);\n if (cmp < 0) {\n // The element was removed if the next element in our ordered\n // walkthrough is only in `before`.\n removed = true;\n } else if (cmp > 0) {\n // The element was added if the next element in our ordered walkthrough\n // is only in `after`.\n added = true;\n }\n } else if (beforeValue != null) {\n removed = true;\n } else {\n added = true;\n }\n\n if (added) {\n onAdd(afterValue!);\n afterValue = advanceIterator(afterIt);\n } else if (removed) {\n onRemove(beforeValue!);\n beforeValue = advanceIterator(beforeIt);\n } else {\n beforeValue = advanceIterator(beforeIt);\n afterValue = advanceIterator(afterIt);\n }\n }\n}\n\n/**\n * Returns the next element from the iterator or `undefined` if none available.\n */\nfunction advanceIterator(it: SortedSetIterator): T | undefined {\n return it.hasNext() ? it.getNext() : undefined;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { debugAssert } from '../util/assert';\nimport { arrayEquals } from '../util/misc';\nimport { SortedSet } from '../util/sorted_set';\n\nimport { FieldPath } from './path';\n\n/**\n * Provides a set of fields that can be used to partially patch a document.\n * FieldMask is used in conjunction with ObjectValue.\n * Examples:\n * foo - Overwrites foo entirely with the provided value. If foo is not\n * present in the companion ObjectValue, the field is deleted.\n * foo.bar - Overwrites only the field bar of the object foo.\n * If foo is not an object, foo is replaced with an object\n * containing foo\n */\nexport class FieldMask {\n constructor(readonly fields: FieldPath[]) {\n // TODO(dimond): validation of FieldMask\n // Sort the field mask to support `FieldMask.isEqual()` and assert below.\n fields.sort(FieldPath.comparator);\n debugAssert(\n !fields.some((v, i) => i !== 0 && v.isEqual(fields[i - 1])),\n 'FieldMask contains field that is not unique: ' +\n fields.find((v, i) => i !== 0 && v.isEqual(fields[i - 1]))!\n );\n }\n\n static empty(): FieldMask {\n return new FieldMask([]);\n }\n\n /**\n * Returns a new FieldMask object that is the result of adding all the given\n * fields paths to this field mask.\n */\n unionWith(extraFields: FieldPath[]): FieldMask {\n let mergedMaskSet = new SortedSet(FieldPath.comparator);\n for (const fieldPath of this.fields) {\n mergedMaskSet = mergedMaskSet.add(fieldPath);\n }\n for (const fieldPath of extraFields) {\n mergedMaskSet = mergedMaskSet.add(fieldPath);\n }\n return new FieldMask(mergedMaskSet.toArray());\n }\n\n /**\n * Verifies that `fieldPath` is included by at least one field in this field\n * mask.\n *\n * This is an O(n) operation, where `n` is the size of the field mask.\n */\n covers(fieldPath: FieldPath): boolean {\n for (const fieldMaskPath of this.fields) {\n if (fieldMaskPath.isPrefixOf(fieldPath)) {\n return true;\n }\n }\n return false;\n }\n\n isEqual(other: FieldMask): boolean {\n return arrayEquals(this.fields, other.fields, (l, r) => l.isEqual(r));\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n MapValue as ProtoMapValue,\n Value as ProtoValue\n} from '../protos/firestore_proto_api';\nimport { debugAssert } from '../util/assert';\nimport { forEach } from '../util/obj';\n\nimport { FieldMask } from './field_mask';\nimport { FieldPath } from './path';\nimport { isServerTimestamp } from './server_timestamps';\nimport { deepClone, isMapValue, valueEquals } from './values';\n\nexport interface JsonObject {\n [name: string]: T;\n}\n/**\n * An ObjectValue represents a MapValue in the Firestore Proto and offers the\n * ability to add and remove fields (via the ObjectValueBuilder).\n */\nexport class ObjectValue {\n constructor(readonly value: { mapValue: ProtoMapValue }) {\n debugAssert(\n !isServerTimestamp(value),\n 'ServerTimestamps should be converted to ServerTimestampValue'\n );\n }\n\n static empty(): ObjectValue {\n return new ObjectValue({ mapValue: {} });\n }\n\n /**\n * Returns the value at the given path or null.\n *\n * @param path - the path to search\n * @returns The value at the path or null if the path is not set.\n */\n field(path: FieldPath): ProtoValue | null {\n if (path.isEmpty()) {\n return this.value;\n } else {\n let currentLevel: ProtoValue = this.value;\n for (let i = 0; i < path.length - 1; ++i) {\n currentLevel = (currentLevel.mapValue!.fields || {})[path.get(i)];\n if (!isMapValue(currentLevel)) {\n return null;\n }\n }\n currentLevel = (currentLevel.mapValue!.fields! || {})[path.lastSegment()];\n return currentLevel || null;\n }\n }\n\n /**\n * Sets the field to the provided value.\n *\n * @param path - The field path to set.\n * @param value - The value to set.\n */\n set(path: FieldPath, value: ProtoValue): void {\n debugAssert(\n !path.isEmpty(),\n 'Cannot set field for empty path on ObjectValue'\n );\n const fieldsMap = this.getFieldsMap(path.popLast());\n fieldsMap[path.lastSegment()] = deepClone(value);\n }\n\n /**\n * Sets the provided fields to the provided values.\n *\n * @param data - A map of fields to values (or null for deletes).\n */\n setAll(data: Map): void {\n let parent = FieldPath.emptyPath();\n\n let upserts: { [key: string]: ProtoValue } = {};\n let deletes: string[] = [];\n\n data.forEach((value, path) => {\n if (!parent.isImmediateParentOf(path)) {\n // Insert the accumulated changes at this parent location\n const fieldsMap = this.getFieldsMap(parent);\n this.applyChanges(fieldsMap, upserts, deletes);\n upserts = {};\n deletes = [];\n parent = path.popLast();\n }\n\n if (value) {\n upserts[path.lastSegment()] = deepClone(value);\n } else {\n deletes.push(path.lastSegment());\n }\n });\n\n const fieldsMap = this.getFieldsMap(parent);\n this.applyChanges(fieldsMap, upserts, deletes);\n }\n\n /**\n * Removes the field at the specified path. If there is no field at the\n * specified path, nothing is changed.\n *\n * @param path - The field path to remove.\n */\n delete(path: FieldPath): void {\n debugAssert(\n !path.isEmpty(),\n 'Cannot delete field for empty path on ObjectValue'\n );\n const nestedValue = this.field(path.popLast());\n if (isMapValue(nestedValue) && nestedValue.mapValue.fields) {\n delete nestedValue.mapValue.fields[path.lastSegment()];\n }\n }\n\n isEqual(other: ObjectValue): boolean {\n return valueEquals(this.value, other.value);\n }\n\n /**\n * Returns the map that contains the leaf element of `path`. If the parent\n * entry does not yet exist, or if it is not a map, a new map will be created.\n */\n private getFieldsMap(path: FieldPath): Record {\n let current = this.value;\n\n if (!current.mapValue!.fields) {\n current.mapValue = { fields: {} };\n }\n\n for (let i = 0; i < path.length; ++i) {\n let next = current.mapValue!.fields![path.get(i)];\n if (!isMapValue(next) || !next.mapValue.fields) {\n next = { mapValue: { fields: {} } };\n current.mapValue!.fields![path.get(i)] = next;\n }\n current = next as { mapValue: ProtoMapValue };\n }\n\n return current.mapValue!.fields!;\n }\n\n /**\n * Modifies `fieldsMap` by adding, replacing or deleting the specified\n * entries.\n */\n private applyChanges(\n fieldsMap: Record,\n inserts: { [key: string]: ProtoValue },\n deletes: string[]\n ): void {\n forEach(inserts, (key, val) => (fieldsMap[key] = val));\n for (const field of deletes) {\n delete fieldsMap[field];\n }\n }\n\n clone(): ObjectValue {\n return new ObjectValue(\n deepClone(this.value) as { mapValue: ProtoMapValue }\n );\n }\n}\n\n/**\n * Returns a FieldMask built from all fields in a MapValue.\n */\nexport function extractFieldMask(value: ProtoMapValue): FieldMask {\n const fields: FieldPath[] = [];\n forEach(value!.fields, (key, value) => {\n const currentPath = new FieldPath([key]);\n if (isMapValue(value)) {\n const nestedMask = extractFieldMask(value.mapValue!);\n const nestedFields = nestedMask.fields;\n if (nestedFields.length === 0) {\n // Preserve the empty map by adding it to the FieldMask.\n fields.push(currentPath);\n } else {\n // For nested and non-empty ObjectValues, add the FieldPath of the\n // leaf nodes.\n for (const nestedPath of nestedFields) {\n fields.push(currentPath.child(nestedPath));\n }\n }\n } else {\n // For nested and non-empty ObjectValues, add the FieldPath of the leaf\n // nodes.\n fields.push(currentPath);\n }\n });\n return new FieldMask(fields);\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { debugAssert, fail } from '../util/assert';\n\nimport { DocumentKey } from './document_key';\nimport { ObjectValue } from './object_value';\nimport { FieldPath } from './path';\nimport { valueCompare } from './values';\n\n/**\n * Whether the document represents an existing document, a document that is\n * known to exist or a document whose state or existence is unknown.\n */\nconst enum DocumentType {\n /**\n * Represents the initial state of a MutableDocument when only the document\n * key is known. Invalid documents transition to other states as mutations are\n * applied. If a document remains invalid after applying mutations, it should\n * be discarded.\n *\n * Invalid documents can have neither local nor committed mutations.\n */\n INVALID,\n /**\n * Represents a document in Firestore with a key, version, data and whether\n * the data has local mutations applied to it.\n *\n * Found documents can be synced or have or committed mutations applied.\n */\n FOUND_DOCUMENT,\n /**\n * Represents that no documents exists for the key at the given version.\n *\n * Documents that are deleted based on a local mutation do not raise snapshots\n * with `hasPendingWrites`. As such, deleted documents never have\n * `HAS_LOCAL_MUTATIONS` set. Once a delete is committed, we store them with\n * `HAS_COMMITTED_MUTATIONS` until we received the delete from the Watch\n * stream.\n */\n NO_DOCUMENT,\n /**\n * Represents an existing document whose data is unknown (e.g. a document that\n * was updated without a known base document).\n *\n * An unknown document always has `HAS_COMMITTED_MUTATIONS` set, since unknown\n * documents can only be generated by applying a patch mutation from a write\n * acknowledgement.\n */\n UNKNOWN_DOCUMENT\n}\n\n/** Describes whether a document has latency-compensated edits applied. */\nconst enum DocumentState {\n /** No mutations applied. Document was sent to us by Watch. */\n SYNCED,\n /**\n * Local mutations applied via the mutation queue. Document is potentially\n * inconsistent.\n */\n HAS_LOCAL_MUTATIONS,\n /**\n * Mutations applied based on a write acknowledgment. Document is potentially\n * inconsistent.\n */\n HAS_COMMITTED_MUTATIONS\n}\n\n/**\n * Represents a document in Firestore with a key, version, data and whether the\n * data has local mutations applied to it.\n */\nexport interface Document {\n /** The key for this document */\n readonly key: DocumentKey;\n\n /**\n * The version of this document if it exists or a version at which this\n * document was guaranteed to not exist.\n */\n readonly version: SnapshotVersion;\n\n /**\n * The timestamp at which this document was read from the remote server. Uses\n * `SnapshotVersion.min()` for documents created by the user.\n */\n readonly readTime: SnapshotVersion;\n\n /**\n * The timestamp at which the document was created. This value increases\n * monotonically when a document is deleted then recreated. It can also be\n * compared to `createTime` of other documents and the `readTime` of a query.\n */\n readonly createTime: SnapshotVersion;\n\n /** The underlying data of this document or an empty value if no data exists. */\n readonly data: ObjectValue;\n\n /** Returns whether local mutations were applied via the mutation queue. */\n readonly hasLocalMutations: boolean;\n\n /** Returns whether mutations were applied based on a write acknowledgment. */\n readonly hasCommittedMutations: boolean;\n\n /**\n * Whether this document had a local mutation applied that has not yet been\n * acknowledged by Watch.\n */\n readonly hasPendingWrites: boolean;\n\n /**\n * Returns whether this document is valid (i.e. it is an entry in the\n * RemoteDocumentCache, was created by a mutation or read from the backend).\n */\n isValidDocument(): boolean;\n\n /**\n * Returns whether the document exists and its data is known at the current\n * version.\n */\n isFoundDocument(): boolean;\n\n /**\n * Returns whether the document is known to not exist at the current version.\n */\n isNoDocument(): boolean;\n\n /**\n * Returns whether the document exists and its data is unknown at the current\n * version.\n */\n isUnknownDocument(): boolean;\n\n isEqual(other: Document | null | undefined): boolean;\n\n /** Creates a mutable copy of this document. */\n mutableCopy(): MutableDocument;\n\n toString(): string;\n}\n\n/**\n * Represents a document in Firestore with a key, version, data and whether it\n * has local mutations applied to it.\n *\n * Documents can transition between states via `convertToFoundDocument()`,\n * `convertToNoDocument()` and `convertToUnknownDocument()`. If a document does\n * not transition to one of these states even after all mutations have been\n * applied, `isValidDocument()` returns false and the document should be removed\n * from all views.\n */\nexport class MutableDocument implements Document {\n private constructor(\n readonly key: DocumentKey,\n private documentType: DocumentType,\n public version: SnapshotVersion,\n public readTime: SnapshotVersion,\n public createTime: SnapshotVersion,\n public data: ObjectValue,\n private documentState: DocumentState\n ) {}\n\n /**\n * Creates a document with no known version or data, but which can serve as\n * base document for mutations.\n */\n static newInvalidDocument(documentKey: DocumentKey): MutableDocument {\n return new MutableDocument(\n documentKey,\n DocumentType.INVALID,\n /* version */ SnapshotVersion.min(),\n /* readTime */ SnapshotVersion.min(),\n /* createTime */ SnapshotVersion.min(),\n ObjectValue.empty(),\n DocumentState.SYNCED\n );\n }\n\n /**\n * Creates a new document that is known to exist with the given data at the\n * given version.\n */\n static newFoundDocument(\n documentKey: DocumentKey,\n version: SnapshotVersion,\n createTime: SnapshotVersion,\n value: ObjectValue\n ): MutableDocument {\n return new MutableDocument(\n documentKey,\n DocumentType.FOUND_DOCUMENT,\n /* version */ version,\n /* readTime */ SnapshotVersion.min(),\n /* createTime */ createTime,\n value,\n DocumentState.SYNCED\n );\n }\n\n /** Creates a new document that is known to not exist at the given version. */\n static newNoDocument(\n documentKey: DocumentKey,\n version: SnapshotVersion\n ): MutableDocument {\n return new MutableDocument(\n documentKey,\n DocumentType.NO_DOCUMENT,\n /* version */ version,\n /* readTime */ SnapshotVersion.min(),\n /* createTime */ SnapshotVersion.min(),\n ObjectValue.empty(),\n DocumentState.SYNCED\n );\n }\n\n /**\n * Creates a new document that is known to exist at the given version but\n * whose data is not known (e.g. a document that was updated without a known\n * base document).\n */\n static newUnknownDocument(\n documentKey: DocumentKey,\n version: SnapshotVersion\n ): MutableDocument {\n return new MutableDocument(\n documentKey,\n DocumentType.UNKNOWN_DOCUMENT,\n /* version */ version,\n /* readTime */ SnapshotVersion.min(),\n /* createTime */ SnapshotVersion.min(),\n ObjectValue.empty(),\n DocumentState.HAS_COMMITTED_MUTATIONS\n );\n }\n\n /**\n * Changes the document type to indicate that it exists and that its version\n * and data are known.\n */\n convertToFoundDocument(\n version: SnapshotVersion,\n value: ObjectValue\n ): MutableDocument {\n // If a document is switching state from being an invalid or deleted\n // document to a valid (FOUND_DOCUMENT) document, either due to receiving an\n // update from Watch or due to applying a local set mutation on top\n // of a deleted document, our best guess about its createTime would be the\n // version at which the document transitioned to a FOUND_DOCUMENT.\n if (\n this.createTime.isEqual(SnapshotVersion.min()) &&\n (this.documentType === DocumentType.NO_DOCUMENT ||\n this.documentType === DocumentType.INVALID)\n ) {\n this.createTime = version;\n }\n this.version = version;\n this.documentType = DocumentType.FOUND_DOCUMENT;\n this.data = value;\n this.documentState = DocumentState.SYNCED;\n return this;\n }\n\n /**\n * Changes the document type to indicate that it doesn't exist at the given\n * version.\n */\n convertToNoDocument(version: SnapshotVersion): MutableDocument {\n this.version = version;\n this.documentType = DocumentType.NO_DOCUMENT;\n this.data = ObjectValue.empty();\n this.documentState = DocumentState.SYNCED;\n return this;\n }\n\n /**\n * Changes the document type to indicate that it exists at a given version but\n * that its data is not known (e.g. a document that was updated without a known\n * base document).\n */\n convertToUnknownDocument(version: SnapshotVersion): MutableDocument {\n this.version = version;\n this.documentType = DocumentType.UNKNOWN_DOCUMENT;\n this.data = ObjectValue.empty();\n this.documentState = DocumentState.HAS_COMMITTED_MUTATIONS;\n return this;\n }\n\n setHasCommittedMutations(): MutableDocument {\n debugAssert(\n this.isValidDocument(),\n 'Invalid documents cannot have committed mutations'\n );\n this.documentState = DocumentState.HAS_COMMITTED_MUTATIONS;\n return this;\n }\n\n setHasLocalMutations(): MutableDocument {\n this.documentState = DocumentState.HAS_LOCAL_MUTATIONS;\n this.version = SnapshotVersion.min();\n return this;\n }\n\n setReadTime(readTime: SnapshotVersion): MutableDocument {\n this.readTime = readTime;\n return this;\n }\n\n get hasLocalMutations(): boolean {\n return this.documentState === DocumentState.HAS_LOCAL_MUTATIONS;\n }\n\n get hasCommittedMutations(): boolean {\n return this.documentState === DocumentState.HAS_COMMITTED_MUTATIONS;\n }\n\n get hasPendingWrites(): boolean {\n return this.hasLocalMutations || this.hasCommittedMutations;\n }\n\n isValidDocument(): boolean {\n return this.documentType !== DocumentType.INVALID;\n }\n\n isFoundDocument(): boolean {\n return this.documentType === DocumentType.FOUND_DOCUMENT;\n }\n\n isNoDocument(): boolean {\n return this.documentType === DocumentType.NO_DOCUMENT;\n }\n\n isUnknownDocument(): boolean {\n return this.documentType === DocumentType.UNKNOWN_DOCUMENT;\n }\n\n isEqual(other: Document | null | undefined): boolean {\n return (\n other instanceof MutableDocument &&\n this.key.isEqual(other.key) &&\n this.version.isEqual(other.version) &&\n this.documentType === other.documentType &&\n this.documentState === other.documentState &&\n this.data.isEqual(other.data)\n );\n }\n\n mutableCopy(): MutableDocument {\n return new MutableDocument(\n this.key,\n this.documentType,\n this.version,\n this.readTime,\n this.createTime,\n this.data.clone(),\n this.documentState\n );\n }\n\n toString(): string {\n return (\n `Document(${this.key}, ${this.version}, ${JSON.stringify(\n this.data.value\n )}, ` +\n `{createTime: ${this.createTime}}), ` +\n `{documentType: ${this.documentType}}), ` +\n `{documentState: ${this.documentState}})`\n );\n }\n}\n\n/**\n * Compares the value for field `field` in the provided documents. Throws if\n * the field does not exist in both documents.\n */\nexport function compareDocumentsByField(\n field: FieldPath,\n d1: Document,\n d2: Document\n): number {\n const v1 = d1.data.field(field);\n const v2 = d2.data.field(field);\n if (v1 !== null && v2 !== null) {\n return valueCompare(v1, v2);\n } else {\n return fail(\n 0xa786,\n \"Trying to compare documents on fields that don't exist\"\n );\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DocumentKey } from '../model/document_key';\nimport {\n FieldIndex,\n fieldIndexGetArraySegment,\n fieldIndexGetDirectionalSegments,\n IndexKind\n} from '../model/field_index';\nimport { FieldPath, ResourcePath } from '../model/path';\nimport {\n canonicalId,\n MAX_VALUE,\n MIN_VALUE,\n lowerBoundCompare,\n upperBoundCompare,\n valuesGetLowerBound,\n valuesGetUpperBound\n} from '../model/values';\nimport { Value as ProtoValue } from '../protos/firestore_proto_api';\nimport { debugCast } from '../util/assert';\nimport { SortedSet } from '../util/sorted_set';\nimport { isNullOrUndefined } from '../util/types';\n\nimport { Bound, boundEquals } from './bound';\nimport {\n Filter,\n FieldFilter,\n canonifyFilter,\n stringifyFilter,\n filterEquals,\n Operator\n} from './filter';\nimport {\n canonifyOrderBy,\n OrderBy,\n orderByEquals,\n stringifyOrderBy\n} from './order_by';\n\n/**\n * A Target represents the WatchTarget representation of a Query, which is used\n * by the LocalStore and the RemoteStore to keep track of and to execute\n * backend queries. While a Query can represent multiple Targets, each Targets\n * maps to a single WatchTarget in RemoteStore and a single TargetData entry\n * in persistence.\n */\nexport interface Target {\n readonly path: ResourcePath;\n readonly collectionGroup: string | null;\n readonly orderBy: OrderBy[];\n readonly filters: Filter[];\n readonly limit: number | null;\n readonly startAt: Bound | null;\n readonly endAt: Bound | null;\n}\n\n// Visible for testing\nexport class TargetImpl implements Target {\n memoizedCanonicalId: string | null = null;\n constructor(\n readonly path: ResourcePath,\n readonly collectionGroup: string | null = null,\n readonly orderBy: OrderBy[] = [],\n readonly filters: Filter[] = [],\n readonly limit: number | null = null,\n readonly startAt: Bound | null = null,\n readonly endAt: Bound | null = null\n ) {}\n}\n\n/**\n * Initializes a Target with a path and optional additional query constraints.\n * Path must currently be empty if this is a collection group query.\n *\n * NOTE: you should always construct `Target` from `Query.toTarget` instead of\n * using this factory method, because `Query` provides an implicit `orderBy`\n * property.\n */\nexport function newTarget(\n path: ResourcePath,\n collectionGroup: string | null = null,\n orderBy: OrderBy[] = [],\n filters: Filter[] = [],\n limit: number | null = null,\n startAt: Bound | null = null,\n endAt: Bound | null = null\n): Target {\n return new TargetImpl(\n path,\n collectionGroup,\n orderBy,\n filters,\n limit,\n startAt,\n endAt\n );\n}\n\nexport function canonifyTarget(target: Target): string {\n const targetImpl = debugCast(target, TargetImpl);\n\n if (targetImpl.memoizedCanonicalId === null) {\n let str = targetImpl.path.canonicalString();\n if (targetImpl.collectionGroup !== null) {\n str += '|cg:' + targetImpl.collectionGroup;\n }\n str += '|f:';\n str += targetImpl.filters.map(f => canonifyFilter(f)).join(',');\n str += '|ob:';\n str += targetImpl.orderBy.map(o => canonifyOrderBy(o)).join(',');\n\n if (!isNullOrUndefined(targetImpl.limit)) {\n str += '|l:';\n str += targetImpl.limit!;\n }\n if (targetImpl.startAt) {\n str += '|lb:';\n str += targetImpl.startAt.inclusive ? 'b:' : 'a:';\n str += targetImpl.startAt.position.map(p => canonicalId(p)).join(',');\n }\n if (targetImpl.endAt) {\n str += '|ub:';\n str += targetImpl.endAt.inclusive ? 'a:' : 'b:';\n str += targetImpl.endAt.position.map(p => canonicalId(p)).join(',');\n }\n targetImpl.memoizedCanonicalId = str;\n }\n return targetImpl.memoizedCanonicalId;\n}\n\nexport function stringifyTarget(target: Target): string {\n let str = target.path.canonicalString();\n if (target.collectionGroup !== null) {\n str += ' collectionGroup=' + target.collectionGroup;\n }\n if (target.filters.length > 0) {\n str += `, filters: [${target.filters\n .map(f => stringifyFilter(f))\n .join(', ')}]`;\n }\n if (!isNullOrUndefined(target.limit)) {\n str += ', limit: ' + target.limit;\n }\n if (target.orderBy.length > 0) {\n str += `, orderBy: [${target.orderBy\n .map(o => stringifyOrderBy(o))\n .join(', ')}]`;\n }\n if (target.startAt) {\n str += ', startAt: ';\n str += target.startAt.inclusive ? 'b:' : 'a:';\n str += target.startAt.position.map(p => canonicalId(p)).join(',');\n }\n if (target.endAt) {\n str += ', endAt: ';\n str += target.endAt.inclusive ? 'a:' : 'b:';\n str += target.endAt.position.map(p => canonicalId(p)).join(',');\n }\n return `Target(${str})`;\n}\n\nexport function targetEquals(left: Target, right: Target): boolean {\n if (left.limit !== right.limit) {\n return false;\n }\n\n if (left.orderBy.length !== right.orderBy.length) {\n return false;\n }\n\n for (let i = 0; i < left.orderBy.length; i++) {\n if (!orderByEquals(left.orderBy[i], right.orderBy[i])) {\n return false;\n }\n }\n\n if (left.filters.length !== right.filters.length) {\n return false;\n }\n\n for (let i = 0; i < left.filters.length; i++) {\n if (!filterEquals(left.filters[i], right.filters[i])) {\n return false;\n }\n }\n\n if (left.collectionGroup !== right.collectionGroup) {\n return false;\n }\n\n if (!left.path.isEqual(right.path)) {\n return false;\n }\n\n if (!boundEquals(left.startAt, right.startAt)) {\n return false;\n }\n\n return boundEquals(left.endAt, right.endAt);\n}\n\nexport function targetIsDocumentTarget(target: Target): boolean {\n return (\n DocumentKey.isDocumentKey(target.path) &&\n target.collectionGroup === null &&\n target.filters.length === 0\n );\n}\n\n/** Returns the field filters that target the given field path. */\nexport function targetGetFieldFiltersForPath(\n target: Target,\n path: FieldPath\n): FieldFilter[] {\n return target.filters.filter(\n f => f instanceof FieldFilter && f.field.isEqual(path)\n ) as FieldFilter[];\n}\n\n/**\n * Returns the values that are used in ARRAY_CONTAINS or ARRAY_CONTAINS_ANY\n * filters. Returns `null` if there are no such filters.\n */\nexport function targetGetArrayValues(\n target: Target,\n fieldIndex: FieldIndex\n): ProtoValue[] | null {\n const segment = fieldIndexGetArraySegment(fieldIndex);\n if (segment === undefined) {\n return null;\n }\n\n for (const fieldFilter of targetGetFieldFiltersForPath(\n target,\n segment.fieldPath\n )) {\n switch (fieldFilter.op) {\n case Operator.ARRAY_CONTAINS_ANY:\n return fieldFilter.value.arrayValue!.values || [];\n case Operator.ARRAY_CONTAINS:\n return [fieldFilter.value];\n default:\n // Remaining filters are not array filters.\n }\n }\n return null;\n}\n\n/**\n * Returns the list of values that are used in != or NOT_IN filters. Returns\n * `null` if there are no such filters.\n */\nexport function targetGetNotInValues(\n target: Target,\n fieldIndex: FieldIndex\n): ProtoValue[] | null {\n const values = new Map();\n\n for (const segment of fieldIndexGetDirectionalSegments(fieldIndex)) {\n for (const fieldFilter of targetGetFieldFiltersForPath(\n target,\n segment.fieldPath\n )) {\n switch (fieldFilter.op) {\n case Operator.EQUAL:\n case Operator.IN:\n // Encode equality prefix, which is encoded in the index value before\n // the inequality (e.g. `a == 'a' && b != 'b'` is encoded to\n // `value != 'ab'`).\n values.set(segment.fieldPath.canonicalString(), fieldFilter.value);\n break;\n case Operator.NOT_IN:\n case Operator.NOT_EQUAL:\n // NotIn/NotEqual is always a suffix. There cannot be any remaining\n // segments and hence we can return early here.\n values.set(segment.fieldPath.canonicalString(), fieldFilter.value);\n return Array.from(values.values());\n default:\n // Remaining filters cannot be used as notIn bounds.\n }\n }\n }\n\n return null;\n}\n\n/**\n * Returns a lower bound of field values that can be used as a starting point to\n * scan the index defined by `fieldIndex`. Returns `MIN_VALUE` if no lower bound\n * exists.\n */\nexport function targetGetLowerBound(\n target: Target,\n fieldIndex: FieldIndex\n): Bound {\n const values: ProtoValue[] = [];\n let inclusive = true;\n\n // For each segment, retrieve a lower bound if there is a suitable filter or\n // startAt.\n for (const segment of fieldIndexGetDirectionalSegments(fieldIndex)) {\n const segmentBound =\n segment.kind === IndexKind.ASCENDING\n ? targetGetAscendingBound(target, segment.fieldPath, target.startAt)\n : targetGetDescendingBound(target, segment.fieldPath, target.startAt);\n\n values.push(segmentBound.value);\n inclusive &&= segmentBound.inclusive;\n }\n return new Bound(values, inclusive);\n}\n\n/**\n * Returns an upper bound of field values that can be used as an ending point\n * when scanning the index defined by `fieldIndex`. Returns `MAX_VALUE` if no\n * upper bound exists.\n */\nexport function targetGetUpperBound(\n target: Target,\n fieldIndex: FieldIndex\n): Bound {\n const values: ProtoValue[] = [];\n let inclusive = true;\n\n // For each segment, retrieve an upper bound if there is a suitable filter or\n // endAt.\n for (const segment of fieldIndexGetDirectionalSegments(fieldIndex)) {\n const segmentBound =\n segment.kind === IndexKind.ASCENDING\n ? targetGetDescendingBound(target, segment.fieldPath, target.endAt)\n : targetGetAscendingBound(target, segment.fieldPath, target.endAt);\n\n values.push(segmentBound.value);\n inclusive &&= segmentBound.inclusive;\n }\n\n return new Bound(values, inclusive);\n}\n\n/**\n * Returns the value to use as the lower bound for ascending index segment at\n * the provided `fieldPath` (or the upper bound for an descending segment).\n */\nfunction targetGetAscendingBound(\n target: Target,\n fieldPath: FieldPath,\n bound: Bound | null\n): { value: ProtoValue; inclusive: boolean } {\n let value: ProtoValue = MIN_VALUE;\n\n let inclusive = true;\n\n // Process all filters to find a value for the current field segment\n for (const fieldFilter of targetGetFieldFiltersForPath(target, fieldPath)) {\n let filterValue: ProtoValue = MIN_VALUE;\n let filterInclusive = true;\n\n switch (fieldFilter.op) {\n case Operator.LESS_THAN:\n case Operator.LESS_THAN_OR_EQUAL:\n filterValue = valuesGetLowerBound(fieldFilter.value);\n break;\n case Operator.EQUAL:\n case Operator.IN:\n case Operator.GREATER_THAN_OR_EQUAL:\n filterValue = fieldFilter.value;\n break;\n case Operator.GREATER_THAN:\n filterValue = fieldFilter.value;\n filterInclusive = false;\n break;\n case Operator.NOT_EQUAL:\n case Operator.NOT_IN:\n filterValue = MIN_VALUE;\n break;\n default:\n // Remaining filters cannot be used as lower bounds.\n }\n\n if (\n lowerBoundCompare(\n { value, inclusive },\n { value: filterValue, inclusive: filterInclusive }\n ) < 0\n ) {\n value = filterValue;\n inclusive = filterInclusive;\n }\n }\n\n // If there is an additional bound, compare the values against the existing\n // range to see if we can narrow the scope.\n if (bound !== null) {\n for (let i = 0; i < target.orderBy.length; ++i) {\n const orderBy = target.orderBy[i];\n if (orderBy.field.isEqual(fieldPath)) {\n const cursorValue = bound.position[i];\n if (\n lowerBoundCompare(\n { value, inclusive },\n { value: cursorValue, inclusive: bound.inclusive }\n ) < 0\n ) {\n value = cursorValue;\n inclusive = bound.inclusive;\n }\n break;\n }\n }\n }\n\n return { value, inclusive };\n}\n\n/**\n * Returns the value to use as the upper bound for ascending index segment at\n * the provided `fieldPath` (or the lower bound for a descending segment).\n */\nfunction targetGetDescendingBound(\n target: Target,\n fieldPath: FieldPath,\n bound: Bound | null\n): { value: ProtoValue; inclusive: boolean } {\n let value: ProtoValue = MAX_VALUE;\n let inclusive = true;\n\n // Process all filters to find a value for the current field segment\n for (const fieldFilter of targetGetFieldFiltersForPath(target, fieldPath)) {\n let filterValue: ProtoValue = MAX_VALUE;\n let filterInclusive = true;\n\n switch (fieldFilter.op) {\n case Operator.GREATER_THAN_OR_EQUAL:\n case Operator.GREATER_THAN:\n filterValue = valuesGetUpperBound(fieldFilter.value);\n filterInclusive = false;\n break;\n case Operator.EQUAL:\n case Operator.IN:\n case Operator.LESS_THAN_OR_EQUAL:\n filterValue = fieldFilter.value;\n break;\n case Operator.LESS_THAN:\n filterValue = fieldFilter.value;\n filterInclusive = false;\n break;\n case Operator.NOT_EQUAL:\n case Operator.NOT_IN:\n filterValue = MAX_VALUE;\n break;\n default:\n // Remaining filters cannot be used as upper bounds.\n }\n\n if (\n upperBoundCompare(\n { value, inclusive },\n { value: filterValue, inclusive: filterInclusive }\n ) > 0\n ) {\n value = filterValue;\n inclusive = filterInclusive;\n }\n }\n\n // If there is an additional bound, compare the values against the existing\n // range to see if we can narrow the scope.\n if (bound !== null) {\n for (let i = 0; i < target.orderBy.length; ++i) {\n const orderBy = target.orderBy[i];\n if (orderBy.field.isEqual(fieldPath)) {\n const cursorValue = bound.position[i];\n if (\n upperBoundCompare(\n { value, inclusive },\n { value: cursorValue, inclusive: bound.inclusive }\n ) > 0\n ) {\n value = cursorValue;\n inclusive = bound.inclusive;\n }\n break;\n }\n }\n }\n\n return { value, inclusive };\n}\n\n/** Returns the number of segments of a perfect index for this target. */\nexport function targetGetSegmentCount(target: Target): number {\n let fields = new SortedSet(FieldPath.comparator);\n let hasArraySegment = false;\n\n for (const filter of target.filters) {\n for (const subFilter of filter.getFlattenedFilters()) {\n // __name__ is not an explicit segment of any index, so we don't need to\n // count it.\n if (subFilter.field.isKeyField()) {\n continue;\n }\n\n // ARRAY_CONTAINS or ARRAY_CONTAINS_ANY filters must be counted separately.\n // For instance, it is possible to have an index for \"a ARRAY a ASC\". Even\n // though these are on the same field, they should be counted as two\n // separate segments in an index.\n if (\n subFilter.op === Operator.ARRAY_CONTAINS ||\n subFilter.op === Operator.ARRAY_CONTAINS_ANY\n ) {\n hasArraySegment = true;\n } else {\n fields = fields.add(subFilter.field);\n }\n }\n }\n\n for (const orderBy of target.orderBy) {\n // __name__ is not an explicit segment of any index, so we don't need to\n // count it.\n if (!orderBy.field.isKeyField()) {\n fields = fields.add(orderBy.field);\n }\n }\n\n return fields.size + (hasArraySegment ? 1 : 0);\n}\n\nexport function targetHasLimit(target: Target): boolean {\n return target.limit !== null;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { compareDocumentsByField, Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { FieldPath, ResourcePath } from '../model/path';\nimport { debugAssert, debugCast, fail } from '../util/assert';\nimport { SortedSet } from '../util/sorted_set';\n\nimport {\n Bound,\n boundSortsAfterDocument,\n boundSortsBeforeDocument\n} from './bound';\nimport { FieldFilter, Filter } from './filter';\nimport { Direction, OrderBy } from './order_by';\nimport {\n canonifyTarget,\n newTarget,\n stringifyTarget,\n Target,\n targetEquals\n} from './target';\n\nexport const enum LimitType {\n First = 'F',\n Last = 'L'\n}\n\n/**\n * The Query interface defines all external properties of a query.\n *\n * QueryImpl implements this interface to provide memoization for `queryNormalizedOrderBy`\n * and `queryToTarget`.\n */\nexport interface Query {\n readonly path: ResourcePath;\n readonly collectionGroup: string | null;\n readonly explicitOrderBy: OrderBy[];\n readonly filters: Filter[];\n readonly limit: number | null;\n readonly limitType: LimitType;\n readonly startAt: Bound | null;\n readonly endAt: Bound | null;\n}\n\n/**\n * Query encapsulates all the query attributes we support in the SDK. It can\n * be run against the LocalStore, as well as be converted to a `Target` to\n * query the RemoteStore results.\n *\n * Visible for testing.\n */\nexport class QueryImpl implements Query {\n memoizedNormalizedOrderBy: OrderBy[] | null = null;\n\n // The corresponding `Target` of this `Query` instance, for use with\n // non-aggregate queries.\n memoizedTarget: Target | null = null;\n\n // The corresponding `Target` of this `Query` instance, for use with\n // aggregate queries. Unlike targets for non-aggregate queries,\n // aggregate query targets do not contain normalized order-bys, they only\n // contain explicit order-bys.\n memoizedAggregateTarget: Target | null = null;\n\n /**\n * Initializes a Query with a path and optional additional query constraints.\n * Path must currently be empty if this is a collection group query.\n */\n constructor(\n readonly path: ResourcePath,\n readonly collectionGroup: string | null = null,\n readonly explicitOrderBy: OrderBy[] = [],\n readonly filters: Filter[] = [],\n readonly limit: number | null = null,\n readonly limitType: LimitType = LimitType.First,\n readonly startAt: Bound | null = null,\n readonly endAt: Bound | null = null\n ) {\n if (this.startAt) {\n debugAssert(\n this.startAt.position.length <= queryNormalizedOrderBy(this).length,\n 'Bound is longer than orderBy'\n );\n }\n if (this.endAt) {\n debugAssert(\n this.endAt.position.length <= queryNormalizedOrderBy(this).length,\n 'Bound is longer than orderBy'\n );\n }\n }\n}\n\n/** Creates a new Query instance with the options provided. */\nexport function newQuery(\n path: ResourcePath,\n collectionGroup: string | null,\n explicitOrderBy: OrderBy[],\n filters: Filter[],\n limit: number | null,\n limitType: LimitType,\n startAt: Bound | null,\n endAt: Bound | null\n): Query {\n return new QueryImpl(\n path,\n collectionGroup,\n explicitOrderBy,\n filters,\n limit,\n limitType,\n startAt,\n endAt\n );\n}\n\n/** Creates a new Query for a query that matches all documents at `path` */\nexport function newQueryForPath(path: ResourcePath): Query {\n return new QueryImpl(path);\n}\n\n/**\n * Helper to convert a collection group query into a collection query at a\n * specific path. This is used when executing collection group queries, since\n * we have to split the query into a set of collection queries at multiple\n * paths.\n */\nexport function asCollectionQueryAtPath(\n query: Query,\n path: ResourcePath\n): Query {\n return new QueryImpl(\n path,\n /*collectionGroup=*/ null,\n query.explicitOrderBy.slice(),\n query.filters.slice(),\n query.limit,\n query.limitType,\n query.startAt,\n query.endAt\n );\n}\n\n/**\n * Returns true if this query does not specify any query constraints that\n * could remove results.\n */\nexport function queryMatchesAllDocuments(query: Query): boolean {\n return (\n query.filters.length === 0 &&\n query.limit === null &&\n query.startAt == null &&\n query.endAt == null &&\n (query.explicitOrderBy.length === 0 ||\n (query.explicitOrderBy.length === 1 &&\n query.explicitOrderBy[0].field.isKeyField()))\n );\n}\n\n// Returns the sorted set of inequality filter fields used in this query.\nexport function getInequalityFilterFields(query: Query): SortedSet {\n let result = new SortedSet(FieldPath.comparator);\n query.filters.forEach((filter: Filter) => {\n const subFilters = filter.getFlattenedFilters();\n subFilters.forEach((filter: FieldFilter) => {\n if (filter.isInequality()) {\n result = result.add(filter.field);\n }\n });\n });\n return result;\n}\n\n/**\n * Creates a new Query for a collection group query that matches all documents\n * within the provided collection group.\n */\nexport function newQueryForCollectionGroup(collectionId: string): Query {\n return new QueryImpl(ResourcePath.emptyPath(), collectionId);\n}\n\n/**\n * Returns whether the query matches a single document by path (rather than a\n * collection).\n */\nexport function isDocumentQuery(query: Query): boolean {\n return (\n DocumentKey.isDocumentKey(query.path) &&\n query.collectionGroup === null &&\n query.filters.length === 0\n );\n}\n\n/**\n * Returns whether the query matches a collection group rather than a specific\n * collection.\n */\nexport function isCollectionGroupQuery(query: Query): boolean {\n return query.collectionGroup !== null;\n}\n\n/**\n * Returns the normalized order-by constraint that is used to execute the Query,\n * which can be different from the order-by constraints the user provided (e.g.\n * the SDK and backend always orders by `__name__`). The normalized order-by\n * includes implicit order-bys in addition to the explicit user provided\n * order-bys.\n */\nexport function queryNormalizedOrderBy(query: Query): OrderBy[] {\n const queryImpl = debugCast(query, QueryImpl);\n if (queryImpl.memoizedNormalizedOrderBy === null) {\n queryImpl.memoizedNormalizedOrderBy = [];\n const fieldsNormalized = new Set();\n\n // Any explicit order by fields should be added as is.\n for (const orderBy of queryImpl.explicitOrderBy) {\n queryImpl.memoizedNormalizedOrderBy.push(orderBy);\n fieldsNormalized.add(orderBy.field.canonicalString());\n }\n\n // The order of the implicit ordering always matches the last explicit order by.\n const lastDirection =\n queryImpl.explicitOrderBy.length > 0\n ? queryImpl.explicitOrderBy[queryImpl.explicitOrderBy.length - 1].dir\n : Direction.ASCENDING;\n\n // Any inequality fields not explicitly ordered should be implicitly ordered in a lexicographical\n // order. When there are multiple inequality filters on the same field, the field should be added\n // only once.\n // Note: `SortedSet` sorts the key field before other fields. However, we want the key\n // field to be sorted last.\n const inequalityFields: SortedSet =\n getInequalityFilterFields(queryImpl);\n inequalityFields.forEach(field => {\n if (\n !fieldsNormalized.has(field.canonicalString()) &&\n !field.isKeyField()\n ) {\n queryImpl.memoizedNormalizedOrderBy!.push(\n new OrderBy(field, lastDirection)\n );\n }\n });\n\n // Add the document key field to the last if it is not explicitly ordered.\n if (!fieldsNormalized.has(FieldPath.keyField().canonicalString())) {\n queryImpl.memoizedNormalizedOrderBy.push(\n new OrderBy(FieldPath.keyField(), lastDirection)\n );\n }\n }\n return queryImpl.memoizedNormalizedOrderBy;\n}\n\n/**\n * Converts this `Query` instance to its corresponding `Target` representation.\n */\nexport function queryToTarget(query: Query): Target {\n const queryImpl = debugCast(query, QueryImpl);\n if (!queryImpl.memoizedTarget) {\n queryImpl.memoizedTarget = _queryToTarget(\n queryImpl,\n queryNormalizedOrderBy(query)\n );\n }\n\n return queryImpl.memoizedTarget;\n}\n\n/**\n * Converts this `Query` instance to its corresponding `Target` representation,\n * for use within an aggregate query. Unlike targets for non-aggregate queries,\n * aggregate query targets do not contain normalized order-bys, they only\n * contain explicit order-bys.\n */\nexport function queryToAggregateTarget(query: Query): Target {\n const queryImpl = debugCast(query, QueryImpl);\n\n if (!queryImpl.memoizedAggregateTarget) {\n // Do not include implicit order-bys for aggregate queries.\n queryImpl.memoizedAggregateTarget = _queryToTarget(\n queryImpl,\n query.explicitOrderBy\n );\n }\n\n return queryImpl.memoizedAggregateTarget;\n}\n\nfunction _queryToTarget(queryImpl: QueryImpl, orderBys: OrderBy[]): Target {\n if (queryImpl.limitType === LimitType.First) {\n return newTarget(\n queryImpl.path,\n queryImpl.collectionGroup,\n orderBys,\n queryImpl.filters,\n queryImpl.limit,\n queryImpl.startAt,\n queryImpl.endAt\n );\n } else {\n // Flip the orderBy directions since we want the last results\n orderBys = orderBys.map(orderBy => {\n const dir =\n orderBy.dir === Direction.DESCENDING\n ? Direction.ASCENDING\n : Direction.DESCENDING;\n return new OrderBy(orderBy.field, dir);\n });\n\n // We need to swap the cursors to match the now-flipped query ordering.\n const startAt = queryImpl.endAt\n ? new Bound(queryImpl.endAt.position, queryImpl.endAt.inclusive)\n : null;\n const endAt = queryImpl.startAt\n ? new Bound(queryImpl.startAt.position, queryImpl.startAt.inclusive)\n : null;\n\n // Now return as a LimitType.First query.\n return newTarget(\n queryImpl.path,\n queryImpl.collectionGroup,\n orderBys,\n queryImpl.filters,\n queryImpl.limit,\n startAt,\n endAt\n );\n }\n}\n\nexport function queryWithAddedFilter(query: Query, filter: Filter): Query {\n debugAssert(\n !isDocumentQuery(query),\n 'No filtering allowed for document query'\n );\n\n const newFilters = query.filters.concat([filter]);\n return new QueryImpl(\n query.path,\n query.collectionGroup,\n query.explicitOrderBy.slice(),\n newFilters,\n query.limit,\n query.limitType,\n query.startAt,\n query.endAt\n );\n}\n\nexport function queryWithAddedOrderBy(query: Query, orderBy: OrderBy): Query {\n debugAssert(\n !query.startAt && !query.endAt,\n 'Bounds must be set after orderBy'\n );\n // TODO(dimond): validate that orderBy does not list the same key twice.\n const newOrderBy = query.explicitOrderBy.concat([orderBy]);\n return new QueryImpl(\n query.path,\n query.collectionGroup,\n newOrderBy,\n query.filters.slice(),\n query.limit,\n query.limitType,\n query.startAt,\n query.endAt\n );\n}\n\nexport function queryWithLimit(\n query: Query,\n limit: number | null,\n limitType: LimitType\n): Query {\n return new QueryImpl(\n query.path,\n query.collectionGroup,\n query.explicitOrderBy.slice(),\n query.filters.slice(),\n limit,\n limitType,\n query.startAt,\n query.endAt\n );\n}\n\nexport function queryWithStartAt(query: Query, bound: Bound): Query {\n return new QueryImpl(\n query.path,\n query.collectionGroup,\n query.explicitOrderBy.slice(),\n query.filters.slice(),\n query.limit,\n query.limitType,\n bound,\n query.endAt\n );\n}\n\nexport function queryWithEndAt(query: Query, bound: Bound): Query {\n return new QueryImpl(\n query.path,\n query.collectionGroup,\n query.explicitOrderBy.slice(),\n query.filters.slice(),\n query.limit,\n query.limitType,\n query.startAt,\n bound\n );\n}\n\nexport function queryEquals(left: Query, right: Query): boolean {\n return (\n targetEquals(queryToTarget(left), queryToTarget(right)) &&\n left.limitType === right.limitType\n );\n}\n\n// TODO(b/29183165): This is used to get a unique string from a query to, for\n// example, use as a dictionary key, but the implementation is subject to\n// collisions. Make it collision-free.\nexport function canonifyQuery(query: Query): string {\n return `${canonifyTarget(queryToTarget(query))}|lt:${query.limitType}`;\n}\n\nexport function stringifyQuery(query: Query): string {\n return `Query(target=${stringifyTarget(queryToTarget(query))}; limitType=${\n query.limitType\n })`;\n}\n\n/** Returns whether `doc` matches the constraints of `query`. */\nexport function queryMatches(query: Query, doc: Document): boolean {\n return (\n doc.isFoundDocument() &&\n queryMatchesPathAndCollectionGroup(query, doc) &&\n queryMatchesOrderBy(query, doc) &&\n queryMatchesFilters(query, doc) &&\n queryMatchesBounds(query, doc)\n );\n}\n\nfunction queryMatchesPathAndCollectionGroup(\n query: Query,\n doc: Document\n): boolean {\n const docPath = doc.key.path;\n if (query.collectionGroup !== null) {\n // NOTE: this.path is currently always empty since we don't expose Collection\n // Group queries rooted at a document path yet.\n return (\n doc.key.hasCollectionId(query.collectionGroup) &&\n query.path.isPrefixOf(docPath)\n );\n } else if (DocumentKey.isDocumentKey(query.path)) {\n // exact match for document queries\n return query.path.isEqual(docPath);\n } else {\n // shallow ancestor queries by default\n return query.path.isImmediateParentOf(docPath);\n }\n}\n\n/**\n * A document must have a value for every ordering clause in order to show up\n * in the results.\n */\nfunction queryMatchesOrderBy(query: Query, doc: Document): boolean {\n // We must use `queryNormalizedOrderBy()` to get the list of all orderBys (both implicit and explicit).\n // Note that for OR queries, orderBy applies to all disjunction terms and implicit orderBys must\n // be taken into account. For example, the query \"a > 1 || b==1\" has an implicit \"orderBy a\" due\n // to the inequality, and is evaluated as \"a > 1 orderBy a || b==1 orderBy a\".\n // A document with content of {b:1} matches the filters, but does not match the orderBy because\n // it's missing the field 'a'.\n for (const orderBy of queryNormalizedOrderBy(query)) {\n // order-by key always matches\n if (!orderBy.field.isKeyField() && doc.data.field(orderBy.field) === null) {\n return false;\n }\n }\n return true;\n}\n\nfunction queryMatchesFilters(query: Query, doc: Document): boolean {\n for (const filter of query.filters) {\n if (!filter.matches(doc)) {\n return false;\n }\n }\n return true;\n}\n\n/** Makes sure a document is within the bounds, if provided. */\nfunction queryMatchesBounds(query: Query, doc: Document): boolean {\n if (\n query.startAt &&\n !boundSortsBeforeDocument(query.startAt, queryNormalizedOrderBy(query), doc)\n ) {\n return false;\n }\n if (\n query.endAt &&\n !boundSortsAfterDocument(query.endAt, queryNormalizedOrderBy(query), doc)\n ) {\n return false;\n }\n return true;\n}\n\n/**\n * Returns the collection group that this query targets.\n *\n * PORTING NOTE: This is only used in the Web SDK to facilitate multi-tab\n * synchronization for query results.\n */\nexport function queryCollectionGroup(query: Query): string {\n return (\n query.collectionGroup ||\n (query.path.length % 2 === 1\n ? query.path.lastSegment()\n : query.path.get(query.path.length - 2))\n );\n}\n\n/**\n * Returns a new comparator function that can be used to compare two documents\n * based on the Query's ordering constraint.\n */\nexport function newQueryComparator(\n query: Query\n): (d1: Document, d2: Document) => number {\n return (d1: Document, d2: Document): number => {\n let comparedOnKeyField = false;\n for (const orderBy of queryNormalizedOrderBy(query)) {\n const comp = compareDocs(orderBy, d1, d2);\n if (comp !== 0) {\n return comp;\n }\n comparedOnKeyField = comparedOnKeyField || orderBy.field.isKeyField();\n }\n // Assert that we actually compared by key\n debugAssert(\n comparedOnKeyField,\n \"orderBy used that doesn't compare on key field\"\n );\n return 0;\n };\n}\n\nexport function compareDocs(\n orderBy: OrderBy,\n d1: Document,\n d2: Document\n): number {\n const comparison = orderBy.field.isKeyField()\n ? DocumentKey.comparator(d1.key, d2.key)\n : compareDocumentsByField(orderBy.field, d1, d2);\n switch (orderBy.dir) {\n case Direction.ASCENDING:\n return comparison;\n case Direction.DESCENDING:\n return -1 * comparison;\n default:\n return fail(0x4d4e, 'Unknown direction', { direction: orderBy.dir });\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Value as ProtoValue } from '../protos/firestore_proto_api';\nimport { isNegativeZero, isSafeInteger } from '../util/types';\n\n/** Base interface for the Serializer implementation. */\nexport interface Serializer {\n readonly useProto3Json: boolean;\n}\n\n/**\n * Returns an DoubleValue for `value` that is encoded based the serializer's\n * `useProto3Json` setting.\n */\nexport function toDouble(serializer: Serializer, value: number): ProtoValue {\n if (serializer.useProto3Json) {\n if (isNaN(value)) {\n return { doubleValue: 'NaN' };\n } else if (value === Infinity) {\n return { doubleValue: 'Infinity' };\n } else if (value === -Infinity) {\n return { doubleValue: '-Infinity' };\n }\n }\n return { doubleValue: isNegativeZero(value) ? '-0' : value };\n}\n\n/**\n * Returns an IntegerValue for `value`.\n */\nexport function toInteger(value: number): ProtoValue {\n return { integerValue: '' + value };\n}\n\n/**\n * Returns a value for a number that's appropriate to put into a proto.\n * The return value is an IntegerValue if it can safely represent the value,\n * otherwise a DoubleValue is returned.\n */\nexport function toNumber(serializer: Serializer, value: number): ProtoValue {\n return isSafeInteger(value) ? toInteger(value) : toDouble(serializer, value);\n}\n","/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Timestamp } from '../lite-api/timestamp';\nimport { Value as ProtoValue } from '../protos/firestore_proto_api';\nimport { Serializer, toDouble, toInteger } from '../remote/number_serializer';\nimport { debugAssert } from '../util/assert';\nimport { arrayEquals } from '../util/misc';\n\nimport { normalizeNumber } from './normalize';\nimport { serverTimestamp } from './server_timestamps';\nimport { isArray, isInteger, isNumber, valueEquals } from './values';\n\n/** Used to represent a field transform on a mutation. */\nexport class TransformOperation {\n // Make sure that the structural type of `TransformOperation` is unique.\n // See https://github.com/microsoft/TypeScript/issues/5451\n private _ = undefined;\n}\n\n/**\n * Computes the local transform result against the provided `previousValue`,\n * optionally using the provided localWriteTime.\n */\nexport function applyTransformOperationToLocalView(\n transform: TransformOperation,\n previousValue: ProtoValue | null,\n localWriteTime: Timestamp\n): ProtoValue {\n if (transform instanceof ServerTimestampTransform) {\n return serverTimestamp(localWriteTime, previousValue);\n } else if (transform instanceof ArrayUnionTransformOperation) {\n return applyArrayUnionTransformOperation(transform, previousValue);\n } else if (transform instanceof ArrayRemoveTransformOperation) {\n return applyArrayRemoveTransformOperation(transform, previousValue);\n } else {\n debugAssert(\n transform instanceof NumericIncrementTransformOperation,\n 'Expected NumericIncrementTransformOperation but was: ' + transform\n );\n return applyNumericIncrementTransformOperationToLocalView(\n transform,\n previousValue\n );\n }\n}\n\n/**\n * Computes a final transform result after the transform has been acknowledged\n * by the server, potentially using the server-provided transformResult.\n */\nexport function applyTransformOperationToRemoteDocument(\n transform: TransformOperation,\n previousValue: ProtoValue | null,\n transformResult: ProtoValue | null\n): ProtoValue {\n // The server just sends null as the transform result for array operations,\n // so we have to calculate a result the same as we do for local\n // applications.\n if (transform instanceof ArrayUnionTransformOperation) {\n return applyArrayUnionTransformOperation(transform, previousValue);\n } else if (transform instanceof ArrayRemoveTransformOperation) {\n return applyArrayRemoveTransformOperation(transform, previousValue);\n }\n\n debugAssert(\n transformResult !== null,\n \"Didn't receive transformResult for non-array transform\"\n );\n return transformResult;\n}\n\n/**\n * If this transform operation is not idempotent, returns the base value to\n * persist for this transform. If a base value is returned, the transform\n * operation is always applied to this base value, even if document has\n * already been updated.\n *\n * Base values provide consistent behavior for non-idempotent transforms and\n * allow us to return the same latency-compensated value even if the backend\n * has already applied the transform operation. The base value is null for\n * idempotent transforms, as they can be re-played even if the backend has\n * already applied them.\n *\n * @returns a base value to store along with the mutation, or null for\n * idempotent transforms.\n */\nexport function computeTransformOperationBaseValue(\n transform: TransformOperation,\n previousValue: ProtoValue | null\n): ProtoValue | null {\n if (transform instanceof NumericIncrementTransformOperation) {\n return isNumber(previousValue) ? previousValue! : { integerValue: 0 };\n }\n return null;\n}\n\nexport function transformOperationEquals(\n left: TransformOperation,\n right: TransformOperation\n): boolean {\n if (\n left instanceof ArrayUnionTransformOperation &&\n right instanceof ArrayUnionTransformOperation\n ) {\n return arrayEquals(left.elements, right.elements, valueEquals);\n } else if (\n left instanceof ArrayRemoveTransformOperation &&\n right instanceof ArrayRemoveTransformOperation\n ) {\n return arrayEquals(left.elements, right.elements, valueEquals);\n } else if (\n left instanceof NumericIncrementTransformOperation &&\n right instanceof NumericIncrementTransformOperation\n ) {\n return valueEquals(left.operand, right.operand);\n }\n\n return (\n left instanceof ServerTimestampTransform &&\n right instanceof ServerTimestampTransform\n );\n}\n\n/** Transforms a value into a server-generated timestamp. */\nexport class ServerTimestampTransform extends TransformOperation {}\n\n/** Transforms an array value via a union operation. */\nexport class ArrayUnionTransformOperation extends TransformOperation {\n constructor(readonly elements: ProtoValue[]) {\n super();\n }\n}\n\nfunction applyArrayUnionTransformOperation(\n transform: ArrayUnionTransformOperation,\n previousValue: ProtoValue | null\n): ProtoValue {\n const values = coercedFieldValuesArray(previousValue);\n for (const toUnion of transform.elements) {\n if (!values.some(element => valueEquals(element, toUnion))) {\n values.push(toUnion);\n }\n }\n return { arrayValue: { values } };\n}\n\n/** Transforms an array value via a remove operation. */\nexport class ArrayRemoveTransformOperation extends TransformOperation {\n constructor(readonly elements: ProtoValue[]) {\n super();\n }\n}\n\nfunction applyArrayRemoveTransformOperation(\n transform: ArrayRemoveTransformOperation,\n previousValue: ProtoValue | null\n): ProtoValue {\n let values = coercedFieldValuesArray(previousValue);\n for (const toRemove of transform.elements) {\n values = values.filter(element => !valueEquals(element, toRemove));\n }\n return { arrayValue: { values } };\n}\n\n/**\n * Implements the backend semantics for locally computed NUMERIC_ADD (increment)\n * transforms. Converts all field values to integers or doubles, but unlike the\n * backend does not cap integer values at 2^63. Instead, JavaScript number\n * arithmetic is used and precision loss can occur for values greater than 2^53.\n */\nexport class NumericIncrementTransformOperation extends TransformOperation {\n constructor(readonly serializer: Serializer, readonly operand: ProtoValue) {\n super();\n debugAssert(\n isNumber(operand),\n 'NumericIncrementTransform transform requires a NumberValue'\n );\n }\n}\n\nexport function applyNumericIncrementTransformOperationToLocalView(\n transform: NumericIncrementTransformOperation,\n previousValue: ProtoValue | null\n): ProtoValue {\n // PORTING NOTE: Since JavaScript's integer arithmetic is limited to 53 bit\n // precision and resolves overflows by reducing precision, we do not\n // manually cap overflows at 2^63.\n const baseValue = computeTransformOperationBaseValue(\n transform,\n previousValue\n )!;\n const sum = asNumber(baseValue) + asNumber(transform.operand);\n if (isInteger(baseValue) && isInteger(transform.operand)) {\n return toInteger(sum);\n } else {\n return toDouble(transform.serializer, sum);\n }\n}\n\nfunction asNumber(value: ProtoValue): number {\n return normalizeNumber(value.integerValue || value.doubleValue);\n}\n\nfunction coercedFieldValuesArray(value: ProtoValue | null): ProtoValue[] {\n return isArray(value) && value.arrayValue.values\n ? value.arrayValue.values.slice()\n : [];\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { Timestamp } from '../lite-api/timestamp';\nimport { Value as ProtoValue } from '../protos/firestore_proto_api';\nimport { debugAssert, hardAssert } from '../util/assert';\nimport { arrayEquals } from '../util/misc';\nimport { SortedSet } from '../util/sorted_set';\n\nimport { Document, MutableDocument } from './document';\nimport { DocumentKey } from './document_key';\nimport { FieldMask } from './field_mask';\nimport { ObjectValue } from './object_value';\nimport { FieldPath } from './path';\nimport {\n applyTransformOperationToLocalView,\n applyTransformOperationToRemoteDocument,\n computeTransformOperationBaseValue,\n TransformOperation,\n transformOperationEquals\n} from './transform_operation';\n\n/** A field path and the TransformOperation to perform upon it. */\nexport class FieldTransform {\n constructor(\n readonly field: FieldPath,\n readonly transform: TransformOperation\n ) {}\n}\n\nexport function fieldTransformEquals(\n left: FieldTransform,\n right: FieldTransform\n): boolean {\n return (\n left.field.isEqual(right.field) &&\n transformOperationEquals(left.transform, right.transform)\n );\n}\n\nexport function fieldTransformsAreEqual(\n left?: FieldTransform[],\n right?: FieldTransform[]\n): boolean {\n if (left === undefined && right === undefined) {\n return true;\n }\n\n if (left && right) {\n return arrayEquals(left, right, (l, r) => fieldTransformEquals(l, r));\n }\n\n return false;\n}\n\n/** The result of successfully applying a mutation to the backend. */\nexport class MutationResult {\n constructor(\n /**\n * The version at which the mutation was committed:\n *\n * - For most operations, this is the updateTime in the WriteResult.\n * - For deletes, the commitTime of the WriteResponse (because deletes are\n * not stored and have no updateTime).\n *\n * Note that these versions can be different: No-op writes will not change\n * the updateTime even though the commitTime advances.\n */\n readonly version: SnapshotVersion,\n /**\n * The resulting fields returned from the backend after a mutation\n * containing field transforms has been committed. Contains one FieldValue\n * for each FieldTransform that was in the mutation.\n *\n * Will be empty if the mutation did not contain any field transforms.\n */\n readonly transformResults: Array\n ) {}\n}\n\nexport const enum MutationType {\n Set,\n Patch,\n Delete,\n Verify\n}\n\n/**\n * Encodes a precondition for a mutation. This follows the model that the\n * backend accepts with the special case of an explicit \"empty\" precondition\n * (meaning no precondition).\n */\nexport class Precondition {\n private constructor(\n readonly updateTime?: SnapshotVersion,\n readonly exists?: boolean\n ) {\n debugAssert(\n updateTime === undefined || exists === undefined,\n 'Precondition can specify \"exists\" or \"updateTime\" but not both'\n );\n }\n\n /** Creates a new empty Precondition. */\n static none(): Precondition {\n return new Precondition();\n }\n\n /** Creates a new Precondition with an exists flag. */\n static exists(exists: boolean): Precondition {\n return new Precondition(undefined, exists);\n }\n\n /** Creates a new Precondition based on a version a document exists at. */\n static updateTime(version: SnapshotVersion): Precondition {\n return new Precondition(version);\n }\n\n /** Returns whether this Precondition is empty. */\n get isNone(): boolean {\n return this.updateTime === undefined && this.exists === undefined;\n }\n\n isEqual(other: Precondition): boolean {\n return (\n this.exists === other.exists &&\n (this.updateTime\n ? !!other.updateTime && this.updateTime.isEqual(other.updateTime)\n : !other.updateTime)\n );\n }\n}\n\n/** Returns true if the preconditions is valid for the given document. */\nexport function preconditionIsValidForDocument(\n precondition: Precondition,\n document: MutableDocument\n): boolean {\n if (precondition.updateTime !== undefined) {\n return (\n document.isFoundDocument() &&\n document.version.isEqual(precondition.updateTime)\n );\n } else if (precondition.exists !== undefined) {\n return precondition.exists === document.isFoundDocument();\n } else {\n debugAssert(precondition.isNone, 'Precondition should be empty');\n return true;\n }\n}\n\n/**\n * A mutation describes a self-contained change to a document. Mutations can\n * create, replace, delete, and update subsets of documents.\n *\n * Mutations not only act on the value of the document but also its version.\n *\n * For local mutations (mutations that haven't been committed yet), we preserve\n * the existing version for Set and Patch mutations. For Delete mutations, we\n * reset the version to 0.\n *\n * Here's the expected transition table.\n *\n * MUTATION APPLIED TO RESULTS IN\n *\n * SetMutation Document(v3) Document(v3)\n * SetMutation NoDocument(v3) Document(v0)\n * SetMutation InvalidDocument(v0) Document(v0)\n * PatchMutation Document(v3) Document(v3)\n * PatchMutation NoDocument(v3) NoDocument(v3)\n * PatchMutation InvalidDocument(v0) UnknownDocument(v3)\n * DeleteMutation Document(v3) NoDocument(v0)\n * DeleteMutation NoDocument(v3) NoDocument(v0)\n * DeleteMutation InvalidDocument(v0) NoDocument(v0)\n *\n * For acknowledged mutations, we use the updateTime of the WriteResponse as\n * the resulting version for Set and Patch mutations. As deletes have no\n * explicit update time, we use the commitTime of the WriteResponse for\n * Delete mutations.\n *\n * If a mutation is acknowledged by the backend but fails the precondition check\n * locally, we transition to an `UnknownDocument` and rely on Watch to send us\n * the updated version.\n *\n * Field transforms are used only with Patch and Set Mutations. We use the\n * `updateTransforms` message to store transforms, rather than the `transforms`s\n * messages.\n *\n * ## Subclassing Notes\n *\n * Every type of mutation needs to implement its own applyToRemoteDocument() and\n * applyToLocalView() to implement the actual behavior of applying the mutation\n * to some source document (see `setMutationApplyToRemoteDocument()` for an\n * example).\n */\nexport abstract class Mutation {\n abstract readonly type: MutationType;\n abstract readonly key: DocumentKey;\n abstract readonly precondition: Precondition;\n abstract readonly fieldTransforms: FieldTransform[];\n /**\n * Returns a `FieldMask` representing the fields that will be changed by\n * applying this mutation. Returns `null` if the mutation will overwrite the\n * entire document.\n */\n abstract getFieldMask(): FieldMask | null;\n}\n\n/**\n * A utility method to calculate a `Mutation` representing the overlay from the\n * final state of the document, and a `FieldMask` representing the fields that\n * are mutated by the local mutations.\n */\nexport function calculateOverlayMutation(\n doc: MutableDocument,\n mask: FieldMask | null\n): Mutation | null {\n if (!doc.hasLocalMutations || (mask && mask!.fields.length === 0)) {\n return null;\n }\n\n // mask is null when sets or deletes are applied to the current document.\n if (mask === null) {\n if (doc.isNoDocument()) {\n return new DeleteMutation(doc.key, Precondition.none());\n } else {\n return new SetMutation(doc.key, doc.data, Precondition.none());\n }\n } else {\n const docValue = doc.data;\n const patchValue = ObjectValue.empty();\n let maskSet = new SortedSet(FieldPath.comparator);\n for (let path of mask.fields) {\n if (!maskSet.has(path)) {\n let value = docValue.field(path);\n // If we are deleting a nested field, we take the immediate parent as\n // the mask used to construct the resulting mutation.\n // Justification: Nested fields can create parent fields implicitly. If\n // only a leaf entry is deleted in later mutations, the parent field\n // should still remain, but we may have lost this information.\n // Consider mutation (foo.bar 1), then mutation (foo.bar delete()).\n // This leaves the final result (foo, {}). Despite the fact that `doc`\n // has the correct result, `foo` is not in `mask`, and the resulting\n // mutation would miss `foo`.\n if (value === null && path.length > 1) {\n path = path.popLast();\n value = docValue.field(path);\n }\n if (value === null) {\n patchValue.delete(path);\n } else {\n patchValue.set(path, value);\n }\n maskSet = maskSet.add(path);\n }\n }\n return new PatchMutation(\n doc.key,\n patchValue,\n new FieldMask(maskSet.toArray()),\n Precondition.none()\n );\n }\n}\n\n/**\n * Applies this mutation to the given document for the purposes of computing a\n * new remote document. If the input document doesn't match the expected state\n * (e.g. it is invalid or outdated), the document type may transition to\n * unknown.\n *\n * @param mutation - The mutation to apply.\n * @param document - The document to mutate. The input document can be an\n * invalid document if the client has no knowledge of the pre-mutation state\n * of the document.\n * @param mutationResult - The result of applying the mutation from the backend.\n */\nexport function mutationApplyToRemoteDocument(\n mutation: Mutation,\n document: MutableDocument,\n mutationResult: MutationResult\n): void {\n mutationVerifyKeyMatches(mutation, document);\n if (mutation instanceof SetMutation) {\n setMutationApplyToRemoteDocument(mutation, document, mutationResult);\n } else if (mutation instanceof PatchMutation) {\n patchMutationApplyToRemoteDocument(mutation, document, mutationResult);\n } else {\n debugAssert(\n mutation instanceof DeleteMutation,\n 'Unexpected mutation type: ' + mutation\n );\n deleteMutationApplyToRemoteDocument(mutation, document, mutationResult);\n }\n}\n\n/**\n * Applies this mutation to the given document for the purposes of computing\n * the new local view of a document. If the input document doesn't match the\n * expected state, the document is not modified.\n *\n * @param mutation - The mutation to apply.\n * @param document - The document to mutate. The input document can be an\n * invalid document if the client has no knowledge of the pre-mutation state\n * of the document.\n * @param previousMask - The fields that have been updated before applying this mutation.\n * @param localWriteTime - A timestamp indicating the local write time of the\n * batch this mutation is a part of.\n * @returns A `FieldMask` representing the fields that are changed by applying this mutation.\n */\nexport function mutationApplyToLocalView(\n mutation: Mutation,\n document: MutableDocument,\n previousMask: FieldMask | null,\n localWriteTime: Timestamp\n): FieldMask | null {\n mutationVerifyKeyMatches(mutation, document);\n\n if (mutation instanceof SetMutation) {\n return setMutationApplyToLocalView(\n mutation,\n document,\n previousMask,\n localWriteTime\n );\n } else if (mutation instanceof PatchMutation) {\n return patchMutationApplyToLocalView(\n mutation,\n document,\n previousMask,\n localWriteTime\n );\n } else {\n debugAssert(\n mutation instanceof DeleteMutation,\n 'Unexpected mutation type: ' + mutation\n );\n return deleteMutationApplyToLocalView(mutation, document, previousMask);\n }\n}\n\n/**\n * If this mutation is not idempotent, returns the base value to persist with\n * this mutation. If a base value is returned, the mutation is always applied\n * to this base value, even if document has already been updated.\n *\n * The base value is a sparse object that consists of only the document\n * fields for which this mutation contains a non-idempotent transformation\n * (e.g. a numeric increment). The provided value guarantees consistent\n * behavior for non-idempotent transforms and allow us to return the same\n * latency-compensated value even if the backend has already applied the\n * mutation. The base value is null for idempotent mutations, as they can be\n * re-played even if the backend has already applied them.\n *\n * @returns a base value to store along with the mutation, or null for\n * idempotent mutations.\n */\nexport function mutationExtractBaseValue(\n mutation: Mutation,\n document: Document\n): ObjectValue | null {\n let baseObject: ObjectValue | null = null;\n for (const fieldTransform of mutation.fieldTransforms) {\n const existingValue = document.data.field(fieldTransform.field);\n const coercedValue = computeTransformOperationBaseValue(\n fieldTransform.transform,\n existingValue || null\n );\n\n if (coercedValue != null) {\n if (baseObject === null) {\n baseObject = ObjectValue.empty();\n }\n baseObject.set(fieldTransform.field, coercedValue);\n }\n }\n return baseObject ? baseObject : null;\n}\n\nexport function mutationEquals(left: Mutation, right: Mutation): boolean {\n if (left.type !== right.type) {\n return false;\n }\n\n if (!left.key.isEqual(right.key)) {\n return false;\n }\n\n if (!left.precondition.isEqual(right.precondition)) {\n return false;\n }\n\n if (!fieldTransformsAreEqual(left.fieldTransforms, right.fieldTransforms)) {\n return false;\n }\n\n if (left.type === MutationType.Set) {\n return (left as SetMutation).value.isEqual((right as SetMutation).value);\n }\n\n if (left.type === MutationType.Patch) {\n return (\n (left as PatchMutation).data.isEqual((right as PatchMutation).data) &&\n (left as PatchMutation).fieldMask.isEqual(\n (right as PatchMutation).fieldMask\n )\n );\n }\n\n return true;\n}\n\nfunction mutationVerifyKeyMatches(\n mutation: Mutation,\n document: MutableDocument\n): void {\n debugAssert(\n document.key.isEqual(mutation.key),\n 'Can only apply a mutation to a document with the same key'\n );\n}\n\n/**\n * A mutation that creates or replaces the document at the given key with the\n * object value contents.\n */\nexport class SetMutation extends Mutation {\n constructor(\n readonly key: DocumentKey,\n readonly value: ObjectValue,\n readonly precondition: Precondition,\n readonly fieldTransforms: FieldTransform[] = []\n ) {\n super();\n }\n\n readonly type: MutationType = MutationType.Set;\n\n getFieldMask(): FieldMask | null {\n return null;\n }\n}\n\nfunction setMutationApplyToRemoteDocument(\n mutation: SetMutation,\n document: MutableDocument,\n mutationResult: MutationResult\n): void {\n // Unlike setMutationApplyToLocalView, if we're applying a mutation to a\n // remote document the server has accepted the mutation so the precondition\n // must have held.\n const newData = mutation.value.clone();\n const transformResults = serverTransformResults(\n mutation.fieldTransforms,\n document,\n mutationResult.transformResults\n );\n newData.setAll(transformResults);\n document\n .convertToFoundDocument(mutationResult.version, newData)\n .setHasCommittedMutations();\n}\n\nfunction setMutationApplyToLocalView(\n mutation: SetMutation,\n document: MutableDocument,\n previousMask: FieldMask | null,\n localWriteTime: Timestamp\n): FieldMask | null {\n if (!preconditionIsValidForDocument(mutation.precondition, document)) {\n // The mutation failed to apply (e.g. a document ID created with add()\n // caused a name collision).\n return previousMask;\n }\n\n const newData = mutation.value.clone();\n const transformResults = localTransformResults(\n mutation.fieldTransforms,\n localWriteTime,\n document\n );\n newData.setAll(transformResults);\n document\n .convertToFoundDocument(document.version, newData)\n .setHasLocalMutations();\n return null; // SetMutation overwrites all fields.\n}\n\n/**\n * A mutation that modifies fields of the document at the given key with the\n * given values. The values are applied through a field mask:\n *\n * * When a field is in both the mask and the values, the corresponding field\n * is updated.\n * * When a field is in neither the mask nor the values, the corresponding\n * field is unmodified.\n * * When a field is in the mask but not in the values, the corresponding field\n * is deleted.\n * * When a field is not in the mask but is in the values, the values map is\n * ignored.\n */\nexport class PatchMutation extends Mutation {\n constructor(\n readonly key: DocumentKey,\n readonly data: ObjectValue,\n readonly fieldMask: FieldMask,\n readonly precondition: Precondition,\n readonly fieldTransforms: FieldTransform[] = []\n ) {\n super();\n }\n\n readonly type: MutationType = MutationType.Patch;\n\n getFieldMask(): FieldMask | null {\n return this.fieldMask;\n }\n}\n\nfunction patchMutationApplyToRemoteDocument(\n mutation: PatchMutation,\n document: MutableDocument,\n mutationResult: MutationResult\n): void {\n if (!preconditionIsValidForDocument(mutation.precondition, document)) {\n // Since the mutation was not rejected, we know that the precondition\n // matched on the backend. We therefore must not have the expected version\n // of the document in our cache and convert to an UnknownDocument with a\n // known updateTime.\n document.convertToUnknownDocument(mutationResult.version);\n return;\n }\n\n const transformResults = serverTransformResults(\n mutation.fieldTransforms,\n document,\n mutationResult.transformResults\n );\n const newData = document.data;\n newData.setAll(getPatch(mutation));\n newData.setAll(transformResults);\n document\n .convertToFoundDocument(mutationResult.version, newData)\n .setHasCommittedMutations();\n}\n\nfunction patchMutationApplyToLocalView(\n mutation: PatchMutation,\n document: MutableDocument,\n previousMask: FieldMask | null,\n localWriteTime: Timestamp\n): FieldMask | null {\n if (!preconditionIsValidForDocument(mutation.precondition, document)) {\n return previousMask;\n }\n\n const transformResults = localTransformResults(\n mutation.fieldTransforms,\n localWriteTime,\n document\n );\n const newData = document.data;\n newData.setAll(getPatch(mutation));\n newData.setAll(transformResults);\n document\n .convertToFoundDocument(document.version, newData)\n .setHasLocalMutations();\n\n if (previousMask === null) {\n return null;\n }\n\n return previousMask\n .unionWith(mutation.fieldMask.fields)\n .unionWith(mutation.fieldTransforms.map(transform => transform.field));\n}\n\n/**\n * Returns a FieldPath/Value map with the content of the PatchMutation.\n */\nfunction getPatch(mutation: PatchMutation): Map {\n const result = new Map();\n mutation.fieldMask.fields.forEach(fieldPath => {\n if (!fieldPath.isEmpty()) {\n const newValue = mutation.data.field(fieldPath);\n result.set(fieldPath, newValue);\n }\n });\n return result;\n}\n\n/**\n * Creates a list of \"transform results\" (a transform result is a field value\n * representing the result of applying a transform) for use after a mutation\n * containing transforms has been acknowledged by the server.\n *\n * @param fieldTransforms - The field transforms to apply the result to.\n * @param mutableDocument - The current state of the document after applying all\n * previous mutations.\n * @param serverTransformResults - The transform results received by the server.\n * @returns The transform results list.\n */\nfunction serverTransformResults(\n fieldTransforms: FieldTransform[],\n mutableDocument: MutableDocument,\n serverTransformResults: Array\n): Map {\n const transformResults = new Map();\n hardAssert(\n fieldTransforms.length === serverTransformResults.length,\n 0x7f90,\n 'server transform result count should match field transform count',\n {\n serverTransformResultCount: serverTransformResults.length,\n fieldTransformCount: fieldTransforms.length\n }\n );\n\n for (let i = 0; i < serverTransformResults.length; i++) {\n const fieldTransform = fieldTransforms[i];\n const transform = fieldTransform.transform;\n const previousValue = mutableDocument.data.field(fieldTransform.field);\n transformResults.set(\n fieldTransform.field,\n applyTransformOperationToRemoteDocument(\n transform,\n previousValue,\n serverTransformResults[i]\n )\n );\n }\n return transformResults;\n}\n\n/**\n * Creates a list of \"transform results\" (a transform result is a field value\n * representing the result of applying a transform) for use when applying a\n * transform locally.\n *\n * @param fieldTransforms - The field transforms to apply the result to.\n * @param localWriteTime - The local time of the mutation (used to\n * generate ServerTimestampValues).\n * @param mutableDocument - The document to apply transforms on.\n * @returns The transform results list.\n */\nfunction localTransformResults(\n fieldTransforms: FieldTransform[],\n localWriteTime: Timestamp,\n mutableDocument: MutableDocument\n): Map {\n const transformResults = new Map();\n for (const fieldTransform of fieldTransforms) {\n const transform = fieldTransform.transform;\n\n const previousValue = mutableDocument.data.field(fieldTransform.field);\n transformResults.set(\n fieldTransform.field,\n applyTransformOperationToLocalView(\n transform,\n previousValue,\n localWriteTime\n )\n );\n }\n return transformResults;\n}\n\n/** A mutation that deletes the document at the given key. */\nexport class DeleteMutation extends Mutation {\n constructor(readonly key: DocumentKey, readonly precondition: Precondition) {\n super();\n }\n\n readonly type: MutationType = MutationType.Delete;\n readonly fieldTransforms: FieldTransform[] = [];\n\n getFieldMask(): FieldMask | null {\n return null;\n }\n}\n\nfunction deleteMutationApplyToRemoteDocument(\n mutation: DeleteMutation,\n document: MutableDocument,\n mutationResult: MutationResult\n): void {\n debugAssert(\n mutationResult.transformResults.length === 0,\n 'Transform results received by DeleteMutation.'\n );\n\n // Unlike applyToLocalView, if we're applying a mutation to a remote\n // document the server has accepted the mutation so the precondition must\n // have held.\n document\n .convertToNoDocument(mutationResult.version)\n .setHasCommittedMutations();\n}\n\nfunction deleteMutationApplyToLocalView(\n mutation: DeleteMutation,\n document: MutableDocument,\n previousMask: FieldMask | null\n): FieldMask | null {\n debugAssert(\n document.key.isEqual(mutation.key),\n 'Can only apply mutation to document with same key'\n );\n if (preconditionIsValidForDocument(mutation.precondition, document)) {\n document.convertToNoDocument(document.version).setHasLocalMutations();\n return null;\n }\n return previousMask;\n}\n\n/**\n * A mutation that verifies the existence of the document at the given key with\n * the provided precondition.\n *\n * The `verify` operation is only used in Transactions, and this class serves\n * primarily to facilitate serialization into protos.\n */\nexport class VerifyMutation extends Mutation {\n constructor(readonly key: DocumentKey, readonly precondition: Precondition) {\n super();\n }\n\n readonly type: MutationType = MutationType.Verify;\n readonly fieldTransforms: FieldTransform[] = [];\n\n getFieldMask(): FieldMask | null {\n return null;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Aggregate } from '../core/aggregate';\nimport { Bound } from '../core/bound';\nimport { DatabaseId } from '../core/database_info';\nimport {\n CompositeFilter,\n compositeFilterIsFlatConjunction,\n CompositeOperator,\n FieldFilter,\n Filter,\n Operator\n} from '../core/filter';\nimport { Direction, OrderBy } from '../core/order_by';\nimport {\n LimitType,\n newQuery,\n newQueryForPath,\n Query,\n queryToTarget\n} from '../core/query';\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { targetIsDocumentTarget, Target } from '../core/target';\nimport { TargetId } from '../core/types';\nimport { Timestamp } from '../lite-api/timestamp';\nimport { TargetData, TargetPurpose } from '../local/target_data';\nimport { MutableDocument } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { FieldMask } from '../model/field_mask';\nimport {\n DeleteMutation,\n FieldTransform,\n Mutation,\n MutationResult,\n PatchMutation,\n Precondition,\n SetMutation,\n VerifyMutation\n} from '../model/mutation';\nimport { normalizeTimestamp } from '../model/normalize';\nimport { ObjectValue } from '../model/object_value';\nimport { FieldPath, ResourcePath } from '../model/path';\nimport {\n ArrayRemoveTransformOperation,\n ArrayUnionTransformOperation,\n NumericIncrementTransformOperation,\n ServerTimestampTransform,\n TransformOperation\n} from '../model/transform_operation';\nimport { isNanValue, isNullValue } from '../model/values';\nimport {\n ApiClientObjectMap as ProtoApiClientObjectMap,\n BatchGetDocumentsResponse as ProtoBatchGetDocumentsResponse,\n CompositeFilterOp as ProtoCompositeFilterOp,\n Cursor as ProtoCursor,\n Document as ProtoDocument,\n DocumentMask as ProtoDocumentMask,\n DocumentsTarget as ProtoDocumentsTarget,\n FieldFilterOp as ProtoFieldFilterOp,\n FieldReference as ProtoFieldReference,\n FieldTransform as ProtoFieldTransform,\n Filter as ProtoFilter,\n ListenResponse as ProtoListenResponse,\n Order as ProtoOrder,\n OrderDirection as ProtoOrderDirection,\n Precondition as ProtoPrecondition,\n QueryTarget as ProtoQueryTarget,\n RunAggregationQueryRequest as ProtoRunAggregationQueryRequest,\n Aggregation as ProtoAggregation,\n Status as ProtoStatus,\n Target as ProtoTarget,\n TargetChangeTargetChangeType as ProtoTargetChangeTargetChangeType,\n Timestamp as ProtoTimestamp,\n Write as ProtoWrite,\n WriteResult as ProtoWriteResult\n} from '../protos/firestore_proto_api';\nimport { debugAssert, fail, hardAssert } from '../util/assert';\nimport { ByteString } from '../util/byte_string';\nimport { Code, FirestoreError } from '../util/error';\nimport { isNullOrUndefined } from '../util/types';\n\nimport { ExistenceFilter } from './existence_filter';\nimport { Serializer } from './number_serializer';\nimport { mapCodeFromRpcCode } from './rpc_error';\nimport {\n DocumentWatchChange,\n ExistenceFilterChange,\n WatchChange,\n WatchTargetChange,\n WatchTargetChangeState\n} from './watch_change';\n\nconst DIRECTIONS = (() => {\n const dirs: { [dir: string]: ProtoOrderDirection } = {};\n dirs[Direction.ASCENDING] = 'ASCENDING';\n dirs[Direction.DESCENDING] = 'DESCENDING';\n return dirs;\n})();\n\nconst OPERATORS = (() => {\n const ops: { [op: string]: ProtoFieldFilterOp } = {};\n ops[Operator.LESS_THAN] = 'LESS_THAN';\n ops[Operator.LESS_THAN_OR_EQUAL] = 'LESS_THAN_OR_EQUAL';\n ops[Operator.GREATER_THAN] = 'GREATER_THAN';\n ops[Operator.GREATER_THAN_OR_EQUAL] = 'GREATER_THAN_OR_EQUAL';\n ops[Operator.EQUAL] = 'EQUAL';\n ops[Operator.NOT_EQUAL] = 'NOT_EQUAL';\n ops[Operator.ARRAY_CONTAINS] = 'ARRAY_CONTAINS';\n ops[Operator.IN] = 'IN';\n ops[Operator.NOT_IN] = 'NOT_IN';\n ops[Operator.ARRAY_CONTAINS_ANY] = 'ARRAY_CONTAINS_ANY';\n return ops;\n})();\n\nconst COMPOSITE_OPERATORS = (() => {\n const ops: { [op: string]: ProtoCompositeFilterOp } = {};\n ops[CompositeOperator.AND] = 'AND';\n ops[CompositeOperator.OR] = 'OR';\n return ops;\n})();\n\nfunction assertPresent(value: unknown, description: string): asserts value {\n debugAssert(!isNullOrUndefined(value), description + ' is missing');\n}\n\n/**\n * This class generates JsonObject values for the Datastore API suitable for\n * sending to either GRPC stub methods or via the JSON/HTTP REST API.\n *\n * The serializer supports both Protobuf.js and Proto3 JSON formats. By\n * setting `useProto3Json` to true, the serializer will use the Proto3 JSON\n * format.\n *\n * For a description of the Proto3 JSON format check\n * https://developers.google.com/protocol-buffers/docs/proto3#json\n *\n * TODO(klimt): We can remove the databaseId argument if we keep the full\n * resource name in documents.\n */\nexport class JsonProtoSerializer implements Serializer {\n constructor(\n readonly databaseId: DatabaseId,\n readonly useProto3Json: boolean\n ) {}\n}\n\nfunction fromRpcStatus(status: ProtoStatus): FirestoreError {\n const code =\n status.code === undefined ? Code.UNKNOWN : mapCodeFromRpcCode(status.code);\n return new FirestoreError(code, status.message || '');\n}\n\n/**\n * Returns a value for a number (or null) that's appropriate to put into\n * a google.protobuf.Int32Value proto.\n * DO NOT USE THIS FOR ANYTHING ELSE.\n * This method cheats. It's typed as returning \"number\" because that's what\n * our generated proto interfaces say Int32Value must be. But GRPC actually\n * expects a { value: } struct.\n */\nfunction toInt32Proto(\n serializer: JsonProtoSerializer,\n val: number | null\n): number | { value: number } | null {\n if (serializer.useProto3Json || isNullOrUndefined(val)) {\n return val;\n } else {\n return { value: val };\n }\n}\n\n/**\n * Returns a number (or null) from a google.protobuf.Int32Value proto.\n */\nfunction fromInt32Proto(\n val: number | { value: number } | undefined\n): number | null {\n let result;\n if (typeof val === 'object') {\n result = val.value;\n } else {\n result = val;\n }\n return isNullOrUndefined(result) ? null : result;\n}\n\n/**\n * Returns a value for a Date that's appropriate to put into a proto.\n */\nexport function toTimestamp(\n serializer: JsonProtoSerializer,\n timestamp: Timestamp\n): ProtoTimestamp {\n if (serializer.useProto3Json) {\n // Serialize to ISO-8601 date format, but with full nano resolution.\n // Since JS Date has only millis, let's only use it for the seconds and\n // then manually add the fractions to the end.\n const jsDateStr = new Date(timestamp.seconds * 1000).toISOString();\n // Remove .xxx frac part and Z in the end.\n const strUntilSeconds = jsDateStr.replace(/\\.\\d*/, '').replace('Z', '');\n // Pad the fraction out to 9 digits (nanos).\n const nanoStr = ('000000000' + timestamp.nanoseconds).slice(-9);\n\n return `${strUntilSeconds}.${nanoStr}Z`;\n } else {\n return {\n seconds: '' + timestamp.seconds,\n nanos: timestamp.nanoseconds\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } as any;\n }\n}\n\n/**\n * Returns a Timestamp typed object given protobuf timestamp value.\n */\nexport function fromTimestamp(date: ProtoTimestamp): Timestamp {\n const timestamp = normalizeTimestamp(date);\n return new Timestamp(timestamp.seconds, timestamp.nanos);\n}\n\n/**\n * Returns a value for bytes that's appropriate to put in a proto.\n *\n * Visible for testing.\n */\nexport function toBytes(\n serializer: JsonProtoSerializer,\n bytes: ByteString\n): string | Uint8Array {\n if (serializer.useProto3Json) {\n return bytes.toBase64();\n } else {\n return bytes.toUint8Array();\n }\n}\n\n/**\n * Returns a ByteString based on the proto string value.\n */\nexport function fromBytes(\n serializer: JsonProtoSerializer,\n value: string | Uint8Array | undefined\n): ByteString {\n if (serializer.useProto3Json) {\n hardAssert(\n value === undefined || typeof value === 'string',\n 0xe30b,\n 'value must be undefined or a string when using proto3 Json'\n );\n return ByteString.fromBase64String(value ? value : '');\n } else {\n hardAssert(\n value === undefined ||\n // Check if the value is an instance of both Buffer and Uint8Array,\n // despite the fact that Buffer extends Uint8Array. In some\n // environments, such as jsdom, the prototype chain of Buffer\n // does not indicate that it extends Uint8Array.\n value instanceof Buffer ||\n value instanceof Uint8Array,\n 0x3f41,\n 'value must be undefined, Buffer, or Uint8Array'\n );\n return ByteString.fromUint8Array(value ? value : new Uint8Array());\n }\n}\n\nexport function toVersion(\n serializer: JsonProtoSerializer,\n version: SnapshotVersion\n): ProtoTimestamp {\n return toTimestamp(serializer, version.toTimestamp());\n}\n\nexport function fromVersion(version: ProtoTimestamp): SnapshotVersion {\n hardAssert(!!version, 0xc050, \"Trying to deserialize version that isn't set\");\n return SnapshotVersion.fromTimestamp(fromTimestamp(version));\n}\n\nexport function toResourceName(\n databaseId: DatabaseId,\n path: ResourcePath\n): string {\n return toResourcePath(databaseId, path).canonicalString();\n}\n\nexport function toResourcePath(\n databaseId: DatabaseId,\n path?: ResourcePath\n): ResourcePath {\n const resourcePath = fullyQualifiedPrefixPath(databaseId).child('documents');\n return path === undefined ? resourcePath : resourcePath.child(path);\n}\n\nfunction fromResourceName(name: string): ResourcePath {\n const resource = ResourcePath.fromString(name);\n hardAssert(\n isValidResourceName(resource),\n 0x27ce,\n 'Tried to deserialize invalid key',\n { key: resource.toString() }\n );\n return resource;\n}\n\nexport function toName(\n serializer: JsonProtoSerializer,\n key: DocumentKey\n): string {\n return toResourceName(serializer.databaseId, key.path);\n}\n\nexport function fromName(\n serializer: JsonProtoSerializer,\n name: string\n): DocumentKey {\n const resource = fromResourceName(name);\n\n if (resource.get(1) !== serializer.databaseId.projectId) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Tried to deserialize key from different project: ' +\n resource.get(1) +\n ' vs ' +\n serializer.databaseId.projectId\n );\n }\n\n if (resource.get(3) !== serializer.databaseId.database) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Tried to deserialize key from different database: ' +\n resource.get(3) +\n ' vs ' +\n serializer.databaseId.database\n );\n }\n return new DocumentKey(extractLocalPathFromResourceName(resource));\n}\n\nfunction toQueryPath(\n serializer: JsonProtoSerializer,\n path: ResourcePath\n): string {\n return toResourceName(serializer.databaseId, path);\n}\n\nfunction fromQueryPath(name: string): ResourcePath {\n const resourceName = fromResourceName(name);\n // In v1beta1 queries for collections at the root did not have a trailing\n // \"/documents\". In v1 all resource paths contain \"/documents\". Preserve the\n // ability to read the v1beta1 form for compatibility with queries persisted\n // in the local target cache.\n if (resourceName.length === 4) {\n return ResourcePath.emptyPath();\n }\n return extractLocalPathFromResourceName(resourceName);\n}\n\nexport function getEncodedDatabaseId(serializer: JsonProtoSerializer): string {\n const path = new ResourcePath([\n 'projects',\n serializer.databaseId.projectId,\n 'databases',\n serializer.databaseId.database\n ]);\n return path.canonicalString();\n}\n\nfunction fullyQualifiedPrefixPath(databaseId: DatabaseId): ResourcePath {\n return new ResourcePath([\n 'projects',\n databaseId.projectId,\n 'databases',\n databaseId.database\n ]);\n}\n\nfunction extractLocalPathFromResourceName(\n resourceName: ResourcePath\n): ResourcePath {\n hardAssert(\n resourceName.length > 4 && resourceName.get(4) === 'documents',\n 0x71a3,\n 'tried to deserialize invalid key',\n { key: resourceName.toString() }\n );\n return resourceName.popFirst(5);\n}\n\n/** Creates a Document proto from key and fields (but no create/update time) */\nexport function toMutationDocument(\n serializer: JsonProtoSerializer,\n key: DocumentKey,\n fields: ObjectValue\n): ProtoDocument {\n return {\n name: toName(serializer, key),\n fields: fields.value.mapValue.fields\n };\n}\n\nexport function toDocument(\n serializer: JsonProtoSerializer,\n document: MutableDocument\n): ProtoDocument {\n debugAssert(\n !document.hasLocalMutations,\n \"Can't serialize documents with mutations.\"\n );\n return {\n name: toName(serializer, document.key),\n fields: document.data.value.mapValue.fields,\n updateTime: toTimestamp(serializer, document.version.toTimestamp()),\n createTime: toTimestamp(serializer, document.createTime.toTimestamp())\n };\n}\n\nexport function fromDocument(\n serializer: JsonProtoSerializer,\n document: ProtoDocument,\n hasCommittedMutations?: boolean\n): MutableDocument {\n const key = fromName(serializer, document.name!);\n const version = fromVersion(document.updateTime!);\n // If we read a document from persistence that is missing createTime, it's due\n // to older SDK versions not storing this information. In such cases, we'll\n // set the createTime to zero. This can be removed in the long term.\n const createTime = document.createTime\n ? fromVersion(document.createTime)\n : SnapshotVersion.min();\n const data = new ObjectValue({ mapValue: { fields: document.fields } });\n const result = MutableDocument.newFoundDocument(\n key,\n version,\n createTime,\n data\n );\n if (hasCommittedMutations) {\n result.setHasCommittedMutations();\n }\n return hasCommittedMutations ? result.setHasCommittedMutations() : result;\n}\n\nfunction fromFound(\n serializer: JsonProtoSerializer,\n doc: ProtoBatchGetDocumentsResponse\n): MutableDocument {\n hardAssert(\n !!doc.found,\n 0xaa33,\n 'Tried to deserialize a found document from a missing document.'\n );\n assertPresent(doc.found.name, 'doc.found.name');\n assertPresent(doc.found.updateTime, 'doc.found.updateTime');\n const key = fromName(serializer, doc.found.name);\n const version = fromVersion(doc.found.updateTime);\n const createTime = doc.found.createTime\n ? fromVersion(doc.found.createTime)\n : SnapshotVersion.min();\n const data = new ObjectValue({ mapValue: { fields: doc.found.fields } });\n return MutableDocument.newFoundDocument(key, version, createTime, data);\n}\n\nfunction fromMissing(\n serializer: JsonProtoSerializer,\n result: ProtoBatchGetDocumentsResponse\n): MutableDocument {\n hardAssert(\n !!result.missing,\n 0x0f36,\n 'Tried to deserialize a missing document from a found document.'\n );\n hardAssert(\n !!result.readTime,\n 0x5995,\n 'Tried to deserialize a missing document without a read time.'\n );\n const key = fromName(serializer, result.missing);\n const version = fromVersion(result.readTime);\n return MutableDocument.newNoDocument(key, version);\n}\n\nexport function fromBatchGetDocumentsResponse(\n serializer: JsonProtoSerializer,\n result: ProtoBatchGetDocumentsResponse\n): MutableDocument {\n if ('found' in result) {\n return fromFound(serializer, result);\n } else if ('missing' in result) {\n return fromMissing(serializer, result);\n }\n return fail(0x1c42, 'invalid batch get response', { result });\n}\n\nexport function fromWatchChange(\n serializer: JsonProtoSerializer,\n change: ProtoListenResponse\n): WatchChange {\n let watchChange: WatchChange;\n if ('targetChange' in change) {\n assertPresent(change.targetChange, 'targetChange');\n // proto3 default value is unset in JSON (undefined), so use 'NO_CHANGE'\n // if unset\n const state = fromWatchTargetChangeState(\n change.targetChange.targetChangeType || 'NO_CHANGE'\n );\n const targetIds: TargetId[] = change.targetChange.targetIds || [];\n\n const resumeToken = fromBytes(serializer, change.targetChange.resumeToken);\n const causeProto = change.targetChange!.cause;\n const cause = causeProto && fromRpcStatus(causeProto);\n watchChange = new WatchTargetChange(\n state,\n targetIds,\n resumeToken,\n cause || null\n );\n } else if ('documentChange' in change) {\n assertPresent(change.documentChange, 'documentChange');\n const entityChange = change.documentChange;\n assertPresent(entityChange.document, 'documentChange.name');\n assertPresent(entityChange.document.name, 'documentChange.document.name');\n assertPresent(\n entityChange.document.updateTime,\n 'documentChange.document.updateTime'\n );\n const key = fromName(serializer, entityChange.document.name);\n const version = fromVersion(entityChange.document.updateTime);\n const createTime = entityChange.document.createTime\n ? fromVersion(entityChange.document.createTime)\n : SnapshotVersion.min();\n const data = new ObjectValue({\n mapValue: { fields: entityChange.document.fields }\n });\n const doc = MutableDocument.newFoundDocument(\n key,\n version,\n createTime,\n data\n );\n const updatedTargetIds = entityChange.targetIds || [];\n const removedTargetIds = entityChange.removedTargetIds || [];\n watchChange = new DocumentWatchChange(\n updatedTargetIds,\n removedTargetIds,\n doc.key,\n doc\n );\n } else if ('documentDelete' in change) {\n assertPresent(change.documentDelete, 'documentDelete');\n const docDelete = change.documentDelete;\n assertPresent(docDelete.document, 'documentDelete.document');\n const key = fromName(serializer, docDelete.document);\n const version = docDelete.readTime\n ? fromVersion(docDelete.readTime)\n : SnapshotVersion.min();\n const doc = MutableDocument.newNoDocument(key, version);\n const removedTargetIds = docDelete.removedTargetIds || [];\n watchChange = new DocumentWatchChange([], removedTargetIds, doc.key, doc);\n } else if ('documentRemove' in change) {\n assertPresent(change.documentRemove, 'documentRemove');\n const docRemove = change.documentRemove;\n assertPresent(docRemove.document, 'documentRemove');\n const key = fromName(serializer, docRemove.document);\n const removedTargetIds = docRemove.removedTargetIds || [];\n watchChange = new DocumentWatchChange([], removedTargetIds, key, null);\n } else if ('filter' in change) {\n // TODO(dimond): implement existence filter parsing with strategy.\n assertPresent(change.filter, 'filter');\n const filter = change.filter;\n assertPresent(filter.targetId, 'filter.targetId');\n const { count = 0, unchangedNames } = filter;\n const existenceFilter = new ExistenceFilter(count, unchangedNames);\n const targetId = filter.targetId;\n watchChange = new ExistenceFilterChange(targetId, existenceFilter);\n } else {\n return fail(0x2d51, 'Unknown change type', { change });\n }\n return watchChange;\n}\n\nfunction fromWatchTargetChangeState(\n state: ProtoTargetChangeTargetChangeType\n): WatchTargetChangeState {\n if (state === 'NO_CHANGE') {\n return WatchTargetChangeState.NoChange;\n } else if (state === 'ADD') {\n return WatchTargetChangeState.Added;\n } else if (state === 'REMOVE') {\n return WatchTargetChangeState.Removed;\n } else if (state === 'CURRENT') {\n return WatchTargetChangeState.Current;\n } else if (state === 'RESET') {\n return WatchTargetChangeState.Reset;\n } else {\n return fail(0x9991, 'Got unexpected TargetChange.state', { state });\n }\n}\n\nexport function versionFromListenResponse(\n change: ProtoListenResponse\n): SnapshotVersion {\n // We have only reached a consistent snapshot for the entire stream if there\n // is a read_time set and it applies to all targets (i.e. the list of\n // targets is empty). The backend is guaranteed to send such responses.\n if (!('targetChange' in change)) {\n return SnapshotVersion.min();\n }\n const targetChange = change.targetChange!;\n if (targetChange.targetIds && targetChange.targetIds.length) {\n return SnapshotVersion.min();\n }\n if (!targetChange.readTime) {\n return SnapshotVersion.min();\n }\n return fromVersion(targetChange.readTime);\n}\n\nexport function toMutation(\n serializer: JsonProtoSerializer,\n mutation: Mutation\n): ProtoWrite {\n let result: ProtoWrite;\n if (mutation instanceof SetMutation) {\n result = {\n update: toMutationDocument(serializer, mutation.key, mutation.value)\n };\n } else if (mutation instanceof DeleteMutation) {\n result = { delete: toName(serializer, mutation.key) };\n } else if (mutation instanceof PatchMutation) {\n result = {\n update: toMutationDocument(serializer, mutation.key, mutation.data),\n updateMask: toDocumentMask(mutation.fieldMask)\n };\n } else if (mutation instanceof VerifyMutation) {\n result = {\n verify: toName(serializer, mutation.key)\n };\n } else {\n return fail(0x40d7, 'Unknown mutation type', {\n mutationType: mutation.type\n });\n }\n\n if (mutation.fieldTransforms.length > 0) {\n result.updateTransforms = mutation.fieldTransforms.map(transform =>\n toFieldTransform(serializer, transform)\n );\n }\n\n if (!mutation.precondition.isNone) {\n result.currentDocument = toPrecondition(serializer, mutation.precondition);\n }\n\n return result;\n}\n\nexport function fromMutation(\n serializer: JsonProtoSerializer,\n proto: ProtoWrite\n): Mutation {\n const precondition = proto.currentDocument\n ? fromPrecondition(proto.currentDocument)\n : Precondition.none();\n\n const fieldTransforms = proto.updateTransforms\n ? proto.updateTransforms.map(transform =>\n fromFieldTransform(serializer, transform)\n )\n : [];\n\n if (proto.update) {\n assertPresent(proto.update.name, 'name');\n const key = fromName(serializer, proto.update.name);\n const value = new ObjectValue({\n mapValue: { fields: proto.update.fields }\n });\n\n if (proto.updateMask) {\n const fieldMask = fromDocumentMask(proto.updateMask);\n return new PatchMutation(\n key,\n value,\n fieldMask,\n precondition,\n fieldTransforms\n );\n } else {\n return new SetMutation(key, value, precondition, fieldTransforms);\n }\n } else if (proto.delete) {\n const key = fromName(serializer, proto.delete);\n return new DeleteMutation(key, precondition);\n } else if (proto.verify) {\n const key = fromName(serializer, proto.verify);\n return new VerifyMutation(key, precondition);\n } else {\n return fail(0x05b7, 'unknown mutation proto', { proto });\n }\n}\n\nfunction toPrecondition(\n serializer: JsonProtoSerializer,\n precondition: Precondition\n): ProtoPrecondition {\n debugAssert(!precondition.isNone, \"Can't serialize an empty precondition\");\n if (precondition.updateTime !== undefined) {\n return {\n updateTime: toVersion(serializer, precondition.updateTime)\n };\n } else if (precondition.exists !== undefined) {\n return { exists: precondition.exists };\n } else {\n return fail(0x6b69, 'Unknown precondition');\n }\n}\n\nfunction fromPrecondition(precondition: ProtoPrecondition): Precondition {\n if (precondition.updateTime !== undefined) {\n return Precondition.updateTime(fromVersion(precondition.updateTime));\n } else if (precondition.exists !== undefined) {\n return Precondition.exists(precondition.exists);\n } else {\n return Precondition.none();\n }\n}\n\nfunction fromWriteResult(\n proto: ProtoWriteResult,\n commitTime: ProtoTimestamp\n): MutationResult {\n // NOTE: Deletes don't have an updateTime.\n let version = proto.updateTime\n ? fromVersion(proto.updateTime)\n : fromVersion(commitTime);\n\n if (version.isEqual(SnapshotVersion.min())) {\n // The Firestore Emulator currently returns an update time of 0 for\n // deletes of non-existing documents (rather than null). This breaks the\n // test \"get deleted doc while offline with source=cache\" as NoDocuments\n // with version 0 are filtered by IndexedDb's RemoteDocumentCache.\n // TODO(#2149): Remove this when Emulator is fixed\n version = fromVersion(commitTime);\n }\n\n return new MutationResult(version, proto.transformResults || []);\n}\n\nexport function fromWriteResults(\n protos: ProtoWriteResult[] | undefined,\n commitTime?: ProtoTimestamp\n): MutationResult[] {\n if (protos && protos.length > 0) {\n hardAssert(\n commitTime !== undefined,\n 0x3811,\n 'Received a write result without a commit time'\n );\n return protos.map(proto => fromWriteResult(proto, commitTime));\n } else {\n return [];\n }\n}\n\nfunction toFieldTransform(\n serializer: JsonProtoSerializer,\n fieldTransform: FieldTransform\n): ProtoFieldTransform {\n const transform = fieldTransform.transform;\n if (transform instanceof ServerTimestampTransform) {\n return {\n fieldPath: fieldTransform.field.canonicalString(),\n setToServerValue: 'REQUEST_TIME'\n };\n } else if (transform instanceof ArrayUnionTransformOperation) {\n return {\n fieldPath: fieldTransform.field.canonicalString(),\n appendMissingElements: {\n values: transform.elements\n }\n };\n } else if (transform instanceof ArrayRemoveTransformOperation) {\n return {\n fieldPath: fieldTransform.field.canonicalString(),\n removeAllFromArray: {\n values: transform.elements\n }\n };\n } else if (transform instanceof NumericIncrementTransformOperation) {\n return {\n fieldPath: fieldTransform.field.canonicalString(),\n increment: transform.operand\n };\n } else {\n throw fail(0x51c2, 'Unknown transform', {\n transform: fieldTransform.transform\n });\n }\n}\n\nfunction fromFieldTransform(\n serializer: JsonProtoSerializer,\n proto: ProtoFieldTransform\n): FieldTransform {\n let transform: TransformOperation | null = null;\n if ('setToServerValue' in proto) {\n hardAssert(\n proto.setToServerValue === 'REQUEST_TIME',\n 0x40f6,\n 'Unknown server value transform proto',\n { proto }\n );\n transform = new ServerTimestampTransform();\n } else if ('appendMissingElements' in proto) {\n const values = proto.appendMissingElements!.values || [];\n transform = new ArrayUnionTransformOperation(values);\n } else if ('removeAllFromArray' in proto) {\n const values = proto.removeAllFromArray!.values || [];\n transform = new ArrayRemoveTransformOperation(values);\n } else if ('increment' in proto) {\n transform = new NumericIncrementTransformOperation(\n serializer,\n proto.increment!\n );\n } else {\n fail(0x40c8, 'Unknown transform proto', { proto });\n }\n const fieldPath = FieldPath.fromServerFormat(proto.fieldPath!);\n return new FieldTransform(fieldPath, transform!);\n}\n\nexport function toDocumentsTarget(\n serializer: JsonProtoSerializer,\n target: Target\n): ProtoDocumentsTarget {\n return { documents: [toQueryPath(serializer, target.path)] };\n}\n\nexport function fromDocumentsTarget(\n documentsTarget: ProtoDocumentsTarget\n): Target {\n const count = documentsTarget.documents!.length;\n hardAssert(\n count === 1,\n 0x07ae,\n 'DocumentsTarget contained other than 1 document',\n {\n count\n }\n );\n const name = documentsTarget.documents![0];\n return queryToTarget(newQueryForPath(fromQueryPath(name)));\n}\n\nexport function toQueryTarget(\n serializer: JsonProtoSerializer,\n target: Target\n): { queryTarget: ProtoQueryTarget; parent: ResourcePath } {\n // Dissect the path into parent, collectionId, and optional key filter.\n const queryTarget: ProtoQueryTarget = { structuredQuery: {} };\n const path = target.path;\n let parent: ResourcePath;\n if (target.collectionGroup !== null) {\n debugAssert(\n path.length % 2 === 0,\n 'Collection Group queries should be within a document path or root.'\n );\n parent = path;\n queryTarget.structuredQuery!.from = [\n {\n collectionId: target.collectionGroup,\n allDescendants: true\n }\n ];\n } else {\n debugAssert(\n path.length % 2 !== 0,\n 'Document queries with filters are not supported.'\n );\n parent = path.popLast();\n queryTarget.structuredQuery!.from = [{ collectionId: path.lastSegment() }];\n }\n queryTarget.parent = toQueryPath(serializer, parent);\n\n const where = toFilters(target.filters);\n if (where) {\n queryTarget.structuredQuery!.where = where;\n }\n\n const orderBy = toOrder(target.orderBy);\n if (orderBy) {\n queryTarget.structuredQuery!.orderBy = orderBy;\n }\n\n const limit = toInt32Proto(serializer, target.limit);\n if (limit !== null) {\n queryTarget.structuredQuery!.limit = limit;\n }\n\n if (target.startAt) {\n queryTarget.structuredQuery!.startAt = toStartAtCursor(target.startAt);\n }\n if (target.endAt) {\n queryTarget.structuredQuery!.endAt = toEndAtCursor(target.endAt);\n }\n\n return { queryTarget, parent };\n}\n\nexport function toRunAggregationQueryRequest(\n serializer: JsonProtoSerializer,\n target: Target,\n aggregates: Aggregate[],\n skipAliasing?: boolean\n): {\n request: ProtoRunAggregationQueryRequest;\n aliasMap: Record;\n parent: ResourcePath;\n} {\n const { queryTarget, parent } = toQueryTarget(serializer, target);\n const aliasMap: Record = {};\n\n const aggregations: ProtoAggregation[] = [];\n let aggregationNum = 0;\n\n aggregates.forEach(aggregate => {\n // Map all client-side aliases to a unique short-form\n // alias. This avoids issues with client-side aliases that\n // exceed the 1500-byte string size limit.\n const serverAlias = skipAliasing\n ? aggregate.alias\n : `aggregate_${aggregationNum++}`;\n aliasMap[serverAlias] = aggregate.alias;\n\n if (aggregate.aggregateType === 'count') {\n aggregations.push({\n alias: serverAlias,\n count: {}\n });\n } else if (aggregate.aggregateType === 'avg') {\n aggregations.push({\n alias: serverAlias,\n avg: {\n field: toFieldPathReference(aggregate.fieldPath!)\n }\n });\n } else if (aggregate.aggregateType === 'sum') {\n aggregations.push({\n alias: serverAlias,\n sum: {\n field: toFieldPathReference(aggregate.fieldPath!)\n }\n });\n }\n });\n\n return {\n request: {\n structuredAggregationQuery: {\n aggregations,\n structuredQuery: queryTarget.structuredQuery\n },\n parent: queryTarget.parent\n },\n aliasMap,\n parent\n };\n}\n\nexport function convertQueryTargetToQuery(target: ProtoQueryTarget): Query {\n let path = fromQueryPath(target.parent!);\n\n const query = target.structuredQuery!;\n const fromCount = query.from ? query.from.length : 0;\n let collectionGroup: string | null = null;\n if (fromCount > 0) {\n hardAssert(\n fromCount === 1,\n 0xfe26,\n 'StructuredQuery.from with more than one collection is not supported.'\n );\n const from = query.from![0];\n if (from.allDescendants) {\n collectionGroup = from.collectionId!;\n } else {\n path = path.child(from.collectionId!);\n }\n }\n\n let filterBy: Filter[] = [];\n if (query.where) {\n filterBy = fromFilters(query.where);\n }\n\n let orderBy: OrderBy[] = [];\n if (query.orderBy) {\n orderBy = fromOrder(query.orderBy);\n }\n\n let limit: number | null = null;\n if (query.limit) {\n limit = fromInt32Proto(query.limit);\n }\n\n let startAt: Bound | null = null;\n if (query.startAt) {\n startAt = fromStartAtCursor(query.startAt);\n }\n\n let endAt: Bound | null = null;\n if (query.endAt) {\n endAt = fromEndAtCursor(query.endAt);\n }\n\n return newQuery(\n path,\n collectionGroup,\n orderBy,\n filterBy,\n limit,\n LimitType.First,\n startAt,\n endAt\n );\n}\n\nexport function fromQueryTarget(target: ProtoQueryTarget): Target {\n return queryToTarget(convertQueryTargetToQuery(target));\n}\n\nexport function toListenRequestLabels(\n serializer: JsonProtoSerializer,\n targetData: TargetData\n): ProtoApiClientObjectMap | null {\n const value = toLabel(targetData.purpose);\n if (value == null) {\n return null;\n } else {\n return {\n 'goog-listen-tags': value\n };\n }\n}\n\nexport function toLabel(purpose: TargetPurpose): string | null {\n switch (purpose) {\n case TargetPurpose.Listen:\n return null;\n case TargetPurpose.ExistenceFilterMismatch:\n return 'existence-filter-mismatch';\n case TargetPurpose.ExistenceFilterMismatchBloom:\n return 'existence-filter-mismatch-bloom';\n case TargetPurpose.LimboResolution:\n return 'limbo-document';\n default:\n return fail(0x713b, 'Unrecognized query purpose', { purpose });\n }\n}\n\nexport function toTarget(\n serializer: JsonProtoSerializer,\n targetData: TargetData\n): ProtoTarget {\n let result: ProtoTarget;\n const target = targetData.target;\n\n if (targetIsDocumentTarget(target)) {\n result = { documents: toDocumentsTarget(serializer, target) };\n } else {\n result = { query: toQueryTarget(serializer, target).queryTarget };\n }\n\n result.targetId = targetData.targetId;\n\n if (targetData.resumeToken.approximateByteSize() > 0) {\n result.resumeToken = toBytes(serializer, targetData.resumeToken);\n const expectedCount = toInt32Proto(serializer, targetData.expectedCount);\n if (expectedCount !== null) {\n result.expectedCount = expectedCount;\n }\n } else if (targetData.snapshotVersion.compareTo(SnapshotVersion.min()) > 0) {\n // TODO(wuandy): Consider removing above check because it is most likely true.\n // Right now, many tests depend on this behaviour though (leaving min() out\n // of serialization).\n result.readTime = toTimestamp(\n serializer,\n targetData.snapshotVersion.toTimestamp()\n );\n const expectedCount = toInt32Proto(serializer, targetData.expectedCount);\n if (expectedCount !== null) {\n result.expectedCount = expectedCount;\n }\n }\n\n return result;\n}\n\nfunction toFilters(filters: Filter[]): ProtoFilter | undefined {\n if (filters.length === 0) {\n return;\n }\n\n return toFilter(CompositeFilter.create(filters, CompositeOperator.AND));\n}\n\nfunction fromFilters(filter: ProtoFilter): Filter[] {\n const result = fromFilter(filter);\n\n if (\n result instanceof CompositeFilter &&\n compositeFilterIsFlatConjunction(result)\n ) {\n return result.getFilters();\n }\n\n return [result];\n}\n\nfunction fromFilter(filter: ProtoFilter): Filter {\n if (filter.unaryFilter !== undefined) {\n return fromUnaryFilter(filter);\n } else if (filter.fieldFilter !== undefined) {\n return fromFieldFilter(filter);\n } else if (filter.compositeFilter !== undefined) {\n return fromCompositeFilter(filter);\n } else {\n return fail(0x7591, 'Unknown filter', { filter });\n }\n}\n\nfunction toOrder(orderBys: OrderBy[]): ProtoOrder[] | undefined {\n if (orderBys.length === 0) {\n return;\n }\n return orderBys.map(order => toPropertyOrder(order));\n}\n\nfunction fromOrder(orderBys: ProtoOrder[]): OrderBy[] {\n return orderBys.map(order => fromPropertyOrder(order));\n}\n\nfunction toStartAtCursor(cursor: Bound): ProtoCursor {\n return {\n before: cursor.inclusive,\n values: cursor.position\n };\n}\n\nfunction toEndAtCursor(cursor: Bound): ProtoCursor {\n return {\n before: !cursor.inclusive,\n values: cursor.position\n };\n}\n\nfunction fromStartAtCursor(cursor: ProtoCursor): Bound {\n const inclusive = !!cursor.before;\n const position = cursor.values || [];\n return new Bound(position, inclusive);\n}\n\nfunction fromEndAtCursor(cursor: ProtoCursor): Bound {\n const inclusive = !cursor.before;\n const position = cursor.values || [];\n return new Bound(position, inclusive);\n}\n\n// visible for testing\nexport function toDirection(dir: Direction): ProtoOrderDirection {\n return DIRECTIONS[dir];\n}\n\n// visible for testing\nexport function fromDirection(\n dir: ProtoOrderDirection | undefined\n): Direction | undefined {\n switch (dir) {\n case 'ASCENDING':\n return Direction.ASCENDING;\n case 'DESCENDING':\n return Direction.DESCENDING;\n default:\n return undefined;\n }\n}\n\n// visible for testing\nexport function toOperatorName(op: Operator): ProtoFieldFilterOp {\n return OPERATORS[op];\n}\n\nexport function toCompositeOperatorName(\n op: CompositeOperator\n): ProtoCompositeFilterOp {\n return COMPOSITE_OPERATORS[op];\n}\n\nexport function fromOperatorName(op: ProtoFieldFilterOp): Operator {\n switch (op) {\n case 'EQUAL':\n return Operator.EQUAL;\n case 'NOT_EQUAL':\n return Operator.NOT_EQUAL;\n case 'GREATER_THAN':\n return Operator.GREATER_THAN;\n case 'GREATER_THAN_OR_EQUAL':\n return Operator.GREATER_THAN_OR_EQUAL;\n case 'LESS_THAN':\n return Operator.LESS_THAN;\n case 'LESS_THAN_OR_EQUAL':\n return Operator.LESS_THAN_OR_EQUAL;\n case 'ARRAY_CONTAINS':\n return Operator.ARRAY_CONTAINS;\n case 'IN':\n return Operator.IN;\n case 'NOT_IN':\n return Operator.NOT_IN;\n case 'ARRAY_CONTAINS_ANY':\n return Operator.ARRAY_CONTAINS_ANY;\n case 'OPERATOR_UNSPECIFIED':\n return fail(0xe2fe, 'Unspecified operator');\n default:\n return fail(0xc54a, 'Unknown operator');\n }\n}\n\nexport function fromCompositeOperatorName(\n op: ProtoCompositeFilterOp\n): CompositeOperator {\n switch (op) {\n case 'AND':\n return CompositeOperator.AND;\n case 'OR':\n return CompositeOperator.OR;\n default:\n return fail(0x0402, 'Unknown operator');\n }\n}\n\nexport function toFieldPathReference(path: FieldPath): ProtoFieldReference {\n return { fieldPath: path.canonicalString() };\n}\n\nexport function fromFieldPathReference(\n fieldReference: ProtoFieldReference\n): FieldPath {\n return FieldPath.fromServerFormat(fieldReference.fieldPath!);\n}\n\n// visible for testing\nexport function toPropertyOrder(orderBy: OrderBy): ProtoOrder {\n return {\n field: toFieldPathReference(orderBy.field),\n direction: toDirection(orderBy.dir)\n };\n}\n\nexport function fromPropertyOrder(orderBy: ProtoOrder): OrderBy {\n return new OrderBy(\n fromFieldPathReference(orderBy.field!),\n fromDirection(orderBy.direction)\n );\n}\n\n// visible for testing\nexport function toFilter(filter: Filter): ProtoFilter {\n if (filter instanceof FieldFilter) {\n return toUnaryOrFieldFilter(filter);\n } else if (filter instanceof CompositeFilter) {\n return toCompositeFilter(filter);\n } else {\n return fail(0xd65d, 'Unrecognized filter type', { filter });\n }\n}\n\nexport function toCompositeFilter(filter: CompositeFilter): ProtoFilter {\n const protos = filter.getFilters().map(filter => toFilter(filter));\n\n if (protos.length === 1) {\n return protos[0];\n }\n\n return {\n compositeFilter: {\n op: toCompositeOperatorName(filter.op),\n filters: protos\n }\n };\n}\n\nexport function toUnaryOrFieldFilter(filter: FieldFilter): ProtoFilter {\n if (filter.op === Operator.EQUAL) {\n if (isNanValue(filter.value)) {\n return {\n unaryFilter: {\n field: toFieldPathReference(filter.field),\n op: 'IS_NAN'\n }\n };\n } else if (isNullValue(filter.value)) {\n return {\n unaryFilter: {\n field: toFieldPathReference(filter.field),\n op: 'IS_NULL'\n }\n };\n }\n } else if (filter.op === Operator.NOT_EQUAL) {\n if (isNanValue(filter.value)) {\n return {\n unaryFilter: {\n field: toFieldPathReference(filter.field),\n op: 'IS_NOT_NAN'\n }\n };\n } else if (isNullValue(filter.value)) {\n return {\n unaryFilter: {\n field: toFieldPathReference(filter.field),\n op: 'IS_NOT_NULL'\n }\n };\n }\n }\n return {\n fieldFilter: {\n field: toFieldPathReference(filter.field),\n op: toOperatorName(filter.op),\n value: filter.value\n }\n };\n}\n\nexport function fromUnaryFilter(filter: ProtoFilter): Filter {\n switch (filter.unaryFilter!.op!) {\n case 'IS_NAN':\n const nanField = fromFieldPathReference(filter.unaryFilter!.field!);\n return FieldFilter.create(nanField, Operator.EQUAL, {\n doubleValue: NaN\n });\n case 'IS_NULL':\n const nullField = fromFieldPathReference(filter.unaryFilter!.field!);\n return FieldFilter.create(nullField, Operator.EQUAL, {\n nullValue: 'NULL_VALUE'\n });\n case 'IS_NOT_NAN':\n const notNanField = fromFieldPathReference(filter.unaryFilter!.field!);\n return FieldFilter.create(notNanField, Operator.NOT_EQUAL, {\n doubleValue: NaN\n });\n case 'IS_NOT_NULL':\n const notNullField = fromFieldPathReference(filter.unaryFilter!.field!);\n return FieldFilter.create(notNullField, Operator.NOT_EQUAL, {\n nullValue: 'NULL_VALUE'\n });\n case 'OPERATOR_UNSPECIFIED':\n return fail(0xef81, 'Unspecified filter');\n default:\n return fail(0xed36, 'Unknown filter');\n }\n}\n\nexport function fromFieldFilter(filter: ProtoFilter): FieldFilter {\n return FieldFilter.create(\n fromFieldPathReference(filter.fieldFilter!.field!),\n fromOperatorName(filter.fieldFilter!.op!),\n filter.fieldFilter!.value!\n );\n}\n\nexport function fromCompositeFilter(filter: ProtoFilter): CompositeFilter {\n return CompositeFilter.create(\n filter.compositeFilter!.filters!.map(filter => fromFilter(filter)),\n fromCompositeOperatorName(filter.compositeFilter!.op!)\n );\n}\n\nexport function toDocumentMask(fieldMask: FieldMask): ProtoDocumentMask {\n const canonicalFields: string[] = [];\n fieldMask.fields.forEach(field =>\n canonicalFields.push(field.canonicalString())\n );\n return {\n fieldPaths: canonicalFields\n };\n}\n\nexport function fromDocumentMask(proto: ProtoDocumentMask): FieldMask {\n const paths = proto.fieldPaths || [];\n return new FieldMask(paths.map(path => FieldPath.fromServerFormat(path)));\n}\n\nexport function isValidResourceName(path: ResourcePath): boolean {\n // Resource names have at least 4 components (project ID, database ID)\n return (\n path.length >= 4 &&\n path.get(0) === 'projects' &&\n path.get(2) === 'databases'\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** Return the Platform-specific serializer monitor. */\nimport { DatabaseId } from '../../core/database_info';\nimport { JsonProtoSerializer } from '../../remote/serializer';\n\nexport function newSerializer(databaseId: DatabaseId): JsonProtoSerializer {\n return new JsonProtoSerializer(databaseId, /* useProto3Json= */ true);\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { AsyncQueue, DelayedOperation, TimerId } from '../util/async_queue';\nimport { logDebug } from '../util/log';\n\nconst LOG_TAG = 'ExponentialBackoff';\n\n/**\n * Initial backoff time in milliseconds after an error.\n * Set to 1s according to https://cloud.google.com/apis/design/errors.\n */\nconst DEFAULT_BACKOFF_INITIAL_DELAY_MS = 1000;\n\nconst DEFAULT_BACKOFF_FACTOR = 1.5;\n\n/** Maximum backoff time in milliseconds */\nconst DEFAULT_BACKOFF_MAX_DELAY_MS = 60 * 1000;\n\n/**\n * A helper for running delayed tasks following an exponential backoff curve\n * between attempts.\n *\n * Each delay is made up of a \"base\" delay which follows the exponential\n * backoff curve, and a +/- 50% \"jitter\" that is calculated and added to the\n * base delay. This prevents clients from accidentally synchronizing their\n * delays causing spikes of load to the backend.\n */\nexport class ExponentialBackoff {\n private currentBaseMs: number = 0;\n private timerPromise: DelayedOperation | null = null;\n /** The last backoff attempt, as epoch milliseconds. */\n private lastAttemptTime = Date.now();\n\n constructor(\n /**\n * The AsyncQueue to run backoff operations on.\n */\n private readonly queue: AsyncQueue,\n /**\n * The ID to use when scheduling backoff operations on the AsyncQueue.\n */\n private readonly timerId: TimerId,\n /**\n * The initial delay (used as the base delay on the first retry attempt).\n * Note that jitter will still be applied, so the actual delay could be as\n * little as 0.5*initialDelayMs.\n */\n private readonly initialDelayMs: number = DEFAULT_BACKOFF_INITIAL_DELAY_MS,\n /**\n * The multiplier to use to determine the extended base delay after each\n * attempt.\n */\n private readonly backoffFactor: number = DEFAULT_BACKOFF_FACTOR,\n /**\n * The maximum base delay after which no further backoff is performed.\n * Note that jitter will still be applied, so the actual delay could be as\n * much as 1.5*maxDelayMs.\n */\n private readonly maxDelayMs: number = DEFAULT_BACKOFF_MAX_DELAY_MS\n ) {\n this.reset();\n }\n\n /**\n * Resets the backoff delay.\n *\n * The very next backoffAndWait() will have no delay. If it is called again\n * (i.e. due to an error), initialDelayMs (plus jitter) will be used, and\n * subsequent ones will increase according to the backoffFactor.\n */\n reset(): void {\n this.currentBaseMs = 0;\n }\n\n /**\n * Resets the backoff delay to the maximum delay (e.g. for use after a\n * RESOURCE_EXHAUSTED error).\n */\n resetToMax(): void {\n this.currentBaseMs = this.maxDelayMs;\n }\n\n /**\n * Returns a promise that resolves after currentDelayMs, and increases the\n * delay for any subsequent attempts. If there was a pending backoff operation\n * already, it will be canceled.\n */\n backoffAndRun(op: () => Promise): void {\n // Cancel any pending backoff operation.\n this.cancel();\n\n // First schedule using the current base (which may be 0 and should be\n // honored as such).\n const desiredDelayWithJitterMs = Math.floor(\n this.currentBaseMs + this.jitterDelayMs()\n );\n\n // Guard against lastAttemptTime being in the future due to a clock change.\n const delaySoFarMs = Math.max(0, Date.now() - this.lastAttemptTime);\n\n // Guard against the backoff delay already being past.\n const remainingDelayMs = Math.max(\n 0,\n desiredDelayWithJitterMs - delaySoFarMs\n );\n\n if (remainingDelayMs > 0) {\n logDebug(\n LOG_TAG,\n `Backing off for ${remainingDelayMs} ms ` +\n `(base delay: ${this.currentBaseMs} ms, ` +\n `delay with jitter: ${desiredDelayWithJitterMs} ms, ` +\n `last attempt: ${delaySoFarMs} ms ago)`\n );\n }\n\n this.timerPromise = this.queue.enqueueAfterDelay(\n this.timerId,\n remainingDelayMs,\n () => {\n this.lastAttemptTime = Date.now();\n return op();\n }\n );\n\n // Apply backoff factor to determine next delay and ensure it is within\n // bounds.\n this.currentBaseMs *= this.backoffFactor;\n if (this.currentBaseMs < this.initialDelayMs) {\n this.currentBaseMs = this.initialDelayMs;\n }\n if (this.currentBaseMs > this.maxDelayMs) {\n this.currentBaseMs = this.maxDelayMs;\n }\n }\n\n skipBackoff(): void {\n if (this.timerPromise !== null) {\n this.timerPromise.skipDelay();\n this.timerPromise = null;\n }\n }\n\n cancel(): void {\n if (this.timerPromise !== null) {\n this.timerPromise.cancel();\n this.timerPromise = null;\n }\n }\n\n /** Returns a random value in the range [-currentBaseMs/2, currentBaseMs/2] */\n private jitterDelayMs(): number {\n return (Math.random() - 0.5) * this.currentBaseMs;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { CredentialsProvider } from '../api/credentials';\nimport { User } from '../auth/user';\nimport { Aggregate } from '../core/aggregate';\nimport { DatabaseId } from '../core/database_info';\nimport { queryToAggregateTarget, Query, queryToTarget } from '../core/query';\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { Mutation } from '../model/mutation';\nimport { ResourcePath } from '../model/path';\nimport {\n ApiClientObjectMap,\n BatchGetDocumentsRequest as ProtoBatchGetDocumentsRequest,\n BatchGetDocumentsResponse as ProtoBatchGetDocumentsResponse,\n RunAggregationQueryRequest as ProtoRunAggregationQueryRequest,\n RunAggregationQueryResponse as ProtoRunAggregationQueryResponse,\n RunQueryRequest as ProtoRunQueryRequest,\n RunQueryResponse as ProtoRunQueryResponse,\n Value\n} from '../protos/firestore_proto_api';\nimport { debugAssert, debugCast, hardAssert } from '../util/assert';\nimport { AsyncQueue } from '../util/async_queue';\nimport { Code, FirestoreError } from '../util/error';\nimport { isNullOrUndefined } from '../util/types';\n\nimport { Connection } from './connection';\nimport {\n PersistentListenStream,\n PersistentWriteStream,\n WatchStreamListener,\n WriteStreamListener\n} from './persistent_stream';\nimport {\n fromDocument,\n fromBatchGetDocumentsResponse,\n JsonProtoSerializer,\n toMutation,\n toName,\n toQueryTarget,\n toResourcePath,\n toRunAggregationQueryRequest\n} from './serializer';\n\n/**\n * Datastore and its related methods are a wrapper around the external Google\n * Cloud Datastore grpc API, which provides an interface that is more convenient\n * for the rest of the client SDK architecture to consume.\n */\nexport abstract class Datastore {\n abstract terminate(): void;\n abstract serializer: JsonProtoSerializer;\n}\n\n/**\n * An implementation of Datastore that exposes additional state for internal\n * consumption.\n */\nclass DatastoreImpl extends Datastore {\n terminated = false;\n\n constructor(\n readonly authCredentials: CredentialsProvider,\n readonly appCheckCredentials: CredentialsProvider,\n readonly connection: Connection,\n readonly serializer: JsonProtoSerializer\n ) {\n super();\n }\n\n verifyInitialized(): void {\n debugAssert(!!this.connection, 'Datastore.start() not called');\n if (this.terminated) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'The client has already been terminated.'\n );\n }\n }\n\n /** Invokes the provided RPC with auth and AppCheck tokens. */\n invokeRPC(\n rpcName: string,\n databaseId: DatabaseId,\n resourcePath: ResourcePath,\n request: Req\n ): Promise {\n this.verifyInitialized();\n return Promise.all([\n this.authCredentials.getToken(),\n this.appCheckCredentials.getToken()\n ])\n .then(([authToken, appCheckToken]) => {\n return this.connection.invokeRPC(\n rpcName,\n toResourcePath(databaseId, resourcePath),\n request,\n authToken,\n appCheckToken\n );\n })\n .catch((error: FirestoreError) => {\n if (error.name === 'FirebaseError') {\n if (error.code === Code.UNAUTHENTICATED) {\n this.authCredentials.invalidateToken();\n this.appCheckCredentials.invalidateToken();\n }\n throw error;\n } else {\n throw new FirestoreError(Code.UNKNOWN, error.toString());\n }\n });\n }\n\n /** Invokes the provided RPC with streamed results with auth and AppCheck tokens. */\n invokeStreamingRPC(\n rpcName: string,\n databaseId: DatabaseId,\n resourcePath: ResourcePath,\n request: Req,\n expectedResponseCount?: number\n ): Promise {\n this.verifyInitialized();\n return Promise.all([\n this.authCredentials.getToken(),\n this.appCheckCredentials.getToken()\n ])\n .then(([authToken, appCheckToken]) => {\n return this.connection.invokeStreamingRPC(\n rpcName,\n toResourcePath(databaseId, resourcePath),\n request,\n authToken,\n appCheckToken,\n expectedResponseCount\n );\n })\n .catch((error: FirestoreError) => {\n if (error.name === 'FirebaseError') {\n if (error.code === Code.UNAUTHENTICATED) {\n this.authCredentials.invalidateToken();\n this.appCheckCredentials.invalidateToken();\n }\n throw error;\n } else {\n throw new FirestoreError(Code.UNKNOWN, error.toString());\n }\n });\n }\n\n terminate(): void {\n this.terminated = true;\n this.connection.terminate();\n }\n}\n\n// TODO(firestorexp): Make sure there is only one Datastore instance per\n// firestore-exp client.\nexport function newDatastore(\n authCredentials: CredentialsProvider,\n appCheckCredentials: CredentialsProvider,\n connection: Connection,\n serializer: JsonProtoSerializer\n): Datastore {\n return new DatastoreImpl(\n authCredentials,\n appCheckCredentials,\n connection,\n serializer\n );\n}\n\nexport async function invokeCommitRpc(\n datastore: Datastore,\n mutations: Mutation[]\n): Promise {\n const datastoreImpl = debugCast(datastore, DatastoreImpl);\n const request = {\n writes: mutations.map(m => toMutation(datastoreImpl.serializer, m))\n };\n await datastoreImpl.invokeRPC(\n 'Commit',\n datastoreImpl.serializer.databaseId,\n ResourcePath.emptyPath(),\n request\n );\n}\n\nexport async function invokeBatchGetDocumentsRpc(\n datastore: Datastore,\n keys: DocumentKey[]\n): Promise {\n const datastoreImpl = debugCast(datastore, DatastoreImpl);\n const request = {\n documents: keys.map(k => toName(datastoreImpl.serializer, k))\n };\n const response = await datastoreImpl.invokeStreamingRPC<\n ProtoBatchGetDocumentsRequest,\n ProtoBatchGetDocumentsResponse\n >(\n 'BatchGetDocuments',\n datastoreImpl.serializer.databaseId,\n ResourcePath.emptyPath(),\n request,\n keys.length\n );\n\n const docs = new Map();\n response.forEach(proto => {\n const doc = fromBatchGetDocumentsResponse(datastoreImpl.serializer, proto);\n docs.set(doc.key.toString(), doc);\n });\n const result: Document[] = [];\n keys.forEach(key => {\n const doc = docs.get(key.toString());\n hardAssert(!!doc, 0xd7c2, 'Missing entity in write response for `key`', {\n key\n });\n result.push(doc);\n });\n return result;\n}\n\nexport async function invokeRunQueryRpc(\n datastore: Datastore,\n query: Query\n): Promise {\n const datastoreImpl = debugCast(datastore, DatastoreImpl);\n const { queryTarget, parent } = toQueryTarget(\n datastoreImpl.serializer,\n queryToTarget(query)\n );\n const response = await datastoreImpl.invokeStreamingRPC<\n ProtoRunQueryRequest,\n ProtoRunQueryResponse\n >('RunQuery', datastoreImpl.serializer.databaseId, parent, {\n structuredQuery: queryTarget.structuredQuery\n });\n return (\n response\n // Omit RunQueryResponses that only contain readTimes.\n .filter(proto => !!proto.document)\n .map(proto =>\n fromDocument(datastoreImpl.serializer, proto.document!, undefined)\n )\n );\n}\n\nexport async function invokeRunAggregationQueryRpc(\n datastore: Datastore,\n query: Query,\n aggregates: Aggregate[]\n): Promise> {\n const datastoreImpl = debugCast(datastore, DatastoreImpl);\n const { request, aliasMap, parent } = toRunAggregationQueryRequest(\n datastoreImpl.serializer,\n queryToAggregateTarget(query),\n aggregates\n );\n\n if (!datastoreImpl.connection.shouldResourcePathBeIncludedInRequest) {\n delete request.parent;\n }\n const response = await datastoreImpl.invokeStreamingRPC<\n ProtoRunAggregationQueryRequest,\n ProtoRunAggregationQueryResponse\n >(\n 'RunAggregationQuery',\n datastoreImpl.serializer.databaseId,\n parent,\n request,\n /*expectedResponseCount=*/ 1\n );\n\n // Omit RunAggregationQueryResponse that only contain readTimes.\n const filteredResult = response.filter(proto => !!proto.result);\n\n hardAssert(\n filteredResult.length === 1,\n 0xfcd7,\n 'Aggregation fields are missing from result.'\n );\n debugAssert(\n !isNullOrUndefined(filteredResult[0].result),\n 'aggregationQueryResponse.result'\n );\n debugAssert(\n !isNullOrUndefined(filteredResult[0].result.aggregateFields),\n 'aggregationQueryResponse.result.aggregateFields'\n );\n\n // Remap the short-form aliases that were sent to the server\n // to the client-side aliases. Users will access the results\n // using the client-side alias.\n const unmappedAggregateFields = filteredResult[0].result?.aggregateFields;\n const remappedFields = Object.keys(unmappedAggregateFields).reduce<\n ApiClientObjectMap\n >((accumulator, key) => {\n debugAssert(\n !isNullOrUndefined(aliasMap[key]),\n `'${key}' not present in aliasMap result`\n );\n accumulator[aliasMap[key]] = unmappedAggregateFields[key]!;\n return accumulator;\n }, {});\n\n return remappedFields;\n}\n\nexport function newPersistentWriteStream(\n datastore: Datastore,\n queue: AsyncQueue,\n listener: WriteStreamListener\n): PersistentWriteStream {\n const datastoreImpl = debugCast(datastore, DatastoreImpl);\n datastoreImpl.verifyInitialized();\n return new PersistentWriteStream(\n queue,\n datastoreImpl.connection,\n datastoreImpl.authCredentials,\n datastoreImpl.appCheckCredentials,\n datastoreImpl.serializer,\n listener\n );\n}\n\nexport function newPersistentWatchStream(\n datastore: Datastore,\n queue: AsyncQueue,\n listener: WatchStreamListener\n): PersistentListenStream {\n const datastoreImpl = debugCast(datastore, DatastoreImpl);\n datastoreImpl.verifyInitialized();\n return new PersistentListenStream(\n queue,\n datastoreImpl.connection,\n datastoreImpl.authCredentials,\n datastoreImpl.appCheckCredentials,\n datastoreImpl.serializer,\n listener\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport { _FirebaseService } from '@firebase/app';\n\nimport { CredentialsProvider } from '../api/credentials';\nimport { cloneLongPollingOptions } from '../api/long_polling_options';\nimport { User } from '../auth/user';\nimport { DatabaseId, DatabaseInfo } from '../core/database_info';\nimport { newConnection } from '../platform/connection';\nimport { newSerializer } from '../platform/serializer';\nimport { Datastore, newDatastore } from '../remote/datastore';\nimport { Code, FirestoreError } from '../util/error';\nimport { logDebug } from '../util/log';\n\nimport { FirestoreSettingsImpl } from './settings';\n\nexport const LOG_TAG = 'ComponentProvider';\n\n// The components module manages the lifetime of dependencies of the Firestore\n// client. Dependencies can be lazily constructed and only one exists per\n// Firestore instance.\n\n/**\n * An interface implemented by FirebaseFirestore that provides compatibility\n * with the usage in this file.\n *\n * This interface mainly exists to remove a cyclic dependency.\n */\nexport interface FirestoreService extends _FirebaseService {\n _authCredentials: CredentialsProvider;\n _appCheckCredentials: CredentialsProvider;\n _persistenceKey: string;\n _databaseId: DatabaseId;\n _terminated: boolean;\n\n _freezeSettings(): FirestoreSettingsImpl;\n}\n/**\n * An instance map that ensures only one Datastore exists per Firestore\n * instance.\n */\nconst datastoreInstances = new Map();\n\n/**\n * Returns an initialized and started Datastore for the given Firestore\n * instance. Callers must invoke removeComponents() when the Firestore\n * instance is terminated.\n */\nexport function getDatastore(firestore: FirestoreService): Datastore {\n if (firestore._terminated) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'The client has already been terminated.'\n );\n }\n if (!datastoreInstances.has(firestore)) {\n logDebug(LOG_TAG, 'Initializing Datastore');\n const databaseInfo = makeDatabaseInfo(\n firestore._databaseId,\n firestore.app.options.appId || '',\n firestore._persistenceKey,\n firestore._freezeSettings()\n );\n const connection = newConnection(databaseInfo);\n const serializer = newSerializer(firestore._databaseId);\n const datastore = newDatastore(\n firestore._authCredentials,\n firestore._appCheckCredentials,\n connection,\n serializer\n );\n\n datastoreInstances.set(firestore, datastore);\n }\n return datastoreInstances.get(firestore)!;\n}\n\n/**\n * Removes all components associated with the provided instance. Must be called\n * when the `Firestore` instance is terminated.\n */\nexport function removeComponents(firestore: FirestoreService): void {\n const datastore = datastoreInstances.get(firestore);\n if (datastore) {\n logDebug(LOG_TAG, 'Removing Datastore');\n datastoreInstances.delete(firestore);\n datastore.terminate();\n }\n}\n\nexport function makeDatabaseInfo(\n databaseId: DatabaseId,\n appId: string,\n persistenceKey: string,\n settings: FirestoreSettingsImpl\n): DatabaseInfo {\n return new DatabaseInfo(\n databaseId,\n appId,\n persistenceKey,\n settings.host,\n settings.ssl,\n settings.experimentalForceLongPolling,\n settings.experimentalAutoDetectLongPolling,\n cloneLongPollingOptions(settings.experimentalLongPollingOptions),\n settings.useFetchStreams,\n settings.isUsingEmulator\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DatabaseInfo } from '../../core/database_info';\nimport { Connection } from '../../remote/connection';\n\nimport { FetchConnection } from './fetch_connection';\n\nexport { newConnectivityMonitor } from '../browser/connection';\n\n/** Initializes the HTTP connection for the REST API. */\nexport function newConnection(databaseInfo: DatabaseInfo): Connection {\n return new FetchConnection(databaseInfo);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirestoreError } from '../api';\nimport { ListenSequence } from '../core/listen_sequence';\nimport { ListenSequenceNumber } from '../core/types';\nimport { debugAssert } from '../util/assert';\nimport { AsyncQueue, DelayedOperation, TimerId } from '../util/async_queue';\nimport { getLogLevel, logDebug, LogLevel } from '../util/log';\nimport { primitiveComparator } from '../util/misc';\nimport { SortedSet } from '../util/sorted_set';\n\nimport { ignoreIfPrimaryLeaseLoss, LocalStore } from './local_store';\nimport {\n ActiveTargets,\n GC_DID_NOT_RUN,\n LRU_COLLECTION_DISABLED,\n LruDelegate,\n LruGarbageCollector,\n LruParams,\n LruResults\n} from './lru_garbage_collector';\nimport { Scheduler } from './persistence';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { isIndexedDbTransactionError } from './simple_db';\n\nconst LOG_TAG = 'LruGarbageCollector';\n\nexport const LRU_MINIMUM_CACHE_SIZE_BYTES = 1 * 1024 * 1024;\n\n/** How long we wait to try running LRU GC after SDK initialization. */\nconst INITIAL_GC_DELAY_MS = 1 * 60 * 1000;\n/** Minimum amount of time between GC checks, after the first one. */\nconst REGULAR_GC_DELAY_MS = 5 * 60 * 1000;\n\n// The type and comparator for the items contained in the SortedSet used in\n// place of a priority queue for the RollingSequenceNumberBuffer.\ntype BufferEntry = [ListenSequenceNumber, number];\n\nfunction bufferEntryComparator(\n [aSequence, aIndex]: BufferEntry,\n [bSequence, bIndex]: BufferEntry\n): number {\n const seqCmp = primitiveComparator(aSequence, bSequence);\n if (seqCmp === 0) {\n // This order doesn't matter, but we can bias against churn by sorting\n // entries created earlier as less than newer entries.\n return primitiveComparator(aIndex, bIndex);\n } else {\n return seqCmp;\n }\n}\n\n/**\n * Used to calculate the nth sequence number. Keeps a rolling buffer of the\n * lowest n values passed to `addElement`, and finally reports the largest of\n * them in `maxValue`.\n */\nclass RollingSequenceNumberBuffer {\n private buffer: SortedSet = new SortedSet(\n bufferEntryComparator\n );\n\n private previousIndex = 0;\n\n constructor(private readonly maxElements: number) {}\n\n private nextIndex(): number {\n return ++this.previousIndex;\n }\n\n addElement(sequenceNumber: ListenSequenceNumber): void {\n const entry: BufferEntry = [sequenceNumber, this.nextIndex()];\n if (this.buffer.size < this.maxElements) {\n this.buffer = this.buffer.add(entry);\n } else {\n const highestValue = this.buffer.last()!;\n if (bufferEntryComparator(entry, highestValue) < 0) {\n this.buffer = this.buffer.delete(highestValue).add(entry);\n }\n }\n }\n\n get maxValue(): ListenSequenceNumber {\n // Guaranteed to be non-empty. If we decide we are not collecting any\n // sequence numbers, nthSequenceNumber below short-circuits. If we have\n // decided that we are collecting n sequence numbers, it's because n is some\n // percentage of the existing sequence numbers. That means we should never\n // be in a situation where we are collecting sequence numbers but don't\n // actually have any.\n return this.buffer.last()![0];\n }\n}\n\n/**\n * This class is responsible for the scheduling of LRU garbage collection. It handles checking\n * whether or not GC is enabled, as well as which delay to use before the next run.\n */\nexport class LruScheduler implements Scheduler {\n private gcTask: DelayedOperation | null;\n\n constructor(\n private readonly garbageCollector: LruGarbageCollector,\n private readonly asyncQueue: AsyncQueue,\n private readonly localStore: LocalStore\n ) {\n this.gcTask = null;\n }\n\n start(): void {\n debugAssert(\n this.gcTask === null,\n 'Cannot start an already started LruScheduler'\n );\n if (\n this.garbageCollector.params.cacheSizeCollectionThreshold !==\n LRU_COLLECTION_DISABLED\n ) {\n this.scheduleGC(INITIAL_GC_DELAY_MS);\n }\n }\n\n stop(): void {\n if (this.gcTask) {\n this.gcTask.cancel();\n this.gcTask = null;\n }\n }\n\n get started(): boolean {\n return this.gcTask !== null;\n }\n\n private scheduleGC(delay: number): void {\n debugAssert(\n this.gcTask === null,\n 'Cannot schedule GC while a task is pending'\n );\n logDebug(LOG_TAG, `Garbage collection scheduled in ${delay}ms`);\n this.gcTask = this.asyncQueue.enqueueAfterDelay(\n TimerId.LruGarbageCollection,\n delay,\n async () => {\n this.gcTask = null;\n try {\n await this.localStore.collectGarbage(this.garbageCollector);\n } catch (e) {\n if (isIndexedDbTransactionError(e as Error)) {\n logDebug(\n LOG_TAG,\n 'Ignoring IndexedDB error during garbage collection: ',\n e\n );\n } else {\n await ignoreIfPrimaryLeaseLoss(e as FirestoreError);\n }\n }\n await this.scheduleGC(REGULAR_GC_DELAY_MS);\n }\n );\n }\n}\n\n/**\n * Implements the steps for LRU garbage collection.\n */\nclass LruGarbageCollectorImpl implements LruGarbageCollector {\n constructor(\n private readonly delegate: LruDelegate,\n readonly params: LruParams\n ) {}\n\n calculateTargetCount(\n txn: PersistenceTransaction,\n percentile: number\n ): PersistencePromise {\n return this.delegate.getSequenceNumberCount(txn).next(targetCount => {\n return Math.floor((percentile / 100.0) * targetCount);\n });\n }\n\n nthSequenceNumber(\n txn: PersistenceTransaction,\n n: number\n ): PersistencePromise {\n if (n === 0) {\n return PersistencePromise.resolve(ListenSequence.INVALID);\n }\n\n const buffer = new RollingSequenceNumberBuffer(n);\n return this.delegate\n .forEachTarget(txn, target => buffer.addElement(target.sequenceNumber))\n .next(() => {\n return this.delegate.forEachOrphanedDocumentSequenceNumber(\n txn,\n sequenceNumber => buffer.addElement(sequenceNumber)\n );\n })\n .next(() => buffer.maxValue);\n }\n\n removeTargets(\n txn: PersistenceTransaction,\n upperBound: ListenSequenceNumber,\n activeTargetIds: ActiveTargets\n ): PersistencePromise {\n return this.delegate.removeTargets(txn, upperBound, activeTargetIds);\n }\n\n removeOrphanedDocuments(\n txn: PersistenceTransaction,\n upperBound: ListenSequenceNumber\n ): PersistencePromise {\n return this.delegate.removeOrphanedDocuments(txn, upperBound);\n }\n\n collect(\n txn: PersistenceTransaction,\n activeTargetIds: ActiveTargets\n ): PersistencePromise {\n if (this.params.cacheSizeCollectionThreshold === LRU_COLLECTION_DISABLED) {\n logDebug('LruGarbageCollector', 'Garbage collection skipped; disabled');\n return PersistencePromise.resolve(GC_DID_NOT_RUN);\n }\n\n return this.getCacheSize(txn).next(cacheSize => {\n if (cacheSize < this.params.cacheSizeCollectionThreshold) {\n logDebug(\n 'LruGarbageCollector',\n `Garbage collection skipped; Cache size ${cacheSize} ` +\n `is lower than threshold ${this.params.cacheSizeCollectionThreshold}`\n );\n return GC_DID_NOT_RUN;\n } else {\n return this.runGarbageCollection(txn, activeTargetIds);\n }\n });\n }\n\n getCacheSize(txn: PersistenceTransaction): PersistencePromise {\n return this.delegate.getCacheSize(txn);\n }\n\n private runGarbageCollection(\n txn: PersistenceTransaction,\n activeTargetIds: ActiveTargets\n ): PersistencePromise {\n let upperBoundSequenceNumber: number;\n let sequenceNumbersToCollect: number, targetsRemoved: number;\n // Timestamps for various pieces of the process\n let countedTargetsTs: number,\n foundUpperBoundTs: number,\n removedTargetsTs: number,\n removedDocumentsTs: number;\n const startTs = Date.now();\n return this.calculateTargetCount(txn, this.params.percentileToCollect)\n .next(sequenceNumbers => {\n // Cap at the configured max\n if (sequenceNumbers > this.params.maximumSequenceNumbersToCollect) {\n logDebug(\n 'LruGarbageCollector',\n 'Capping sequence numbers to collect down ' +\n `to the maximum of ${this.params.maximumSequenceNumbersToCollect} ` +\n `from ${sequenceNumbers}`\n );\n sequenceNumbersToCollect =\n this.params.maximumSequenceNumbersToCollect;\n } else {\n sequenceNumbersToCollect = sequenceNumbers;\n }\n countedTargetsTs = Date.now();\n\n return this.nthSequenceNumber(txn, sequenceNumbersToCollect);\n })\n .next(upperBound => {\n upperBoundSequenceNumber = upperBound;\n foundUpperBoundTs = Date.now();\n\n return this.removeTargets(\n txn,\n upperBoundSequenceNumber,\n activeTargetIds\n );\n })\n .next(numTargetsRemoved => {\n targetsRemoved = numTargetsRemoved;\n removedTargetsTs = Date.now();\n\n return this.removeOrphanedDocuments(txn, upperBoundSequenceNumber);\n })\n .next(documentsRemoved => {\n removedDocumentsTs = Date.now();\n\n if (getLogLevel() <= LogLevel.DEBUG) {\n const desc =\n 'LRU Garbage Collection\\n' +\n `\\tCounted targets in ${countedTargetsTs - startTs}ms\\n` +\n `\\tDetermined least recently used ${sequenceNumbersToCollect} in ` +\n `${foundUpperBoundTs - countedTargetsTs}ms\\n` +\n `\\tRemoved ${targetsRemoved} targets in ` +\n `${removedTargetsTs - foundUpperBoundTs}ms\\n` +\n `\\tRemoved ${documentsRemoved} documents in ` +\n `${removedDocumentsTs - removedTargetsTs}ms\\n` +\n `Total Duration: ${removedDocumentsTs - startTs}ms`;\n logDebug('LruGarbageCollector', desc);\n }\n\n return PersistencePromise.resolve({\n didRun: true,\n sequenceNumbersCollected: sequenceNumbersToCollect,\n targetsRemoved,\n documentsRemoved\n });\n });\n }\n}\n\nexport function newLruGarbageCollector(\n delegate: LruDelegate,\n params: LruParams\n): LruGarbageCollector {\n return new LruGarbageCollectorImpl(delegate, params);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { EmulatorMockTokenOptions } from '@firebase/util';\n\nimport { FirestoreLocalCache } from '../api/cache_config';\nimport { CredentialsSettings } from '../api/credentials';\nimport {\n ExperimentalLongPollingOptions,\n cloneLongPollingOptions,\n longPollingOptionsEqual\n} from '../api/long_polling_options';\nimport {\n LRU_COLLECTION_DISABLED,\n LRU_DEFAULT_CACHE_SIZE_BYTES\n} from '../local/lru_garbage_collector';\nimport { LRU_MINIMUM_CACHE_SIZE_BYTES } from '../local/lru_garbage_collector_impl';\nimport { Code, FirestoreError } from '../util/error';\nimport { validateIsNotUsedTogether } from '../util/input_validation';\n\n// settings() defaults:\nexport const DEFAULT_HOST = 'firestore.googleapis.com';\nexport const DEFAULT_SSL = true;\n\n// The minimum long-polling timeout is hardcoded on the server. The value here\n// should be kept in sync with the value used by the server, as the server will\n// silently ignore a value below the minimum and fall back to the default.\n// Googlers see b/266868871 for relevant discussion.\nconst MIN_LONG_POLLING_TIMEOUT_SECONDS = 5;\n\n// No maximum long-polling timeout is configured in the server, and defaults to\n// 30 seconds, which is what Watch appears to use.\n// Googlers see b/266868871 for relevant discussion.\nconst MAX_LONG_POLLING_TIMEOUT_SECONDS = 30;\n\n// Whether long-polling auto-detected is enabled by default.\nconst DEFAULT_AUTO_DETECT_LONG_POLLING = true;\n\n/**\n * Specifies custom configurations for your Cloud Firestore instance.\n * You must set these before invoking any other methods.\n */\nexport interface FirestoreSettings {\n /** The hostname to connect to. */\n host?: string;\n\n /** Whether to use SSL when connecting. */\n ssl?: boolean;\n\n /**\n * Whether to skip nested properties that are set to `undefined` during\n * object serialization. If set to `true`, these properties are skipped\n * and not written to Firestore. If set to `false` or omitted, the SDK\n * throws an exception when it encounters properties of type `undefined`.\n */\n ignoreUndefinedProperties?: boolean;\n}\n\n/**\n * @internal\n * Undocumented, private additional settings not exposed in our public API.\n */\nexport interface PrivateSettings extends FirestoreSettings {\n // Can be a google-auth-library or gapi client.\n credentials?: CredentialsSettings;\n cacheSizeBytes?: number;\n experimentalForceLongPolling?: boolean;\n experimentalAutoDetectLongPolling?: boolean;\n experimentalLongPollingOptions?: ExperimentalLongPollingOptions;\n useFetchStreams?: boolean;\n emulatorOptions?: { mockUserToken?: EmulatorMockTokenOptions | string };\n\n localCache?: FirestoreLocalCache;\n}\n\n/**\n * A concrete type describing all the values that can be applied via a\n * user-supplied `FirestoreSettings` object. This is a separate type so that\n * defaults can be supplied and the value can be checked for equality.\n */\nexport class FirestoreSettingsImpl {\n /** The hostname to connect to. */\n readonly host: string;\n\n /** Whether to use SSL when connecting. */\n readonly ssl: boolean;\n\n readonly cacheSizeBytes: number;\n\n readonly experimentalForceLongPolling: boolean;\n\n readonly experimentalAutoDetectLongPolling: boolean;\n\n readonly experimentalLongPollingOptions: ExperimentalLongPollingOptions;\n\n readonly ignoreUndefinedProperties: boolean;\n\n readonly useFetchStreams: boolean;\n readonly localCache?: FirestoreLocalCache;\n\n readonly isUsingEmulator: boolean;\n\n // Can be a google-auth-library or gapi client.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n credentials?: any;\n\n constructor(settings: PrivateSettings) {\n if (settings.host === undefined) {\n if (settings.ssl !== undefined) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n \"Can't provide ssl option if host option is not set\"\n );\n }\n this.host = DEFAULT_HOST;\n this.ssl = DEFAULT_SSL;\n } else {\n this.host = settings.host;\n this.ssl = settings.ssl ?? DEFAULT_SSL;\n }\n this.isUsingEmulator = settings.emulatorOptions !== undefined;\n\n this.credentials = settings.credentials;\n this.ignoreUndefinedProperties = !!settings.ignoreUndefinedProperties;\n this.localCache = settings.localCache;\n\n if (settings.cacheSizeBytes === undefined) {\n this.cacheSizeBytes = LRU_DEFAULT_CACHE_SIZE_BYTES;\n } else {\n if (\n settings.cacheSizeBytes !== LRU_COLLECTION_DISABLED &&\n settings.cacheSizeBytes < LRU_MINIMUM_CACHE_SIZE_BYTES\n ) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `cacheSizeBytes must be at least ${LRU_MINIMUM_CACHE_SIZE_BYTES}`\n );\n } else {\n this.cacheSizeBytes = settings.cacheSizeBytes;\n }\n }\n\n validateIsNotUsedTogether(\n 'experimentalForceLongPolling',\n settings.experimentalForceLongPolling,\n 'experimentalAutoDetectLongPolling',\n settings.experimentalAutoDetectLongPolling\n );\n\n this.experimentalForceLongPolling = !!settings.experimentalForceLongPolling;\n\n if (this.experimentalForceLongPolling) {\n this.experimentalAutoDetectLongPolling = false;\n } else if (settings.experimentalAutoDetectLongPolling === undefined) {\n this.experimentalAutoDetectLongPolling = DEFAULT_AUTO_DETECT_LONG_POLLING;\n } else {\n // For backwards compatibility, coerce the value to boolean even though\n // the TypeScript compiler has narrowed the type to boolean already.\n // noinspection PointlessBooleanExpressionJS\n this.experimentalAutoDetectLongPolling =\n !!settings.experimentalAutoDetectLongPolling;\n }\n\n this.experimentalLongPollingOptions = cloneLongPollingOptions(\n settings.experimentalLongPollingOptions ?? {}\n );\n validateLongPollingOptions(this.experimentalLongPollingOptions);\n\n this.useFetchStreams = !!settings.useFetchStreams;\n }\n\n isEqual(other: FirestoreSettingsImpl): boolean {\n return (\n this.host === other.host &&\n this.ssl === other.ssl &&\n this.credentials === other.credentials &&\n this.cacheSizeBytes === other.cacheSizeBytes &&\n this.experimentalForceLongPolling ===\n other.experimentalForceLongPolling &&\n this.experimentalAutoDetectLongPolling ===\n other.experimentalAutoDetectLongPolling &&\n longPollingOptionsEqual(\n this.experimentalLongPollingOptions,\n other.experimentalLongPollingOptions\n ) &&\n this.ignoreUndefinedProperties === other.ignoreUndefinedProperties &&\n this.useFetchStreams === other.useFetchStreams\n );\n }\n}\n\nfunction validateLongPollingOptions(\n options: ExperimentalLongPollingOptions\n): void {\n if (options.timeoutSeconds !== undefined) {\n if (isNaN(options.timeoutSeconds)) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `invalid long polling timeout: ` +\n `${options.timeoutSeconds} (must not be NaN)`\n );\n }\n if (options.timeoutSeconds < MIN_LONG_POLLING_TIMEOUT_SECONDS) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `invalid long polling timeout: ${options.timeoutSeconds} ` +\n `(minimum allowed value is ${MIN_LONG_POLLING_TIMEOUT_SECONDS})`\n );\n }\n if (options.timeoutSeconds > MAX_LONG_POLLING_TIMEOUT_SECONDS) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `invalid long polling timeout: ${options.timeoutSeconds} ` +\n `(maximum allowed value is ${MAX_LONG_POLLING_TIMEOUT_SECONDS})`\n );\n }\n }\n}\n","/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ListenSequenceNumber, TargetId } from '../core/types';\nimport { SortedMap } from '../util/sorted_map';\n\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { TargetData } from './target_data';\n\n/**\n * Describes a map whose keys are active target ids. We do not care about the type of the\n * values.\n */\nexport type ActiveTargets = SortedMap;\n\nexport const GC_DID_NOT_RUN: LruResults = {\n didRun: false,\n sequenceNumbersCollected: 0,\n targetsRemoved: 0,\n documentsRemoved: 0\n};\n\nexport const LRU_COLLECTION_DISABLED = -1;\nexport const LRU_DEFAULT_CACHE_SIZE_BYTES = 40 * 1024 * 1024;\n\nexport class LruParams {\n private static readonly DEFAULT_COLLECTION_PERCENTILE = 10;\n private static readonly DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT = 1000;\n\n static withCacheSize(cacheSize: number): LruParams {\n return new LruParams(\n cacheSize,\n LruParams.DEFAULT_COLLECTION_PERCENTILE,\n LruParams.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT\n );\n }\n\n static readonly DEFAULT: LruParams = new LruParams(\n LRU_DEFAULT_CACHE_SIZE_BYTES,\n LruParams.DEFAULT_COLLECTION_PERCENTILE,\n LruParams.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT\n );\n\n static readonly DISABLED: LruParams = new LruParams(\n LRU_COLLECTION_DISABLED,\n 0,\n 0\n );\n\n constructor(\n // When we attempt to collect, we will only do so if the cache size is greater than this\n // threshold. Passing `COLLECTION_DISABLED` here will cause collection to always be skipped.\n readonly cacheSizeCollectionThreshold: number,\n // The percentage of sequence numbers that we will attempt to collect\n readonly percentileToCollect: number,\n // A cap on the total number of sequence numbers that will be collected. This prevents\n // us from collecting a huge number of sequence numbers if the cache has grown very large.\n readonly maximumSequenceNumbersToCollect: number\n ) {}\n}\n\nexport interface LruGarbageCollector {\n readonly params: LruParams;\n\n collect(\n txn: PersistenceTransaction,\n activeTargetIds: ActiveTargets\n ): PersistencePromise;\n\n /** Given a percentile of target to collect, returns the number of targets to collect. */\n calculateTargetCount(\n txn: PersistenceTransaction,\n percentile: number\n ): PersistencePromise;\n\n /** Returns the nth sequence number, counting in order from the smallest. */\n nthSequenceNumber(\n txn: PersistenceTransaction,\n n: number\n ): PersistencePromise;\n\n /**\n * Removes documents that have a sequence number equal to or less than the\n * upper bound and are not otherwise pinned.\n */\n removeOrphanedDocuments(\n txn: PersistenceTransaction,\n upperBound: ListenSequenceNumber\n ): PersistencePromise;\n\n getCacheSize(txn: PersistenceTransaction): PersistencePromise;\n\n /**\n * Removes targets with a sequence number equal to or less than the given\n * upper bound, and removes document associations with those targets.\n */\n removeTargets(\n txn: PersistenceTransaction,\n upperBound: ListenSequenceNumber,\n activeTargetIds: ActiveTargets\n ): PersistencePromise;\n}\n\n/**\n * Describes the results of a garbage collection run. `didRun` will be set to\n * `false` if collection was skipped (either it is disabled or the cache size\n * has not hit the threshold). If collection ran, the other fields will be\n * filled in with the details of the results.\n */\nexport interface LruResults {\n readonly didRun: boolean;\n readonly sequenceNumbersCollected: number;\n readonly targetsRemoved: number;\n readonly documentsRemoved: number;\n}\n\n/**\n * Persistence layers intending to use LRU Garbage collection should have\n * reference delegates that implement this interface. This interface defines the\n * operations that the LRU garbage collector needs from the persistence layer.\n */\nexport interface LruDelegate {\n readonly garbageCollector: LruGarbageCollector;\n\n /** Enumerates all the targets in the TargetCache. */\n forEachTarget(\n txn: PersistenceTransaction,\n f: (target: TargetData) => void\n ): PersistencePromise;\n\n getSequenceNumberCount(\n txn: PersistenceTransaction\n ): PersistencePromise;\n\n /**\n * Enumerates sequence numbers for documents not associated with a target.\n * Note that this may include duplicate sequence numbers.\n */\n forEachOrphanedDocumentSequenceNumber(\n txn: PersistenceTransaction,\n f: (sequenceNumber: ListenSequenceNumber) => void\n ): PersistencePromise;\n\n /**\n * Removes all targets that have a sequence number less than or equal to\n * `upperBound`, and are not present in the `activeTargetIds` set.\n *\n * @returns the number of targets removed.\n */\n removeTargets(\n txn: PersistenceTransaction,\n upperBound: ListenSequenceNumber,\n activeTargetIds: ActiveTargets\n ): PersistencePromise;\n\n /**\n * Removes all unreferenced documents from the cache that have a sequence\n * number less than or equal to the given `upperBound`.\n *\n * @returns the number of documents removed.\n */\n removeOrphanedDocuments(\n txn: PersistenceTransaction,\n upperBound: ListenSequenceNumber\n ): PersistencePromise;\n\n getCacheSize(txn: PersistenceTransaction): PersistencePromise;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport {\n _getProvider,\n _removeServiceInstance,\n FirebaseApp,\n getApp\n} from '@firebase/app';\nimport {\n createMockUserToken,\n deepEqual,\n EmulatorMockTokenOptions,\n getDefaultEmulatorHostnameAndPort,\n isCloudWorkstation,\n pingServer,\n updateEmulatorBanner\n} from '@firebase/util';\n\nimport {\n CredentialsProvider,\n EmulatorAuthCredentialsProvider,\n makeAuthCredentialsProvider,\n OAuthToken\n} from '../api/credentials';\nimport { User } from '../auth/user';\nimport { DatabaseId, DEFAULT_DATABASE_NAME } from '../core/database_info';\nimport { Code, FirestoreError } from '../util/error';\nimport { cast } from '../util/input_validation';\nimport { logWarn } from '../util/log';\n\nimport { FirestoreService, removeComponents } from './components';\nimport {\n DEFAULT_HOST,\n FirestoreSettingsImpl,\n PrivateSettings,\n FirestoreSettings\n} from './settings';\n\nexport { EmulatorMockTokenOptions } from '@firebase/util';\n\ndeclare module '@firebase/component' {\n interface NameServiceMapping {\n 'firestore/lite': Firestore;\n }\n}\n\n/**\n * The Cloud Firestore service interface.\n *\n * Do not call this constructor directly. Instead, use {@link (getFirestore:1)}.\n */\nexport class Firestore implements FirestoreService {\n /**\n * Whether it's a Firestore or Firestore Lite instance.\n */\n type: 'firestore-lite' | 'firestore' = 'firestore-lite';\n\n readonly _persistenceKey: string = '(lite)';\n\n private _settings = new FirestoreSettingsImpl({});\n private _settingsFrozen = false;\n private _emulatorOptions: {\n mockUserToken?: EmulatorMockTokenOptions | string;\n } = {};\n\n // A task that is assigned when the terminate() is invoked and resolved when\n // all components have shut down. Otherwise, Firestore is not terminated,\n // which can mean either the FirestoreClient is in the process of starting,\n // or restarting.\n private _terminateTask: Promise | 'notTerminated' = 'notTerminated';\n\n /** @hideconstructor */\n constructor(\n public _authCredentials: CredentialsProvider,\n public _appCheckCredentials: CredentialsProvider,\n readonly _databaseId: DatabaseId,\n readonly _app?: FirebaseApp\n ) {}\n\n /**\n * The {@link @firebase/app#FirebaseApp} associated with this `Firestore` service\n * instance.\n */\n get app(): FirebaseApp {\n if (!this._app) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n \"Firestore was not initialized using the Firebase SDK. 'app' is \" +\n 'not available'\n );\n }\n return this._app;\n }\n\n get _initialized(): boolean {\n return this._settingsFrozen;\n }\n\n get _terminated(): boolean {\n return this._terminateTask !== 'notTerminated';\n }\n\n _setSettings(settings: PrivateSettings): void {\n if (this._settingsFrozen) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'Firestore has already been started and its settings can no longer ' +\n 'be changed. You can only modify settings before calling any other ' +\n 'methods on a Firestore object.'\n );\n }\n this._settings = new FirestoreSettingsImpl(settings);\n this._emulatorOptions = settings.emulatorOptions || {};\n\n if (settings.credentials !== undefined) {\n this._authCredentials = makeAuthCredentialsProvider(settings.credentials);\n }\n }\n\n _getSettings(): FirestoreSettingsImpl {\n return this._settings;\n }\n\n _getEmulatorOptions(): { mockUserToken?: EmulatorMockTokenOptions | string } {\n return this._emulatorOptions;\n }\n\n _freezeSettings(): FirestoreSettingsImpl {\n this._settingsFrozen = true;\n return this._settings;\n }\n\n _delete(): Promise {\n // The `_terminateTask` must be assigned future that completes when\n // terminate is complete. The existence of this future puts SDK in state\n // that will not accept further API interaction.\n if (this._terminateTask === 'notTerminated') {\n this._terminateTask = this._terminate();\n }\n return this._terminateTask;\n }\n\n async _restart(): Promise {\n // The `_terminateTask` must equal 'notTerminated' after restart to\n // signal that client is in a state that accepts API calls.\n if (this._terminateTask === 'notTerminated') {\n await this._terminate();\n } else {\n this._terminateTask = 'notTerminated';\n }\n }\n\n /** Returns a JSON-serializable representation of this `Firestore` instance. */\n toJSON(): object {\n return {\n app: this._app,\n databaseId: this._databaseId,\n settings: this._settings\n };\n }\n\n /**\n * Terminates all components used by this client. Subclasses can override\n * this method to clean up their own dependencies, but must also call this\n * method.\n *\n * Only ever called once.\n */\n protected _terminate(): Promise {\n removeComponents(this);\n return Promise.resolve();\n }\n}\n\n/**\n * Initializes a new instance of Cloud Firestore with the provided settings.\n * Can only be called before any other functions, including\n * {@link (getFirestore:1)}. If the custom settings are empty, this function is\n * equivalent to calling {@link (getFirestore:1)}.\n *\n * @param app - The {@link @firebase/app#FirebaseApp} with which the `Firestore` instance will\n * be associated.\n * @param settings - A settings object to configure the `Firestore` instance.\n * @returns A newly initialized `Firestore` instance.\n */\nexport function initializeFirestore(\n app: FirebaseApp,\n settings: FirestoreSettings\n): Firestore;\n/**\n * Initializes a new instance of Cloud Firestore with the provided settings.\n * Can only be called before any other functions, including\n * {@link (getFirestore:1)}. If the custom settings are empty, this function is\n * equivalent to calling {@link (getFirestore:1)}.\n *\n * @param app - The {@link @firebase/app#FirebaseApp} with which the `Firestore` instance will\n * be associated.\n * @param settings - A settings object to configure the `Firestore` instance.\n * @param databaseId - The name of the database.\n * @returns A newly initialized `Firestore` instance.\n * @beta\n */\nexport function initializeFirestore(\n app: FirebaseApp,\n settings: FirestoreSettings,\n databaseId?: string\n): Firestore;\nexport function initializeFirestore(\n app: FirebaseApp,\n settings: FirestoreSettings,\n databaseId?: string\n): Firestore {\n if (!databaseId) {\n databaseId = DEFAULT_DATABASE_NAME;\n }\n const provider = _getProvider(app, 'firestore/lite');\n\n if (provider.isInitialized(databaseId)) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'Firestore can only be initialized once per app.'\n );\n }\n\n return provider.initialize({\n options: settings,\n instanceIdentifier: databaseId\n });\n}\n\n/**\n * Returns the existing default {@link Firestore} instance that is associated with the\n * default {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new\n * instance with default settings.\n *\n * @returns The {@link Firestore} instance of the provided app.\n */\nexport function getFirestore(): Firestore;\n/**\n * Returns the existing default {@link Firestore} instance that is associated with the\n * provided {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new\n * instance with default settings.\n *\n * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned {@link Firestore}\n * instance is associated with.\n * @returns The {@link Firestore} instance of the provided app.\n */\nexport function getFirestore(app: FirebaseApp): Firestore;\n/**\n * Returns the existing {@link Firestore} instance that is associated with the\n * default {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new\n * instance with default settings.\n *\n * @param databaseId - The name of the database.\n * @returns The {@link Firestore} instance of the provided app.\n * @beta\n */\nexport function getFirestore(databaseId: string): Firestore;\n/**\n * Returns the existing {@link Firestore} instance that is associated with the\n * provided {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new\n * instance with default settings.\n *\n * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned {@link Firestore}\n * instance is associated with.\n * @param databaseId - The name of the database.\n * @returns The {@link Firestore} instance of the provided app.\n * @beta\n */\nexport function getFirestore(app: FirebaseApp, databaseId: string): Firestore;\nexport function getFirestore(\n appOrDatabaseId?: FirebaseApp | string,\n optionalDatabaseId?: string\n): Firestore {\n const app: FirebaseApp =\n typeof appOrDatabaseId === 'object' ? appOrDatabaseId : getApp();\n const databaseId =\n typeof appOrDatabaseId === 'string'\n ? appOrDatabaseId\n : optionalDatabaseId || '(default)';\n const db = _getProvider(app, 'firestore/lite').getImmediate({\n identifier: databaseId\n }) as Firestore;\n if (!db._initialized) {\n const emulator = getDefaultEmulatorHostnameAndPort('firestore');\n if (emulator) {\n connectFirestoreEmulator(db, ...emulator);\n }\n }\n return db;\n}\n\n/**\n * Modify this instance to communicate with the Cloud Firestore emulator.\n *\n * Note: This must be called before this instance has been used to do any\n * operations.\n *\n * @param firestore - The `Firestore` instance to configure to connect to the\n * emulator.\n * @param host - the emulator host (ex: localhost).\n * @param port - the emulator port (ex: 9000).\n * @param options.mockUserToken - the mock auth token to use for unit testing\n * Security Rules.\n */\nexport function connectFirestoreEmulator(\n firestore: Firestore,\n host: string,\n port: number,\n options: {\n mockUserToken?: EmulatorMockTokenOptions | string;\n } = {}\n): void {\n firestore = cast(firestore, Firestore);\n const useSsl = isCloudWorkstation(host);\n const settings = firestore._getSettings();\n const existingConfig = {\n ...settings,\n emulatorOptions: firestore._getEmulatorOptions()\n };\n const newHostSetting = `${host}:${port}`;\n if (useSsl) {\n void pingServer(`https://${newHostSetting}`);\n updateEmulatorBanner('Firestore', true);\n }\n if (settings.host !== DEFAULT_HOST && settings.host !== newHostSetting) {\n logWarn(\n 'Host has been set in both settings() and connectFirestoreEmulator(), emulator host ' +\n 'will be used.'\n );\n }\n const newConfig = {\n ...settings,\n host: newHostSetting,\n ssl: useSsl,\n emulatorOptions: options\n };\n // No-op if the new configuration matches the current configuration. This supports SSR\n // enviornments which might call `connectFirestoreEmulator` multiple times as a standard practice.\n if (deepEqual(newConfig, existingConfig)) {\n return;\n }\n\n firestore._setSettings(newConfig);\n\n if (options.mockUserToken) {\n let token: string;\n let user: User;\n if (typeof options.mockUserToken === 'string') {\n token = options.mockUserToken;\n user = User.MOCK_USER;\n } else {\n // Let createMockUserToken validate first (catches common mistakes like\n // invalid field \"uid\" and missing field \"sub\" / \"user_id\".)\n token = createMockUserToken(\n options.mockUserToken,\n firestore._app?.options.projectId\n );\n const uid = options.mockUserToken.sub || options.mockUserToken.user_id;\n if (!uid) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n \"mockUserToken must contain 'sub' or 'user_id' field!\"\n );\n }\n user = new User(uid);\n }\n\n firestore._authCredentials = new EmulatorAuthCredentialsProvider(\n new OAuthToken(token, user)\n );\n }\n}\n\n/**\n * Terminates the provided `Firestore` instance.\n *\n * After calling `terminate()` only the `clearIndexedDbPersistence()` functions\n * may be used. Any other function will throw a `FirestoreError`. Termination\n * does not cancel any pending writes, and any promises that are awaiting a\n * response from the server will not be resolved.\n *\n * To restart after termination, create a new instance of `Firestore` with\n * {@link (getFirestore:1)}.\n *\n * Note: Under normal circumstances, calling `terminate()` is not required. This\n * function is useful only when you want to force this instance to release all of\n * its resources or in combination with {@link clearIndexedDbPersistence} to\n * ensure that all local state is destroyed between test runs.\n *\n * @param firestore - The `Firestore` instance to terminate.\n * @returns A `Promise` that is resolved when the instance has been successfully\n * terminated.\n */\nexport function terminate(firestore: Firestore): Promise {\n firestore = cast(firestore, Firestore);\n _removeServiceInstance(firestore.app, 'firestore/lite');\n return firestore._delete();\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { AggregateType } from '../core/aggregate';\nimport { FieldPath as InternalFieldPath } from '../model/path';\nimport { ApiClientObjectMap, Value } from '../protos/firestore_proto_api';\n\nimport { average, count, sum } from './aggregate';\nimport { DocumentData, Query } from './reference';\nimport { AbstractUserDataWriter } from './user_data_writer';\n\nexport { AggregateType };\n\n/**\n * Represents an aggregation that can be performed by Firestore.\n */\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport class AggregateField {\n /** A type string to uniquely identify instances of this class. */\n readonly type = 'AggregateField';\n\n /** Indicates the aggregation operation of this AggregateField. */\n readonly aggregateType: AggregateType;\n\n /**\n * Create a new AggregateField\n * @param aggregateType Specifies the type of aggregation operation to perform.\n * @param _internalFieldPath Optionally specifies the field that is aggregated.\n * @internal\n */\n constructor(\n aggregateType: AggregateType = 'count',\n readonly _internalFieldPath?: InternalFieldPath\n ) {\n this.aggregateType = aggregateType;\n }\n}\n\n/**\n * The union of all `AggregateField` types that are supported by Firestore.\n */\nexport type AggregateFieldType =\n | ReturnType\n | ReturnType\n | ReturnType;\n\n/**\n * Specifies a set of aggregations and their aliases.\n */\nexport interface AggregateSpec {\n [field: string]: AggregateFieldType;\n}\n\n/**\n * A type whose keys are taken from an `AggregateSpec`, and whose values are the\n * result of the aggregation performed by the corresponding `AggregateField`\n * from the input `AggregateSpec`.\n */\nexport type AggregateSpecData = {\n [P in keyof T]: T[P] extends AggregateField ? U : never;\n};\n\n/**\n * The results of executing an aggregation query.\n */\nexport class AggregateQuerySnapshot<\n AggregateSpecType extends AggregateSpec,\n AppModelType = DocumentData,\n DbModelType extends DocumentData = DocumentData\n> {\n /** A type string to uniquely identify instances of this class. */\n readonly type = 'AggregateQuerySnapshot';\n\n /**\n * The underlying query over which the aggregations recorded in this\n * `AggregateQuerySnapshot` were performed.\n */\n readonly query: Query;\n\n /** @hideconstructor */\n constructor(\n query: Query,\n private readonly _userDataWriter: AbstractUserDataWriter,\n private readonly _data: ApiClientObjectMap\n ) {\n this.query = query;\n }\n\n /**\n * Returns the results of the aggregations performed over the underlying\n * query.\n *\n * The keys of the returned object will be the same as those of the\n * `AggregateSpec` object specified to the aggregation method, and the values\n * will be the corresponding aggregation result.\n *\n * @returns The results of the aggregations performed over the underlying\n * query.\n */\n data(): AggregateSpecData {\n return this._userDataWriter.convertObjectMap(\n this._data\n ) as AggregateSpecData;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getModularInstance } from '@firebase/util';\n\nimport {\n newQueryForCollectionGroup,\n newQueryForPath,\n Query as InternalQuery,\n queryEquals\n} from '../core/query';\nimport { DocumentKey } from '../model/document_key';\nimport { ResourcePath } from '../model/path';\nimport { Code, FirestoreError } from '../util/error';\nimport {\n cast,\n validateCollectionPath,\n validateDocumentPath,\n validateNonEmptyArgument\n} from '../util/input_validation';\n// API extractor fails importing property unless we also explicitly import Property.\n// eslint-disable-next-line @typescript-eslint/no-unused-vars, unused-imports/no-unused-imports-ts\nimport { Property, property, validateJSON } from '../util/json_validation';\nimport { AutoId } from '../util/misc';\n\nimport { Firestore } from './database';\nimport { FieldPath } from './field_path';\nimport { FieldValue } from './field_value';\nimport { FirestoreDataConverter } from './snapshot';\nimport { NestedUpdateFields, Primitive } from './types';\n\n/**\n * Document data (for use with {@link @firebase/firestore/lite#(setDoc:1)}) consists of fields mapped to\n * values.\n */\nexport interface DocumentData {\n /** A mapping between a field and its value. */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [field: string]: any;\n}\n\n/**\n * Similar to TypeScript's `Partial`, but allows nested fields to be\n * omitted and FieldValues to be passed in as property values.\n */\nexport type PartialWithFieldValue =\n | Partial\n | (T extends Primitive\n ? T\n : T extends {}\n ? { [K in keyof T]?: PartialWithFieldValue | FieldValue }\n : never);\n\n/**\n * Allows FieldValues to be passed in as a property value while maintaining\n * type safety.\n */\nexport type WithFieldValue =\n | T\n | (T extends Primitive\n ? T\n : T extends {}\n ? { [K in keyof T]: WithFieldValue | FieldValue }\n : never);\n\n/**\n * Update data (for use with {@link (updateDoc:1)}) that consists of field paths\n * (e.g. 'foo' or 'foo.baz') mapped to values. Fields that contain dots\n * reference nested fields within the document. FieldValues can be passed in\n * as property values.\n */\nexport type UpdateData = T extends Primitive\n ? T\n : T extends {}\n ? { [K in keyof T]?: UpdateData | FieldValue } & NestedUpdateFields\n : Partial;\n/**\n * An options object that configures the behavior of {@link @firebase/firestore/lite#(setDoc:1)}, {@link\n * @firebase/firestore/lite#(WriteBatch.set:1)} and {@link @firebase/firestore/lite#(Transaction.set:1)} calls. These calls can be\n * configured to perform granular merges instead of overwriting the target\n * documents in their entirety by providing a `SetOptions` with `merge: true`.\n *\n * @param merge - Changes the behavior of a `setDoc()` call to only replace the\n * values specified in its data argument. Fields omitted from the `setDoc()`\n * call remain untouched. If your input sets any field to an empty map, all\n * nested fields are overwritten.\n * @param mergeFields - Changes the behavior of `setDoc()` calls to only replace\n * the specified field paths. Any field path that is not specified is ignored\n * and remains untouched. If your input sets any field to an empty map, all\n * nested fields are overwritten.\n */\nexport type SetOptions =\n | {\n readonly merge?: boolean;\n }\n | {\n readonly mergeFields?: Array;\n };\n\n/**\n * A `Query` refers to a query which you can read or listen to. You can also\n * construct refined `Query` objects by adding filters and ordering.\n */\nexport class Query<\n AppModelType = DocumentData,\n DbModelType extends DocumentData = DocumentData\n> {\n /** The type of this Firestore reference. */\n readonly type: 'query' | 'collection' = 'query';\n\n /**\n * The `Firestore` instance for the Firestore database (useful for performing\n * transactions, etc.).\n */\n readonly firestore: Firestore;\n\n // This is the lite version of the Query class in the main SDK.\n\n /** @hideconstructor protected */\n constructor(\n firestore: Firestore,\n /**\n * If provided, the `FirestoreDataConverter` associated with this instance.\n */\n readonly converter: FirestoreDataConverter<\n AppModelType,\n DbModelType\n > | null,\n readonly _query: InternalQuery\n ) {\n this.firestore = firestore;\n }\n\n /**\n * Removes the current converter.\n *\n * @param converter - `null` removes the current converter.\n * @returns A `Query` that does not use a\n * converter.\n */\n withConverter(converter: null): Query;\n /**\n * Applies a custom data converter to this query, allowing you to use your own\n * custom model objects with Firestore. When you call {@link getDocs} with\n * the returned query, the provided converter will convert between Firestore\n * data of type `NewDbModelType` and your custom type `NewAppModelType`.\n *\n * @param converter - Converts objects to and from Firestore.\n * @returns A `Query` that uses the provided converter.\n */\n withConverter<\n NewAppModelType,\n NewDbModelType extends DocumentData = DocumentData\n >(\n converter: FirestoreDataConverter\n ): Query;\n withConverter<\n NewAppModelType,\n NewDbModelType extends DocumentData = DocumentData\n >(\n converter: FirestoreDataConverter | null\n ): Query {\n return new Query(\n this.firestore,\n converter,\n this._query\n );\n }\n}\n\n/**\n * A `DocumentReference` refers to a document location in a Firestore database\n * and can be used to write, read, or listen to the location. The document at\n * the referenced location may or may not exist.\n */\nexport class DocumentReference<\n AppModelType = DocumentData,\n DbModelType extends DocumentData = DocumentData\n> {\n /** The type of this Firestore reference. */\n readonly type = 'document';\n\n /**\n * The {@link Firestore} instance the document is in.\n * This is useful for performing transactions, for example.\n */\n readonly firestore: Firestore;\n\n /** @hideconstructor */\n constructor(\n firestore: Firestore,\n /**\n * If provided, the `FirestoreDataConverter` associated with this instance.\n */\n readonly converter: FirestoreDataConverter<\n AppModelType,\n DbModelType\n > | null,\n readonly _key: DocumentKey\n ) {\n this.firestore = firestore;\n }\n\n get _path(): ResourcePath {\n return this._key.path;\n }\n\n /**\n * The document's identifier within its collection.\n */\n get id(): string {\n return this._key.path.lastSegment();\n }\n\n /**\n * A string representing the path of the referenced document (relative\n * to the root of the database).\n */\n get path(): string {\n return this._key.path.canonicalString();\n }\n\n /**\n * The collection this `DocumentReference` belongs to.\n */\n get parent(): CollectionReference {\n return new CollectionReference(\n this.firestore,\n this.converter,\n this._key.path.popLast()\n );\n }\n\n /**\n * Applies a custom data converter to this `DocumentReference`, allowing you\n * to use your own custom model objects with Firestore. When you call {@link\n * @firebase/firestore/lite#(setDoc:1)}, {@link @firebase/firestore/lite#getDoc}, etc. with the returned `DocumentReference`\n * instance, the provided converter will convert between Firestore data of\n * type `NewDbModelType` and your custom type `NewAppModelType`.\n *\n * @param converter - Converts objects to and from Firestore.\n * @returns A `DocumentReference` that uses the provided converter.\n */\n withConverter<\n NewAppModelType,\n NewDbModelType extends DocumentData = DocumentData\n >(\n converter: FirestoreDataConverter\n ): DocumentReference;\n /**\n * Removes the current converter.\n *\n * @param converter - `null` removes the current converter.\n * @returns A `DocumentReference` that does not\n * use a converter.\n */\n withConverter(converter: null): DocumentReference;\n withConverter<\n NewAppModelType,\n NewDbModelType extends DocumentData = DocumentData\n >(\n converter: FirestoreDataConverter | null\n ): DocumentReference {\n return new DocumentReference(\n this.firestore,\n converter,\n this._key\n );\n }\n\n static _jsonSchemaVersion: string = 'firestore/documentReference/1.0';\n static _jsonSchema = {\n type: property('string', DocumentReference._jsonSchemaVersion),\n referencePath: property('string')\n };\n\n /**\n * Returns a JSON-serializable representation of this `DocumentReference` instance.\n *\n * @returns a JSON representation of this object.\n */\n toJSON(): object {\n return {\n type: DocumentReference._jsonSchemaVersion,\n referencePath: this._key.toString()\n };\n }\n\n /**\n * Builds a `DocumentReference` instance from a JSON object created by\n * {@link DocumentReference.toJSON}.\n *\n * @param firestore - The {@link Firestore} instance the snapshot should be loaded for.\n * @param json a JSON object represention of a `DocumentReference` instance\n * @returns an instance of {@link DocumentReference} if the JSON object could be parsed. Throws a\n * {@link FirestoreError} if an error occurs.\n */\n static fromJSON(firestore: Firestore, json: object): DocumentReference;\n /**\n * Builds a `DocumentReference` instance from a JSON object created by\n * {@link DocumentReference.toJSON}.\n *\n * @param firestore - The {@link Firestore} instance the snapshot should be loaded for.\n * @param json a JSON object represention of a `DocumentReference` instance\n * @param converter - Converts objects to and from Firestore.\n * @returns an instance of {@link DocumentReference} if the JSON object could be parsed. Throws a\n * {@link FirestoreError} if an error occurs.\n */\n static fromJSON<\n NewAppModelType = DocumentData,\n NewDbModelType extends DocumentData = DocumentData\n >(\n firestore: Firestore,\n json: object,\n converter: FirestoreDataConverter\n ): DocumentReference;\n static fromJSON<\n NewAppModelType = DocumentData,\n NewDbModelType extends DocumentData = DocumentData\n >(\n firestore: Firestore,\n json: object,\n converter?: FirestoreDataConverter\n ): DocumentReference {\n if (validateJSON(json, DocumentReference._jsonSchema)) {\n return new DocumentReference(\n firestore,\n converter ? converter : null,\n new DocumentKey(ResourcePath.fromString(json.referencePath))\n );\n }\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Unexpected error creating Bytes from JSON.'\n );\n }\n}\n\n/**\n * A `CollectionReference` object can be used for adding documents, getting\n * document references, and querying for documents (using {@link (query:1)}).\n */\nexport class CollectionReference<\n AppModelType = DocumentData,\n DbModelType extends DocumentData = DocumentData\n> extends Query {\n /** The type of this Firestore reference. */\n readonly type = 'collection';\n\n /** @hideconstructor */\n constructor(\n firestore: Firestore,\n converter: FirestoreDataConverter | null,\n readonly _path: ResourcePath\n ) {\n super(firestore, converter, newQueryForPath(_path));\n }\n\n /** The collection's identifier. */\n get id(): string {\n return this._query.path.lastSegment();\n }\n\n /**\n * A string representing the path of the referenced collection (relative\n * to the root of the database).\n */\n get path(): string {\n return this._query.path.canonicalString();\n }\n\n /**\n * A reference to the containing `DocumentReference` if this is a\n * subcollection. If this isn't a subcollection, the reference is null.\n */\n get parent(): DocumentReference | null {\n const parentPath = this._path.popLast();\n if (parentPath.isEmpty()) {\n return null;\n } else {\n return new DocumentReference(\n this.firestore,\n /* converter= */ null,\n new DocumentKey(parentPath)\n );\n }\n }\n\n /**\n * Applies a custom data converter to this `CollectionReference`, allowing you\n * to use your own custom model objects with Firestore. When you call {@link\n * addDoc} with the returned `CollectionReference` instance, the provided\n * converter will convert between Firestore data of type `NewDbModelType` and\n * your custom type `NewAppModelType`.\n *\n * @param converter - Converts objects to and from Firestore.\n * @returns A `CollectionReference` that uses the provided converter.\n */\n withConverter<\n NewAppModelType,\n NewDbModelType extends DocumentData = DocumentData\n >(\n converter: FirestoreDataConverter\n ): CollectionReference;\n /**\n * Removes the current converter.\n *\n * @param converter - `null` removes the current converter.\n * @returns A `CollectionReference` that does not\n * use a converter.\n */\n withConverter(\n converter: null\n ): CollectionReference;\n withConverter<\n NewAppModelType,\n NewDbModelType extends DocumentData = DocumentData\n >(\n converter: FirestoreDataConverter | null\n ): CollectionReference {\n return new CollectionReference(\n this.firestore,\n converter,\n this._path\n );\n }\n}\n\n/**\n * Gets a `CollectionReference` instance that refers to the collection at\n * the specified absolute path.\n *\n * @param firestore - A reference to the root `Firestore` instance.\n * @param path - A slash-separated path to a collection.\n * @param pathSegments - Additional path segments to apply relative to the first\n * argument.\n * @throws If the final path has an even number of segments and does not point\n * to a collection.\n * @returns The `CollectionReference` instance.\n */\nexport function collection(\n firestore: Firestore,\n path: string,\n ...pathSegments: string[]\n): CollectionReference;\n/**\n * Gets a `CollectionReference` instance that refers to a subcollection of\n * `reference` at the specified relative path.\n *\n * @param reference - A reference to a collection.\n * @param path - A slash-separated path to a collection.\n * @param pathSegments - Additional path segments to apply relative to the first\n * argument.\n * @throws If the final path has an even number of segments and does not point\n * to a collection.\n * @returns The `CollectionReference` instance.\n */\nexport function collection(\n reference: CollectionReference,\n path: string,\n ...pathSegments: string[]\n): CollectionReference;\n/**\n * Gets a `CollectionReference` instance that refers to a subcollection of\n * `reference` at the specified relative path.\n *\n * @param reference - A reference to a Firestore document.\n * @param path - A slash-separated path to a collection.\n * @param pathSegments - Additional path segments that will be applied relative\n * to the first argument.\n * @throws If the final path has an even number of segments and does not point\n * to a collection.\n * @returns The `CollectionReference` instance.\n */\nexport function collection(\n reference: DocumentReference,\n path: string,\n ...pathSegments: string[]\n): CollectionReference;\nexport function collection(\n parent:\n | Firestore\n | DocumentReference\n | CollectionReference,\n path: string,\n ...pathSegments: string[]\n): CollectionReference {\n parent = getModularInstance(parent);\n\n validateNonEmptyArgument('collection', 'path', path);\n if (parent instanceof Firestore) {\n const absolutePath = ResourcePath.fromString(path, ...pathSegments);\n validateCollectionPath(absolutePath);\n return new CollectionReference(parent, /* converter= */ null, absolutePath);\n } else {\n if (\n !(parent instanceof DocumentReference) &&\n !(parent instanceof CollectionReference)\n ) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Expected first argument to collection() to be a CollectionReference, ' +\n 'a DocumentReference or FirebaseFirestore'\n );\n }\n const absolutePath = parent._path.child(\n ResourcePath.fromString(path, ...pathSegments)\n );\n validateCollectionPath(absolutePath);\n return new CollectionReference(\n parent.firestore,\n /* converter= */ null,\n absolutePath\n );\n }\n}\n\n// TODO(firestorelite): Consider using ErrorFactory -\n// https://github.com/firebase/firebase-js-sdk/blob/0131e1f/packages/util/src/errors.ts#L106\n\n/**\n * Creates and returns a new `Query` instance that includes all documents in the\n * database that are contained in a collection or subcollection with the\n * given `collectionId`.\n *\n * @param firestore - A reference to the root `Firestore` instance.\n * @param collectionId - Identifies the collections to query over. Every\n * collection or subcollection with this ID as the last segment of its path\n * will be included. Cannot contain a slash.\n * @returns The created `Query`.\n */\nexport function collectionGroup(\n firestore: Firestore,\n collectionId: string\n): Query {\n firestore = cast(firestore, Firestore);\n\n validateNonEmptyArgument('collectionGroup', 'collection id', collectionId);\n if (collectionId.indexOf('/') >= 0) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid collection ID '${collectionId}' passed to function ` +\n `collectionGroup(). Collection IDs must not contain '/'.`\n );\n }\n\n return new Query(\n firestore,\n /* converter= */ null,\n newQueryForCollectionGroup(collectionId)\n );\n}\n\n/**\n * Gets a `DocumentReference` instance that refers to the document at the\n * specified absolute path.\n *\n * @param firestore - A reference to the root `Firestore` instance.\n * @param path - A slash-separated path to a document.\n * @param pathSegments - Additional path segments that will be applied relative\n * to the first argument.\n * @throws If the final path has an odd number of segments and does not point to\n * a document.\n * @returns The `DocumentReference` instance.\n */\nexport function doc(\n firestore: Firestore,\n path: string,\n ...pathSegments: string[]\n): DocumentReference;\n/**\n * Gets a `DocumentReference` instance that refers to a document within\n * `reference` at the specified relative path. If no path is specified, an\n * automatically-generated unique ID will be used for the returned\n * `DocumentReference`.\n *\n * @param reference - A reference to a collection.\n * @param path - A slash-separated path to a document. Has to be omitted to use\n * auto-generated IDs.\n * @param pathSegments - Additional path segments that will be applied relative\n * to the first argument.\n * @throws If the final path has an odd number of segments and does not point to\n * a document.\n * @returns The `DocumentReference` instance.\n */\nexport function doc(\n reference: CollectionReference,\n path?: string,\n ...pathSegments: string[]\n): DocumentReference;\n/**\n * Gets a `DocumentReference` instance that refers to a document within\n * `reference` at the specified relative path.\n *\n * @param reference - A reference to a Firestore document.\n * @param path - A slash-separated path to a document.\n * @param pathSegments - Additional path segments that will be applied relative\n * to the first argument.\n * @throws If the final path has an odd number of segments and does not point to\n * a document.\n * @returns The `DocumentReference` instance.\n */\nexport function doc(\n reference: DocumentReference,\n path: string,\n ...pathSegments: string[]\n): DocumentReference;\nexport function doc(\n parent:\n | Firestore\n | CollectionReference\n | DocumentReference,\n path?: string,\n ...pathSegments: string[]\n): DocumentReference {\n parent = getModularInstance(parent);\n\n // We allow omission of 'pathString' but explicitly prohibit passing in both\n // 'undefined' and 'null'.\n if (arguments.length === 1) {\n path = AutoId.newId();\n }\n validateNonEmptyArgument('doc', 'path', path);\n\n if (parent instanceof Firestore) {\n const absolutePath = ResourcePath.fromString(path, ...pathSegments);\n validateDocumentPath(absolutePath);\n return new DocumentReference(\n parent,\n /* converter= */ null,\n new DocumentKey(absolutePath)\n );\n } else {\n if (\n !(parent instanceof DocumentReference) &&\n !(parent instanceof CollectionReference)\n ) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Expected first argument to collection() to be a CollectionReference, ' +\n 'a DocumentReference or FirebaseFirestore'\n );\n }\n const absolutePath = parent._path.child(\n ResourcePath.fromString(path, ...pathSegments)\n );\n validateDocumentPath(absolutePath);\n return new DocumentReference(\n parent.firestore,\n parent instanceof CollectionReference ? parent.converter : null,\n new DocumentKey(absolutePath)\n );\n }\n}\n\n/**\n * Returns true if the provided references are equal.\n *\n * @param left - A reference to compare.\n * @param right - A reference to compare.\n * @returns true if the references point to the same location in the same\n * Firestore database.\n */\nexport function refEqual(\n left:\n | DocumentReference\n | CollectionReference,\n right:\n | DocumentReference\n | CollectionReference\n): boolean {\n left = getModularInstance(left);\n right = getModularInstance(right);\n\n if (\n (left instanceof DocumentReference ||\n left instanceof CollectionReference) &&\n (right instanceof DocumentReference || right instanceof CollectionReference)\n ) {\n return (\n left.firestore === right.firestore &&\n left.path === right.path &&\n left.converter === right.converter\n );\n }\n return false;\n}\n\n/**\n * Returns true if the provided queries point to the same collection and apply\n * the same constraints.\n *\n * @param left - A `Query` to compare.\n * @param right - A `Query` to compare.\n * @returns true if the references point to the same location in the same\n * Firestore database.\n */\nexport function queryEqual(\n left: Query,\n right: Query\n): boolean {\n left = getModularInstance(left);\n right = getModularInstance(right);\n\n if (left instanceof Query && right instanceof Query) {\n return (\n left.firestore === right.firestore &&\n queryEquals(left._query, right._query) &&\n left.converter === right.converter\n );\n }\n return false;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ByteString } from '../util/byte_string';\nimport { Code, FirestoreError } from '../util/error';\n// API extractor fails importing property unless we also explicitly import Property.\n// eslint-disable-next-line @typescript-eslint/no-unused-vars, unused-imports/no-unused-imports-ts\nimport { Property, property, validateJSON } from '../util/json_validation';\n\n/**\n * An immutable object representing an array of bytes.\n */\nexport class Bytes {\n _byteString: ByteString;\n\n /** @hideconstructor */\n constructor(byteString: ByteString) {\n this._byteString = byteString;\n }\n\n /**\n * Creates a new `Bytes` object from the given Base64 string, converting it to\n * bytes.\n *\n * @param base64 - The Base64 string used to create the `Bytes` object.\n */\n static fromBase64String(base64: string): Bytes {\n try {\n return new Bytes(ByteString.fromBase64String(base64));\n } catch (e) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Failed to construct data from Base64 string: ' + e\n );\n }\n }\n\n /**\n * Creates a new `Bytes` object from the given Uint8Array.\n *\n * @param array - The Uint8Array used to create the `Bytes` object.\n */\n static fromUint8Array(array: Uint8Array): Bytes {\n return new Bytes(ByteString.fromUint8Array(array));\n }\n\n /**\n * Returns the underlying bytes as a Base64-encoded string.\n *\n * @returns The Base64-encoded string created from the `Bytes` object.\n */\n toBase64(): string {\n return this._byteString.toBase64();\n }\n\n /**\n * Returns the underlying bytes in a new `Uint8Array`.\n *\n * @returns The Uint8Array created from the `Bytes` object.\n */\n toUint8Array(): Uint8Array {\n return this._byteString.toUint8Array();\n }\n\n /**\n * Returns a string representation of the `Bytes` object.\n *\n * @returns A string representation of the `Bytes` object.\n */\n toString(): string {\n return 'Bytes(base64: ' + this.toBase64() + ')';\n }\n\n /**\n * Returns true if this `Bytes` object is equal to the provided one.\n *\n * @param other - The `Bytes` object to compare against.\n * @returns true if this `Bytes` object is equal to the provided one.\n */\n isEqual(other: Bytes): boolean {\n return this._byteString.isEqual(other._byteString);\n }\n\n static _jsonSchemaVersion: string = 'firestore/bytes/1.0';\n static _jsonSchema = {\n type: property('string', Bytes._jsonSchemaVersion),\n bytes: property('string')\n };\n\n /**\n * Returns a JSON-serializable representation of this `Bytes` instance.\n *\n * @returns a JSON representation of this object.\n */\n toJSON(): object {\n return {\n type: Bytes._jsonSchemaVersion,\n bytes: this.toBase64()\n };\n }\n\n /**\n * Builds a `Bytes` instance from a JSON object created by {@link Bytes.toJSON}.\n *\n * @param json a JSON object represention of a `Bytes` instance\n * @returns an instance of {@link Bytes} if the JSON object could be parsed. Throws a\n * {@link FirestoreError} if an error occurs.\n */\n static fromJSON(json: object): Bytes {\n if (validateJSON(json, Bytes._jsonSchema)) {\n return Bytes.fromBase64String(json.bytes);\n }\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Unexpected error creating Bytes from JSON.'\n );\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n DOCUMENT_KEY_NAME,\n FieldPath as InternalFieldPath\n} from '../model/path';\nimport { Code, FirestoreError } from '../util/error';\n\n/**\n * A `FieldPath` refers to a field in a document. The path may consist of a\n * single field name (referring to a top-level field in the document), or a\n * list of field names (referring to a nested field in the document).\n *\n * Create a `FieldPath` by providing field names. If more than one field\n * name is provided, the path will point to a nested field in a document.\n */\nexport class FieldPath {\n /** Internal representation of a Firestore field path. */\n readonly _internalPath: InternalFieldPath;\n\n /**\n * Creates a `FieldPath` from the provided field names. If more than one field\n * name is provided, the path will point to a nested field in a document.\n *\n * @param fieldNames - A list of field names.\n */\n constructor(...fieldNames: string[]) {\n for (let i = 0; i < fieldNames.length; ++i) {\n if (fieldNames[i].length === 0) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid field name at argument $(i + 1). ` +\n 'Field names must not be empty.'\n );\n }\n }\n\n this._internalPath = new InternalFieldPath(fieldNames);\n }\n\n /**\n * Returns true if this `FieldPath` is equal to the provided one.\n *\n * @param other - The `FieldPath` to compare against.\n * @returns true if this `FieldPath` is equal to the provided one.\n */\n isEqual(other: FieldPath): boolean {\n return this._internalPath.isEqual(other._internalPath);\n }\n}\n\n/**\n * Returns a special sentinel `FieldPath` to refer to the ID of a document.\n * It can be used in queries to sort or filter by the document ID.\n */\nexport function documentId(): FieldPath {\n return new FieldPath(DOCUMENT_KEY_NAME);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ParseContext } from '../api/parse_context';\nimport { FieldTransform } from '../model/mutation';\n\n/**\n * Sentinel values that can be used when writing document fields with `set()`\n * or `update()`.\n */\nexport abstract class FieldValue {\n /**\n * @param _methodName - The public API endpoint that returns this class.\n * @hideconstructor\n */\n constructor(public _methodName: string) {}\n\n /** Compares `FieldValue`s for equality. */\n abstract isEqual(other: FieldValue): boolean;\n abstract _toFieldTransform(context: ParseContext): FieldTransform | null;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Code, FirestoreError } from '../util/error';\n// API extractor fails importing 'property' unless we also explicitly import 'Property'.\n// eslint-disable-next-line @typescript-eslint/no-unused-vars, unused-imports/no-unused-imports-ts\nimport { Property, property, validateJSON } from '../util/json_validation';\nimport { primitiveComparator } from '../util/misc';\n\n/**\n * An immutable object representing a geographic location in Firestore. The\n * location is represented as latitude/longitude pair.\n *\n * Latitude values are in the range of [-90, 90].\n * Longitude values are in the range of [-180, 180].\n */\nexport class GeoPoint {\n // Prefix with underscore to signal this is a private variable in JS and\n // prevent it showing up for autocompletion when typing latitude or longitude.\n private _lat: number;\n private _long: number;\n\n /**\n * Creates a new immutable `GeoPoint` object with the provided latitude and\n * longitude values.\n * @param latitude - The latitude as number between -90 and 90.\n * @param longitude - The longitude as number between -180 and 180.\n */\n constructor(latitude: number, longitude: number) {\n if (!isFinite(latitude) || latitude < -90 || latitude > 90) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Latitude must be a number between -90 and 90, but was: ' + latitude\n );\n }\n if (!isFinite(longitude) || longitude < -180 || longitude > 180) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Longitude must be a number between -180 and 180, but was: ' + longitude\n );\n }\n\n this._lat = latitude;\n this._long = longitude;\n }\n\n /**\n * The latitude of this `GeoPoint` instance.\n */\n get latitude(): number {\n return this._lat;\n }\n\n /**\n * The longitude of this `GeoPoint` instance.\n */\n get longitude(): number {\n return this._long;\n }\n\n /**\n * Returns true if this `GeoPoint` is equal to the provided one.\n *\n * @param other - The `GeoPoint` to compare against.\n * @returns true if this `GeoPoint` is equal to the provided one.\n */\n isEqual(other: GeoPoint): boolean {\n return this._lat === other._lat && this._long === other._long;\n }\n\n /**\n * Actually private to JS consumers of our API, so this function is prefixed\n * with an underscore.\n */\n _compareTo(other: GeoPoint): number {\n return (\n primitiveComparator(this._lat, other._lat) ||\n primitiveComparator(this._long, other._long)\n );\n }\n\n static _jsonSchemaVersion: string = 'firestore/geoPoint/1.0';\n static _jsonSchema = {\n type: property('string', GeoPoint._jsonSchemaVersion),\n latitude: property('number'),\n longitude: property('number')\n };\n\n /**\n * Returns a JSON-serializable representation of this `GeoPoint` instance.\n *\n * @returns a JSON representation of this object.\n */\n toJSON(): { latitude: number; longitude: number; type: string } {\n return {\n latitude: this._lat,\n longitude: this._long,\n type: GeoPoint._jsonSchemaVersion\n };\n }\n\n /**\n * Builds a `GeoPoint` instance from a JSON object created by {@link GeoPoint.toJSON}.\n *\n * @param json a JSON object represention of a `GeoPoint` instance\n * @returns an instance of {@link GeoPoint} if the JSON object could be parsed. Throws a\n * {@link FirestoreError} if an error occurs.\n */\n static fromJSON(json: object): GeoPoint {\n if (validateJSON(json, GeoPoint._jsonSchema)) {\n return new GeoPoint(json.latitude, json.longitude);\n }\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Unexpected error creating GeoPoint from JSON.'\n );\n }\n}\n","/**\n * @license\n * Copyright 2024 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isPrimitiveArrayEqual } from '../util/array';\nimport { Code, FirestoreError } from '../util/error';\n// API extractor fails importing 'property' unless we also explicitly import 'Property'.\n// eslint-disable-next-line @typescript-eslint/no-unused-vars, unused-imports/no-unused-imports-ts\nimport { Property, property, validateJSON } from '../util/json_validation';\n\n/**\n * Represents a vector type in Firestore documents.\n * Create an instance with {@link vector}.\n *\n * @class VectorValue\n */\nexport class VectorValue {\n private readonly _values: number[];\n\n /**\n * @private\n * @internal\n */\n constructor(values: number[] | undefined) {\n // Making a copy of the parameter.\n this._values = (values || []).map(n => n);\n }\n\n /**\n * Returns a copy of the raw number array form of the vector.\n */\n toArray(): number[] {\n return this._values.map(n => n);\n }\n\n /**\n * Returns `true` if the two `VectorValue` values have the same raw number arrays, returns `false` otherwise.\n */\n isEqual(other: VectorValue): boolean {\n return isPrimitiveArrayEqual(this._values, other._values);\n }\n\n static _jsonSchemaVersion: string = 'firestore/vectorValue/1.0';\n static _jsonSchema = {\n type: property('string', VectorValue._jsonSchemaVersion),\n vectorValues: property('object')\n };\n\n /**\n * Returns a JSON-serializable representation of this `VectorValue` instance.\n *\n * @returns a JSON representation of this object.\n */\n toJSON(): object {\n return {\n type: VectorValue._jsonSchemaVersion,\n vectorValues: this._values\n };\n }\n\n /**\n * Builds a `VectorValue` instance from a JSON object created by {@link VectorValue.toJSON}.\n *\n * @param json a JSON object represention of a `VectorValue` instance.\n * @returns an instance of {@link VectorValue} if the JSON object could be parsed. Throws a\n * {@link FirestoreError} if an error occurs.\n */\n static fromJSON(json: object): VectorValue {\n if (validateJSON(json, VectorValue._jsonSchema)) {\n if (\n Array.isArray(json.vectorValues) &&\n json.vectorValues.every(element => typeof element === 'number')\n ) {\n return new VectorValue(json.vectorValues);\n }\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n \"Expected 'vectorValues' field to be a number array\"\n );\n }\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Unexpected error creating Timestamp from JSON.'\n );\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Returns true iff the array contains the value using strong equality.\n */\nexport function includes(array: T[], value: T): boolean {\n for (let i = 0; i < array.length; i++) {\n if (array[i] === value) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * Returns true iff the array contains any value matching the predicate\n */\nexport function some(array: T[], predicate: (t: T) => boolean): boolean {\n for (let i = 0; i < array.length; i++) {\n if (predicate(array[i])) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * Calls predicate function for each item in the array until the predicate\n * returns true, at which point the index of that item is returned. If the\n * predicate does not return true for any item, null is returned.\n */\nexport function findIndex
(\n array: A[],\n predicate: (value: A) => boolean\n): number | null {\n for (let i = 0; i < array.length; i++) {\n if (predicate(array[i])) {\n return i;\n }\n }\n return null;\n}\n\n/**\n * Compares two array for equality using comparator. The method computes the\n * intersection and invokes `onAdd` for every element that is in `after` but not\n * `before`. `onRemove` is invoked for every element in `before` but missing\n * from `after`.\n *\n * The method creates a copy of both `before` and `after` and runs in O(n log\n * n), where n is the size of the two lists.\n *\n * @param before - The elements that exist in the original array.\n * @param after - The elements to diff against the original array.\n * @param comparator - The comparator for the elements in before and after.\n * @param onAdd - A function to invoke for every element that is part of `\n * after` but not `before`.\n * @param onRemove - A function to invoke for every element that is part of\n * `before` but not `after`.\n */\nexport function diffArrays(\n before: T[],\n after: T[],\n comparator: (l: T, r: T) => number,\n onAdd: (entry: T) => void,\n onRemove: (entry: T) => void\n): void {\n before = [...before];\n after = [...after];\n before.sort(comparator);\n after.sort(comparator);\n\n const bLen = before.length;\n const aLen = after.length;\n let a = 0;\n let b = 0;\n while (a < aLen && b < bLen) {\n const cmp = comparator(before[b], after[a]);\n if (cmp < 0) {\n // The element was removed if the next element in our ordered\n // walkthrough is only in `before`.\n onRemove(before[b++]);\n } else if (cmp > 0) {\n // The element was added if the next element in our ordered walkthrough\n // is only in `after`.\n onAdd(after[a++]);\n } else {\n a++;\n b++;\n }\n }\n while (a < aLen) {\n onAdd(after[a++]);\n }\n while (b < bLen) {\n onRemove(before[b++]);\n }\n}\n\n/**\n * Verifies equality for an array of objects using the `isEqual` interface.\n *\n * @private\n * @internal\n * @param left Array of objects supporting `isEqual`.\n * @param right Array of objects supporting `isEqual`.\n * @return True if arrays are equal.\n */\nexport function isArrayEqual boolean }>(\n left: T[],\n right: T[]\n): boolean {\n if (left.length !== right.length) {\n return false;\n }\n\n for (let i = 0; i < left.length; ++i) {\n if (!left[i].isEqual(right[i])) {\n return false;\n }\n }\n\n return true;\n}\n\n/**\n * Verifies equality for an array of primitives.\n *\n * @private\n * @internal\n * @param left Array of primitives.\n * @param right Array of primitives.\n * @return True if arrays are equal.\n */\nexport function isPrimitiveArrayEqual(\n left: T[],\n right: T[]\n): boolean {\n if (left.length !== right.length) {\n return false;\n }\n\n for (let i = 0; i < left.length; ++i) {\n if (left[i] !== right[i]) {\n return false;\n }\n }\n\n return true;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n DocumentData,\n FieldPath as PublicFieldPath,\n SetOptions\n} from '@firebase/firestore-types';\nimport { Compat, deepEqual, getModularInstance } from '@firebase/util';\n\nimport { ParseContext } from '../api/parse_context';\nimport { DatabaseId } from '../core/database_info';\nimport { DocumentKey } from '../model/document_key';\nimport { FieldMask } from '../model/field_mask';\nimport {\n FieldTransform,\n Mutation,\n PatchMutation,\n Precondition,\n SetMutation\n} from '../model/mutation';\nimport { ObjectValue } from '../model/object_value';\nimport { FieldPath as InternalFieldPath } from '../model/path';\nimport {\n ArrayRemoveTransformOperation,\n ArrayUnionTransformOperation,\n NumericIncrementTransformOperation,\n ServerTimestampTransform\n} from '../model/transform_operation';\nimport {\n TYPE_KEY,\n VECTOR_MAP_VECTORS_KEY,\n VECTOR_VALUE_SENTINEL\n} from '../model/values';\nimport { newSerializer } from '../platform/serializer';\nimport {\n MapValue as ProtoMapValue,\n Value as ProtoValue\n} from '../protos/firestore_proto_api';\nimport { toDouble, toNumber } from '../remote/number_serializer';\nimport {\n JsonProtoSerializer,\n toBytes,\n toResourceName,\n toTimestamp\n} from '../remote/serializer';\nimport { debugAssert, fail } from '../util/assert';\nimport { Code, FirestoreError } from '../util/error';\nimport { isPlainObject, valueDescription } from '../util/input_validation';\nimport { Dict, forEach, isEmpty } from '../util/obj';\n\nimport { Bytes } from './bytes';\nimport { Firestore } from './database';\nimport { FieldPath } from './field_path';\nimport { FieldValue } from './field_value';\nimport { GeoPoint } from './geo_point';\nimport {\n DocumentReference,\n PartialWithFieldValue,\n WithFieldValue\n} from './reference';\nimport { Timestamp } from './timestamp';\nimport { VectorValue } from './vector_value';\n\nconst RESERVED_FIELD_REGEX = /^__.*__$/;\n\n/**\n * An untyped Firestore Data Converter interface that is shared between the\n * lite, firestore-exp and classic SDK.\n */\nexport interface UntypedFirestoreDataConverter<\n AppModelType,\n DbModelType extends DocumentData = DocumentData\n> {\n toFirestore(\n modelObject: WithFieldValue\n ): WithFieldValue;\n toFirestore(\n modelObject: PartialWithFieldValue,\n options: SetOptions\n ): PartialWithFieldValue;\n fromFirestore(snapshot: unknown, options?: unknown): AppModelType;\n}\n\n/** The result of parsing document data (e.g. for a setData call). */\nexport class ParsedSetData {\n constructor(\n readonly data: ObjectValue,\n readonly fieldMask: FieldMask | null,\n readonly fieldTransforms: FieldTransform[]\n ) {}\n\n toMutation(key: DocumentKey, precondition: Precondition): Mutation {\n if (this.fieldMask !== null) {\n return new PatchMutation(\n key,\n this.data,\n this.fieldMask,\n precondition,\n this.fieldTransforms\n );\n } else {\n return new SetMutation(\n key,\n this.data,\n precondition,\n this.fieldTransforms\n );\n }\n }\n}\n\n/** The result of parsing \"update\" data (i.e. for an updateData call). */\nexport class ParsedUpdateData {\n constructor(\n readonly data: ObjectValue,\n // The fieldMask does not include document transforms.\n readonly fieldMask: FieldMask,\n readonly fieldTransforms: FieldTransform[]\n ) {}\n\n toMutation(key: DocumentKey, precondition: Precondition): Mutation {\n return new PatchMutation(\n key,\n this.data,\n this.fieldMask,\n precondition,\n this.fieldTransforms\n );\n }\n}\n\n/*\n * Represents what type of API method provided the data being parsed; useful\n * for determining which error conditions apply during parsing and providing\n * better error messages.\n */\nexport const enum UserDataSource {\n Set,\n Update,\n MergeSet,\n /**\n * Indicates the source is a where clause, cursor bound, arrayUnion()\n * element, etc. Of note, isWrite(source) will return false.\n */\n Argument,\n /**\n * Indicates that the source is an Argument that may directly contain nested\n * arrays (e.g. the operand of an `in` query).\n */\n ArrayArgument\n}\n\nfunction isWrite(dataSource: UserDataSource): boolean {\n switch (dataSource) {\n case UserDataSource.Set: // fall through\n case UserDataSource.MergeSet: // fall through\n case UserDataSource.Update:\n return true;\n case UserDataSource.Argument:\n case UserDataSource.ArrayArgument:\n return false;\n default:\n throw fail(0x9c4b, 'Unexpected case for UserDataSource', {\n dataSource\n });\n }\n}\n\n/** Contains the settings that are mutated as we parse user data. */\ninterface ContextSettings {\n /** Indicates what kind of API method this data came from. */\n readonly dataSource: UserDataSource;\n /** The name of the method the user called to create the ParseContext. */\n readonly methodName: string;\n /** The document the user is attempting to modify, if that applies. */\n readonly targetDoc?: DocumentKey;\n /**\n * A path within the object being parsed. This could be an empty path (in\n * which case the context represents the root of the data being parsed), or a\n * nonempty path (indicating the context represents a nested location within\n * the data).\n */\n readonly path?: InternalFieldPath;\n /**\n * Whether or not this context corresponds to an element of an array.\n * If not set, elements are treated as if they were outside of arrays.\n */\n readonly arrayElement?: boolean;\n /**\n * Whether or not a converter was specified in this context. If true, error\n * messages will reference the converter when invalid data is provided.\n */\n readonly hasConverter?: boolean;\n}\n\n/** A \"context\" object passed around while parsing user data. */\nclass ParseContextImpl implements ParseContext {\n readonly fieldTransforms: FieldTransform[];\n readonly fieldMask: InternalFieldPath[];\n /**\n * Initializes a ParseContext with the given source and path.\n *\n * @param settings - The settings for the parser.\n * @param databaseId - The database ID of the Firestore instance.\n * @param serializer - The serializer to use to generate the Value proto.\n * @param ignoreUndefinedProperties - Whether to ignore undefined properties\n * rather than throw.\n * @param fieldTransforms - A mutable list of field transforms encountered\n * while parsing the data.\n * @param fieldMask - A mutable list of field paths encountered while parsing\n * the data.\n *\n * TODO(b/34871131): We don't support array paths right now, so path can be\n * null to indicate the context represents any location within an array (in\n * which case certain features will not work and errors will be somewhat\n * compromised).\n */\n constructor(\n readonly settings: ContextSettings,\n readonly databaseId: DatabaseId,\n readonly serializer: JsonProtoSerializer,\n readonly ignoreUndefinedProperties: boolean,\n fieldTransforms?: FieldTransform[],\n fieldMask?: InternalFieldPath[]\n ) {\n // Minor hack: If fieldTransforms is undefined, we assume this is an\n // external call and we need to validate the entire path.\n if (fieldTransforms === undefined) {\n this.validatePath();\n }\n this.fieldTransforms = fieldTransforms || [];\n this.fieldMask = fieldMask || [];\n }\n\n get path(): InternalFieldPath | undefined {\n return this.settings.path;\n }\n\n get dataSource(): UserDataSource {\n return this.settings.dataSource;\n }\n\n /** Returns a new context with the specified settings overwritten. */\n contextWith(configuration: Partial): ParseContextImpl {\n return new ParseContextImpl(\n { ...this.settings, ...configuration },\n this.databaseId,\n this.serializer,\n this.ignoreUndefinedProperties,\n this.fieldTransforms,\n this.fieldMask\n );\n }\n\n childContextForField(field: string): ParseContextImpl {\n const childPath = this.path?.child(field);\n const context = this.contextWith({ path: childPath, arrayElement: false });\n context.validatePathSegment(field);\n return context;\n }\n\n childContextForFieldPath(field: InternalFieldPath): ParseContextImpl {\n const childPath = this.path?.child(field);\n const context = this.contextWith({ path: childPath, arrayElement: false });\n context.validatePath();\n return context;\n }\n\n childContextForArray(index: number): ParseContextImpl {\n // TODO(b/34871131): We don't support array paths right now; so make path\n // undefined.\n return this.contextWith({ path: undefined, arrayElement: true });\n }\n\n createError(reason: string): FirestoreError {\n return createError(\n reason,\n this.settings.methodName,\n this.settings.hasConverter || false,\n this.path,\n this.settings.targetDoc\n );\n }\n\n /** Returns 'true' if 'fieldPath' was traversed when creating this context. */\n contains(fieldPath: InternalFieldPath): boolean {\n return (\n this.fieldMask.find(field => fieldPath.isPrefixOf(field)) !== undefined ||\n this.fieldTransforms.find(transform =>\n fieldPath.isPrefixOf(transform.field)\n ) !== undefined\n );\n }\n\n private validatePath(): void {\n // TODO(b/34871131): Remove null check once we have proper paths for fields\n // within arrays.\n if (!this.path) {\n return;\n }\n for (let i = 0; i < this.path.length; i++) {\n this.validatePathSegment(this.path.get(i));\n }\n }\n\n private validatePathSegment(segment: string): void {\n if (segment.length === 0) {\n throw this.createError('Document fields must not be empty');\n }\n if (isWrite(this.dataSource) && RESERVED_FIELD_REGEX.test(segment)) {\n throw this.createError('Document fields cannot begin and end with \"__\"');\n }\n }\n}\n\n/**\n * Helper for parsing raw user input (provided via the API) into internal model\n * classes.\n */\nexport class UserDataReader {\n private readonly serializer: JsonProtoSerializer;\n\n constructor(\n private readonly databaseId: DatabaseId,\n private readonly ignoreUndefinedProperties: boolean,\n serializer?: JsonProtoSerializer\n ) {\n this.serializer = serializer || newSerializer(databaseId);\n }\n\n /** Creates a new top-level parse context. */\n createContext(\n dataSource: UserDataSource,\n methodName: string,\n targetDoc?: DocumentKey,\n hasConverter = false\n ): ParseContextImpl {\n return new ParseContextImpl(\n {\n dataSource,\n methodName,\n targetDoc,\n path: InternalFieldPath.emptyPath(),\n arrayElement: false,\n hasConverter\n },\n this.databaseId,\n this.serializer,\n this.ignoreUndefinedProperties\n );\n }\n}\n\nexport function newUserDataReader(firestore: Firestore): UserDataReader {\n const settings = firestore._freezeSettings();\n const serializer = newSerializer(firestore._databaseId);\n return new UserDataReader(\n firestore._databaseId,\n !!settings.ignoreUndefinedProperties,\n serializer\n );\n}\n\n/** Parse document data from a set() call. */\nexport function parseSetData(\n userDataReader: UserDataReader,\n methodName: string,\n targetDoc: DocumentKey,\n input: unknown,\n hasConverter: boolean,\n options: SetOptions = {}\n): ParsedSetData {\n const context = userDataReader.createContext(\n options.merge || options.mergeFields\n ? UserDataSource.MergeSet\n : UserDataSource.Set,\n methodName,\n targetDoc,\n hasConverter\n );\n validatePlainObject('Data must be an object, but it was:', context, input);\n const updateData = parseObject(input, context)!;\n\n let fieldMask: FieldMask | null;\n let fieldTransforms: FieldTransform[];\n\n if (options.merge) {\n fieldMask = new FieldMask(context.fieldMask);\n fieldTransforms = context.fieldTransforms;\n } else if (options.mergeFields) {\n const validatedFieldPaths: InternalFieldPath[] = [];\n\n for (const stringOrFieldPath of options.mergeFields) {\n const fieldPath = fieldPathFromArgument(\n methodName,\n stringOrFieldPath,\n targetDoc\n );\n if (!context.contains(fieldPath)) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Field '${fieldPath}' is specified in your field mask but missing from your input data.`\n );\n }\n\n if (!fieldMaskContains(validatedFieldPaths, fieldPath)) {\n validatedFieldPaths.push(fieldPath);\n }\n }\n\n fieldMask = new FieldMask(validatedFieldPaths);\n fieldTransforms = context.fieldTransforms.filter(transform =>\n fieldMask!.covers(transform.field)\n );\n } else {\n fieldMask = null;\n fieldTransforms = context.fieldTransforms;\n }\n\n return new ParsedSetData(\n new ObjectValue(updateData),\n fieldMask,\n fieldTransforms\n );\n}\n\nexport class DeleteFieldValueImpl extends FieldValue {\n _toFieldTransform(context: ParseContextImpl): null {\n if (context.dataSource === UserDataSource.MergeSet) {\n // No transform to add for a delete, but we need to add it to our\n // fieldMask so it gets deleted.\n context.fieldMask.push(context.path!);\n } else if (context.dataSource === UserDataSource.Update) {\n debugAssert(\n context.path!.length > 0,\n `${this._methodName}() at the top level should have already ` +\n 'been handled.'\n );\n throw context.createError(\n `${this._methodName}() can only appear at the top level ` +\n 'of your update data'\n );\n } else {\n // We shouldn't encounter delete sentinels for queries or non-merge set() calls.\n throw context.createError(\n `${this._methodName}() cannot be used with set() unless you pass ` +\n '{merge:true}'\n );\n }\n return null;\n }\n\n isEqual(other: FieldValue): boolean {\n return other instanceof DeleteFieldValueImpl;\n }\n}\n\n/**\n * Creates a child context for parsing SerializableFieldValues.\n *\n * This is different than calling `ParseContext.contextWith` because it keeps\n * the fieldTransforms and fieldMask separate.\n *\n * The created context has its `dataSource` set to `UserDataSource.Argument`.\n * Although these values are used with writes, any elements in these FieldValues\n * are not considered writes since they cannot contain any FieldValue sentinels,\n * etc.\n *\n * @param fieldValue - The sentinel FieldValue for which to create a child\n * context.\n * @param context - The parent context.\n * @param arrayElement - Whether or not the FieldValue has an array.\n */\nfunction createSentinelChildContext(\n fieldValue: FieldValue,\n context: ParseContextImpl,\n arrayElement: boolean\n): ParseContextImpl {\n return new ParseContextImpl(\n {\n dataSource: UserDataSource.Argument,\n targetDoc: context.settings.targetDoc,\n methodName: fieldValue._methodName,\n arrayElement\n },\n context.databaseId,\n context.serializer,\n context.ignoreUndefinedProperties\n );\n}\n\nexport class ServerTimestampFieldValueImpl extends FieldValue {\n _toFieldTransform(context: ParseContextImpl): FieldTransform {\n return new FieldTransform(context.path!, new ServerTimestampTransform());\n }\n\n isEqual(other: FieldValue): boolean {\n return other instanceof ServerTimestampFieldValueImpl;\n }\n}\n\nexport class ArrayUnionFieldValueImpl extends FieldValue {\n constructor(methodName: string, private readonly _elements: unknown[]) {\n super(methodName);\n }\n\n _toFieldTransform(context: ParseContextImpl): FieldTransform {\n const parseContext = createSentinelChildContext(\n this,\n context,\n /*array=*/ true\n );\n const parsedElements = this._elements.map(\n element => parseData(element, parseContext)!\n );\n const arrayUnion = new ArrayUnionTransformOperation(parsedElements);\n return new FieldTransform(context.path!, arrayUnion);\n }\n\n isEqual(other: FieldValue): boolean {\n return (\n other instanceof ArrayUnionFieldValueImpl &&\n deepEqual(this._elements, other._elements)\n );\n }\n}\n\nexport class ArrayRemoveFieldValueImpl extends FieldValue {\n constructor(methodName: string, private readonly _elements: unknown[]) {\n super(methodName);\n }\n\n _toFieldTransform(context: ParseContextImpl): FieldTransform {\n const parseContext = createSentinelChildContext(\n this,\n context,\n /*array=*/ true\n );\n const parsedElements = this._elements.map(\n element => parseData(element, parseContext)!\n );\n const arrayUnion = new ArrayRemoveTransformOperation(parsedElements);\n return new FieldTransform(context.path!, arrayUnion);\n }\n\n isEqual(other: FieldValue): boolean {\n return (\n other instanceof ArrayRemoveFieldValueImpl &&\n deepEqual(this._elements, other._elements)\n );\n }\n}\n\nexport class NumericIncrementFieldValueImpl extends FieldValue {\n constructor(methodName: string, private readonly _operand: number) {\n super(methodName);\n }\n\n _toFieldTransform(context: ParseContextImpl): FieldTransform {\n const numericIncrement = new NumericIncrementTransformOperation(\n context.serializer,\n toNumber(context.serializer, this._operand)\n );\n return new FieldTransform(context.path!, numericIncrement);\n }\n\n isEqual(other: FieldValue): boolean {\n return (\n other instanceof NumericIncrementFieldValueImpl &&\n this._operand === other._operand\n );\n }\n}\n\n/** Parse update data from an update() call. */\nexport function parseUpdateData(\n userDataReader: UserDataReader,\n methodName: string,\n targetDoc: DocumentKey,\n input: unknown\n): ParsedUpdateData {\n const context = userDataReader.createContext(\n UserDataSource.Update,\n methodName,\n targetDoc\n );\n validatePlainObject('Data must be an object, but it was:', context, input);\n\n const fieldMaskPaths: InternalFieldPath[] = [];\n const updateData = ObjectValue.empty();\n forEach(input as Dict, (key, value) => {\n const path = fieldPathFromDotSeparatedString(methodName, key, targetDoc);\n\n // For Compat types, we have to \"extract\" the underlying types before\n // performing validation.\n value = getModularInstance(value);\n\n const childContext = context.childContextForFieldPath(path);\n if (value instanceof DeleteFieldValueImpl) {\n // Add it to the field mask, but don't add anything to updateData.\n fieldMaskPaths.push(path);\n } else {\n const parsedValue = parseData(value, childContext);\n if (parsedValue != null) {\n fieldMaskPaths.push(path);\n updateData.set(path, parsedValue);\n }\n }\n });\n\n const mask = new FieldMask(fieldMaskPaths);\n return new ParsedUpdateData(updateData, mask, context.fieldTransforms);\n}\n\n/** Parse update data from a list of field/value arguments. */\nexport function parseUpdateVarargs(\n userDataReader: UserDataReader,\n methodName: string,\n targetDoc: DocumentKey,\n field: string | PublicFieldPath | Compat,\n value: unknown,\n moreFieldsAndValues: unknown[]\n): ParsedUpdateData {\n const context = userDataReader.createContext(\n UserDataSource.Update,\n methodName,\n targetDoc\n );\n const keys = [fieldPathFromArgument(methodName, field, targetDoc)];\n const values = [value];\n\n if (moreFieldsAndValues.length % 2 !== 0) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Function ${methodName}() needs to be called with an even number ` +\n 'of arguments that alternate between field names and values.'\n );\n }\n\n for (let i = 0; i < moreFieldsAndValues.length; i += 2) {\n keys.push(\n fieldPathFromArgument(\n methodName,\n moreFieldsAndValues[i] as string | PublicFieldPath\n )\n );\n values.push(moreFieldsAndValues[i + 1]);\n }\n\n const fieldMaskPaths: InternalFieldPath[] = [];\n const updateData = ObjectValue.empty();\n\n // We iterate in reverse order to pick the last value for a field if the\n // user specified the field multiple times.\n for (let i = keys.length - 1; i >= 0; --i) {\n if (!fieldMaskContains(fieldMaskPaths, keys[i])) {\n const path = keys[i];\n let value = values[i];\n\n // For Compat types, we have to \"extract\" the underlying types before\n // performing validation.\n value = getModularInstance(value);\n\n const childContext = context.childContextForFieldPath(path);\n if (value instanceof DeleteFieldValueImpl) {\n // Add it to the field mask, but don't add anything to updateData.\n fieldMaskPaths.push(path);\n } else {\n const parsedValue = parseData(value, childContext);\n if (parsedValue != null) {\n fieldMaskPaths.push(path);\n updateData.set(path, parsedValue);\n }\n }\n }\n }\n\n const mask = new FieldMask(fieldMaskPaths);\n return new ParsedUpdateData(updateData, mask, context.fieldTransforms);\n}\n\n/**\n * Parse a \"query value\" (e.g. value in a where filter or a value in a cursor\n * bound).\n *\n * @param allowArrays - Whether the query value is an array that may directly\n * contain additional arrays (e.g. the operand of an `in` query).\n */\nexport function parseQueryValue(\n userDataReader: UserDataReader,\n methodName: string,\n input: unknown,\n allowArrays = false\n): ProtoValue {\n const context = userDataReader.createContext(\n allowArrays ? UserDataSource.ArrayArgument : UserDataSource.Argument,\n methodName\n );\n const parsed = parseData(input, context);\n debugAssert(parsed != null, 'Parsed data should not be null.');\n debugAssert(\n context.fieldTransforms.length === 0,\n 'Field transforms should have been disallowed.'\n );\n return parsed;\n}\n\n/**\n * Parses user data to Protobuf Values.\n *\n * @param input - Data to be parsed.\n * @param context - A context object representing the current path being parsed,\n * the source of the data being parsed, etc.\n * @returns The parsed value, or null if the value was a FieldValue sentinel\n * that should not be included in the resulting parsed data.\n */\nexport function parseData(\n input: unknown,\n context: ParseContextImpl\n): ProtoValue | null {\n // Unwrap the API type from the Compat SDK. This will return the API type\n // from firestore-exp.\n input = getModularInstance(input);\n\n if (looksLikeJsonObject(input)) {\n validatePlainObject('Unsupported field value:', context, input);\n return parseObject(input, context);\n } else if (input instanceof FieldValue) {\n // FieldValues usually parse into transforms (except deleteField())\n // in which case we do not want to include this field in our parsed data\n // (as doing so will overwrite the field directly prior to the transform\n // trying to transform it). So we don't add this location to\n // context.fieldMask and we return null as our parsing result.\n parseSentinelFieldValue(input, context);\n return null;\n } else if (input === undefined && context.ignoreUndefinedProperties) {\n // If the input is undefined it can never participate in the fieldMask, so\n // don't handle this below. If `ignoreUndefinedProperties` is false,\n // `parseScalarValue` will reject an undefined value.\n return null;\n } else {\n // If context.path is null we are inside an array and we don't support\n // field mask paths more granular than the top-level array.\n if (context.path) {\n context.fieldMask.push(context.path);\n }\n\n if (input instanceof Array) {\n // TODO(b/34871131): Include the path containing the array in the error\n // message.\n // In the case of IN queries, the parsed data is an array (representing\n // the set of values to be included for the IN query) that may directly\n // contain additional arrays (each representing an individual field\n // value), so we disable this validation.\n if (\n context.settings.arrayElement &&\n context.dataSource !== UserDataSource.ArrayArgument\n ) {\n throw context.createError('Nested arrays are not supported');\n }\n return parseArray(input as unknown[], context);\n } else {\n return parseScalarValue(input, context);\n }\n }\n}\n\nexport function parseObject(\n obj: Dict,\n context: ParseContextImpl\n): { mapValue: ProtoMapValue } {\n const fields: Dict = {};\n\n if (isEmpty(obj)) {\n // If we encounter an empty object, we explicitly add it to the update\n // mask to ensure that the server creates a map entry.\n if (context.path && context.path.length > 0) {\n context.fieldMask.push(context.path);\n }\n } else {\n forEach(obj, (key: string, val: unknown) => {\n const parsedValue = parseData(val, context.childContextForField(key));\n if (parsedValue != null) {\n fields[key] = parsedValue;\n }\n });\n }\n\n return { mapValue: { fields } };\n}\n\nfunction parseArray(array: unknown[], context: ParseContextImpl): ProtoValue {\n const values: ProtoValue[] = [];\n let entryIndex = 0;\n for (const entry of array) {\n let parsedEntry = parseData(\n entry,\n context.childContextForArray(entryIndex)\n );\n if (parsedEntry == null) {\n // Just include nulls in the array for fields being replaced with a\n // sentinel.\n parsedEntry = { nullValue: 'NULL_VALUE' };\n }\n values.push(parsedEntry);\n entryIndex++;\n }\n return { arrayValue: { values } };\n}\n\n/**\n * \"Parses\" the provided FieldValueImpl, adding any necessary transforms to\n * context.fieldTransforms.\n */\nfunction parseSentinelFieldValue(\n value: FieldValue,\n context: ParseContextImpl\n): void {\n // Sentinels are only supported with writes, and not within arrays.\n if (!isWrite(context.dataSource)) {\n throw context.createError(\n `${value._methodName}() can only be used with update() and set()`\n );\n }\n if (!context.path) {\n throw context.createError(\n `${value._methodName}() is not currently supported inside arrays`\n );\n }\n\n const fieldTransform = value._toFieldTransform(context);\n if (fieldTransform) {\n context.fieldTransforms.push(fieldTransform);\n }\n}\n\n/**\n * Helper to parse a scalar value (i.e. not an Object, Array, or FieldValue)\n *\n * @returns The parsed value\n */\nfunction parseScalarValue(\n value: unknown,\n context: ParseContextImpl\n): ProtoValue | null {\n value = getModularInstance(value);\n\n if (value === null) {\n return { nullValue: 'NULL_VALUE' };\n } else if (typeof value === 'number') {\n return toNumber(context.serializer, value);\n } else if (typeof value === 'boolean') {\n return { booleanValue: value };\n } else if (typeof value === 'string') {\n return { stringValue: value };\n } else if (value instanceof Date) {\n const timestamp = Timestamp.fromDate(value);\n return {\n timestampValue: toTimestamp(context.serializer, timestamp)\n };\n } else if (value instanceof Timestamp) {\n // Firestore backend truncates precision down to microseconds. To ensure\n // offline mode works the same with regards to truncation, perform the\n // truncation immediately without waiting for the backend to do that.\n const timestamp = new Timestamp(\n value.seconds,\n Math.floor(value.nanoseconds / 1000) * 1000\n );\n return {\n timestampValue: toTimestamp(context.serializer, timestamp)\n };\n } else if (value instanceof GeoPoint) {\n return {\n geoPointValue: {\n latitude: value.latitude,\n longitude: value.longitude\n }\n };\n } else if (value instanceof Bytes) {\n return { bytesValue: toBytes(context.serializer, value._byteString) };\n } else if (value instanceof DocumentReference) {\n const thisDb = context.databaseId;\n const otherDb = value.firestore._databaseId;\n if (!otherDb.isEqual(thisDb)) {\n throw context.createError(\n 'Document reference is for database ' +\n `${otherDb.projectId}/${otherDb.database} but should be ` +\n `for database ${thisDb.projectId}/${thisDb.database}`\n );\n }\n return {\n referenceValue: toResourceName(\n value.firestore._databaseId || context.databaseId,\n value._key.path\n )\n };\n } else if (value instanceof VectorValue) {\n return parseVectorValue(value, context);\n } else {\n throw context.createError(\n `Unsupported field value: ${valueDescription(value)}`\n );\n }\n}\n\n/**\n * Creates a new VectorValue proto value (using the internal format).\n */\nexport function parseVectorValue(\n value: VectorValue,\n context: ParseContextImpl\n): ProtoValue {\n const mapValue: ProtoMapValue = {\n fields: {\n [TYPE_KEY]: {\n stringValue: VECTOR_VALUE_SENTINEL\n },\n [VECTOR_MAP_VECTORS_KEY]: {\n arrayValue: {\n values: value.toArray().map(value => {\n if (typeof value !== 'number') {\n throw context.createError(\n 'VectorValues must only contain numeric values.'\n );\n }\n\n return toDouble(context.serializer, value);\n })\n }\n }\n }\n };\n\n return { mapValue };\n}\n\n/**\n * Checks whether an object looks like a JSON object that should be converted\n * into a struct. Normal class/prototype instances are considered to look like\n * JSON objects since they should be converted to a struct value. Arrays, Dates,\n * GeoPoints, etc. are not considered to look like JSON objects since they map\n * to specific FieldValue types other than ObjectValue.\n */\nfunction looksLikeJsonObject(input: unknown): boolean {\n return (\n typeof input === 'object' &&\n input !== null &&\n !(input instanceof Array) &&\n !(input instanceof Date) &&\n !(input instanceof Timestamp) &&\n !(input instanceof GeoPoint) &&\n !(input instanceof Bytes) &&\n !(input instanceof DocumentReference) &&\n !(input instanceof FieldValue) &&\n !(input instanceof VectorValue)\n );\n}\n\nfunction validatePlainObject(\n message: string,\n context: ParseContextImpl,\n input: unknown\n): asserts input is Dict {\n if (!looksLikeJsonObject(input) || !isPlainObject(input)) {\n const description = valueDescription(input);\n if (description === 'an object') {\n // Massage the error if it was an object.\n throw context.createError(message + ' a custom object');\n } else {\n throw context.createError(message + ' ' + description);\n }\n }\n}\n\n/**\n * Helper that calls fromDotSeparatedString() but wraps any error thrown.\n */\nexport function fieldPathFromArgument(\n methodName: string,\n path: string | PublicFieldPath | Compat,\n targetDoc?: DocumentKey\n): InternalFieldPath {\n // If required, replace the FieldPath Compat class with the firestore-exp\n // FieldPath.\n path = getModularInstance(path);\n\n if (path instanceof FieldPath) {\n return path._internalPath;\n } else if (typeof path === 'string') {\n return fieldPathFromDotSeparatedString(methodName, path);\n } else {\n const message = 'Field path arguments must be of type string or ';\n throw createError(\n message,\n methodName,\n /* hasConverter= */ false,\n /* path= */ undefined,\n targetDoc\n );\n }\n}\n\n/**\n * Matches any characters in a field path string that are reserved.\n */\nconst FIELD_PATH_RESERVED = new RegExp('[~\\\\*/\\\\[\\\\]]');\n\n/**\n * Wraps fromDotSeparatedString with an error message about the method that\n * was thrown.\n * @param methodName - The publicly visible method name\n * @param path - The dot-separated string form of a field path which will be\n * split on dots.\n * @param targetDoc - The document against which the field path will be\n * evaluated.\n */\nexport function fieldPathFromDotSeparatedString(\n methodName: string,\n path: string,\n targetDoc?: DocumentKey\n): InternalFieldPath {\n const found = path.search(FIELD_PATH_RESERVED);\n if (found >= 0) {\n throw createError(\n `Invalid field path (${path}). Paths must not contain ` +\n `'~', '*', '/', '[', or ']'`,\n methodName,\n /* hasConverter= */ false,\n /* path= */ undefined,\n targetDoc\n );\n }\n\n try {\n return new FieldPath(...path.split('.'))._internalPath;\n } catch (e) {\n throw createError(\n `Invalid field path (${path}). Paths must not be empty, ` +\n `begin with '.', end with '.', or contain '..'`,\n methodName,\n /* hasConverter= */ false,\n /* path= */ undefined,\n targetDoc\n );\n }\n}\n\nfunction createError(\n reason: string,\n methodName: string,\n hasConverter: boolean,\n path?: InternalFieldPath,\n targetDoc?: DocumentKey\n): FirestoreError {\n const hasPath = path && !path.isEmpty();\n const hasDocument = targetDoc !== undefined;\n let message = `Function ${methodName}() called with invalid data`;\n if (hasConverter) {\n message += ' (via `toFirestore()`)';\n }\n message += '. ';\n\n let description = '';\n if (hasPath || hasDocument) {\n description += ' (found';\n\n if (hasPath) {\n description += ` in field ${path}`;\n }\n if (hasDocument) {\n description += ` in document ${targetDoc}`;\n }\n description += ')';\n }\n\n return new FirestoreError(\n Code.INVALID_ARGUMENT,\n message + reason + description\n );\n}\n\n/** Checks `haystack` if FieldPath `needle` is present. Runs in O(n). */\nfunction fieldMaskContains(\n haystack: InternalFieldPath[],\n needle: InternalFieldPath\n): boolean {\n return haystack.some(v => v.isEqual(needle));\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Compat, getModularInstance } from '@firebase/util';\n\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { FieldPath as InternalFieldPath } from '../model/path';\nimport { arrayEquals } from '../util/misc';\n\nimport { Firestore } from './database';\nimport { FieldPath } from './field_path';\nimport {\n DocumentData,\n DocumentReference,\n PartialWithFieldValue,\n Query,\n queryEqual,\n SetOptions,\n WithFieldValue\n} from './reference';\nimport {\n fieldPathFromDotSeparatedString,\n UntypedFirestoreDataConverter\n} from './user_data_reader';\nimport { AbstractUserDataWriter } from './user_data_writer';\n\n/**\n * Converter used by `withConverter()` to transform user objects of type\n * `AppModelType` into Firestore data of type `DbModelType`.\n *\n * Using the converter allows you to specify generic type arguments when\n * storing and retrieving objects from Firestore.\n *\n * In this context, an \"AppModel\" is a class that is used in an application to\n * package together related information and functionality. Such a class could,\n * for example, have properties with complex, nested data types, properties used\n * for memoization, properties of types not supported by Firestore (such as\n * `symbol` and `bigint`), and helper functions that perform compound\n * operations. Such classes are not suitable and/or possible to store into a\n * Firestore database. Instead, instances of such classes need to be converted\n * to \"plain old JavaScript objects\" (POJOs) with exclusively primitive\n * properties, potentially nested inside other POJOs or arrays of POJOs. In this\n * context, this type is referred to as the \"DbModel\" and would be an object\n * suitable for persisting into Firestore. For convenience, applications can\n * implement `FirestoreDataConverter` and register the converter with Firestore\n * objects, such as `DocumentReference` or `Query`, to automatically convert\n * `AppModel` to `DbModel` when storing into Firestore, and convert `DbModel`\n * to `AppModel` when retrieving from Firestore.\n *\n * @example\n *\n * Simple Example\n *\n * ```typescript\n * const numberConverter = {\n * toFirestore(value: WithFieldValue) {\n * return { value };\n * },\n * fromFirestore(snapshot: QueryDocumentSnapshot, options: SnapshotOptions) {\n * return snapshot.data(options).value as number;\n * }\n * };\n *\n * async function simpleDemo(db: Firestore): Promise {\n * const documentRef = doc(db, 'values/value123').withConverter(numberConverter);\n *\n * // converters are used with `setDoc`, `addDoc`, and `getDoc`\n * await setDoc(documentRef, 42);\n * const snapshot1 = await getDoc(documentRef);\n * assertEqual(snapshot1.data(), 42);\n *\n * // converters are not used when writing data with `updateDoc`\n * await updateDoc(documentRef, { value: 999 });\n * const snapshot2 = await getDoc(documentRef);\n * assertEqual(snapshot2.data(), 999);\n * }\n * ```\n *\n * Advanced Example\n *\n * ```typescript\n * // The Post class is a model that is used by our application.\n * // This class may have properties and methods that are specific\n * // to our application execution, which do not need to be persisted\n * // to Firestore.\n * class Post {\n * constructor(\n * readonly title: string,\n * readonly author: string,\n * readonly lastUpdatedMillis: number\n * ) {}\n * toString(): string {\n * return `${this.title} by ${this.author}`;\n * }\n * }\n *\n * // The PostDbModel represents how we want our posts to be stored\n * // in Firestore. This DbModel has different properties (`ttl`,\n * // `aut`, and `lut`) from the Post class we use in our application.\n * interface PostDbModel {\n * ttl: string;\n * aut: { firstName: string; lastName: string };\n * lut: Timestamp;\n * }\n *\n * // The `PostConverter` implements `FirestoreDataConverter` and specifies\n * // how the Firestore SDK can convert `Post` objects to `PostDbModel`\n * // objects and vice versa.\n * class PostConverter implements FirestoreDataConverter {\n * toFirestore(post: WithFieldValue): WithFieldValue {\n * return {\n * ttl: post.title,\n * aut: this._autFromAuthor(post.author),\n * lut: this._lutFromLastUpdatedMillis(post.lastUpdatedMillis)\n * };\n * }\n *\n * fromFirestore(snapshot: QueryDocumentSnapshot, options: SnapshotOptions): Post {\n * const data = snapshot.data(options) as PostDbModel;\n * const author = `${data.aut.firstName} ${data.aut.lastName}`;\n * return new Post(data.ttl, author, data.lut.toMillis());\n * }\n *\n * _autFromAuthor(\n * author: string | FieldValue\n * ): { firstName: string; lastName: string } | FieldValue {\n * if (typeof author !== 'string') {\n * // `author` is a FieldValue, so just return it.\n * return author;\n * }\n * const [firstName, lastName] = author.split(' ');\n * return {firstName, lastName};\n * }\n *\n * _lutFromLastUpdatedMillis(\n * lastUpdatedMillis: number | FieldValue\n * ): Timestamp | FieldValue {\n * if (typeof lastUpdatedMillis !== 'number') {\n * // `lastUpdatedMillis` must be a FieldValue, so just return it.\n * return lastUpdatedMillis;\n * }\n * return Timestamp.fromMillis(lastUpdatedMillis);\n * }\n * }\n *\n * async function advancedDemo(db: Firestore): Promise {\n * // Create a `DocumentReference` with a `FirestoreDataConverter`.\n * const documentRef = doc(db, 'posts/post123').withConverter(new PostConverter());\n *\n * // The `data` argument specified to `setDoc()` is type checked by the\n * // TypeScript compiler to be compatible with `Post`. Since the `data`\n * // argument is typed as `WithFieldValue` rather than just `Post`,\n * // this allows properties of the `data` argument to also be special\n * // Firestore values that perform server-side mutations, such as\n * // `arrayRemove()`, `deleteField()`, and `serverTimestamp()`.\n * await setDoc(documentRef, {\n * title: 'My Life',\n * author: 'Foo Bar',\n * lastUpdatedMillis: serverTimestamp()\n * });\n *\n * // The TypeScript compiler will fail to compile if the `data` argument to\n * // `setDoc()` is _not_ compatible with `WithFieldValue`. This\n * // type checking prevents the caller from specifying objects with incorrect\n * // properties or property values.\n * // @ts-expect-error \"Argument of type { ttl: string; } is not assignable\n * // to parameter of type WithFieldValue\"\n * await setDoc(documentRef, { ttl: 'The Title' });\n *\n * // When retrieving a document with `getDoc()` the `DocumentSnapshot`\n * // object's `data()` method returns a `Post`, rather than a generic object,\n * // which would have been returned if the `DocumentReference` did _not_ have a\n * // `FirestoreDataConverter` attached to it.\n * const snapshot1: DocumentSnapshot = await getDoc(documentRef);\n * const post1: Post = snapshot1.data()!;\n * if (post1) {\n * assertEqual(post1.title, 'My Life');\n * assertEqual(post1.author, 'Foo Bar');\n * }\n *\n * // The `data` argument specified to `updateDoc()` is type checked by the\n * // TypeScript compiler to be compatible with `PostDbModel`. Note that\n * // unlike `setDoc()`, whose `data` argument must be compatible with `Post`,\n * // the `data` argument to `updateDoc()` must be compatible with\n * // `PostDbModel`. Similar to `setDoc()`, since the `data` argument is typed\n * // as `WithFieldValue` rather than just `PostDbModel`, this\n * // allows properties of the `data` argument to also be those special\n * // Firestore values, like `arrayRemove()`, `deleteField()`, and\n * // `serverTimestamp()`.\n * await updateDoc(documentRef, {\n * 'aut.firstName': 'NewFirstName',\n * lut: serverTimestamp()\n * });\n *\n * // The TypeScript compiler will fail to compile if the `data` argument to\n * // `updateDoc()` is _not_ compatible with `WithFieldValue`.\n * // This type checking prevents the caller from specifying objects with\n * // incorrect properties or property values.\n * // @ts-expect-error \"Argument of type { title: string; } is not assignable\n * // to parameter of type WithFieldValue\"\n * await updateDoc(documentRef, { title: 'New Title' });\n * const snapshot2: DocumentSnapshot = await getDoc(documentRef);\n * const post2: Post = snapshot2.data()!;\n * if (post2) {\n * assertEqual(post2.title, 'My Life');\n * assertEqual(post2.author, 'NewFirstName Bar');\n * }\n * }\n * ```\n */\nexport interface FirestoreDataConverter<\n AppModelType,\n DbModelType extends DocumentData = DocumentData\n> {\n /**\n * Called by the Firestore SDK to convert a custom model object of type\n * `AppModelType` into a plain JavaScript object (suitable for writing\n * directly to the Firestore database) of type `DbModelType`. Used with\n * {@link @firebase/firestore/lite#(setDoc:1)},\n * {@link @firebase/firestore/lite#(WriteBatch.set:1)} and\n * {@link @firebase/firestore/lite#(Transaction.set:1)}.\n *\n * The `WithFieldValue` type extends `T` to also allow FieldValues such as\n * {@link (deleteField:1)} to be used as property values.\n */\n toFirestore(\n modelObject: WithFieldValue\n ): WithFieldValue;\n\n /**\n * Called by the Firestore SDK to convert a custom model object of type\n * `AppModelType` into a plain JavaScript object (suitable for writing\n * directly to the Firestore database) of type `DbModelType`. Used with\n * {@link @firebase/firestore/lite#(setDoc:1)},\n * {@link @firebase/firestore/lite#(WriteBatch.set:1)} and\n * {@link @firebase/firestore/lite#(Transaction.set:1)} with `merge:true`\n * or `mergeFields`.\n *\n * The `PartialWithFieldValue` type extends `Partial` to allow\n * FieldValues such as {@link (arrayUnion:1)} to be used as property values.\n * It also supports nested `Partial` by allowing nested fields to be\n * omitted.\n */\n toFirestore(\n modelObject: PartialWithFieldValue,\n options: SetOptions\n ): PartialWithFieldValue;\n\n /**\n * Called by the Firestore SDK to convert Firestore data into an object of\n * type `AppModelType`. You can access your data by calling:\n * `snapshot.data()`.\n *\n *\n * Generally, the data returned from `snapshot.data()` can be cast to\n * `DbModelType`; however, this is not guaranteed because Firestore does not\n * enforce a schema on the database. For example, writes from a previous\n * version of the application or writes from another client that did not use a\n * type converter could have written data with different properties and/or\n * property types. The implementation will need to choose whether to\n * gracefully recover from non-conforming data or throw an error.\n *\n * @param snapshot - A `QueryDocumentSnapshot` containing your data and\n * metadata.\n */\n fromFirestore(\n snapshot: QueryDocumentSnapshot\n ): AppModelType;\n}\n\n/**\n * A `DocumentSnapshot` contains data read from a document in your Firestore\n * database. The data can be extracted with `.data()` or `.get()` to\n * get a specific field.\n *\n * For a `DocumentSnapshot` that points to a non-existing document, any data\n * access will return 'undefined'. You can use the `exists()` method to\n * explicitly verify a document's existence.\n */\nexport class DocumentSnapshot<\n AppModelType = DocumentData,\n DbModelType extends DocumentData = DocumentData\n> {\n // Note: This class is stripped down version of the DocumentSnapshot in\n // the legacy SDK. The changes are:\n // - No support for SnapshotMetadata.\n // - No support for SnapshotOptions.\n\n /** @hideconstructor protected */\n constructor(\n public _firestore: Firestore,\n public _userDataWriter: AbstractUserDataWriter,\n public _key: DocumentKey,\n public _document: Document | null,\n public _converter: UntypedFirestoreDataConverter<\n AppModelType,\n DbModelType\n > | null\n ) {}\n\n /** Property of the `DocumentSnapshot` that provides the document's ID. */\n get id(): string {\n return this._key.path.lastSegment();\n }\n\n /**\n * The `DocumentReference` for the document included in the `DocumentSnapshot`.\n */\n get ref(): DocumentReference {\n return new DocumentReference(\n this._firestore,\n this._converter,\n this._key\n );\n }\n\n /**\n * Signals whether or not the document at the snapshot's location exists.\n *\n * @returns true if the document exists.\n */\n exists(): this is QueryDocumentSnapshot {\n return this._document !== null;\n }\n\n /**\n * Retrieves all fields in the document as an `Object`. Returns `undefined` if\n * the document doesn't exist.\n *\n * @returns An `Object` containing all fields in the document or `undefined`\n * if the document doesn't exist.\n */\n data(): AppModelType | undefined {\n if (!this._document) {\n return undefined;\n } else if (this._converter) {\n // We only want to use the converter and create a new DocumentSnapshot\n // if a converter has been provided.\n const snapshot = new QueryDocumentSnapshot(\n this._firestore,\n this._userDataWriter,\n this._key,\n this._document,\n /* converter= */ null\n );\n return this._converter.fromFirestore(snapshot);\n } else {\n return this._userDataWriter.convertValue(\n this._document.data.value\n ) as AppModelType;\n }\n }\n\n /**\n * Retrieves the field specified by `fieldPath`. Returns `undefined` if the\n * document or field doesn't exist.\n *\n * @param fieldPath - The path (for example 'foo' or 'foo.bar') to a specific\n * field.\n * @returns The data at the specified field location or undefined if no such\n * field exists in the document.\n */\n // We are using `any` here to avoid an explicit cast by our users.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n get(fieldPath: string | FieldPath): any {\n if (this._document) {\n const value = this._document.data.field(\n fieldPathFromArgument('DocumentSnapshot.get', fieldPath)\n );\n if (value !== null) {\n return this._userDataWriter.convertValue(value);\n }\n }\n return undefined;\n }\n}\n\n/**\n * A `QueryDocumentSnapshot` contains data read from a document in your\n * Firestore database as part of a query. The document is guaranteed to exist\n * and its data can be extracted with `.data()` or `.get()` to get a\n * specific field.\n *\n * A `QueryDocumentSnapshot` offers the same API surface as a\n * `DocumentSnapshot`. Since query results contain only existing documents, the\n * `exists` property will always be true and `data()` will never return\n * 'undefined'.\n */\nexport class QueryDocumentSnapshot<\n AppModelType = DocumentData,\n DbModelType extends DocumentData = DocumentData\n> extends DocumentSnapshot {\n /**\n * Retrieves all fields in the document as an `Object`.\n *\n * @override\n * @returns An `Object` containing all fields in the document.\n */\n data(): AppModelType {\n return super.data() as AppModelType;\n }\n}\n\n/**\n * A `QuerySnapshot` contains zero or more `DocumentSnapshot` objects\n * representing the results of a query. The documents can be accessed as an\n * array via the `docs` property or enumerated using the `forEach` method. The\n * number of documents can be determined via the `empty` and `size`\n * properties.\n */\nexport class QuerySnapshot<\n AppModelType = DocumentData,\n DbModelType extends DocumentData = DocumentData\n> {\n /**\n * The query on which you called {@link getDocs} in order to get this\n * `QuerySnapshot`.\n */\n readonly query: Query;\n\n /** @hideconstructor */\n constructor(\n _query: Query,\n readonly _docs: Array>\n ) {\n this.query = _query;\n }\n\n /** An array of all the documents in the `QuerySnapshot`. */\n get docs(): Array> {\n return [...this._docs];\n }\n\n /** The number of documents in the `QuerySnapshot`. */\n get size(): number {\n return this.docs.length;\n }\n\n /** True if there are no documents in the `QuerySnapshot`. */\n get empty(): boolean {\n return this.docs.length === 0;\n }\n\n /**\n * Enumerates all of the documents in the `QuerySnapshot`.\n *\n * @param callback - A callback to be called with a `QueryDocumentSnapshot` for\n * each document in the snapshot.\n * @param thisArg - The `this` binding for the callback.\n */\n forEach(\n callback: (\n result: QueryDocumentSnapshot\n ) => void,\n thisArg?: unknown\n ): void {\n this._docs.forEach(callback, thisArg);\n }\n}\n\n/**\n * Returns true if the provided snapshots are equal.\n *\n * @param left - A snapshot to compare.\n * @param right - A snapshot to compare.\n * @returns true if the snapshots are equal.\n */\nexport function snapshotEqual(\n left:\n | DocumentSnapshot\n | QuerySnapshot,\n right:\n | DocumentSnapshot\n | QuerySnapshot\n): boolean {\n left = getModularInstance(left);\n right = getModularInstance(right);\n\n if (left instanceof DocumentSnapshot && right instanceof DocumentSnapshot) {\n return (\n left._firestore === right._firestore &&\n left._key.isEqual(right._key) &&\n (left._document === null\n ? right._document === null\n : left._document.isEqual(right._document)) &&\n left._converter === right._converter\n );\n } else if (left instanceof QuerySnapshot && right instanceof QuerySnapshot) {\n return (\n queryEqual(left.query, right.query) &&\n arrayEquals(left.docs, right.docs, snapshotEqual)\n );\n }\n\n return false;\n}\n\n/**\n * Helper that calls `fromDotSeparatedString()` but wraps any error thrown.\n */\nexport function fieldPathFromArgument(\n methodName: string,\n arg: string | FieldPath | Compat\n): InternalFieldPath {\n if (typeof arg === 'string') {\n return fieldPathFromDotSeparatedString(methodName, arg);\n } else if (arg instanceof FieldPath) {\n return arg._internalPath;\n } else {\n return arg._delegate._internalPath;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getModularInstance } from '@firebase/util';\n\nimport { Bound } from '../core/bound';\nimport { DatabaseId } from '../core/database_info';\nimport {\n CompositeFilter,\n CompositeOperator,\n FieldFilter,\n Filter,\n Operator\n} from '../core/filter';\nimport { Direction, OrderBy } from '../core/order_by';\nimport {\n isCollectionGroupQuery,\n LimitType,\n Query as InternalQuery,\n queryNormalizedOrderBy,\n queryWithAddedFilter,\n queryWithAddedOrderBy,\n queryWithEndAt,\n queryWithLimit,\n queryWithStartAt\n} from '../core/query';\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { FieldPath as InternalFieldPath, ResourcePath } from '../model/path';\nimport { isServerTimestamp } from '../model/server_timestamps';\nimport { refValue } from '../model/values';\nimport { Value as ProtoValue } from '../protos/firestore_proto_api';\nimport { Code, FirestoreError } from '../util/error';\nimport {\n validatePositiveNumber,\n valueDescription\n} from '../util/input_validation';\n\nimport { FieldPath } from './field_path';\nimport { DocumentData, DocumentReference, Query } from './reference';\nimport { DocumentSnapshot, fieldPathFromArgument } from './snapshot';\nimport {\n newUserDataReader,\n parseQueryValue,\n UserDataReader\n} from './user_data_reader';\n\nexport function validateHasExplicitOrderByForLimitToLast(\n query: InternalQuery\n): void {\n if (\n query.limitType === LimitType.Last &&\n query.explicitOrderBy.length === 0\n ) {\n throw new FirestoreError(\n Code.UNIMPLEMENTED,\n 'limitToLast() queries require specifying at least one orderBy() clause'\n );\n }\n}\n\n/** Describes the different query constraints available in this SDK. */\nexport type QueryConstraintType =\n | 'where'\n | 'orderBy'\n | 'limit'\n | 'limitToLast'\n | 'startAt'\n | 'startAfter'\n | 'endAt'\n | 'endBefore';\n\n/**\n * An `AppliableConstraint` is an abstraction of a constraint that can be applied\n * to a Firestore query.\n */\nexport abstract class AppliableConstraint {\n /**\n * Takes the provided {@link Query} and returns a copy of the {@link Query} with this\n * {@link AppliableConstraint} applied.\n */\n abstract _apply(\n query: Query\n ): Query;\n}\n\n/**\n * A `QueryConstraint` is used to narrow the set of documents returned by a\n * Firestore query. `QueryConstraint`s are created by invoking {@link where},\n * {@link orderBy}, {@link (startAt:1)}, {@link (startAfter:1)}, {@link\n * (endBefore:1)}, {@link (endAt:1)}, {@link limit}, {@link limitToLast} and\n * can then be passed to {@link (query:1)} to create a new query instance that\n * also contains this `QueryConstraint`.\n */\nexport abstract class QueryConstraint extends AppliableConstraint {\n /** The type of this query constraint */\n abstract readonly type: QueryConstraintType;\n\n /**\n * Takes the provided {@link Query} and returns a copy of the {@link Query} with this\n * {@link AppliableConstraint} applied.\n */\n abstract _apply(\n query: Query\n ): Query;\n}\n\n/**\n * Creates a new immutable instance of {@link Query} that is extended to also\n * include additional query constraints.\n *\n * @param query - The {@link Query} instance to use as a base for the new\n * constraints.\n * @param compositeFilter - The {@link QueryCompositeFilterConstraint} to\n * apply. Create {@link QueryCompositeFilterConstraint} using {@link and} or\n * {@link or}.\n * @param queryConstraints - Additional {@link QueryNonFilterConstraint}s to\n * apply (e.g. {@link orderBy}, {@link limit}).\n * @throws if any of the provided query constraints cannot be combined with the\n * existing or new constraints.\n */\nexport function query(\n query: Query,\n compositeFilter: QueryCompositeFilterConstraint,\n ...queryConstraints: QueryNonFilterConstraint[]\n): Query;\n\n/**\n * Creates a new immutable instance of {@link Query} that is extended to also\n * include additional query constraints.\n *\n * @param query - The {@link Query} instance to use as a base for the new\n * constraints.\n * @param queryConstraints - The list of {@link QueryConstraint}s to apply.\n * @throws if any of the provided query constraints cannot be combined with the\n * existing or new constraints.\n */\nexport function query(\n query: Query,\n ...queryConstraints: QueryConstraint[]\n): Query;\n\nexport function query(\n query: Query,\n queryConstraint: QueryCompositeFilterConstraint | QueryConstraint | undefined,\n ...additionalQueryConstraints: Array<\n QueryConstraint | QueryNonFilterConstraint\n >\n): Query {\n let queryConstraints: AppliableConstraint[] = [];\n\n if (queryConstraint instanceof AppliableConstraint) {\n queryConstraints.push(queryConstraint);\n }\n\n queryConstraints = queryConstraints.concat(additionalQueryConstraints);\n\n validateQueryConstraintArray(queryConstraints);\n\n for (const constraint of queryConstraints) {\n query = constraint._apply(query);\n }\n return query;\n}\n\n/**\n * A `QueryFieldFilterConstraint` is used to narrow the set of documents returned by\n * a Firestore query by filtering on one or more document fields.\n * `QueryFieldFilterConstraint`s are created by invoking {@link where} and can then\n * be passed to {@link (query:1)} to create a new query instance that also contains\n * this `QueryFieldFilterConstraint`.\n */\nexport class QueryFieldFilterConstraint extends QueryConstraint {\n /** The type of this query constraint */\n readonly type = 'where';\n\n /**\n * @internal\n */\n protected constructor(\n private readonly _field: InternalFieldPath,\n private _op: Operator,\n private _value: unknown\n ) {\n super();\n }\n\n static _create(\n _field: InternalFieldPath,\n _op: Operator,\n _value: unknown\n ): QueryFieldFilterConstraint {\n return new QueryFieldFilterConstraint(_field, _op, _value);\n }\n\n _apply(\n query: Query\n ): Query {\n const filter = this._parse(query);\n validateNewFieldFilter(query._query, filter);\n return new Query(\n query.firestore,\n query.converter,\n queryWithAddedFilter(query._query, filter)\n );\n }\n\n _parse(\n query: Query\n ): FieldFilter {\n const reader = newUserDataReader(query.firestore);\n const filter = newQueryFilter(\n query._query,\n 'where',\n reader,\n query.firestore._databaseId,\n this._field,\n this._op,\n this._value\n );\n return filter;\n }\n}\n\n/**\n * Filter conditions in a {@link where} clause are specified using the\n * strings '<', '<=', '==', '!=', '>=', '>', 'array-contains', 'in',\n * 'array-contains-any', and 'not-in'.\n */\nexport type WhereFilterOp =\n | '<'\n | '<='\n | '=='\n | '!='\n | '>='\n | '>'\n | 'array-contains'\n | 'in'\n | 'array-contains-any'\n | 'not-in';\n\n/**\n * Creates a {@link QueryFieldFilterConstraint} that enforces that documents\n * must contain the specified field and that the value should satisfy the\n * relation constraint provided.\n *\n * @param fieldPath - The path to compare\n * @param opStr - The operation string (e.g \"<\", \"<=\", \"==\", \"<\",\n * \"<=\", \"!=\").\n * @param value - The value for comparison\n * @returns The created {@link QueryFieldFilterConstraint}.\n */\nexport function where(\n fieldPath: string | FieldPath,\n opStr: WhereFilterOp,\n value: unknown\n): QueryFieldFilterConstraint {\n const op = opStr as Operator;\n const field = fieldPathFromArgument('where', fieldPath);\n return QueryFieldFilterConstraint._create(field, op, value);\n}\n\n/**\n * A `QueryCompositeFilterConstraint` is used to narrow the set of documents\n * returned by a Firestore query by performing the logical OR or AND of multiple\n * {@link QueryFieldFilterConstraint}s or {@link QueryCompositeFilterConstraint}s.\n * `QueryCompositeFilterConstraint`s are created by invoking {@link or} or\n * {@link and} and can then be passed to {@link (query:1)} to create a new query\n * instance that also contains the `QueryCompositeFilterConstraint`.\n */\nexport class QueryCompositeFilterConstraint extends AppliableConstraint {\n /**\n * @internal\n */\n protected constructor(\n /** The type of this query constraint */\n readonly type: 'or' | 'and',\n private readonly _queryConstraints: QueryFilterConstraint[]\n ) {\n super();\n }\n\n static _create(\n type: 'or' | 'and',\n _queryConstraints: QueryFilterConstraint[]\n ): QueryCompositeFilterConstraint {\n return new QueryCompositeFilterConstraint(type, _queryConstraints);\n }\n\n _parse(\n query: Query\n ): Filter {\n const parsedFilters = this._queryConstraints\n .map(queryConstraint => {\n return queryConstraint._parse(query);\n })\n .filter(parsedFilter => parsedFilter.getFilters().length > 0);\n\n if (parsedFilters.length === 1) {\n return parsedFilters[0];\n }\n\n return CompositeFilter.create(parsedFilters, this._getOperator());\n }\n\n _apply(\n query: Query\n ): Query {\n const parsedFilter = this._parse(query);\n if (parsedFilter.getFilters().length === 0) {\n // Return the existing query if not adding any more filters (e.g. an empty\n // composite filter).\n return query;\n }\n validateNewFilter(query._query, parsedFilter);\n\n return new Query(\n query.firestore,\n query.converter,\n queryWithAddedFilter(query._query, parsedFilter)\n );\n }\n\n _getQueryConstraints(): readonly AppliableConstraint[] {\n return this._queryConstraints;\n }\n\n _getOperator(): CompositeOperator {\n return this.type === 'and' ? CompositeOperator.AND : CompositeOperator.OR;\n }\n}\n\n/**\n * `QueryNonFilterConstraint` is a helper union type that represents\n * QueryConstraints which are used to narrow or order the set of documents,\n * but that do not explicitly filter on a document field.\n * `QueryNonFilterConstraint`s are created by invoking {@link orderBy},\n * {@link (startAt:1)}, {@link (startAfter:1)}, {@link (endBefore:1)}, {@link (endAt:1)},\n * {@link limit} or {@link limitToLast} and can then be passed to {@link (query:1)}\n * to create a new query instance that also contains the `QueryConstraint`.\n */\nexport type QueryNonFilterConstraint =\n | QueryOrderByConstraint\n | QueryLimitConstraint\n | QueryStartAtConstraint\n | QueryEndAtConstraint;\n\n/**\n * `QueryFilterConstraint` is a helper union type that represents\n * {@link QueryFieldFilterConstraint} and {@link QueryCompositeFilterConstraint}.\n */\nexport type QueryFilterConstraint =\n | QueryFieldFilterConstraint\n | QueryCompositeFilterConstraint;\n\n/**\n * Creates a new {@link QueryCompositeFilterConstraint} that is a disjunction of\n * the given filter constraints. A disjunction filter includes a document if it\n * satisfies any of the given filters.\n *\n * @param queryConstraints - Optional. The list of\n * {@link QueryFilterConstraint}s to perform a disjunction for. These must be\n * created with calls to {@link where}, {@link or}, or {@link and}.\n * @returns The newly created {@link QueryCompositeFilterConstraint}.\n */\nexport function or(\n ...queryConstraints: QueryFilterConstraint[]\n): QueryCompositeFilterConstraint {\n // Only support QueryFilterConstraints\n queryConstraints.forEach(queryConstraint =>\n validateQueryFilterConstraint('or', queryConstraint)\n );\n\n return QueryCompositeFilterConstraint._create(\n CompositeOperator.OR,\n queryConstraints as QueryFilterConstraint[]\n );\n}\n\n/**\n * Creates a new {@link QueryCompositeFilterConstraint} that is a conjunction of\n * the given filter constraints. A conjunction filter includes a document if it\n * satisfies all of the given filters.\n *\n * @param queryConstraints - Optional. The list of\n * {@link QueryFilterConstraint}s to perform a conjunction for. These must be\n * created with calls to {@link where}, {@link or}, or {@link and}.\n * @returns The newly created {@link QueryCompositeFilterConstraint}.\n */\nexport function and(\n ...queryConstraints: QueryFilterConstraint[]\n): QueryCompositeFilterConstraint {\n // Only support QueryFilterConstraints\n queryConstraints.forEach(queryConstraint =>\n validateQueryFilterConstraint('and', queryConstraint)\n );\n\n return QueryCompositeFilterConstraint._create(\n CompositeOperator.AND,\n queryConstraints as QueryFilterConstraint[]\n );\n}\n\n/**\n * A `QueryOrderByConstraint` is used to sort the set of documents returned by a\n * Firestore query. `QueryOrderByConstraint`s are created by invoking\n * {@link orderBy} and can then be passed to {@link (query:1)} to create a new query\n * instance that also contains this `QueryOrderByConstraint`.\n *\n * Note: Documents that do not contain the orderBy field will not be present in\n * the query result.\n */\nexport class QueryOrderByConstraint extends QueryConstraint {\n /** The type of this query constraint */\n readonly type = 'orderBy';\n\n /**\n * @internal\n */\n protected constructor(\n private readonly _field: InternalFieldPath,\n private _direction: Direction\n ) {\n super();\n }\n\n static _create(\n _field: InternalFieldPath,\n _direction: Direction\n ): QueryOrderByConstraint {\n return new QueryOrderByConstraint(_field, _direction);\n }\n\n _apply(\n query: Query\n ): Query {\n const orderBy = newQueryOrderBy(query._query, this._field, this._direction);\n return new Query(\n query.firestore,\n query.converter,\n queryWithAddedOrderBy(query._query, orderBy)\n );\n }\n}\n\n/**\n * The direction of a {@link orderBy} clause is specified as 'desc' or 'asc'\n * (descending or ascending).\n */\nexport type OrderByDirection = 'desc' | 'asc';\n\n/**\n * Creates a {@link QueryOrderByConstraint} that sorts the query result by the\n * specified field, optionally in descending order instead of ascending.\n *\n * Note: Documents that do not contain the specified field will not be present\n * in the query result.\n *\n * @param fieldPath - The field to sort by.\n * @param directionStr - Optional direction to sort by ('asc' or 'desc'). If\n * not specified, order will be ascending.\n * @returns The created {@link QueryOrderByConstraint}.\n */\nexport function orderBy(\n fieldPath: string | FieldPath,\n directionStr: OrderByDirection = 'asc'\n): QueryOrderByConstraint {\n const direction = directionStr as Direction;\n const path = fieldPathFromArgument('orderBy', fieldPath);\n return QueryOrderByConstraint._create(path, direction);\n}\n\n/**\n * A `QueryLimitConstraint` is used to limit the number of documents returned by\n * a Firestore query.\n * `QueryLimitConstraint`s are created by invoking {@link limit} or\n * {@link limitToLast} and can then be passed to {@link (query:1)} to create a new\n * query instance that also contains this `QueryLimitConstraint`.\n */\nexport class QueryLimitConstraint extends QueryConstraint {\n /**\n * @internal\n */\n protected constructor(\n /** The type of this query constraint */\n readonly type: 'limit' | 'limitToLast',\n private readonly _limit: number,\n private readonly _limitType: LimitType\n ) {\n super();\n }\n\n static _create(\n type: 'limit' | 'limitToLast',\n _limit: number,\n _limitType: LimitType\n ): QueryLimitConstraint {\n return new QueryLimitConstraint(type, _limit, _limitType);\n }\n\n _apply(\n query: Query\n ): Query {\n return new Query(\n query.firestore,\n query.converter,\n queryWithLimit(query._query, this._limit, this._limitType)\n );\n }\n}\n\n/**\n * Creates a {@link QueryLimitConstraint} that only returns the first matching\n * documents.\n *\n * @param limit - The maximum number of items to return.\n * @returns The created {@link QueryLimitConstraint}.\n */\nexport function limit(limit: number): QueryLimitConstraint {\n validatePositiveNumber('limit', limit);\n return QueryLimitConstraint._create('limit', limit, LimitType.First);\n}\n\n/**\n * Creates a {@link QueryLimitConstraint} that only returns the last matching\n * documents.\n *\n * You must specify at least one `orderBy` clause for `limitToLast` queries,\n * otherwise an exception will be thrown during execution.\n *\n * @param limit - The maximum number of items to return.\n * @returns The created {@link QueryLimitConstraint}.\n */\nexport function limitToLast(limit: number): QueryLimitConstraint {\n validatePositiveNumber('limitToLast', limit);\n return QueryLimitConstraint._create('limitToLast', limit, LimitType.Last);\n}\n\n/**\n * A `QueryStartAtConstraint` is used to exclude documents from the start of a\n * result set returned by a Firestore query.\n * `QueryStartAtConstraint`s are created by invoking {@link (startAt:1)} or\n * {@link (startAfter:1)} and can then be passed to {@link (query:1)} to create a\n * new query instance that also contains this `QueryStartAtConstraint`.\n */\nexport class QueryStartAtConstraint extends QueryConstraint {\n /**\n * @internal\n */\n protected constructor(\n /** The type of this query constraint */\n readonly type: 'startAt' | 'startAfter',\n private readonly _docOrFields: Array>,\n private readonly _inclusive: boolean\n ) {\n super();\n }\n\n static _create(\n type: 'startAt' | 'startAfter',\n _docOrFields: Array>,\n _inclusive: boolean\n ): QueryStartAtConstraint {\n return new QueryStartAtConstraint(type, _docOrFields, _inclusive);\n }\n\n _apply(\n query: Query\n ): Query {\n const bound = newQueryBoundFromDocOrFields(\n query,\n this.type,\n this._docOrFields,\n this._inclusive\n );\n return new Query(\n query.firestore,\n query.converter,\n queryWithStartAt(query._query, bound)\n );\n }\n}\n\n/**\n * Creates a {@link QueryStartAtConstraint} that modifies the result set to\n * start at the provided document (inclusive). The starting position is relative\n * to the order of the query. The document must contain all of the fields\n * provided in the `orderBy` of this query.\n *\n * @param snapshot - The snapshot of the document to start at.\n * @returns A {@link QueryStartAtConstraint} to pass to `query()`.\n */\nexport function startAt(\n snapshot: DocumentSnapshot\n): QueryStartAtConstraint;\n/**\n * Creates a {@link QueryStartAtConstraint} that modifies the result set to\n * start at the provided fields relative to the order of the query. The order of\n * the field values must match the order of the order by clauses of the query.\n *\n * @param fieldValues - The field values to start this query at, in order\n * of the query's order by.\n * @returns A {@link QueryStartAtConstraint} to pass to `query()`.\n */\nexport function startAt(...fieldValues: unknown[]): QueryStartAtConstraint;\nexport function startAt(\n ...docOrFields: Array>\n): QueryStartAtConstraint {\n return QueryStartAtConstraint._create(\n 'startAt',\n docOrFields,\n /*inclusive=*/ true\n );\n}\n\n/**\n * Creates a {@link QueryStartAtConstraint} that modifies the result set to\n * start after the provided document (exclusive). The starting position is\n * relative to the order of the query. The document must contain all of the\n * fields provided in the orderBy of the query.\n *\n * @param snapshot - The snapshot of the document to start after.\n * @returns A {@link QueryStartAtConstraint} to pass to `query()`\n */\nexport function startAfter(\n snapshot: DocumentSnapshot\n): QueryStartAtConstraint;\n/**\n * Creates a {@link QueryStartAtConstraint} that modifies the result set to\n * start after the provided fields relative to the order of the query. The order\n * of the field values must match the order of the order by clauses of the query.\n *\n * @param fieldValues - The field values to start this query after, in order\n * of the query's order by.\n * @returns A {@link QueryStartAtConstraint} to pass to `query()`\n */\nexport function startAfter(...fieldValues: unknown[]): QueryStartAtConstraint;\nexport function startAfter(\n ...docOrFields: Array>\n): QueryStartAtConstraint {\n return QueryStartAtConstraint._create(\n 'startAfter',\n docOrFields,\n /*inclusive=*/ false\n );\n}\n\n/**\n * A `QueryEndAtConstraint` is used to exclude documents from the end of a\n * result set returned by a Firestore query.\n * `QueryEndAtConstraint`s are created by invoking {@link (endAt:1)} or\n * {@link (endBefore:1)} and can then be passed to {@link (query:1)} to create a new\n * query instance that also contains this `QueryEndAtConstraint`.\n */\nexport class QueryEndAtConstraint extends QueryConstraint {\n /**\n * @internal\n */\n protected constructor(\n /** The type of this query constraint */\n readonly type: 'endBefore' | 'endAt',\n private readonly _docOrFields: Array>,\n private readonly _inclusive: boolean\n ) {\n super();\n }\n\n static _create(\n type: 'endBefore' | 'endAt',\n _docOrFields: Array>,\n _inclusive: boolean\n ): QueryEndAtConstraint {\n return new QueryEndAtConstraint(type, _docOrFields, _inclusive);\n }\n\n _apply(\n query: Query\n ): Query {\n const bound = newQueryBoundFromDocOrFields(\n query,\n this.type,\n this._docOrFields,\n this._inclusive\n );\n return new Query(\n query.firestore,\n query.converter,\n queryWithEndAt(query._query, bound)\n );\n }\n}\n\n/**\n * Creates a {@link QueryEndAtConstraint} that modifies the result set to end\n * before the provided document (exclusive). The end position is relative to the\n * order of the query. The document must contain all of the fields provided in\n * the orderBy of the query.\n *\n * @param snapshot - The snapshot of the document to end before.\n * @returns A {@link QueryEndAtConstraint} to pass to `query()`\n */\nexport function endBefore(\n snapshot: DocumentSnapshot\n): QueryEndAtConstraint;\n/**\n * Creates a {@link QueryEndAtConstraint} that modifies the result set to end\n * before the provided fields relative to the order of the query. The order of\n * the field values must match the order of the order by clauses of the query.\n *\n * @param fieldValues - The field values to end this query before, in order\n * of the query's order by.\n * @returns A {@link QueryEndAtConstraint} to pass to `query()`\n */\nexport function endBefore(...fieldValues: unknown[]): QueryEndAtConstraint;\nexport function endBefore(\n ...docOrFields: Array>\n): QueryEndAtConstraint {\n return QueryEndAtConstraint._create(\n 'endBefore',\n docOrFields,\n /*inclusive=*/ false\n );\n}\n\n/**\n * Creates a {@link QueryEndAtConstraint} that modifies the result set to end at\n * the provided document (inclusive). The end position is relative to the order\n * of the query. The document must contain all of the fields provided in the\n * orderBy of the query.\n *\n * @param snapshot - The snapshot of the document to end at.\n * @returns A {@link QueryEndAtConstraint} to pass to `query()`\n */\nexport function endAt(\n snapshot: DocumentSnapshot\n): QueryEndAtConstraint;\n/**\n * Creates a {@link QueryEndAtConstraint} that modifies the result set to end at\n * the provided fields relative to the order of the query. The order of the field\n * values must match the order of the order by clauses of the query.\n *\n * @param fieldValues - The field values to end this query at, in order\n * of the query's order by.\n * @returns A {@link QueryEndAtConstraint} to pass to `query()`\n */\nexport function endAt(...fieldValues: unknown[]): QueryEndAtConstraint;\nexport function endAt(\n ...docOrFields: Array>\n): QueryEndAtConstraint {\n return QueryEndAtConstraint._create(\n 'endAt',\n docOrFields,\n /*inclusive=*/ true\n );\n}\n\n/** Helper function to create a bound from a document or fields */\nfunction newQueryBoundFromDocOrFields<\n AppModelType,\n DbModelType extends DocumentData\n>(\n query: Query,\n methodName: string,\n docOrFields: Array>,\n inclusive: boolean\n): Bound {\n docOrFields[0] = getModularInstance(docOrFields[0]);\n\n if (docOrFields[0] instanceof DocumentSnapshot) {\n return newQueryBoundFromDocument(\n query._query,\n query.firestore._databaseId,\n methodName,\n docOrFields[0]._document,\n inclusive\n );\n } else {\n const reader = newUserDataReader(query.firestore);\n return newQueryBoundFromFields(\n query._query,\n query.firestore._databaseId,\n reader,\n methodName,\n docOrFields,\n inclusive\n );\n }\n}\n\nexport function newQueryFilter(\n query: InternalQuery,\n methodName: string,\n dataReader: UserDataReader,\n databaseId: DatabaseId,\n fieldPath: InternalFieldPath,\n op: Operator,\n value: unknown\n): FieldFilter {\n let fieldValue: ProtoValue;\n if (fieldPath.isKeyField()) {\n if (op === Operator.ARRAY_CONTAINS || op === Operator.ARRAY_CONTAINS_ANY) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid Query. You can't perform '${op}' queries on documentId().`\n );\n } else if (op === Operator.IN || op === Operator.NOT_IN) {\n validateDisjunctiveFilterElements(value, op);\n const referenceList: ProtoValue[] = [];\n for (const arrayValue of value as ProtoValue[]) {\n referenceList.push(parseDocumentIdValue(databaseId, query, arrayValue));\n }\n fieldValue = { arrayValue: { values: referenceList } };\n } else {\n fieldValue = parseDocumentIdValue(databaseId, query, value);\n }\n } else {\n if (\n op === Operator.IN ||\n op === Operator.NOT_IN ||\n op === Operator.ARRAY_CONTAINS_ANY\n ) {\n validateDisjunctiveFilterElements(value, op);\n }\n fieldValue = parseQueryValue(\n dataReader,\n methodName,\n value,\n /* allowArrays= */ op === Operator.IN || op === Operator.NOT_IN\n );\n }\n const filter = FieldFilter.create(fieldPath, op, fieldValue);\n return filter;\n}\n\nexport function newQueryOrderBy(\n query: InternalQuery,\n fieldPath: InternalFieldPath,\n direction: Direction\n): OrderBy {\n if (query.startAt !== null) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Invalid query. You must not call startAt() or startAfter() before ' +\n 'calling orderBy().'\n );\n }\n if (query.endAt !== null) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Invalid query. You must not call endAt() or endBefore() before ' +\n 'calling orderBy().'\n );\n }\n const orderBy = new OrderBy(fieldPath, direction);\n return orderBy;\n}\n\n/**\n * Create a `Bound` from a query and a document.\n *\n * Note that the `Bound` will always include the key of the document\n * and so only the provided document will compare equal to the returned\n * position.\n *\n * Will throw if the document does not contain all fields of the order by\n * of the query or if any of the fields in the order by are an uncommitted\n * server timestamp.\n */\nexport function newQueryBoundFromDocument(\n query: InternalQuery,\n databaseId: DatabaseId,\n methodName: string,\n doc: Document | null,\n inclusive: boolean\n): Bound {\n if (!doc) {\n throw new FirestoreError(\n Code.NOT_FOUND,\n `Can't use a DocumentSnapshot that doesn't exist for ` +\n `${methodName}().`\n );\n }\n\n const components: ProtoValue[] = [];\n\n // Because people expect to continue/end a query at the exact document\n // provided, we need to use the implicit sort order rather than the explicit\n // sort order, because it's guaranteed to contain the document key. That way\n // the position becomes unambiguous and the query continues/ends exactly at\n // the provided document. Without the key (by using the explicit sort\n // orders), multiple documents could match the position, yielding duplicate\n // results.\n for (const orderBy of queryNormalizedOrderBy(query)) {\n if (orderBy.field.isKeyField()) {\n components.push(refValue(databaseId, doc.key));\n } else {\n const value = doc.data.field(orderBy.field);\n if (isServerTimestamp(value)) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Invalid query. You are trying to start or end a query using a ' +\n 'document for which the field \"' +\n orderBy.field +\n '\" is an uncommitted server timestamp. (Since the value of ' +\n 'this field is unknown, you cannot start/end a query with it.)'\n );\n } else if (value !== null) {\n components.push(value);\n } else {\n const field = orderBy.field.canonicalString();\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid query. You are trying to start or end a query using a ` +\n `document for which the field '${field}' (used as the ` +\n `orderBy) does not exist.`\n );\n }\n }\n }\n return new Bound(components, inclusive);\n}\n\n/**\n * Converts a list of field values to a `Bound` for the given query.\n */\nexport function newQueryBoundFromFields(\n query: InternalQuery,\n databaseId: DatabaseId,\n dataReader: UserDataReader,\n methodName: string,\n values: unknown[],\n inclusive: boolean\n): Bound {\n // Use explicit order by's because it has to match the query the user made\n const orderBy = query.explicitOrderBy;\n if (values.length > orderBy.length) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Too many arguments provided to ${methodName}(). ` +\n `The number of arguments must be less than or equal to the ` +\n `number of orderBy() clauses`\n );\n }\n\n const components: ProtoValue[] = [];\n for (let i = 0; i < values.length; i++) {\n const rawValue = values[i];\n const orderByComponent = orderBy[i];\n if (orderByComponent.field.isKeyField()) {\n if (typeof rawValue !== 'string') {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid query. Expected a string for document ID in ` +\n `${methodName}(), but got a ${typeof rawValue}`\n );\n }\n if (!isCollectionGroupQuery(query) && rawValue.indexOf('/') !== -1) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid query. When querying a collection and ordering by documentId(), ` +\n `the value passed to ${methodName}() must be a plain document ID, but ` +\n `'${rawValue}' contains a slash.`\n );\n }\n const path = query.path.child(ResourcePath.fromString(rawValue));\n if (!DocumentKey.isDocumentKey(path)) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid query. When querying a collection group and ordering by ` +\n `documentId(), the value passed to ${methodName}() must result in a ` +\n `valid document path, but '${path}' is not because it contains an odd number ` +\n `of segments.`\n );\n }\n const key = new DocumentKey(path);\n components.push(refValue(databaseId, key));\n } else {\n const wrapped = parseQueryValue(dataReader, methodName, rawValue);\n components.push(wrapped);\n }\n }\n\n return new Bound(components, inclusive);\n}\n\n/**\n * Parses the given `documentIdValue` into a `ReferenceValue`, throwing\n * appropriate errors if the value is anything other than a `DocumentReference`\n * or `string`, or if the string is malformed.\n */\nfunction parseDocumentIdValue(\n databaseId: DatabaseId,\n query: InternalQuery,\n documentIdValue: unknown\n): ProtoValue {\n documentIdValue = getModularInstance(documentIdValue);\n\n if (typeof documentIdValue === 'string') {\n if (documentIdValue === '') {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Invalid query. When querying with documentId(), you ' +\n 'must provide a valid document ID, but it was an empty string.'\n );\n }\n if (!isCollectionGroupQuery(query) && documentIdValue.indexOf('/') !== -1) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid query. When querying a collection by ` +\n `documentId(), you must provide a plain document ID, but ` +\n `'${documentIdValue}' contains a '/' character.`\n );\n }\n const path = query.path.child(ResourcePath.fromString(documentIdValue));\n if (!DocumentKey.isDocumentKey(path)) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid query. When querying a collection group by ` +\n `documentId(), the value provided must result in a valid document path, ` +\n `but '${path}' is not because it has an odd number of segments (${path.length}).`\n );\n }\n return refValue(databaseId, new DocumentKey(path));\n } else if (documentIdValue instanceof DocumentReference) {\n return refValue(databaseId, documentIdValue._key);\n } else {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid query. When querying with documentId(), you must provide a valid ` +\n `string or a DocumentReference, but it was: ` +\n `${valueDescription(documentIdValue)}.`\n );\n }\n}\n\n/**\n * Validates that the value passed into a disjunctive filter satisfies all\n * array requirements.\n */\nfunction validateDisjunctiveFilterElements(\n value: unknown,\n operator: Operator\n): void {\n if (!Array.isArray(value) || value.length === 0) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Invalid Query. A non-empty array is required for ' +\n `'${operator.toString()}' filters.`\n );\n }\n}\n\n/**\n * Given an operator, returns the set of operators that cannot be used with it.\n *\n * This is not a comprehensive check, and this function should be removed in the\n * long term. Validations should occur in the Firestore backend.\n *\n * Operators in a query must adhere to the following set of rules:\n * 1. Only one inequality per query.\n * 2. `NOT_IN` cannot be used with array, disjunctive, or `NOT_EQUAL` operators.\n */\nfunction conflictingOps(op: Operator): Operator[] {\n switch (op) {\n case Operator.NOT_EQUAL:\n return [Operator.NOT_EQUAL, Operator.NOT_IN];\n case Operator.ARRAY_CONTAINS_ANY:\n case Operator.IN:\n return [Operator.NOT_IN];\n case Operator.NOT_IN:\n return [\n Operator.ARRAY_CONTAINS_ANY,\n Operator.IN,\n Operator.NOT_IN,\n Operator.NOT_EQUAL\n ];\n default:\n return [];\n }\n}\n\nfunction validateNewFieldFilter(\n query: InternalQuery,\n fieldFilter: FieldFilter\n): void {\n const conflictingOp = findOpInsideFilters(\n query.filters,\n conflictingOps(fieldFilter.op)\n );\n if (conflictingOp !== null) {\n // Special case when it's a duplicate op to give a slightly clearer error message.\n if (conflictingOp === fieldFilter.op) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Invalid query. You cannot use more than one ' +\n `'${fieldFilter.op.toString()}' filter.`\n );\n } else {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid query. You cannot use '${fieldFilter.op.toString()}' filters ` +\n `with '${conflictingOp.toString()}' filters.`\n );\n }\n }\n}\n\nfunction validateNewFilter(query: InternalQuery, filter: Filter): void {\n let testQuery = query;\n const subFilters = filter.getFlattenedFilters();\n for (const subFilter of subFilters) {\n validateNewFieldFilter(testQuery, subFilter);\n testQuery = queryWithAddedFilter(testQuery, subFilter);\n }\n}\n\n// Checks if any of the provided filter operators are included in the given list of filters and\n// returns the first one that is, or null if none are.\nfunction findOpInsideFilters(\n filters: Filter[],\n operators: Operator[]\n): Operator | null {\n for (const filter of filters) {\n for (const fieldFilter of filter.getFlattenedFilters()) {\n if (operators.indexOf(fieldFilter.op) >= 0) {\n return fieldFilter.op;\n }\n }\n }\n return null;\n}\n\nexport function validateQueryFilterConstraint(\n functionName: string,\n queryConstraint: AppliableConstraint\n): void {\n if (\n !(queryConstraint instanceof QueryFieldFilterConstraint) &&\n !(queryConstraint instanceof QueryCompositeFilterConstraint)\n ) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Function ${functionName}() requires AppliableConstraints created with a call to 'where(...)', 'or(...)', or 'and(...)'.`\n );\n }\n}\n\nfunction validateQueryConstraintArray(\n queryConstraint: AppliableConstraint[]\n): void {\n const compositeFilterCount = queryConstraint.filter(\n filter => filter instanceof QueryCompositeFilterConstraint\n ).length;\n const fieldFilterCount = queryConstraint.filter(\n filter => filter instanceof QueryFieldFilterConstraint\n ).length;\n\n if (\n compositeFilterCount > 1 ||\n (compositeFilterCount > 0 && fieldFilterCount > 0)\n ) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'InvalidQuery. When using composite filters, you cannot use ' +\n 'more than one filter at the top level. Consider nesting the multiple ' +\n 'filters within an `and(...)` statement. For example: ' +\n 'change `query(query, where(...), or(...))` to ' +\n '`query(query, and(where(...), or(...)))`.'\n );\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DocumentData } from '@firebase/firestore-types';\n\nimport { DatabaseId } from '../core/database_info';\nimport { DocumentKey } from '../model/document_key';\nimport {\n normalizeByteString,\n normalizeNumber,\n normalizeTimestamp\n} from '../model/normalize';\nimport { ResourcePath } from '../model/path';\nimport {\n getLocalWriteTime,\n getPreviousValue\n} from '../model/server_timestamps';\nimport { TypeOrder } from '../model/type_order';\nimport { VECTOR_MAP_VECTORS_KEY, typeOrder } from '../model/values';\nimport {\n ApiClientObjectMap,\n ArrayValue as ProtoArrayValue,\n LatLng as ProtoLatLng,\n MapValue as ProtoMapValue,\n Timestamp as ProtoTimestamp,\n Value,\n Value as ProtoValue\n} from '../protos/firestore_proto_api';\nimport { isValidResourceName } from '../remote/serializer';\nimport { fail, hardAssert } from '../util/assert';\nimport { ByteString } from '../util/byte_string';\nimport { logError } from '../util/log';\nimport { forEach } from '../util/obj';\n\nimport { GeoPoint } from './geo_point';\nimport { Timestamp } from './timestamp';\nimport { VectorValue } from './vector_value';\n\nexport type ServerTimestampBehavior = 'estimate' | 'previous' | 'none';\n\n/**\n * Converts Firestore's internal types to the JavaScript types that we expose\n * to the user.\n *\n * @internal\n */\nexport abstract class AbstractUserDataWriter {\n convertValue(\n value: ProtoValue,\n serverTimestampBehavior: ServerTimestampBehavior = 'none'\n ): unknown {\n switch (typeOrder(value)) {\n case TypeOrder.NullValue:\n return null;\n case TypeOrder.BooleanValue:\n return value.booleanValue!;\n case TypeOrder.NumberValue:\n return normalizeNumber(value.integerValue || value.doubleValue);\n case TypeOrder.TimestampValue:\n return this.convertTimestamp(value.timestampValue!);\n case TypeOrder.ServerTimestampValue:\n return this.convertServerTimestamp(value, serverTimestampBehavior);\n case TypeOrder.StringValue:\n return value.stringValue!;\n case TypeOrder.BlobValue:\n return this.convertBytes(normalizeByteString(value.bytesValue!));\n case TypeOrder.RefValue:\n return this.convertReference(value.referenceValue!);\n case TypeOrder.GeoPointValue:\n return this.convertGeoPoint(value.geoPointValue!);\n case TypeOrder.ArrayValue:\n return this.convertArray(value.arrayValue!, serverTimestampBehavior);\n case TypeOrder.ObjectValue:\n return this.convertObject(value.mapValue!, serverTimestampBehavior);\n case TypeOrder.VectorValue:\n return this.convertVectorValue(value.mapValue!);\n default:\n throw fail(0xf2a2, 'Invalid value type', {\n value\n });\n }\n }\n\n private convertObject(\n mapValue: ProtoMapValue,\n serverTimestampBehavior: ServerTimestampBehavior\n ): DocumentData {\n return this.convertObjectMap(mapValue.fields, serverTimestampBehavior);\n }\n\n /**\n * @internal\n */\n convertObjectMap(\n fields: ApiClientObjectMap | undefined,\n serverTimestampBehavior: ServerTimestampBehavior = 'none'\n ): DocumentData {\n const result: DocumentData = {};\n forEach(fields, (key, value) => {\n result[key] = this.convertValue(value, serverTimestampBehavior);\n });\n return result;\n }\n\n /**\n * @internal\n */\n convertVectorValue(mapValue: ProtoMapValue): VectorValue {\n const values = mapValue.fields?.[\n VECTOR_MAP_VECTORS_KEY\n ].arrayValue?.values?.map(value => {\n return normalizeNumber(value.doubleValue);\n });\n\n return new VectorValue(values);\n }\n\n private convertGeoPoint(value: ProtoLatLng): GeoPoint {\n return new GeoPoint(\n normalizeNumber(value.latitude),\n normalizeNumber(value.longitude)\n );\n }\n\n private convertArray(\n arrayValue: ProtoArrayValue,\n serverTimestampBehavior: ServerTimestampBehavior\n ): unknown[] {\n return (arrayValue.values || []).map(value =>\n this.convertValue(value, serverTimestampBehavior)\n );\n }\n\n private convertServerTimestamp(\n value: ProtoValue,\n serverTimestampBehavior: ServerTimestampBehavior\n ): unknown {\n switch (serverTimestampBehavior) {\n case 'previous':\n const previousValue = getPreviousValue(value);\n if (previousValue == null) {\n return null;\n }\n return this.convertValue(previousValue, serverTimestampBehavior);\n case 'estimate':\n return this.convertTimestamp(getLocalWriteTime(value));\n default:\n return null;\n }\n }\n\n private convertTimestamp(value: ProtoTimestamp): Timestamp {\n const normalizedValue = normalizeTimestamp(value);\n return new Timestamp(normalizedValue.seconds, normalizedValue.nanos);\n }\n\n protected convertDocumentKey(\n name: string,\n expectedDatabaseId: DatabaseId\n ): DocumentKey {\n const resourcePath = ResourcePath.fromString(name);\n hardAssert(\n isValidResourceName(resourcePath),\n 0x25d8,\n 'ReferenceValue is not valid',\n { name }\n );\n const databaseId = new DatabaseId(resourcePath.get(1), resourcePath.get(3));\n const key = new DocumentKey(resourcePath.popFirst(5));\n\n if (!databaseId.isEqual(expectedDatabaseId)) {\n // TODO(b/64130202): Somehow support foreign references.\n logError(\n `Document ${key} contains a document ` +\n `reference within a different database (` +\n `${databaseId.projectId}/${databaseId.database}) which is not ` +\n `supported. It will be treated as a reference in the current ` +\n `database (${expectedDatabaseId.projectId}/${expectedDatabaseId.database}) ` +\n `instead.`\n );\n }\n return key;\n }\n\n protected abstract convertReference(name: string): unknown;\n\n protected abstract convertBytes(bytes: ByteString): unknown;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n DocumentData as PublicDocumentData,\n SetOptions as PublicSetOptions\n} from '@firebase/firestore-types';\nimport { getModularInstance } from '@firebase/util';\n\nimport { LimitType } from '../core/query';\nimport { DeleteMutation, Precondition } from '../model/mutation';\nimport {\n invokeBatchGetDocumentsRpc,\n invokeCommitRpc,\n invokeRunQueryRpc\n} from '../remote/datastore';\nimport { hardAssert } from '../util/assert';\nimport { ByteString } from '../util/byte_string';\nimport { cast } from '../util/input_validation';\n\nimport { Bytes } from './bytes';\nimport { getDatastore } from './components';\nimport { Firestore } from './database';\nimport { FieldPath } from './field_path';\nimport { validateHasExplicitOrderByForLimitToLast } from './query';\nimport {\n CollectionReference,\n doc,\n DocumentData,\n DocumentReference,\n PartialWithFieldValue,\n Query,\n SetOptions,\n UpdateData,\n WithFieldValue\n} from './reference';\nimport {\n DocumentSnapshot,\n QueryDocumentSnapshot,\n QuerySnapshot\n} from './snapshot';\nimport {\n newUserDataReader,\n ParsedUpdateData,\n parseSetData,\n parseUpdateData,\n parseUpdateVarargs,\n UntypedFirestoreDataConverter\n} from './user_data_reader';\nimport { AbstractUserDataWriter } from './user_data_writer';\n\n/**\n * Converts custom model object of type T into `DocumentData` by applying the\n * converter if it exists.\n *\n * This function is used when converting user objects to `DocumentData`\n * because we want to provide the user with a more specific error message if\n * their `set()` or fails due to invalid data originating from a `toFirestore()`\n * call.\n */\nexport function applyFirestoreDataConverter(\n converter: UntypedFirestoreDataConverter | null,\n value: WithFieldValue | PartialWithFieldValue,\n options?: PublicSetOptions\n): PublicDocumentData {\n let convertedValue;\n if (converter) {\n if (options && (options.merge || options.mergeFields)) {\n // Cast to `any` in order to satisfy the union type constraint on\n // toFirestore().\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n convertedValue = (converter as any).toFirestore(value, options);\n } else {\n convertedValue = converter.toFirestore(value as WithFieldValue);\n }\n } else {\n convertedValue = value as PublicDocumentData;\n }\n return convertedValue;\n}\n\nexport class LiteUserDataWriter extends AbstractUserDataWriter {\n constructor(protected firestore: Firestore) {\n super();\n }\n\n protected convertBytes(bytes: ByteString): Bytes {\n return new Bytes(bytes);\n }\n\n protected convertReference(name: string): DocumentReference {\n const key = this.convertDocumentKey(name, this.firestore._databaseId);\n return new DocumentReference(this.firestore, /* converter= */ null, key);\n }\n}\n\n/**\n * Reads the document referred to by the specified document reference.\n *\n * All documents are directly fetched from the server, even if the document was\n * previously read or modified. Recent modifications are only reflected in the\n * retrieved `DocumentSnapshot` if they have already been applied by the\n * backend. If the client is offline, the read fails. If you like to use\n * caching or see local modifications, please use the full Firestore SDK.\n *\n * @param reference - The reference of the document to fetch.\n * @returns A Promise resolved with a `DocumentSnapshot` containing the current\n * document contents.\n */\nexport function getDoc(\n reference: DocumentReference\n): Promise> {\n reference = cast>(\n reference,\n DocumentReference\n );\n const datastore = getDatastore(reference.firestore);\n const userDataWriter = new LiteUserDataWriter(reference.firestore);\n\n return invokeBatchGetDocumentsRpc(datastore, [reference._key]).then(\n result => {\n hardAssert(\n result.length === 1,\n 0x3d02,\n 'Expected a single document result'\n );\n const document = result[0];\n return new DocumentSnapshot(\n reference.firestore,\n userDataWriter,\n reference._key,\n document.isFoundDocument() ? document : null,\n reference.converter\n );\n }\n );\n}\n\n/**\n * Executes the query and returns the results as a {@link QuerySnapshot}.\n *\n * All queries are executed directly by the server, even if the query was\n * previously executed. Recent modifications are only reflected in the retrieved\n * results if they have already been applied by the backend. If the client is\n * offline, the operation fails. To see previously cached result and local\n * modifications, use the full Firestore SDK.\n *\n * @param query - The `Query` to execute.\n * @returns A Promise that will be resolved with the results of the query.\n */\nexport function getDocs(\n query: Query\n): Promise> {\n query = cast>(query, Query);\n validateHasExplicitOrderByForLimitToLast(query._query);\n\n const datastore = getDatastore(query.firestore);\n const userDataWriter = new LiteUserDataWriter(query.firestore);\n return invokeRunQueryRpc(datastore, query._query).then(result => {\n const docs = result.map(\n doc =>\n new QueryDocumentSnapshot(\n query.firestore,\n userDataWriter,\n doc.key,\n doc,\n query.converter\n )\n );\n\n if (query._query.limitType === LimitType.Last) {\n // Limit to last queries reverse the orderBy constraint that was\n // specified by the user. As such, we need to reverse the order of the\n // results to return the documents in the expected order.\n docs.reverse();\n }\n\n return new QuerySnapshot(query, docs);\n });\n}\n\n/**\n * Writes to the document referred to by the specified `DocumentReference`. If\n * the document does not yet exist, it will be created.\n *\n * The result of this write will only be reflected in document reads that occur\n * after the returned promise resolves. If the client is offline, the\n * write fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the document to write.\n * @param data - A map of the fields and values for the document.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns A `Promise` resolved once the data has been successfully written\n * to the backend.\n */\nexport function setDoc(\n reference: DocumentReference,\n data: WithFieldValue\n): Promise;\n/**\n * Writes to the document referred to by the specified `DocumentReference`. If\n * the document does not yet exist, it will be created. If you provide `merge`\n * or `mergeFields`, the provided data can be merged into an existing document.\n *\n * The result of this write will only be reflected in document reads that occur\n * after the returned promise resolves. If the client is offline, the\n * write fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the document to write.\n * @param data - A map of the fields and values for the document.\n * @param options - An object to configure the set behavior.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns A `Promise` resolved once the data has been successfully written\n * to the backend.\n */\nexport function setDoc(\n reference: DocumentReference,\n data: PartialWithFieldValue,\n options: SetOptions\n): Promise;\nexport function setDoc(\n reference: DocumentReference,\n data: PartialWithFieldValue,\n options?: SetOptions\n): Promise {\n reference = cast>(\n reference,\n DocumentReference\n );\n const convertedValue = applyFirestoreDataConverter(\n reference.converter,\n data,\n options\n );\n const dataReader = newUserDataReader(reference.firestore);\n const parsed = parseSetData(\n dataReader,\n 'setDoc',\n reference._key,\n convertedValue,\n reference.converter !== null,\n options\n );\n\n const datastore = getDatastore(reference.firestore);\n return invokeCommitRpc(datastore, [\n parsed.toMutation(reference._key, Precondition.none())\n ]);\n}\n\n/**\n * Updates fields in the document referred to by the specified\n * `DocumentReference`. The update will fail if applied to a document that does\n * not exist.\n *\n * The result of this update will only be reflected in document reads that occur\n * after the returned promise resolves. If the client is offline, the\n * update fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the document to update.\n * @param data - An object containing the fields and values with which to\n * update the document. Fields can contain dots to reference nested fields\n * within the document.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns A `Promise` resolved once the data has been successfully written\n * to the backend.\n */\nexport function updateDoc(\n reference: DocumentReference,\n data: UpdateData\n): Promise;\n/**\n * Updates fields in the document referred to by the specified\n * `DocumentReference` The update will fail if applied to a document that does\n * not exist.\n *\n * Nested fields can be updated by providing dot-separated field path\n * strings or by providing `FieldPath` objects.\n *\n * The result of this update will only be reflected in document reads that occur\n * after the returned promise resolves. If the client is offline, the\n * update fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the document to update.\n * @param field - The first field to update.\n * @param value - The first value.\n * @param moreFieldsAndValues - Additional key value pairs.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns A `Promise` resolved once the data has been successfully written\n * to the backend.\n */\nexport function updateDoc(\n reference: DocumentReference,\n field: string | FieldPath,\n value: unknown,\n ...moreFieldsAndValues: unknown[]\n): Promise;\nexport function updateDoc(\n reference: DocumentReference,\n fieldOrUpdateData: string | FieldPath | UpdateData,\n value?: unknown,\n ...moreFieldsAndValues: unknown[]\n): Promise {\n reference = cast>(\n reference,\n DocumentReference\n );\n const dataReader = newUserDataReader(reference.firestore);\n\n // For Compat types, we have to \"extract\" the underlying types before\n // performing validation.\n fieldOrUpdateData = getModularInstance(fieldOrUpdateData);\n\n let parsed: ParsedUpdateData;\n if (\n typeof fieldOrUpdateData === 'string' ||\n fieldOrUpdateData instanceof FieldPath\n ) {\n parsed = parseUpdateVarargs(\n dataReader,\n 'updateDoc',\n reference._key,\n fieldOrUpdateData,\n value,\n moreFieldsAndValues\n );\n } else {\n parsed = parseUpdateData(\n dataReader,\n 'updateDoc',\n reference._key,\n fieldOrUpdateData\n );\n }\n\n const datastore = getDatastore(reference.firestore);\n return invokeCommitRpc(datastore, [\n parsed.toMutation(reference._key, Precondition.exists(true))\n ]);\n}\n\n/**\n * Deletes the document referred to by the specified `DocumentReference`.\n *\n * The deletion will only be reflected in document reads that occur after the\n * returned promise resolves. If the client is offline, the\n * delete fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the document to delete.\n * @returns A `Promise` resolved once the document has been successfully\n * deleted from the backend.\n */\nexport function deleteDoc(\n reference: DocumentReference\n): Promise {\n reference = cast>(\n reference,\n DocumentReference\n );\n const datastore = getDatastore(reference.firestore);\n return invokeCommitRpc(datastore, [\n new DeleteMutation(reference._key, Precondition.none())\n ]);\n}\n\n/**\n * Add a new document to specified `CollectionReference` with the given data,\n * assigning it a document ID automatically.\n *\n * The result of this write will only be reflected in document reads that occur\n * after the returned promise resolves. If the client is offline, the\n * write fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the collection to add this document to.\n * @param data - An Object containing the data for the new document.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns A `Promise` resolved with a `DocumentReference` pointing to the\n * newly created document after it has been written to the backend.\n */\nexport function addDoc(\n reference: CollectionReference,\n data: WithFieldValue\n): Promise> {\n reference = cast>(\n reference,\n CollectionReference\n );\n const docRef = doc(reference);\n\n const convertedValue = applyFirestoreDataConverter(\n reference.converter,\n data as PartialWithFieldValue\n );\n\n const dataReader = newUserDataReader(reference.firestore);\n const parsed = parseSetData(\n dataReader,\n 'addDoc',\n docRef._key,\n convertedValue,\n docRef.converter !== null,\n {}\n );\n\n const datastore = getDatastore(reference.firestore);\n return invokeCommitRpc(datastore, [\n parsed.toMutation(docRef._key, Precondition.exists(false))\n ]).then(() => docRef);\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { deepEqual } from '@firebase/util';\n\nimport { AggregateImpl } from '../core/aggregate';\nimport { ApiClientObjectMap, Value } from '../protos/firestore_proto_api';\nimport { invokeRunAggregationQueryRpc } from '../remote/datastore';\nimport { cast } from '../util/input_validation';\nimport { mapToArray } from '../util/obj';\n\nimport {\n AggregateField,\n AggregateQuerySnapshot,\n AggregateSpec\n} from './aggregate_types';\nimport { getDatastore } from './components';\nimport { Firestore } from './database';\nimport { FieldPath } from './field_path';\nimport { DocumentData, Query, queryEqual } from './reference';\nimport { LiteUserDataWriter } from './reference_impl';\nimport { fieldPathFromArgument } from './user_data_reader';\n\n/**\n * Calculates the number of documents in the result set of the given query\n * without actually downloading the documents.\n *\n * Using this function to count the documents is efficient because only the\n * final count, not the documents' data, is downloaded. This function can\n * count the documents in cases where the result set is prohibitively large to\n * download entirely (thousands of documents).\n *\n * @param query The query whose result set size is calculated.\n * @returns A Promise that will be resolved with the count; the count can be\n * retrieved from `snapshot.data().count`, where `snapshot` is the\n * `AggregateQuerySnapshot` to which the returned Promise resolves.\n */\nexport function getCount(\n query: Query\n): Promise<\n AggregateQuerySnapshot<\n { count: AggregateField },\n AppModelType,\n DbModelType\n >\n> {\n const countQuerySpec: { count: AggregateField } = {\n count: count()\n };\n\n return getAggregate(query, countQuerySpec);\n}\n\n/**\n * Calculates the specified aggregations over the documents in the result\n * set of the given query without actually downloading the documents.\n *\n * Using this function to perform aggregations is efficient because only the\n * final aggregation values, not the documents' data, are downloaded. This\n * function can perform aggregations of the documents in cases where the result\n * set is prohibitively large to download entirely (thousands of documents).\n *\n * @param query The query whose result set is aggregated over.\n * @param aggregateSpec An `AggregateSpec` object that specifies the aggregates\n * to perform over the result set. The AggregateSpec specifies aliases for each\n * aggregate, which can be used to retrieve the aggregate result.\n * @example\n * ```typescript\n * const aggregateSnapshot = await getAggregate(query, {\n * countOfDocs: count(),\n * totalHours: sum('hours'),\n * averageScore: average('score')\n * });\n *\n * const countOfDocs: number = aggregateSnapshot.data().countOfDocs;\n * const totalHours: number = aggregateSnapshot.data().totalHours;\n * const averageScore: number | null = aggregateSnapshot.data().averageScore;\n * ```\n */\nexport function getAggregate<\n AggregateSpecType extends AggregateSpec,\n AppModelType,\n DbModelType extends DocumentData\n>(\n query: Query,\n aggregateSpec: AggregateSpecType\n): Promise<\n AggregateQuerySnapshot\n> {\n const firestore = cast(query.firestore, Firestore);\n const datastore = getDatastore(firestore);\n\n const internalAggregates = mapToArray(aggregateSpec, (aggregate, alias) => {\n return new AggregateImpl(\n alias,\n aggregate.aggregateType,\n aggregate._internalFieldPath\n );\n });\n\n // Run the aggregation and convert the results\n return invokeRunAggregationQueryRpc(\n datastore,\n query._query,\n internalAggregates\n ).then(aggregateResult =>\n convertToAggregateQuerySnapshot(firestore, query, aggregateResult)\n );\n}\n\nfunction convertToAggregateQuerySnapshot<\n AggregateSpecType extends AggregateSpec,\n AppModelType,\n DbModelType extends DocumentData\n>(\n firestore: Firestore,\n query: Query,\n aggregateResult: ApiClientObjectMap\n): AggregateQuerySnapshot {\n const userDataWriter = new LiteUserDataWriter(firestore);\n const querySnapshot = new AggregateQuerySnapshot<\n AggregateSpecType,\n AppModelType,\n DbModelType\n >(query, userDataWriter, aggregateResult);\n return querySnapshot;\n}\n\n/**\n * Create an AggregateField object that can be used to compute the sum of\n * a specified field over a range of documents in the result set of a query.\n * @param field Specifies the field to sum across the result set.\n */\nexport function sum(field: string | FieldPath): AggregateField {\n return new AggregateField('sum', fieldPathFromArgument('sum', field));\n}\n\n/**\n * Create an AggregateField object that can be used to compute the average of\n * a specified field over a range of documents in the result set of a query.\n * @param field Specifies the field to average across the result set.\n */\nexport function average(\n field: string | FieldPath\n): AggregateField {\n return new AggregateField('avg', fieldPathFromArgument('average', field));\n}\n\n/**\n * Create an AggregateField object that can be used to compute the count of\n * documents in the result set of a query.\n */\nexport function count(): AggregateField {\n return new AggregateField('count');\n}\n\n/**\n * Compares two 'AggregateField` instances for equality.\n *\n * @param left Compare this AggregateField to the `right`.\n * @param right Compare this AggregateField to the `left`.\n */\nexport function aggregateFieldEqual(\n left: AggregateField,\n right: AggregateField\n): boolean {\n return (\n left instanceof AggregateField &&\n right instanceof AggregateField &&\n left.aggregateType === right.aggregateType &&\n left._internalFieldPath?.canonicalString() ===\n right._internalFieldPath?.canonicalString()\n );\n}\n\n/**\n * Compares two `AggregateQuerySnapshot` instances for equality.\n *\n * Two `AggregateQuerySnapshot` instances are considered \"equal\" if they have\n * underlying queries that compare equal, and the same data.\n *\n * @param left - The first `AggregateQuerySnapshot` to compare.\n * @param right - The second `AggregateQuerySnapshot` to compare.\n *\n * @returns `true` if the objects are \"equal\", as defined above, or `false`\n * otherwise.\n */\nexport function aggregateQuerySnapshotEqual<\n AggregateSpecType extends AggregateSpec,\n AppModelType,\n DbModelType extends DocumentData\n>(\n left: AggregateQuerySnapshot,\n right: AggregateQuerySnapshot\n): boolean {\n return (\n queryEqual(left.query, right.query) && deepEqual(left.data(), right.data())\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FieldValue } from './field_value';\nimport {\n ArrayRemoveFieldValueImpl,\n ArrayUnionFieldValueImpl,\n DeleteFieldValueImpl,\n NumericIncrementFieldValueImpl,\n ServerTimestampFieldValueImpl\n} from './user_data_reader';\nimport { VectorValue } from './vector_value';\n\n/**\n * Returns a sentinel for use with {@link @firebase/firestore/lite#(updateDoc:1)} or\n * {@link @firebase/firestore/lite#(setDoc:1)} with `{merge: true}` to mark a field for deletion.\n */\nexport function deleteField(): FieldValue {\n return new DeleteFieldValueImpl('deleteField');\n}\n\n/**\n * Returns a sentinel used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link @firebase/firestore/lite#(updateDoc:1)} to\n * include a server-generated timestamp in the written data.\n */\nexport function serverTimestamp(): FieldValue {\n return new ServerTimestampFieldValueImpl('serverTimestamp');\n}\n\n/**\n * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link\n * @firebase/firestore/lite#(updateDoc:1)} that tells the server to union the given elements with any array\n * value that already exists on the server. Each specified element that doesn't\n * already exist in the array will be added to the end. If the field being\n * modified is not already an array it will be overwritten with an array\n * containing exactly the specified elements.\n *\n * @param elements - The elements to union into the array.\n * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or\n * `updateDoc()`.\n */\nexport function arrayUnion(...elements: unknown[]): FieldValue {\n // NOTE: We don't actually parse the data until it's used in set() or\n // update() since we'd need the Firestore instance to do this.\n return new ArrayUnionFieldValueImpl('arrayUnion', elements);\n}\n\n/**\n * Returns a special value that can be used with {@link (setDoc:1)} or {@link\n * updateDoc:1} that tells the server to remove the given elements from any\n * array value that already exists on the server. All instances of each element\n * specified will be removed from the array. If the field being modified is not\n * already an array it will be overwritten with an empty array.\n *\n * @param elements - The elements to remove from the array.\n * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or\n * `updateDoc()`\n */\nexport function arrayRemove(...elements: unknown[]): FieldValue {\n // NOTE: We don't actually parse the data until it's used in set() or\n // update() since we'd need the Firestore instance to do this.\n return new ArrayRemoveFieldValueImpl('arrayRemove', elements);\n}\n\n/**\n * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link\n * @firebase/firestore/lite#(updateDoc:1)} that tells the server to increment the field's current value by\n * the given value.\n *\n * If either the operand or the current field value uses floating point\n * precision, all arithmetic follows IEEE 754 semantics. If both values are\n * integers, values outside of JavaScript's safe number range\n * (`Number.MIN_SAFE_INTEGER` to `Number.MAX_SAFE_INTEGER`) are also subject to\n * precision loss. Furthermore, once processed by the Firestore backend, all\n * integer operations are capped between -2^63 and 2^63-1.\n *\n * If the current field value is not of type `number`, or if the field does not\n * yet exist, the transformation sets the field to the given value.\n *\n * @param n - The value to increment by.\n * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or\n * `updateDoc()`\n */\nexport function increment(n: number): FieldValue {\n return new NumericIncrementFieldValueImpl('increment', n);\n}\n\n/**\n * Creates a new `VectorValue` constructed with a copy of the given array of numbers.\n *\n * @param values - Create a `VectorValue` instance with a copy of this array of numbers.\n *\n * @returns A new `VectorValue` constructed with a copy of the given array of numbers.\n */\nexport function vector(values?: number[]): VectorValue {\n return new VectorValue(values);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Compat, getModularInstance } from '@firebase/util';\n\nimport { DeleteMutation, Mutation, Precondition } from '../model/mutation';\nimport { invokeCommitRpc } from '../remote/datastore';\nimport { Code, FirestoreError } from '../util/error';\nimport { cast } from '../util/input_validation';\n\nimport { getDatastore } from './components';\nimport { Firestore } from './database';\nimport { FieldPath } from './field_path';\nimport {\n DocumentData,\n DocumentReference,\n PartialWithFieldValue,\n SetOptions,\n UpdateData,\n WithFieldValue\n} from './reference';\nimport { applyFirestoreDataConverter } from './reference_impl';\nimport {\n newUserDataReader,\n parseSetData,\n parseUpdateData,\n parseUpdateVarargs,\n UserDataReader\n} from './user_data_reader';\n\n/**\n * A write batch, used to perform multiple writes as a single atomic unit.\n *\n * A `WriteBatch` object can be acquired by calling {@link writeBatch}. It\n * provides methods for adding writes to the write batch. None of the writes\n * will be committed (or visible locally) until {@link WriteBatch.commit} is\n * called.\n */\nexport class WriteBatch {\n // This is the lite version of the WriteBatch API used in the legacy SDK. The\n // class is a close copy but takes different input types.\n\n private readonly _dataReader: UserDataReader;\n private _mutations = [] as Mutation[];\n private _committed = false;\n\n /** @hideconstructor */\n constructor(\n private readonly _firestore: Firestore,\n private readonly _commitHandler: (m: Mutation[]) => Promise\n ) {\n this._dataReader = newUserDataReader(_firestore);\n }\n\n /**\n * Writes to the document referred to by the provided {@link\n * DocumentReference}. If the document does not exist yet, it will be created.\n *\n * @param documentRef - A reference to the document to be set.\n * @param data - An object of the fields and values for the document.\n * @returns This `WriteBatch` instance. Used for chaining method calls.\n */\n set(\n documentRef: DocumentReference,\n data: WithFieldValue\n ): WriteBatch;\n /**\n * Writes to the document referred to by the provided {@link\n * DocumentReference}. If the document does not exist yet, it will be created.\n * If you provide `merge` or `mergeFields`, the provided data can be merged\n * into an existing document.\n *\n * @param documentRef - A reference to the document to be set.\n * @param data - An object of the fields and values for the document.\n * @param options - An object to configure the set behavior.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns This `WriteBatch` instance. Used for chaining method calls.\n */\n set(\n documentRef: DocumentReference,\n data: PartialWithFieldValue,\n options: SetOptions\n ): WriteBatch;\n set(\n documentRef: DocumentReference,\n data: WithFieldValue | PartialWithFieldValue,\n options?: SetOptions\n ): WriteBatch {\n this._verifyNotCommitted();\n const ref = validateReference(documentRef, this._firestore);\n\n const convertedValue = applyFirestoreDataConverter(\n ref.converter,\n data,\n options\n );\n const parsed = parseSetData(\n this._dataReader,\n 'WriteBatch.set',\n ref._key,\n convertedValue,\n ref.converter !== null,\n options\n );\n this._mutations.push(parsed.toMutation(ref._key, Precondition.none()));\n return this;\n }\n\n /**\n * Updates fields in the document referred to by the provided {@link\n * DocumentReference}. The update will fail if applied to a document that does\n * not exist.\n *\n * @param documentRef - A reference to the document to be updated.\n * @param data - An object containing the fields and values with which to\n * update the document. Fields can contain dots to reference nested fields\n * within the document.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns This `WriteBatch` instance. Used for chaining method calls.\n */\n update(\n documentRef: DocumentReference,\n data: UpdateData\n ): WriteBatch;\n /**\n * Updates fields in the document referred to by this {@link\n * DocumentReference}. The update will fail if applied to a document that does\n * not exist.\n *\n * Nested fields can be update by providing dot-separated field path strings\n * or by providing `FieldPath` objects.\n *\n * @param documentRef - A reference to the document to be updated.\n * @param field - The first field to update.\n * @param value - The first value.\n * @param moreFieldsAndValues - Additional key value pairs.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns This `WriteBatch` instance. Used for chaining method calls.\n */\n update(\n documentRef: DocumentReference,\n field: string | FieldPath,\n value: unknown,\n ...moreFieldsAndValues: unknown[]\n ): WriteBatch;\n update(\n documentRef: DocumentReference,\n fieldOrUpdateData: string | FieldPath | UpdateData,\n value?: unknown,\n ...moreFieldsAndValues: unknown[]\n ): WriteBatch {\n this._verifyNotCommitted();\n const ref = validateReference(documentRef, this._firestore);\n\n // For Compat types, we have to \"extract\" the underlying types before\n // performing validation.\n fieldOrUpdateData = getModularInstance(fieldOrUpdateData);\n\n let parsed;\n if (\n typeof fieldOrUpdateData === 'string' ||\n fieldOrUpdateData instanceof FieldPath\n ) {\n parsed = parseUpdateVarargs(\n this._dataReader,\n 'WriteBatch.update',\n ref._key,\n fieldOrUpdateData,\n value,\n moreFieldsAndValues\n );\n } else {\n parsed = parseUpdateData(\n this._dataReader,\n 'WriteBatch.update',\n ref._key,\n fieldOrUpdateData\n );\n }\n\n this._mutations.push(\n parsed.toMutation(ref._key, Precondition.exists(true))\n );\n return this;\n }\n\n /**\n * Deletes the document referred to by the provided {@link DocumentReference}.\n *\n * @param documentRef - A reference to the document to be deleted.\n * @returns This `WriteBatch` instance. Used for chaining method calls.\n */\n delete(\n documentRef: DocumentReference\n ): WriteBatch {\n this._verifyNotCommitted();\n const ref = validateReference(documentRef, this._firestore);\n this._mutations = this._mutations.concat(\n new DeleteMutation(ref._key, Precondition.none())\n );\n return this;\n }\n\n /**\n * Commits all of the writes in this write batch as a single atomic unit.\n *\n * The result of these writes will only be reflected in document reads that\n * occur after the returned promise resolves. If the client is offline, the\n * write fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @returns A `Promise` resolved once all of the writes in the batch have been\n * successfully written to the backend as an atomic unit (note that it won't\n * resolve while you're offline).\n */\n commit(): Promise {\n this._verifyNotCommitted();\n this._committed = true;\n if (this._mutations.length > 0) {\n return this._commitHandler(this._mutations);\n }\n\n return Promise.resolve();\n }\n\n private _verifyNotCommitted(): void {\n if (this._committed) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'A write batch can no longer be used after commit() ' +\n 'has been called.'\n );\n }\n }\n}\n\nexport function validateReference<\n AppModelType,\n DbModelType extends DocumentData\n>(\n documentRef:\n | DocumentReference\n | Compat>,\n firestore: Firestore\n): DocumentReference {\n documentRef = getModularInstance(documentRef);\n\n if (documentRef.firestore !== firestore) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Provided document reference is from a different Firestore instance.'\n );\n } else {\n return documentRef as DocumentReference;\n }\n}\n\n/**\n * Creates a write batch, used for performing multiple writes as a single\n * atomic operation. The maximum number of writes allowed in a single WriteBatch\n * is 500.\n *\n * The result of these writes will only be reflected in document reads that\n * occur after the returned promise resolves. If the client is offline, the\n * write fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @returns A `WriteBatch` that can be used to atomically execute multiple\n * writes.\n */\nexport function writeBatch(firestore: Firestore): WriteBatch {\n firestore = cast(firestore, Firestore);\n const datastore = getDatastore(firestore);\n return new WriteBatch(firestore, writes =>\n invokeCommitRpc(datastore, writes)\n );\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ParsedSetData, ParsedUpdateData } from '../lite-api/user_data_reader';\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport {\n DeleteMutation,\n Mutation,\n Precondition,\n VerifyMutation\n} from '../model/mutation';\nimport {\n Datastore,\n invokeBatchGetDocumentsRpc,\n invokeCommitRpc\n} from '../remote/datastore';\nimport { fail, debugAssert } from '../util/assert';\nimport { Code, FirestoreError } from '../util/error';\n\nimport { SnapshotVersion } from './snapshot_version';\n\n/**\n * Internal transaction object responsible for accumulating the mutations to\n * perform and the base versions for any documents read.\n */\nexport class Transaction {\n // The version of each document that was read during this transaction.\n private readVersions = new Map();\n private mutations: Mutation[] = [];\n private committed = false;\n\n /**\n * A deferred usage error that occurred previously in this transaction that\n * will cause the transaction to fail once it actually commits.\n */\n private lastTransactionError: FirestoreError | null = null;\n\n /**\n * Set of documents that have been written in the transaction.\n *\n * When there's more than one write to the same key in a transaction, any\n * writes after the first are handled differently.\n */\n private writtenDocs: Set = new Set();\n\n constructor(private datastore: Datastore) {}\n\n async lookup(keys: DocumentKey[]): Promise {\n this.ensureCommitNotCalled();\n\n if (this.mutations.length > 0) {\n this.lastTransactionError = new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Firestore transactions require all reads to be executed before all writes.'\n );\n throw this.lastTransactionError;\n }\n const docs = await invokeBatchGetDocumentsRpc(this.datastore, keys);\n docs.forEach(doc => this.recordVersion(doc));\n return docs;\n }\n\n set(key: DocumentKey, data: ParsedSetData): void {\n this.write(data.toMutation(key, this.precondition(key)));\n this.writtenDocs.add(key.toString());\n }\n\n update(key: DocumentKey, data: ParsedUpdateData): void {\n try {\n this.write(data.toMutation(key, this.preconditionForUpdate(key)));\n } catch (e) {\n this.lastTransactionError = e as FirestoreError | null;\n }\n this.writtenDocs.add(key.toString());\n }\n\n delete(key: DocumentKey): void {\n this.write(new DeleteMutation(key, this.precondition(key)));\n this.writtenDocs.add(key.toString());\n }\n\n async commit(): Promise {\n this.ensureCommitNotCalled();\n\n if (this.lastTransactionError) {\n throw this.lastTransactionError;\n }\n const unwritten = this.readVersions;\n // For each mutation, note that the doc was written.\n this.mutations.forEach(mutation => {\n unwritten.delete(mutation.key.toString());\n });\n // For each document that was read but not written to, we want to perform\n // a `verify` operation.\n unwritten.forEach((_, path) => {\n const key = DocumentKey.fromPath(path);\n this.mutations.push(new VerifyMutation(key, this.precondition(key)));\n });\n await invokeCommitRpc(this.datastore, this.mutations);\n this.committed = true;\n }\n\n private recordVersion(doc: Document): void {\n let docVersion: SnapshotVersion;\n\n if (doc.isFoundDocument()) {\n docVersion = doc.version;\n } else if (doc.isNoDocument()) {\n // Represent a deleted doc using SnapshotVersion.min().\n docVersion = SnapshotVersion.min();\n } else {\n throw fail(0xc542, 'Document in a transaction was a ', {\n documentName: doc.constructor.name\n });\n }\n\n const existingVersion = this.readVersions.get(doc.key.toString());\n if (existingVersion) {\n if (!docVersion.isEqual(existingVersion)) {\n // This transaction will fail no matter what.\n throw new FirestoreError(\n Code.ABORTED,\n 'Document version changed between two reads.'\n );\n }\n } else {\n this.readVersions.set(doc.key.toString(), docVersion);\n }\n }\n\n /**\n * Returns the version of this document when it was read in this transaction,\n * as a precondition, or no precondition if it was not read.\n */\n private precondition(key: DocumentKey): Precondition {\n const version = this.readVersions.get(key.toString());\n if (!this.writtenDocs.has(key.toString()) && version) {\n if (version.isEqual(SnapshotVersion.min())) {\n return Precondition.exists(false);\n } else {\n return Precondition.updateTime(version);\n }\n } else {\n return Precondition.none();\n }\n }\n\n /**\n * Returns the precondition for a document if the operation is an update.\n */\n private preconditionForUpdate(key: DocumentKey): Precondition {\n const version = this.readVersions.get(key.toString());\n // The first time a document is written, we want to take into account the\n // read time and existence\n if (!this.writtenDocs.has(key.toString()) && version) {\n if (version.isEqual(SnapshotVersion.min())) {\n // The document doesn't exist, so fail the transaction.\n\n // This has to be validated locally because you can't send a\n // precondition that a document does not exist without changing the\n // semantics of the backend write to be an insert. This is the reverse\n // of what we want, since we want to assert that the document doesn't\n // exist but then send the update and have it fail. Since we can't\n // express that to the backend, we have to validate locally.\n\n // Note: this can change once we can send separate verify writes in the\n // transaction.\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n \"Can't update a document that doesn't exist.\"\n );\n }\n // Document exists, base precondition on document update time.\n return Precondition.updateTime(version);\n } else {\n // Document was not read, so we just use the preconditions for a blind\n // update.\n return Precondition.exists(true);\n }\n }\n\n private write(mutation: Mutation): void {\n this.ensureCommitNotCalled();\n this.mutations.push(mutation);\n }\n\n private ensureCommitNotCalled(): void {\n debugAssert(\n !this.committed,\n 'A transaction object cannot be used after its update callback has been invoked.'\n );\n }\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Code, FirestoreError } from '../util/error';\n\nexport const DEFAULT_TRANSACTION_OPTIONS: TransactionOptions = {\n maxAttempts: 5\n};\n\n/**\n * Options to customize transaction behavior.\n */\nexport declare interface TransactionOptions {\n /** Maximum number of attempts to commit, after which transaction fails. Default is 5. */\n readonly maxAttempts: number;\n}\n\nexport function validateTransactionOptions(options: TransactionOptions): void {\n if (options.maxAttempts < 1) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Max attempts must be at least 1'\n );\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ExponentialBackoff } from '../remote/backoff';\nimport { Datastore } from '../remote/datastore';\nimport { isPermanentError } from '../remote/rpc_error';\nimport { AsyncQueue, TimerId } from '../util/async_queue';\nimport { FirestoreError } from '../util/error';\nimport { Deferred } from '../util/promise';\nimport { isNullOrUndefined } from '../util/types';\n\nimport { Transaction } from './transaction';\nimport { TransactionOptions } from './transaction_options';\n\n/**\n * TransactionRunner encapsulates the logic needed to run and retry transactions\n * with backoff.\n */\nexport class TransactionRunner {\n private attemptsRemaining: number;\n private backoff: ExponentialBackoff;\n\n constructor(\n private readonly asyncQueue: AsyncQueue,\n private readonly datastore: Datastore,\n private readonly options: TransactionOptions,\n private readonly updateFunction: (transaction: Transaction) => Promise,\n private readonly deferred: Deferred\n ) {\n this.attemptsRemaining = options.maxAttempts;\n this.backoff = new ExponentialBackoff(\n this.asyncQueue,\n TimerId.TransactionRetry\n );\n }\n\n /** Runs the transaction and sets the result on deferred. */\n run(): void {\n this.attemptsRemaining -= 1;\n this.runWithBackOff();\n }\n\n private runWithBackOff(): void {\n this.backoff.backoffAndRun(async () => {\n const transaction = new Transaction(this.datastore);\n const userPromise = this.tryRunUpdateFunction(transaction);\n if (userPromise) {\n userPromise\n .then(result => {\n this.asyncQueue.enqueueAndForget(() => {\n return transaction\n .commit()\n .then(() => {\n this.deferred.resolve(result);\n })\n .catch(commitError => {\n this.handleTransactionError(commitError);\n });\n });\n })\n .catch(userPromiseError => {\n this.handleTransactionError(userPromiseError);\n });\n }\n });\n }\n\n private tryRunUpdateFunction(transaction: Transaction): Promise | null {\n try {\n const userPromise = this.updateFunction(transaction);\n if (\n isNullOrUndefined(userPromise) ||\n !userPromise.catch ||\n !userPromise.then\n ) {\n this.deferred.reject(\n Error('Transaction callback must return a Promise')\n );\n return null;\n }\n return userPromise;\n } catch (error) {\n // Do not retry errors thrown by user provided updateFunction.\n this.deferred.reject(error as Error);\n return null;\n }\n }\n\n private handleTransactionError(error: Error): void {\n if (this.attemptsRemaining > 0 && this.isRetryableTransactionError(error)) {\n this.attemptsRemaining -= 1;\n this.asyncQueue.enqueueAndForget(() => {\n this.runWithBackOff();\n return Promise.resolve();\n });\n } else {\n this.deferred.reject(error);\n }\n }\n\n private isRetryableTransactionError(error: Error | undefined): boolean {\n if (error?.name === 'FirebaseError') {\n // In transactions, the backend will fail outdated reads with FAILED_PRECONDITION and\n // non-matching document versions with ABORTED. These errors should be retried.\n const code = (error as FirestoreError).code;\n return (\n code === 'aborted' ||\n code === 'failed-precondition' ||\n code === 'already-exists' ||\n !isPermanentError(code)\n );\n }\n return false;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** The Platform's 'window' implementation or null if not available. */\nexport function getWindow(): Window | null {\n // `window` is not always available, e.g. in ReactNative and WebWorkers.\n // eslint-disable-next-line no-restricted-globals\n return typeof window !== 'undefined' ? window : null;\n}\n\n/** The Platform's 'document' implementation or null if not available. */\nexport function getDocument(): Document | null {\n // `document` is not always available, e.g. in ReactNative and WebWorkers.\n // eslint-disable-next-line no-restricted-globals\n return typeof document !== 'undefined' ? document : null;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isIndexedDbTransactionError } from '../local/simple_db';\n\nimport { Code, FirestoreError } from './error';\nimport { logError } from './log';\nimport { Deferred } from './promise';\n\nconst LOG_TAG = 'AsyncQueue';\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype TimerHandle = any;\n\n/**\n * Wellknown \"timer\" IDs used when scheduling delayed operations on the\n * AsyncQueue. These IDs can then be used from tests to check for the presence\n * of operations or to run them early.\n *\n * The string values are used when encoding these timer IDs in JSON spec tests.\n */\nexport const enum TimerId {\n /** All can be used with runDelayedOperationsEarly() to run all timers. */\n All = 'all',\n\n /**\n * The following 5 timers are used in persistent_stream.ts for the listen and\n * write streams. The \"Idle\" timer is used to close the stream due to\n * inactivity. The \"ConnectionBackoff\" timer is used to restart a stream once\n * the appropriate backoff delay has elapsed. The health check is used to mark\n * a stream healthy if it has not received an error during its initial setup.\n */\n ListenStreamIdle = 'listen_stream_idle',\n ListenStreamConnectionBackoff = 'listen_stream_connection_backoff',\n WriteStreamIdle = 'write_stream_idle',\n WriteStreamConnectionBackoff = 'write_stream_connection_backoff',\n HealthCheckTimeout = 'health_check_timeout',\n\n /**\n * A timer used in online_state_tracker.ts to transition from\n * OnlineState.Unknown to Offline after a set timeout, rather than waiting\n * indefinitely for success or failure.\n */\n OnlineStateTimeout = 'online_state_timeout',\n\n /**\n * A timer used to update the client metadata in IndexedDb, which is used\n * to determine the primary leaseholder.\n */\n ClientMetadataRefresh = 'client_metadata_refresh',\n\n /** A timer used to periodically attempt LRU Garbage collection */\n LruGarbageCollection = 'lru_garbage_collection',\n\n /**\n * A timer used to retry transactions. Since there can be multiple concurrent\n * transactions, multiple of these may be in the queue at a given time.\n */\n TransactionRetry = 'transaction_retry',\n\n /**\n * A timer used to retry operations scheduled via retryable AsyncQueue\n * operations.\n */\n AsyncQueueRetry = 'async_queue_retry',\n\n /**\n * A timer used to periodically attempt index backfill.\n */\n IndexBackfill = 'index_backfill'\n}\n\n/**\n * Represents an operation scheduled to be run in the future on an AsyncQueue.\n *\n * It is created via DelayedOperation.createAndSchedule().\n *\n * Supports cancellation (via cancel()) and early execution (via skipDelay()).\n *\n * Note: We implement `PromiseLike` instead of `Promise`, as the `Promise` type\n * in newer versions of TypeScript defines `finally`, which is not available in\n * IE.\n */\nexport class DelayedOperation implements PromiseLike {\n // handle for use with clearTimeout(), or null if the operation has been\n // executed or canceled already.\n private timerHandle: TimerHandle | null;\n\n private readonly deferred = new Deferred();\n\n private constructor(\n private readonly asyncQueue: AsyncQueue,\n readonly timerId: TimerId,\n readonly targetTimeMs: number,\n private readonly op: () => Promise,\n private readonly removalCallback: (op: DelayedOperation) => void\n ) {\n // It's normal for the deferred promise to be canceled (due to cancellation)\n // and so we attach a dummy catch callback to avoid\n // 'UnhandledPromiseRejectionWarning' log spam.\n this.deferred.promise.catch(err => {});\n }\n\n get promise(): Promise {\n return this.deferred.promise;\n }\n\n /**\n * Creates and returns a DelayedOperation that has been scheduled to be\n * executed on the provided asyncQueue after the provided delayMs.\n *\n * @param asyncQueue - The queue to schedule the operation on.\n * @param id - A Timer ID identifying the type of operation this is.\n * @param delayMs - The delay (ms) before the operation should be scheduled.\n * @param op - The operation to run.\n * @param removalCallback - A callback to be called synchronously once the\n * operation is executed or canceled, notifying the AsyncQueue to remove it\n * from its delayedOperations list.\n * PORTING NOTE: This exists to prevent making removeDelayedOperation() and\n * the DelayedOperation class public.\n */\n static createAndSchedule(\n asyncQueue: AsyncQueue,\n timerId: TimerId,\n delayMs: number,\n op: () => Promise,\n removalCallback: (op: DelayedOperation) => void\n ): DelayedOperation {\n const targetTime = Date.now() + delayMs;\n const delayedOp = new DelayedOperation(\n asyncQueue,\n timerId,\n targetTime,\n op,\n removalCallback\n );\n delayedOp.start(delayMs);\n return delayedOp;\n }\n\n /**\n * Starts the timer. This is called immediately after construction by\n * createAndSchedule().\n */\n private start(delayMs: number): void {\n this.timerHandle = setTimeout(() => this.handleDelayElapsed(), delayMs);\n }\n\n /**\n * Queues the operation to run immediately (if it hasn't already been run or\n * canceled).\n */\n skipDelay(): void {\n return this.handleDelayElapsed();\n }\n\n /**\n * Cancels the operation if it hasn't already been executed or canceled. The\n * promise will be rejected.\n *\n * As long as the operation has not yet been run, calling cancel() provides a\n * guarantee that the operation will not be run.\n */\n cancel(reason?: string): void {\n if (this.timerHandle !== null) {\n this.clearTimeout();\n this.deferred.reject(\n new FirestoreError(\n Code.CANCELLED,\n 'Operation cancelled' + (reason ? ': ' + reason : '')\n )\n );\n }\n }\n\n then = this.deferred.promise.then.bind(this.deferred.promise);\n\n private handleDelayElapsed(): void {\n this.asyncQueue.enqueueAndForget(() => {\n if (this.timerHandle !== null) {\n this.clearTimeout();\n return this.op().then(result => {\n return this.deferred.resolve(result);\n });\n } else {\n return Promise.resolve();\n }\n });\n }\n\n private clearTimeout(): void {\n if (this.timerHandle !== null) {\n this.removalCallback(this);\n clearTimeout(this.timerHandle);\n this.timerHandle = null;\n }\n }\n}\n\nexport interface AsyncQueue {\n // Is this AsyncQueue being shut down? If true, this instance will not enqueue\n // any new operations, Promises from enqueue requests will not resolve.\n readonly isShuttingDown: boolean;\n\n /**\n * Adds a new operation to the queue without waiting for it to complete (i.e.\n * we ignore the Promise result).\n */\n enqueueAndForget(op: () => Promise): void;\n\n /**\n * Regardless if the queue has initialized shutdown, adds a new operation to the\n * queue without waiting for it to complete (i.e. we ignore the Promise result).\n */\n enqueueAndForgetEvenWhileRestricted(\n op: () => Promise\n ): void;\n\n /**\n * Initialize the shutdown of this queue. Once this method is called, the\n * only possible way to request running an operation is through\n * `enqueueEvenWhileRestricted()`.\n *\n * @param purgeExistingTasks Whether already enqueued tasked should be\n * rejected (unless enqueued with `enqueueEvenWhileRestricted()`). Defaults\n * to false.\n */\n enterRestrictedMode(purgeExistingTasks?: boolean): void;\n\n /**\n * Adds a new operation to the queue. Returns a promise that will be resolved\n * when the promise returned by the new operation is (with its value).\n */\n enqueue(op: () => Promise): Promise;\n\n /**\n * Enqueue a retryable operation.\n *\n * A retryable operation is rescheduled with backoff if it fails with a\n * IndexedDbTransactionError (the error type used by SimpleDb). All\n * retryable operations are executed in order and only run if all prior\n * operations were retried successfully.\n */\n enqueueRetryable(op: () => Promise): void;\n\n /**\n * Schedules an operation to be queued on the AsyncQueue once the specified\n * `delayMs` has elapsed. The returned DelayedOperation can be used to cancel\n * or fast-forward the operation prior to its running.\n */\n enqueueAfterDelay(\n timerId: TimerId,\n delayMs: number,\n op: () => Promise\n ): DelayedOperation;\n\n /**\n * Verifies there's an operation currently in-progress on the AsyncQueue.\n * Unfortunately we can't verify that the running code is in the promise chain\n * of that operation, so this isn't a foolproof check, but it should be enough\n * to catch some bugs.\n */\n verifyOperationInProgress(): void;\n}\n\n/**\n * Returns a FirestoreError that can be surfaced to the user if the provided\n * error is an IndexedDbTransactionError. Re-throws the error otherwise.\n */\nexport function wrapInUserErrorIfRecoverable(\n e: Error,\n msg: string\n): FirestoreError {\n logError(LOG_TAG, `${msg}: ${e}`);\n if (isIndexedDbTransactionError(e)) {\n return new FirestoreError(Code.UNAVAILABLE, `${msg}: ${e}`);\n } else {\n throw e;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isIndexedDbTransactionError } from '../local/simple_db';\nimport { getDocument } from '../platform/dom';\nimport { ExponentialBackoff } from '../remote/backoff';\n\nimport { debugAssert, fail } from './assert';\nimport { AsyncQueue, DelayedOperation, TimerId } from './async_queue';\nimport { FirestoreError } from './error';\nimport { logDebug, logError } from './log';\nimport { Deferred } from './promise';\n\nconst LOG_TAG = 'AsyncQueue';\n\nexport class AsyncQueueImpl implements AsyncQueue {\n // The last promise in the queue.\n private tail: Promise;\n\n // A list of retryable operations. Retryable operations are run in order and\n // retried with backoff.\n private retryableOps: Array<() => Promise> = [];\n\n // Is this AsyncQueue being shut down? Once it is set to true, it will not\n // be changed again.\n private _isShuttingDown: boolean = false;\n\n // Operations scheduled to be queued in the future. Operations are\n // automatically removed after they are run or canceled.\n private delayedOperations: Array> = [];\n\n // visible for testing\n failure: FirestoreError | null = null;\n\n // Flag set while there's an outstanding AsyncQueue operation, used for\n // assertion sanity-checks.\n private operationInProgress = false;\n\n // Enabled during shutdown on Safari to prevent future access to IndexedDB.\n private skipNonRestrictedTasks = false;\n\n // List of TimerIds to fast-forward delays for.\n private timerIdsToSkip: TimerId[] = [];\n\n // Backoff timer used to schedule retries for retryable operations\n private backoff = new ExponentialBackoff(this, TimerId.AsyncQueueRetry);\n\n // Visibility handler that triggers an immediate retry of all retryable\n // operations. Meant to speed up recovery when we regain file system access\n // after page comes into foreground.\n private visibilityHandler: () => void = () => {\n const document = getDocument();\n if (document) {\n logDebug(\n LOG_TAG,\n 'Visibility state changed to ' + document.visibilityState\n );\n }\n this.backoff.skipBackoff();\n };\n\n constructor(tail: Promise = Promise.resolve()) {\n this.tail = tail;\n const document = getDocument();\n if (document && typeof document.addEventListener === 'function') {\n document.addEventListener('visibilitychange', this.visibilityHandler);\n }\n }\n\n get isShuttingDown(): boolean {\n return this._isShuttingDown;\n }\n\n /**\n * Adds a new operation to the queue without waiting for it to complete (i.e.\n * we ignore the Promise result).\n */\n enqueueAndForget(op: () => Promise): void {\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.enqueue(op);\n }\n\n enqueueAndForgetEvenWhileRestricted(\n op: () => Promise\n ): void {\n this.verifyNotFailed();\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.enqueueInternal(op);\n }\n\n enterRestrictedMode(purgeExistingTasks?: boolean): void {\n if (!this._isShuttingDown) {\n this._isShuttingDown = true;\n this.skipNonRestrictedTasks = purgeExistingTasks || false;\n const document = getDocument();\n if (document && typeof document.removeEventListener === 'function') {\n document.removeEventListener(\n 'visibilitychange',\n this.visibilityHandler\n );\n }\n }\n }\n\n enqueue(op: () => Promise): Promise {\n this.verifyNotFailed();\n if (this._isShuttingDown) {\n // Return a Promise which never resolves.\n return new Promise(() => {});\n }\n\n // Create a deferred Promise that we can return to the callee. This\n // allows us to return a \"hanging Promise\" only to the callee and still\n // advance the queue even when the operation is not run.\n const task = new Deferred();\n return this.enqueueInternal(() => {\n if (this._isShuttingDown && this.skipNonRestrictedTasks) {\n // We do not resolve 'task'\n return Promise.resolve();\n }\n\n op().then(task.resolve, task.reject);\n return task.promise;\n }).then(() => task.promise);\n }\n\n enqueueRetryable(op: () => Promise): void {\n this.enqueueAndForget(() => {\n this.retryableOps.push(op);\n return this.retryNextOp();\n });\n }\n\n /**\n * Runs the next operation from the retryable queue. If the operation fails,\n * reschedules with backoff.\n */\n private async retryNextOp(): Promise {\n if (this.retryableOps.length === 0) {\n return;\n }\n\n try {\n await this.retryableOps[0]();\n this.retryableOps.shift();\n this.backoff.reset();\n } catch (e) {\n if (isIndexedDbTransactionError(e as Error)) {\n logDebug(LOG_TAG, 'Operation failed with retryable error: ' + e);\n } else {\n throw e; // Failure will be handled by AsyncQueue\n }\n }\n\n if (this.retryableOps.length > 0) {\n // If there are additional operations, we re-schedule `retryNextOp()`.\n // This is necessary to run retryable operations that failed during\n // their initial attempt since we don't know whether they are already\n // enqueued. If, for example, `op1`, `op2`, `op3` are enqueued and `op1`\n // needs to be re-run, we will run `op1`, `op1`, `op2` using the\n // already enqueued calls to `retryNextOp()`. `op3()` will then run in the\n // call scheduled here.\n // Since `backoffAndRun()` cancels an existing backoff and schedules a\n // new backoff on every call, there is only ever a single additional\n // operation in the queue.\n this.backoff.backoffAndRun(() => this.retryNextOp());\n }\n }\n\n private enqueueInternal(op: () => Promise): Promise {\n const newTail = this.tail.then(() => {\n this.operationInProgress = true;\n return op()\n .catch((error: FirestoreError) => {\n this.failure = error;\n this.operationInProgress = false;\n const message = getMessageOrStack(error);\n logError('INTERNAL UNHANDLED ERROR: ', message);\n\n // Re-throw the error so that this.tail becomes a rejected Promise and\n // all further attempts to chain (via .then) will just short-circuit\n // and return the rejected Promise.\n throw error;\n })\n .then(result => {\n this.operationInProgress = false;\n return result;\n });\n });\n this.tail = newTail;\n return newTail;\n }\n\n enqueueAfterDelay(\n timerId: TimerId,\n delayMs: number,\n op: () => Promise\n ): DelayedOperation {\n this.verifyNotFailed();\n\n debugAssert(\n delayMs >= 0,\n `Attempted to schedule an operation with a negative delay of ${delayMs}`\n );\n\n // Fast-forward delays for timerIds that have been overridden.\n if (this.timerIdsToSkip.indexOf(timerId) > -1) {\n delayMs = 0;\n }\n\n const delayedOp = DelayedOperation.createAndSchedule(\n this,\n timerId,\n delayMs,\n op,\n removedOp =>\n this.removeDelayedOperation(removedOp as DelayedOperation)\n );\n this.delayedOperations.push(delayedOp as DelayedOperation);\n return delayedOp;\n }\n\n private verifyNotFailed(): void {\n if (this.failure) {\n fail(0xb815, 'AsyncQueue is already failed', {\n messageOrStack: getMessageOrStack(this.failure)\n });\n }\n }\n\n verifyOperationInProgress(): void {\n debugAssert(\n this.operationInProgress,\n 'verifyOpInProgress() called when no op in progress on this queue.'\n );\n }\n\n /**\n * Waits until all currently queued tasks are finished executing. Delayed\n * operations are not run.\n */\n async drain(): Promise {\n // Operations in the queue prior to draining may have enqueued additional\n // operations. Keep draining the queue until the tail is no longer advanced,\n // which indicates that no more new operations were enqueued and that all\n // operations were executed.\n let currentTail: Promise;\n do {\n currentTail = this.tail;\n await currentTail;\n } while (currentTail !== this.tail);\n }\n\n /**\n * For Tests: Determine if a delayed operation with a particular TimerId\n * exists.\n */\n containsDelayedOperation(timerId: TimerId): boolean {\n for (const op of this.delayedOperations) {\n if (op.timerId === timerId) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * For Tests: Runs some or all delayed operations early.\n *\n * @param lastTimerId - Delayed operations up to and including this TimerId\n * will be drained. Pass TimerId.All to run all delayed operations.\n * @returns a Promise that resolves once all operations have been run.\n */\n runAllDelayedOperationsUntil(lastTimerId: TimerId): Promise {\n // Note that draining may generate more delayed ops, so we do that first.\n return this.drain().then(() => {\n // Run ops in the same order they'd run if they ran naturally.\n /* eslint-disable-next-line @typescript-eslint/no-floating-promises */\n this.delayedOperations.sort((a, b) => a.targetTimeMs - b.targetTimeMs);\n\n for (const op of this.delayedOperations) {\n op.skipDelay();\n if (lastTimerId !== TimerId.All && op.timerId === lastTimerId) {\n break;\n }\n }\n\n return this.drain();\n });\n }\n\n /**\n * For Tests: Skip all subsequent delays for a timer id.\n */\n skipDelaysForTimerId(timerId: TimerId): void {\n this.timerIdsToSkip.push(timerId);\n }\n\n /** Called once a DelayedOperation is run or canceled. */\n private removeDelayedOperation(op: DelayedOperation): void {\n // NOTE: indexOf / slice are O(n), but delayedOperations is expected to be small.\n const index = this.delayedOperations.indexOf(op);\n debugAssert(index >= 0, 'Delayed operation not found.');\n /* eslint-disable-next-line @typescript-eslint/no-floating-promises */\n this.delayedOperations.splice(index, 1);\n }\n}\n\nexport function newAsyncQueue(): AsyncQueue {\n return new AsyncQueueImpl();\n}\n\n/**\n * Chrome includes Error.message in Error.stack. Other browsers do not.\n * This returns expected output of message + stack when available.\n * @param error - Error or FirestoreError\n */\nfunction getMessageOrStack(error: Error): string {\n let message = error.message || '';\n if (error.stack) {\n if (error.stack.includes(error.message)) {\n message = error.stack;\n } else {\n message = error.message + '\\n' + error.stack;\n }\n }\n return message;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getGlobal, getUA, isIndexedDBAvailable } from '@firebase/util';\n\nimport { debugAssert } from '../util/assert';\nimport { Code, FirestoreError } from '../util/error';\nimport { logDebug, logError } from '../util/log';\nimport { Deferred } from '../util/promise';\n\nimport { PersistencePromise } from './persistence_promise';\n\n// References to `indexedDB` are guarded by SimpleDb.isAvailable() and getGlobal()\n/* eslint-disable no-restricted-globals */\n\nconst LOG_TAG = 'SimpleDb';\n\n/**\n * The maximum number of retry attempts for an IndexedDb transaction that fails\n * with a DOMException.\n */\nconst TRANSACTION_RETRY_COUNT = 3;\n\n// The different modes supported by `SimpleDb.runTransaction()`\ntype SimpleDbTransactionMode = 'readonly' | 'readwrite';\n\nexport interface SimpleDbSchemaConverter {\n createOrUpgrade(\n db: IDBDatabase,\n txn: IDBTransaction,\n fromVersion: number,\n toVersion: number\n ): PersistencePromise;\n}\n\n/**\n * Wraps an IDBTransaction and exposes a store() method to get a handle to a\n * specific object store.\n */\nexport class SimpleDbTransaction {\n private aborted = false;\n\n /**\n * A `Promise` that resolves with the result of the IndexedDb transaction.\n */\n private readonly completionDeferred = new Deferred();\n\n static open(\n db: IDBDatabase,\n action: string,\n mode: IDBTransactionMode,\n objectStoreNames: string[]\n ): SimpleDbTransaction {\n try {\n return new SimpleDbTransaction(\n action,\n db.transaction(objectStoreNames, mode)\n );\n } catch (e) {\n throw new IndexedDbTransactionError(action, e as Error);\n }\n }\n\n constructor(\n private readonly action: string,\n private readonly transaction: IDBTransaction\n ) {\n this.transaction.oncomplete = () => {\n this.completionDeferred.resolve();\n };\n this.transaction.onabort = () => {\n if (transaction.error) {\n this.completionDeferred.reject(\n new IndexedDbTransactionError(action, transaction.error)\n );\n } else {\n this.completionDeferred.resolve();\n }\n };\n this.transaction.onerror = (event: Event) => {\n const error = checkForAndReportiOSError(\n (event.target as IDBRequest).error!\n );\n this.completionDeferred.reject(\n new IndexedDbTransactionError(action, error)\n );\n };\n }\n\n get completionPromise(): Promise {\n return this.completionDeferred.promise;\n }\n\n abort(error?: Error): void {\n if (error) {\n this.completionDeferred.reject(error);\n }\n\n if (!this.aborted) {\n logDebug(\n LOG_TAG,\n 'Aborting transaction:',\n error ? error.message : 'Client-initiated abort'\n );\n this.aborted = true;\n this.transaction.abort();\n }\n }\n\n maybeCommit(): void {\n // If the browser supports V3 IndexedDB, we invoke commit() explicitly to\n // speed up index DB processing if the event loop remains blocks.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const maybeV3IndexedDb = this.transaction as any;\n if (!this.aborted && typeof maybeV3IndexedDb.commit === 'function') {\n maybeV3IndexedDb.commit();\n }\n }\n\n /**\n * Returns a SimpleDbStore for the specified store. All\n * operations performed on the SimpleDbStore happen within the context of this\n * transaction and it cannot be used anymore once the transaction is\n * completed.\n *\n * Note that we can't actually enforce that the KeyType and ValueType are\n * correct, but they allow type safety through the rest of the consuming code.\n */\n store(\n storeName: string\n ): SimpleDbStore {\n const store = this.transaction.objectStore(storeName);\n debugAssert(!!store, 'Object store not part of transaction: ' + storeName);\n return new SimpleDbStore(store);\n }\n}\n\n/**\n * Provides a wrapper around IndexedDb with a simplified interface that uses\n * Promise-like return values to chain operations. Real promises cannot be used\n * since .then() continuations are executed asynchronously (e.g. via\n * .setImmediate), which would cause IndexedDB to end the transaction.\n * See PersistencePromise for more details.\n */\nexport class SimpleDb {\n private db?: IDBDatabase;\n private lastClosedDbVersion: number | null = null;\n private versionchangelistener?: (event: IDBVersionChangeEvent) => void;\n\n /** Deletes the specified database. */\n static delete(name: string): Promise {\n logDebug(LOG_TAG, 'Removing database:', name);\n const globals = getGlobal();\n return wrapRequest(\n globals.indexedDB.deleteDatabase(name)\n ).toPromise();\n }\n\n /** Returns true if IndexedDB is available in the current environment. */\n static isAvailable(): boolean {\n if (!isIndexedDBAvailable()) {\n return false;\n }\n\n if (SimpleDb.isMockPersistence()) {\n return true;\n }\n\n // We extensively use indexed array values and compound keys,\n // which IE and Edge do not support. However, they still have indexedDB\n // defined on the window, so we need to check for them here and make sure\n // to return that persistence is not enabled for those browsers.\n // For tracking support of this feature, see here:\n // https://developer.microsoft.com/en-us/microsoft-edge/platform/status/indexeddbarraysandmultientrysupport/\n\n // Check the UA string to find out the browser.\n const ua = getUA();\n\n // IE 10\n // ua = 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)';\n\n // IE 11\n // ua = 'Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko';\n\n // Edge\n // ua = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML,\n // like Gecko) Chrome/39.0.2171.71 Safari/537.36 Edge/12.0';\n\n // iOS Safari: Disable for users running iOS version < 10.\n const iOSVersion = SimpleDb.getIOSVersion(ua);\n const isUnsupportedIOS = 0 < iOSVersion && iOSVersion < 10;\n\n // Android browser: Disable for users running version < 4.5.\n const androidVersion = getAndroidVersion(ua);\n const isUnsupportedAndroid = 0 < androidVersion && androidVersion < 4.5;\n\n if (\n ua.indexOf('MSIE ') > 0 ||\n ua.indexOf('Trident/') > 0 ||\n ua.indexOf('Edge/') > 0 ||\n isUnsupportedIOS ||\n isUnsupportedAndroid\n ) {\n return false;\n } else {\n return true;\n }\n }\n\n /**\n * Returns true if the backing IndexedDB store is the Node IndexedDBShim\n * (see https://github.com/axemclion/IndexedDBShim).\n */\n static isMockPersistence(): boolean {\n return (\n typeof process !== 'undefined' &&\n process.env?.USE_MOCK_PERSISTENCE === 'YES'\n );\n }\n\n /** Helper to get a typed SimpleDbStore from a transaction. */\n static getStore(\n txn: SimpleDbTransaction,\n store: string\n ): SimpleDbStore {\n return txn.store(store);\n }\n\n // visible for testing\n /** Parse User Agent to determine iOS version. Returns -1 if not found. */\n static getIOSVersion(ua: string): number {\n const iOSVersionRegex = ua.match(/i(?:phone|pad|pod) os ([\\d_]+)/i);\n const version = iOSVersionRegex\n ? iOSVersionRegex[1].split('_').slice(0, 2).join('.')\n : '-1';\n return Number(version);\n }\n\n /*\n * Creates a new SimpleDb wrapper for IndexedDb database `name`.\n *\n * Note that `version` must not be a downgrade. IndexedDB does not support\n * downgrading the schema version. We currently do not support any way to do\n * versioning outside of IndexedDB's versioning mechanism, as only\n * version-upgrade transactions are allowed to do things like create\n * objectstores.\n */\n constructor(\n private readonly name: string,\n private readonly version: number,\n private readonly schemaConverter: SimpleDbSchemaConverter\n ) {\n debugAssert(\n SimpleDb.isAvailable(),\n 'IndexedDB not supported in current environment.'\n );\n\n const iOSVersion = SimpleDb.getIOSVersion(getUA());\n // NOTE: According to https://bugs.webkit.org/show_bug.cgi?id=197050, the\n // bug we're checking for should exist in iOS >= 12.2 and < 13, but for\n // whatever reason it's much harder to hit after 12.2 so we only proactively\n // log on 12.2.\n if (iOSVersion === 12.2) {\n logError(\n 'Firestore persistence suffers from a bug in iOS 12.2 ' +\n 'Safari that may cause your app to stop working. See ' +\n 'https://stackoverflow.com/q/56496296/110915 for details ' +\n 'and a potential workaround.'\n );\n }\n }\n\n /**\n * Opens the specified database, creating or upgrading it if necessary.\n */\n async ensureDb(action: string): Promise {\n if (!this.db) {\n logDebug(LOG_TAG, 'Opening database:', this.name);\n this.db = await new Promise((resolve, reject) => {\n // TODO(mikelehen): Investigate browser compatibility.\n // https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API/Using_IndexedDB\n // suggests IE9 and older WebKit browsers handle upgrade\n // differently. They expect setVersion, as described here:\n // https://developer.mozilla.org/en-US/docs/Web/API/IDBVersionChangeRequest/setVersion\n const request = indexedDB.open(this.name, this.version);\n\n request.onsuccess = (event: Event) => {\n const db = (event.target as IDBOpenDBRequest).result;\n resolve(db);\n };\n\n request.onblocked = () => {\n reject(\n new IndexedDbTransactionError(\n action,\n 'Cannot upgrade IndexedDB schema while another tab is open. ' +\n 'Close all tabs that access Firestore and reload this page to proceed.'\n )\n );\n };\n\n request.onerror = (event: Event) => {\n const error: DOMException = (event.target as IDBOpenDBRequest).error!;\n if (error.name === 'VersionError') {\n reject(\n new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'A newer version of the Firestore SDK was previously used and so the persisted ' +\n 'data is not compatible with the version of the SDK you are now using. The SDK ' +\n 'will operate with persistence disabled. If you need persistence, please ' +\n 're-upgrade to a newer version of the SDK or else clear the persisted IndexedDB ' +\n 'data for your app to start fresh.'\n )\n );\n } else if (error.name === 'InvalidStateError') {\n reject(\n new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'Unable to open an IndexedDB connection. This could be due to running in a ' +\n 'private browsing session on a browser whose private browsing sessions do not ' +\n 'support IndexedDB: ' +\n error\n )\n );\n } else {\n reject(new IndexedDbTransactionError(action, error));\n }\n };\n\n request.onupgradeneeded = (event: IDBVersionChangeEvent) => {\n logDebug(\n LOG_TAG,\n 'Database \"' + this.name + '\" requires upgrade from version:',\n event.oldVersion\n );\n const db = (event.target as IDBOpenDBRequest).result;\n this.schemaConverter\n .createOrUpgrade(\n db,\n request.transaction!,\n event.oldVersion,\n this.version\n )\n .next(() => {\n logDebug(\n LOG_TAG,\n 'Database upgrade to version ' + this.version + ' complete'\n );\n });\n };\n });\n }\n\n if (this.versionchangelistener) {\n this.db.onversionchange = event => this.versionchangelistener!(event);\n }\n\n return this.db;\n }\n\n setVersionChangeListener(\n versionChangeListener: (event: IDBVersionChangeEvent) => void\n ): void {\n this.versionchangelistener = versionChangeListener;\n if (this.db) {\n this.db.onversionchange = (event: IDBVersionChangeEvent) => {\n return versionChangeListener(event);\n };\n }\n }\n\n async runTransaction(\n action: string,\n mode: SimpleDbTransactionMode,\n objectStores: string[],\n transactionFn: (transaction: SimpleDbTransaction) => PersistencePromise\n ): Promise {\n const readonly = mode === 'readonly';\n let attemptNumber = 0;\n\n while (true) {\n ++attemptNumber;\n\n try {\n this.db = await this.ensureDb(action);\n\n const transaction = SimpleDbTransaction.open(\n this.db,\n action,\n readonly ? 'readonly' : 'readwrite',\n objectStores\n );\n const transactionFnResult = transactionFn(transaction)\n .next(result => {\n transaction.maybeCommit();\n return result;\n })\n .catch(error => {\n // Abort the transaction if there was an error.\n transaction.abort(error);\n // We cannot actually recover, and calling `abort()` will cause the transaction's\n // completion promise to be rejected. This in turn means that we won't use\n // `transactionFnResult` below. We return a rejection here so that we don't add the\n // possibility of returning `void` to the type of `transactionFnResult`.\n return PersistencePromise.reject(error);\n })\n .toPromise();\n\n // As noted above, errors are propagated by aborting the transaction. So\n // we swallow any error here to avoid the browser logging it as unhandled.\n transactionFnResult.catch(() => {});\n\n // Wait for the transaction to complete (i.e. IndexedDb's onsuccess event to\n // fire), but still return the original transactionFnResult back to the\n // caller.\n await transaction.completionPromise;\n return transactionFnResult;\n } catch (e) {\n const error = e as Error;\n // TODO(schmidt-sebastian): We could probably be smarter about this and\n // not retry exceptions that are likely unrecoverable (such as quota\n // exceeded errors).\n\n // Note: We cannot use an instanceof check for FirestoreException, since the\n // exception is wrapped in a generic error by our async/await handling.\n const retryable =\n error.name !== 'FirebaseError' &&\n attemptNumber < TRANSACTION_RETRY_COUNT;\n logDebug(\n LOG_TAG,\n 'Transaction failed with error:',\n error.message,\n 'Retrying:',\n retryable\n );\n\n this.close();\n\n if (!retryable) {\n return Promise.reject(error);\n }\n }\n }\n }\n\n close(): void {\n if (this.db) {\n this.db.close();\n }\n this.db = undefined;\n }\n}\n\n/** Parse User Agent to determine Android version. Returns -1 if not found. */\nexport function getAndroidVersion(ua: string): number {\n const androidVersionRegex = ua.match(/Android ([\\d.]+)/i);\n const version = androidVersionRegex\n ? androidVersionRegex[1].split('.').slice(0, 2).join('.')\n : '-1';\n return Number(version);\n}\n\n/**\n * A controller for iterating over a key range or index. It allows an iterate\n * callback to delete the currently-referenced object, or jump to a new key\n * within the key range or index.\n */\nexport class IterationController {\n private shouldStop = false;\n private nextKey: IDBValidKey | null = null;\n\n constructor(private dbCursor: IDBCursorWithValue) {}\n\n get isDone(): boolean {\n return this.shouldStop;\n }\n\n get skipToKey(): IDBValidKey | null {\n return this.nextKey;\n }\n\n set cursor(value: IDBCursorWithValue) {\n this.dbCursor = value;\n }\n\n /**\n * This function can be called to stop iteration at any point.\n */\n done(): void {\n this.shouldStop = true;\n }\n\n /**\n * This function can be called to skip to that next key, which could be\n * an index or a primary key.\n */\n skip(key: IDBValidKey): void {\n this.nextKey = key;\n }\n\n /**\n * Delete the current cursor value from the object store.\n *\n * NOTE: You CANNOT do this with a keysOnly query.\n */\n delete(): PersistencePromise {\n return wrapRequest(this.dbCursor.delete());\n }\n}\n\n/**\n * Callback used with iterate() method.\n */\nexport type IterateCallback = (\n key: KeyType,\n value: ValueType,\n control: IterationController\n) => void | PersistencePromise;\n\n/** Options available to the iterate() method. */\nexport interface IterateOptions {\n /** Index to iterate over (else primary keys will be iterated) */\n index?: string;\n\n /** IndexedDB Range to iterate over (else entire store will be iterated) */\n range?: IDBKeyRange;\n\n /** If true, values aren't read while iterating. */\n keysOnly?: boolean;\n\n /** If true, iterate over the store in reverse. */\n reverse?: boolean;\n}\n\n/** An error that wraps exceptions that thrown during IndexedDB execution. */\nexport class IndexedDbTransactionError extends FirestoreError {\n name = 'IndexedDbTransactionError';\n\n constructor(actionName: string, cause: Error | string) {\n super(\n Code.UNAVAILABLE,\n `IndexedDB transaction '${actionName}' failed: ${cause}`\n );\n }\n}\n\n/** Verifies whether `e` is an IndexedDbTransactionError. */\nexport function isIndexedDbTransactionError(e: Error): boolean {\n // Use name equality, as instanceof checks on errors don't work with errors\n // that wrap other errors.\n return e.name === 'IndexedDbTransactionError';\n}\n\n/**\n * A wrapper around an IDBObjectStore providing an API that:\n *\n * 1) Has generic KeyType / ValueType parameters to provide strongly-typed\n * methods for acting against the object store.\n * 2) Deals with IndexedDB's onsuccess / onerror event callbacks, making every\n * method return a PersistencePromise instead.\n * 3) Provides a higher-level API to avoid needing to do excessive wrapping of\n * intermediate IndexedDB types (IDBCursorWithValue, etc.)\n */\nexport class SimpleDbStore<\n KeyType extends IDBValidKey,\n ValueType extends unknown\n> {\n constructor(private store: IDBObjectStore) {}\n\n /**\n * Writes a value into the Object Store.\n *\n * @param key - Optional explicit key to use when writing the object, else the\n * key will be auto-assigned (e.g. via the defined keyPath for the store).\n * @param value - The object to write.\n */\n put(value: ValueType): PersistencePromise;\n put(key: KeyType, value: ValueType): PersistencePromise;\n put(\n keyOrValue: KeyType | ValueType,\n value?: ValueType\n ): PersistencePromise {\n let request;\n if (value !== undefined) {\n logDebug(LOG_TAG, 'PUT', this.store.name, keyOrValue, value);\n request = this.store.put(value, keyOrValue as KeyType);\n } else {\n logDebug(LOG_TAG, 'PUT', this.store.name, '', keyOrValue);\n request = this.store.put(keyOrValue as ValueType);\n }\n return wrapRequest(request);\n }\n\n /**\n * Adds a new value into an Object Store and returns the new key. Similar to\n * IndexedDb's `add()`, this method will fail on primary key collisions.\n *\n * @param value - The object to write.\n * @returns The key of the value to add.\n */\n add(value: ValueType): PersistencePromise {\n logDebug(LOG_TAG, 'ADD', this.store.name, value, value);\n const request = this.store.add(value as ValueType);\n return wrapRequest(request);\n }\n\n /**\n * Gets the object with the specified key from the specified store, or null\n * if no object exists with the specified key.\n *\n * @key The key of the object to get.\n * @returns The object with the specified key or null if no object exists.\n */\n get(key: KeyType): PersistencePromise {\n const request = this.store.get(key);\n // We're doing an unsafe cast to ValueType.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return wrapRequest(request).next(result => {\n // Normalize nonexistence to null.\n if (result === undefined) {\n result = null;\n }\n logDebug(LOG_TAG, 'GET', this.store.name, key, result);\n return result;\n });\n }\n\n delete(key: KeyType | IDBKeyRange): PersistencePromise {\n logDebug(LOG_TAG, 'DELETE', this.store.name, key);\n const request = this.store.delete(key);\n return wrapRequest(request);\n }\n\n /**\n * If we ever need more of the count variants, we can add overloads. For now,\n * all we need is to count everything in a store.\n *\n * Returns the number of rows in the store.\n */\n count(): PersistencePromise {\n logDebug(LOG_TAG, 'COUNT', this.store.name);\n const request = this.store.count();\n return wrapRequest(request);\n }\n\n /** Loads all elements from the object store. */\n loadAll(): PersistencePromise;\n /** Loads all elements for the index range from the object store. */\n loadAll(range: IDBKeyRange): PersistencePromise;\n /** Loads all elements ordered by the given index. */\n loadAll(index: string): PersistencePromise;\n /**\n * Loads all elements from the object store that fall into the provided in the\n * index range for the given index.\n */\n loadAll(index: string, range: IDBKeyRange): PersistencePromise;\n loadAll(\n indexOrRange?: string | IDBKeyRange,\n range?: IDBKeyRange\n ): PersistencePromise {\n const iterateOptions = this.options(indexOrRange, range);\n // Use `getAll()` if the browser supports IndexedDB v3, as it is roughly\n // 20% faster.\n const store = iterateOptions.index\n ? this.store.index(iterateOptions.index)\n : this.store;\n if (typeof store.getAll === 'function') {\n const request = store.getAll(iterateOptions.range);\n return new PersistencePromise((resolve, reject) => {\n request.onerror = (event: Event) => {\n reject((event.target as IDBRequest).error!);\n };\n request.onsuccess = (event: Event) => {\n resolve((event.target as IDBRequest).result);\n };\n });\n } else {\n const cursor = this.cursor(iterateOptions);\n const results: ValueType[] = [];\n return this.iterateCursor(cursor, (key, value) => {\n results.push(value);\n }).next(() => {\n return results;\n });\n }\n }\n\n /**\n * Loads the first `count` elements from the provided index range. Loads all\n * elements if no limit is provided.\n */\n loadFirst(\n range: IDBKeyRange,\n count: number | null\n ): PersistencePromise {\n const request = this.store.getAll(\n range,\n count === null ? undefined : count\n );\n return new PersistencePromise((resolve, reject) => {\n request.onerror = (event: Event) => {\n reject((event.target as IDBRequest).error!);\n };\n request.onsuccess = (event: Event) => {\n resolve((event.target as IDBRequest).result);\n };\n });\n }\n\n deleteAll(): PersistencePromise;\n deleteAll(range: IDBKeyRange): PersistencePromise;\n deleteAll(index: string, range: IDBKeyRange): PersistencePromise;\n deleteAll(\n indexOrRange?: string | IDBKeyRange,\n range?: IDBKeyRange\n ): PersistencePromise {\n logDebug(LOG_TAG, 'DELETE ALL', this.store.name);\n const options = this.options(indexOrRange, range);\n options.keysOnly = false;\n const cursor = this.cursor(options);\n return this.iterateCursor(cursor, (key, value, control) => {\n // NOTE: Calling delete() on a cursor is documented as more efficient than\n // calling delete() on an object store with a single key\n // (https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/delete),\n // however, this requires us *not* to use a keysOnly cursor\n // (https://developer.mozilla.org/en-US/docs/Web/API/IDBCursor/delete). We\n // may want to compare the performance of each method.\n return control.delete();\n });\n }\n\n /**\n * Iterates over keys and values in an object store.\n *\n * @param options - Options specifying how to iterate the objects in the\n * store.\n * @param callback - will be called for each iterated object. Iteration can be\n * canceled at any point by calling the doneFn passed to the callback.\n * The callback can return a PersistencePromise if it performs async\n * operations but note that iteration will continue without waiting for them\n * to complete.\n * @returns A PersistencePromise that resolves once all PersistencePromises\n * returned by callbacks resolve.\n */\n iterate(\n callback: IterateCallback\n ): PersistencePromise;\n iterate(\n options: IterateOptions,\n callback: IterateCallback\n ): PersistencePromise;\n iterate(\n optionsOrCallback: IterateOptions | IterateCallback,\n callback?: IterateCallback\n ): PersistencePromise {\n let options;\n if (!callback) {\n options = {};\n callback = optionsOrCallback as IterateCallback;\n } else {\n options = optionsOrCallback as IterateOptions;\n }\n const cursor = this.cursor(options);\n return this.iterateCursor(cursor, callback);\n }\n\n /**\n * Iterates over a store, but waits for the given callback to complete for\n * each entry before iterating the next entry. This allows the callback to do\n * asynchronous work to determine if this iteration should continue.\n *\n * The provided callback should return `true` to continue iteration, and\n * `false` otherwise.\n */\n iterateSerial(\n callback: (k: KeyType, v: ValueType) => PersistencePromise\n ): PersistencePromise {\n const cursorRequest = this.cursor({});\n return new PersistencePromise((resolve, reject) => {\n cursorRequest.onerror = (event: Event) => {\n const error = checkForAndReportiOSError(\n (event.target as IDBRequest).error!\n );\n reject(error);\n };\n cursorRequest.onsuccess = (event: Event) => {\n const cursor: IDBCursorWithValue = (event.target as IDBRequest).result;\n if (!cursor) {\n resolve();\n return;\n }\n\n callback(cursor.primaryKey as KeyType, cursor.value).next(\n shouldContinue => {\n if (shouldContinue) {\n cursor.continue();\n } else {\n resolve();\n }\n }\n );\n };\n });\n }\n\n private iterateCursor(\n cursorRequest: IDBRequest,\n fn: IterateCallback\n ): PersistencePromise {\n const results: Array> = [];\n return new PersistencePromise((resolve, reject) => {\n cursorRequest.onerror = (event: Event) => {\n reject((event.target as IDBRequest).error!);\n };\n cursorRequest.onsuccess = (event: Event) => {\n const cursor: IDBCursorWithValue = (event.target as IDBRequest).result;\n if (!cursor) {\n resolve();\n return;\n }\n const controller = new IterationController(cursor);\n const userResult = fn(\n cursor.primaryKey as KeyType,\n cursor.value,\n controller\n );\n if (userResult instanceof PersistencePromise) {\n const userPromise: PersistencePromise = userResult.catch(\n err => {\n controller.done();\n return PersistencePromise.reject(err);\n }\n );\n results.push(userPromise);\n }\n if (controller.isDone) {\n resolve();\n } else if (controller.skipToKey === null) {\n cursor.continue();\n } else {\n cursor.continue(controller.skipToKey);\n }\n };\n }).next(() => PersistencePromise.waitFor(results));\n }\n\n private options(\n indexOrRange?: string | IDBKeyRange,\n range?: IDBKeyRange\n ): IterateOptions {\n let indexName: string | undefined = undefined;\n if (indexOrRange !== undefined) {\n if (typeof indexOrRange === 'string') {\n indexName = indexOrRange;\n } else {\n debugAssert(\n range === undefined,\n '3rd argument must not be defined if 2nd is a range.'\n );\n range = indexOrRange;\n }\n }\n return { index: indexName, range };\n }\n\n private cursor(options: IterateOptions): IDBRequest {\n let direction: IDBCursorDirection = 'next';\n if (options.reverse) {\n direction = 'prev';\n }\n if (options.index) {\n const index = this.store.index(options.index);\n if (options.keysOnly) {\n return index.openKeyCursor(options.range, direction);\n } else {\n return index.openCursor(options.range, direction);\n }\n } else {\n return this.store.openCursor(options.range, direction);\n }\n }\n}\n\n/**\n * Wraps an IDBRequest in a PersistencePromise, using the onsuccess / onerror\n * handlers to resolve / reject the PersistencePromise as appropriate.\n */\nfunction wrapRequest(request: IDBRequest): PersistencePromise {\n return new PersistencePromise((resolve, reject) => {\n request.onsuccess = (event: Event) => {\n const result = (event.target as IDBRequest).result;\n resolve(result);\n };\n\n request.onerror = (event: Event) => {\n const error = checkForAndReportiOSError(\n (event.target as IDBRequest).error!\n );\n reject(error);\n };\n });\n}\n\n// Guard so we only report the error once.\nlet reportedIOSError = false;\nfunction checkForAndReportiOSError(error: DOMException): Error {\n const iOSVersion = SimpleDb.getIOSVersion(getUA());\n if (iOSVersion >= 12.2 && iOSVersion < 13) {\n const IOS_ERROR =\n 'An internal error was encountered in the Indexed Database server';\n if (error.message.indexOf(IOS_ERROR) >= 0) {\n // Wrap error in a more descriptive one.\n const newError = new FirestoreError(\n 'internal',\n `IOS_INDEXEDDB_BUG1: IndexedDb has thrown '${IOS_ERROR}'. This is likely ` +\n `due to an unavoidable bug in iOS. See https://stackoverflow.com/q/56496296/110915 ` +\n `for details and a potential workaround.`\n );\n if (!reportedIOSError) {\n reportedIOSError = true;\n // Throw a global exception outside of this promise chain, for the user to\n // potentially catch.\n setTimeout(() => {\n throw newError;\n }, 0);\n }\n return newError;\n }\n }\n return error;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getModularInstance } from '@firebase/util';\n\nimport { Transaction as InternalTransaction } from '../core/transaction';\nimport {\n DEFAULT_TRANSACTION_OPTIONS,\n TransactionOptions as TransactionOptionsInternal,\n validateTransactionOptions\n} from '../core/transaction_options';\nimport { TransactionRunner } from '../core/transaction_runner';\nimport { fail } from '../util/assert';\nimport { newAsyncQueue } from '../util/async_queue_impl';\nimport { cast } from '../util/input_validation';\nimport { Deferred } from '../util/promise';\n\nimport { getDatastore } from './components';\nimport { Firestore } from './database';\nimport { FieldPath } from './field_path';\nimport {\n DocumentData,\n DocumentReference,\n PartialWithFieldValue,\n SetOptions,\n UpdateData,\n WithFieldValue\n} from './reference';\nimport {\n applyFirestoreDataConverter,\n LiteUserDataWriter\n} from './reference_impl';\nimport { DocumentSnapshot } from './snapshot';\nimport { TransactionOptions } from './transaction_options';\nimport {\n newUserDataReader,\n parseSetData,\n parseUpdateData,\n parseUpdateVarargs,\n UserDataReader\n} from './user_data_reader';\nimport { validateReference } from './write_batch';\n\n// TODO(mrschmidt) Consider using `BaseTransaction` as the base class in the\n// legacy SDK.\n\n/**\n * A reference to a transaction.\n *\n * The `Transaction` object passed to a transaction's `updateFunction` provides\n * the methods to read and write data within the transaction context. See\n * {@link runTransaction}.\n */\nexport class Transaction {\n // This is the tree-shakeable version of the Transaction class used in the\n // legacy SDK. The class is a close copy but takes different input and output\n // types. The firestore-exp SDK further extends this class to return its API\n // type.\n\n private readonly _dataReader: UserDataReader;\n\n /** @hideconstructor */\n constructor(\n protected readonly _firestore: Firestore,\n private readonly _transaction: InternalTransaction\n ) {\n this._dataReader = newUserDataReader(_firestore);\n }\n\n /**\n * Reads the document referenced by the provided {@link DocumentReference}.\n *\n * @param documentRef - A reference to the document to be read.\n * @returns A `DocumentSnapshot` with the read data.\n */\n get(\n documentRef: DocumentReference\n ): Promise> {\n const ref = validateReference(documentRef, this._firestore);\n const userDataWriter = new LiteUserDataWriter(this._firestore);\n return this._transaction.lookup([ref._key]).then(docs => {\n if (!docs || docs.length !== 1) {\n return fail(0x5de9, 'Mismatch in docs returned from document lookup.');\n }\n const doc = docs[0];\n if (doc.isFoundDocument()) {\n return new DocumentSnapshot(\n this._firestore,\n userDataWriter,\n doc.key,\n doc,\n ref.converter\n );\n } else if (doc.isNoDocument()) {\n return new DocumentSnapshot(\n this._firestore,\n userDataWriter,\n ref._key,\n null,\n ref.converter\n );\n } else {\n throw fail(\n 0x4801,\n 'BatchGetDocumentsRequest returned unexpected document',\n {\n doc\n }\n );\n }\n });\n }\n\n /**\n * Writes to the document referred to by the provided {@link\n * DocumentReference}. If the document does not exist yet, it will be created.\n *\n * @param documentRef - A reference to the document to be set.\n * @param data - An object of the fields and values for the document.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns This `Transaction` instance. Used for chaining method calls.\n */\n set(\n documentRef: DocumentReference,\n data: WithFieldValue\n ): this;\n /**\n * Writes to the document referred to by the provided {@link\n * DocumentReference}. If the document does not exist yet, it will be created.\n * If you provide `merge` or `mergeFields`, the provided data can be merged\n * into an existing document.\n *\n * @param documentRef - A reference to the document to be set.\n * @param data - An object of the fields and values for the document.\n * @param options - An object to configure the set behavior.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns This `Transaction` instance. Used for chaining method calls.\n */\n set(\n documentRef: DocumentReference,\n data: PartialWithFieldValue,\n options: SetOptions\n ): this;\n set(\n documentRef: DocumentReference,\n value: PartialWithFieldValue,\n options?: SetOptions\n ): this {\n const ref = validateReference(documentRef, this._firestore);\n const convertedValue = applyFirestoreDataConverter(\n ref.converter,\n value,\n options\n );\n const parsed = parseSetData(\n this._dataReader,\n 'Transaction.set',\n ref._key,\n convertedValue,\n ref.converter !== null,\n options\n );\n this._transaction.set(ref._key, parsed);\n return this;\n }\n\n /**\n * Updates fields in the document referred to by the provided {@link\n * DocumentReference}. The update will fail if applied to a document that does\n * not exist.\n *\n * @param documentRef - A reference to the document to be updated.\n * @param data - An object containing the fields and values with which to\n * update the document. Fields can contain dots to reference nested fields\n * within the document.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns This `Transaction` instance. Used for chaining method calls.\n */\n update(\n documentRef: DocumentReference,\n data: UpdateData\n ): this;\n /**\n * Updates fields in the document referred to by the provided {@link\n * DocumentReference}. The update will fail if applied to a document that does\n * not exist.\n *\n * Nested fields can be updated by providing dot-separated field path\n * strings or by providing `FieldPath` objects.\n *\n * @param documentRef - A reference to the document to be updated.\n * @param field - The first field to update.\n * @param value - The first value.\n * @param moreFieldsAndValues - Additional key/value pairs.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns This `Transaction` instance. Used for chaining method calls.\n */\n update(\n documentRef: DocumentReference,\n field: string | FieldPath,\n value: unknown,\n ...moreFieldsAndValues: unknown[]\n ): this;\n update(\n documentRef: DocumentReference,\n fieldOrUpdateData: string | FieldPath | UpdateData,\n value?: unknown,\n ...moreFieldsAndValues: unknown[]\n ): this {\n const ref = validateReference(documentRef, this._firestore);\n\n // For Compat types, we have to \"extract\" the underlying types before\n // performing validation.\n fieldOrUpdateData = getModularInstance(fieldOrUpdateData);\n\n let parsed;\n if (\n typeof fieldOrUpdateData === 'string' ||\n fieldOrUpdateData instanceof FieldPath\n ) {\n parsed = parseUpdateVarargs(\n this._dataReader,\n 'Transaction.update',\n ref._key,\n fieldOrUpdateData,\n value,\n moreFieldsAndValues\n );\n } else {\n parsed = parseUpdateData(\n this._dataReader,\n 'Transaction.update',\n ref._key,\n fieldOrUpdateData\n );\n }\n\n this._transaction.update(ref._key, parsed);\n return this;\n }\n\n /**\n * Deletes the document referred to by the provided {@link DocumentReference}.\n *\n * @param documentRef - A reference to the document to be deleted.\n * @returns This `Transaction` instance. Used for chaining method calls.\n */\n delete(\n documentRef: DocumentReference\n ): this {\n const ref = validateReference(documentRef, this._firestore);\n this._transaction.delete(ref._key);\n return this;\n }\n}\n\n/**\n * Executes the given `updateFunction` and then attempts to commit the changes\n * applied within the transaction. If any document read within the transaction\n * has changed, Cloud Firestore retries the `updateFunction`. If it fails to\n * commit after 5 attempts, the transaction fails.\n *\n * The maximum number of writes allowed in a single transaction is 500.\n *\n * @param firestore - A reference to the Firestore database to run this\n * transaction against.\n * @param updateFunction - The function to execute within the transaction\n * context.\n * @param options - An options object to configure maximum number of attempts to\n * commit.\n * @returns If the transaction completed successfully or was explicitly aborted\n * (the `updateFunction` returned a failed promise), the promise returned by the\n * `updateFunction `is returned here. Otherwise, if the transaction failed, a\n * rejected promise with the corresponding failure error is returned.\n */\nexport function runTransaction(\n firestore: Firestore,\n updateFunction: (transaction: Transaction) => Promise,\n options?: TransactionOptions\n): Promise {\n firestore = cast(firestore, Firestore);\n const datastore = getDatastore(firestore);\n const optionsWithDefaults: TransactionOptionsInternal = {\n ...DEFAULT_TRANSACTION_OPTIONS,\n ...options\n };\n validateTransactionOptions(optionsWithDefaults);\n const deferred = new Deferred();\n new TransactionRunner(\n newAsyncQueue(),\n datastore,\n optionsWithDefaults,\n internalTransaction =>\n updateFunction(new Transaction(firestore, internalTransaction)),\n deferred\n ).run();\n return deferred.promise;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n _registerComponent,\n registerVersion,\n SDK_VERSION\n} from '@firebase/app';\nimport { Component, ComponentType } from '@firebase/component';\n\nimport { version } from '../package.json';\nimport {\n LiteAppCheckTokenProvider,\n LiteAuthCredentialsProvider\n} from '../src/api/credentials';\nimport { databaseIdFromApp } from '../src/core/database_info';\nimport { setSDKVersion } from '../src/core/version';\nimport { Firestore } from '../src/lite-api/database';\n\ndeclare module '@firebase/component' {\n interface NameServiceMapping {\n 'firestore/lite': Firestore;\n }\n}\n\nexport function registerFirestore(): void {\n setSDKVersion(`${SDK_VERSION}_lite`);\n _registerComponent(\n new Component(\n 'firestore/lite',\n (container, { instanceIdentifier: databaseId, options: settings }) => {\n const app = container.getProvider('app').getImmediate()!;\n const firestoreInstance = new Firestore(\n new LiteAuthCredentialsProvider(\n container.getProvider('auth-internal')\n ),\n new LiteAppCheckTokenProvider(\n app,\n container.getProvider('app-check-internal')\n ),\n databaseIdFromApp(app, databaseId),\n app\n );\n if (settings) {\n firestoreInstance._setSettings(settings);\n }\n return firestoreInstance;\n },\n 'PUBLIC' as ComponentType.PUBLIC\n ).setMultipleInstances(true)\n );\n // RUNTIME_ENV and BUILD_TARGET are replaced by real values during the compilation\n registerVersion('firestore-lite', version, '__RUNTIME_ENV__');\n registerVersion('firestore-lite', version, '__BUILD_TARGET__');\n}\n","/**\n * Firestore Lite\n *\n * @remarks Firestore Lite is a small online-only SDK that allows read\n * and write access to your Firestore database. All operations connect\n * directly to the backend, and `onSnapshot()` APIs are not supported.\n * @packageDocumentation\n */\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { registerFirestore } from './register';\nregisterFirestore();\n\nexport {\n aggregateQuerySnapshotEqual,\n getCount,\n getAggregate,\n count,\n sum,\n average,\n aggregateFieldEqual\n} from '../src/lite-api/aggregate';\n\nexport {\n AggregateField,\n AggregateFieldType,\n AggregateSpec,\n AggregateSpecData,\n AggregateQuerySnapshot,\n AggregateType\n} from '../src/lite-api/aggregate_types';\n\nexport { FirestoreSettings as Settings } from '../src/lite-api/settings';\n\nexport {\n Firestore as Firestore,\n EmulatorMockTokenOptions,\n initializeFirestore,\n getFirestore,\n terminate,\n connectFirestoreEmulator\n} from '../src/lite-api/database';\n\nexport {\n DocumentData,\n UpdateData,\n WithFieldValue,\n PartialWithFieldValue,\n SetOptions,\n DocumentReference,\n Query,\n CollectionReference,\n collection,\n collectionGroup,\n doc,\n refEqual,\n queryEqual\n} from '../src/lite-api/reference';\n\nexport {\n and,\n endAt,\n endBefore,\n startAt,\n startAfter,\n limit,\n limitToLast,\n where,\n or,\n orderBy,\n query,\n QueryConstraint,\n QueryConstraintType,\n QueryCompositeFilterConstraint,\n QueryFilterConstraint,\n QueryFieldFilterConstraint,\n QueryOrderByConstraint,\n QueryLimitConstraint,\n QueryNonFilterConstraint,\n QueryStartAtConstraint,\n QueryEndAtConstraint,\n OrderByDirection,\n WhereFilterOp\n} from '../src/lite-api/query';\n\nexport {\n addDoc,\n deleteDoc,\n updateDoc,\n setDoc,\n getDoc,\n getDocs\n} from '../src/lite-api/reference_impl';\n\nexport {\n Primitive,\n NestedUpdateFields,\n ChildUpdateFields,\n AddPrefixToKeys,\n UnionToIntersection\n} from '../src/lite-api/types';\n\n// TODO(firestorelite): Add tests when Queries are usable\nexport { FieldPath, documentId } from '../src/lite-api/field_path';\n\n// TODO(firestorelite): Add tests when setDoc() is available\nexport { FieldValue } from '../src/lite-api/field_value';\n\nexport {\n increment,\n arrayRemove,\n arrayUnion,\n serverTimestamp,\n deleteField,\n vector\n} from '../src/lite-api/field_value_impl';\n\nexport {\n FirestoreDataConverter,\n DocumentSnapshot,\n QueryDocumentSnapshot,\n QuerySnapshot,\n snapshotEqual\n} from '../src/lite-api/snapshot';\n\nexport { VectorValue } from '../src/lite-api/vector_value';\n\nexport { WriteBatch, writeBatch } from '../src/lite-api/write_batch';\n\nexport { TransactionOptions } from '../src/lite-api/transaction_options';\n\nexport { Transaction, runTransaction } from '../src/lite-api/transaction';\n\nexport { setLogLevel, LogLevelString as LogLevel } from '../src/util/log';\n\nexport { Bytes } from '../src/lite-api/bytes';\n\nexport { GeoPoint } from '../src/lite-api/geo_point';\n\nexport { Timestamp } from '../src/lite-api/timestamp';\n\nexport { FirestoreErrorCode, FirestoreError } from '../src/util/error';\n"],"names":["User","constructor","uid","this","isAuthenticated","toKey","isEqual","otherUser","UNAUTHENTICATED","GOOGLE_CREDENTIALS","FIRST_PARTY","MOCK_USER","SDK_VERSION","__PRIVATE_logClient","Logger","setLogLevel","logLevel","__PRIVATE_logDebug","msg","obj","LogLevel","DEBUG","args","map","__PRIVATE_argToString","debug","__PRIVATE_logError","ERROR","error","__PRIVATE_logWarn","WARN","warn","__PRIVATE_formatJSON","value","JSON","stringify","e","fail","id","__PRIVATE_messageOrContext","context","message","__PRIVATE__fail","__PRIVATE_failure","toString","undefined","Error","__PRIVATE_hardAssert","assertion","__PRIVATE_debugCast","Code","FirestoreError","FirebaseError","code","super","name","__PRIVATE_Deferred","promise","Promise","resolve","reject","__PRIVATE_OAuthToken","user","type","headers","Map","set","__PRIVATE_EmptyAuthCredentialsProvider","getToken","invalidateToken","start","asyncQueue","changeListener","enqueueRetryable","shutdown","__PRIVATE_EmulatorAuthCredentialsProvider","token","__PRIVATE_LiteAuthCredentialsProvider","__PRIVATE_authProvider","auth","onInit","then","__PRIVATE_tokenData","accessToken","getUid","__PRIVATE_FirstPartyToken","__PRIVATE_sessionIndex","__PRIVATE_iamToken","__PRIVATE_authTokenFactory","__PRIVATE_getAuthToken","__PRIVATE__headers","__PRIVATE_authHeaderTokenValue","__PRIVATE_FirstPartyAuthCredentialsProvider","AppCheckToken","length","__PRIVATE_LiteAppCheckTokenProvider","app","__PRIVATE_appCheckProvider","appCheck","__PRIVATE_serverAppAppCheckToken","_isFirebaseServerApp","settings","appCheckToken","tokenResult","DatabaseInfo","databaseId","appId","persistenceKey","host","ssl","forceLongPolling","autoDetectLongPolling","longPollingOptions","useFetchStreams","isUsingEmulator","__PRIVATE_DEFAULT_DATABASE_NAME","DatabaseId","projectId","database","empty","isDefaultDatabase","other","__PRIVATE_randomBytes","__PRIVATE_nBytes","crypto","self","bytes","Uint8Array","getRandomValues","__PRIVATE_i","Math","floor","random","__PRIVATE_AutoId","newId","__PRIVATE_chars","__PRIVATE_maxMultiple","__PRIVATE_autoId","charAt","__PRIVATE_primitiveComparator","left","right","__PRIVATE_compareUtf8Strings","min","__PRIVATE_leftChar","__PRIVATE_rightChar","__PRIVATE_isSurrogate","__PRIVATE_MIN_SURROGATE","__PRIVATE_MAX_SURROGATE","s","c","charCodeAt","__PRIVATE_arrayEquals","comparator","every","index","__PRIVATE_DOCUMENT_KEY_NAME","BasePath","segments","offset","range","len","child","nameOrPath","slice","limit","forEach","segment","push","construct","popFirst","size","popLast","firstSegment","lastSegment","get","isEmpty","isPrefixOf","isImmediateParentOf","potentialChild","fn","end","toArray","p1","p2","comparison","compareSegments","__PRIVATE_lhs","__PRIVATE_rhs","__PRIVATE_isLhsNumeric","isNumericId","__PRIVATE_isRhsNumeric","extractNumericId","compare","startsWith","endsWith","Integer","fromString","substring","ResourcePath","canonicalString","join","toUriEncodedString","encodeURIComponent","pathComponents","path","indexOf","split","filter","emptyPath","__PRIVATE_identifierRegExp","FieldPath","isValidIdentifier","test","str","replace","isKeyField","keyField","fromServerFormat","current","__PRIVATE_addCurrentSegment","__PRIVATE_inBackticks","next","DocumentKey","fromPath","fromName","collectionGroup","hasCollectionId","collectionId","getCollectionGroup","getCollectionPath","k1","k2","isDocumentKey","fromSegments","__PRIVATE_validateNonEmptyArgument","__PRIVATE_functionName","__PRIVATE_argumentName","__PRIVATE_argument","__PRIVATE_validateDocumentPath","__PRIVATE_validateCollectionPath","__PRIVATE_isPlainObject","input","Object","getPrototypeOf","prototype","__PRIVATE_valueDescription","Array","__PRIVATE_customObjectName","__PRIVATE_tryGetCustomObjectType","__PRIVATE_cast","_delegate","description","__PRIVATE_validatePositiveNumber","n","__PRIVATE_cloneLongPollingOptions","options","clone","timeoutSeconds","__PRIVATE_lastUniqueDebugId","__PRIVATE_generateUniqueDebugId","__PRIVATE_generateInitialUniqueDebugId","round","__PRIVATE_maxResult","__PRIVATE_isNullOrUndefined","__PRIVATE_isNegativeZero","__PRIVATE_LOG_TAG","__PRIVATE_RPC_NAME_URL_MAPPING","__PRIVATE_RestConnection","__PRIVATE_shouldResourcePathBeIncludedInRequest","databaseInfo","proto","__PRIVATE_baseUrl","__PRIVATE_databasePath","__PRIVATE_requestParams","__PRIVATE_invokeRPC","__PRIVATE_rpcName","__PRIVATE_req","__PRIVATE_authToken","streamId","url","__PRIVATE_makeUrl","__PRIVATE_modifyHeadersForRequest","URL","__PRIVATE_forwardCredentials","isCloudWorkstation","__PRIVATE_performRPCRequest","response","err","__PRIVATE_invokeStreamingRPC","request","__PRIVATE_expectedResponseCount","__PRIVATE_getGoogApiClientValue","key","__PRIVATE_urlRpcName","terminate","__PRIVATE_RpcCode","RpcCode","__PRIVATE_mapCodeFromHttpStatus","status","__PRIVATE_FetchConnection","__PRIVATE_openStream","body","__PRIVATE_requestJson","__PRIVATE_fetchArgs","method","credentials","fetch","statusText","ok","__PRIVATE_errorResponse","json","isArray","__PRIVATE_errorMessage","__PRIVATE_AggregateImpl","alias","aggregateType","fieldPath","__PRIVATE_objectSize","count","hasOwnProperty","call","__PRIVATE_Base64DecodeError","ByteString","binaryString","fromBase64String","base64","__PRIVATE_decodeBase64","__PRIVATE_encoded","atob","DOMException","fromUint8Array","array","__PRIVATE_binaryStringFromUint8Array","String","fromCharCode","Symbol","iterator","done","toBase64","__PRIVATE_encodeBase64","raw","btoa","toUint8Array","__PRIVATE_uint8ArrayFromBinaryString","buffer","approximateByteSize","compareTo","EMPTY_BYTE_STRING","__PRIVATE_ISO_TIMESTAMP_REG_EXP","RegExp","__PRIVATE_normalizeTimestamp","date","nanos","__PRIVATE_fraction","exec","timestamp","__PRIVATE_nanoStr","substr","Number","__PRIVATE_parsedDate","Date","seconds","getTime","__PRIVATE_normalizeNumber","__PRIVATE_normalizeByteString","blob","property","typeString","__PRIVATE_optionalValue","result","__PRIVATE_validateJSON","__PRIVATE_schema","__PRIVATE_fieldValue","__PRIVATE_MIN_SECONDS","__PRIVATE_MS_TO_NANOS","Timestamp","now","fromMillis","fromDate","milliseconds","nanoseconds","toDate","toMillis","_compareTo","toJSON","_jsonSchemaVersion","fromJSON","_jsonSchema","valueOf","__PRIVATE_adjustedSeconds","padStart","__PRIVATE_isServerTimestamp","mapValue","fields","stringValue","__PRIVATE_getPreviousValue","previousValue","__PRIVATE_getLocalWriteTime","localWriteTime","timestampValue","__PRIVATE_TYPE_KEY","__PRIVATE_MAX_VALUE_TYPE","MAX_VALUE","__type__","__PRIVATE_VECTOR_VALUE_SENTINEL","__PRIVATE_VECTOR_MAP_VECTORS_KEY","__PRIVATE_typeOrder","__PRIVATE_isMaxValue","__PRIVATE_isVectorValue","__PRIVATE_valueEquals","__PRIVATE_leftType","booleanValue","__PRIVATE_timestampEquals","__PRIVATE_leftTimestamp","__PRIVATE_rightTimestamp","__PRIVATE_blobEquals","bytesValue","referenceValue","__PRIVATE_geoPointEquals","geoPointValue","latitude","longitude","__PRIVATE_numberEquals","integerValue","__PRIVATE_n1","doubleValue","__PRIVATE_n2","isNaN","arrayValue","values","__PRIVATE_objectEquals","__PRIVATE_leftMap","__PRIVATE_rightMap","__PRIVATE_arrayValueContains","__PRIVATE_haystack","__PRIVATE_needle","find","v","__PRIVATE_valueCompare","__PRIVATE_rightType","__PRIVATE_compareNumbers","__PRIVATE_leftNumber","__PRIVATE_rightNumber","__PRIVATE_compareTimestamps","__PRIVATE_compareBlobs","__PRIVATE_leftBytes","__PRIVATE_rightBytes","__PRIVATE_compareReferences","__PRIVATE_leftPath","__PRIVATE_rightPath","__PRIVATE_leftSegments","__PRIVATE_rightSegments","__PRIVATE_compareGeoPoints","__PRIVATE_compareArrays","__PRIVATE_compareVectors","__PRIVATE_leftArrayValue","__PRIVATE_rightArrayValue","__PRIVATE_lengthCompare","__PRIVATE_compareMaps","__PRIVATE_leftKeys","keys","__PRIVATE_rightKeys","sort","__PRIVATE_keyCompare","__PRIVATE_leftArray","__PRIVATE_rightArray","__PRIVATE_refValue","__PRIVATE_isNullValue","__PRIVATE_isNanValue","__PRIVATE_isMapValue","__PRIVATE_deepClone","source","target","val","Bound","position","inclusive","__PRIVATE_boundEquals","Filter","FieldFilter","field","op","create","createKeyFieldInFilter","__PRIVATE_KeyFieldFilter","__PRIVATE_ArrayContainsFilter","__PRIVATE_InFilter","__PRIVATE_NotInFilter","__PRIVATE_ArrayContainsAnyFilter","__PRIVATE_KeyFieldInFilter","__PRIVATE_KeyFieldNotInFilter","matches","doc","data","nullValue","matchesComparison","operator","isInequality","getFlattenedFilters","getFilters","CompositeFilter","filters","__PRIVATE_memoizedFlattenedFilters","__PRIVATE_compositeFilterIsConjunction","compositeFilter","reduce","__PRIVATE_subfilter","concat","assign","__PRIVATE_filterEquals","__PRIVATE_f1","__PRIVATE_f2","__PRIVATE_fieldFilterEquals","__PRIVATE_compositeFilterEquals","__PRIVATE_f1Filter","__PRIVATE_extractDocumentKeysFromArrayValue","some","OrderBy","dir","__PRIVATE_orderByEquals","SnapshotVersion","fromTimestamp","max","toMicroseconds","toTimestamp","SortedMap","root","LLRBNode","EMPTY","insert","copy","BLACK","remove","node","cmp","__PRIVATE_prunedNodes","minKey","maxKey","inorderTraversal","action","k","__PRIVATE_descriptions","reverseTraversal","getIterator","SortedMapIterator","getIteratorFrom","getReverseIterator","getReverseIteratorFrom","startKey","isReverse","nodeStack","getNext","pop","hasNext","peek","color","RED","fixUp","removeMin","isRed","moveRedLeft","__PRIVATE_smallest","rotateRight","moveRedRight","rotateLeft","colorFlip","__PRIVATE_nl","__PRIVATE_nr","checkMaxDepth","__PRIVATE_blackDepth","check","pow","LLRBEmptyNode","SortedSet","has","elem","first","last","cb","forEachInRange","iter","forEachWhile","firstAfterOrEqual","SortedSetIterator","add","unionWith","__PRIVATE_thisIt","__PRIVATE_otherIt","__PRIVATE_thisElem","__PRIVATE_otherElem","__PRIVATE_res","targetId","FieldMask","extraFields","__PRIVATE_mergedMaskSet","covers","__PRIVATE_fieldMaskPath","l","r","ObjectValue","__PRIVATE_currentLevel","getFieldsMap","setAll","parent","__PRIVATE_upserts","__PRIVATE_deletes","__PRIVATE_fieldsMap","applyChanges","__PRIVATE_nestedValue","__PRIVATE_inserts","MutableDocument","documentType","version","readTime","createTime","documentState","newInvalidDocument","documentKey","newFoundDocument","newNoDocument","newUnknownDocument","convertToFoundDocument","convertToNoDocument","convertToUnknownDocument","setHasCommittedMutations","setHasLocalMutations","setReadTime","hasLocalMutations","hasCommittedMutations","hasPendingWrites","isValidDocument","isFoundDocument","isNoDocument","isUnknownDocument","mutableCopy","__PRIVATE_TargetImpl","orderBy","startAt","endAt","__PRIVATE_memoizedCanonicalId","__PRIVATE_newTarget","__PRIVATE_QueryImpl","explicitOrderBy","limitType","__PRIVATE_memoizedNormalizedOrderBy","__PRIVATE_memoizedTarget","__PRIVATE_memoizedAggregateTarget","__PRIVATE_isCollectionGroupQuery","query","__PRIVATE_queryNormalizedOrderBy","__PRIVATE_queryImpl","__PRIVATE_fieldsNormalized","Set","__PRIVATE_lastDirection","__PRIVATE_inequalityFields","__PRIVATE_getInequalityFilterFields","__PRIVATE_queryToTarget","__PRIVATE__queryToTarget","__PRIVATE_orderBys","__PRIVATE_queryWithAddedFilter","__PRIVATE_newFilters","__PRIVATE_queryEquals","__PRIVATE_targetEquals","__PRIVATE_toDouble","serializer","useProto3Json","Infinity","toNumber","isSafeInteger","isInteger","MAX_SAFE_INTEGER","MIN_SAFE_INTEGER","__PRIVATE_toInteger","TransformOperation","_","__PRIVATE_ServerTimestampTransform","__PRIVATE_ArrayUnionTransformOperation","elements","__PRIVATE_ArrayRemoveTransformOperation","__PRIVATE_NumericIncrementTransformOperation","__PRIVATE_operand","FieldTransform","transform","Precondition","updateTime","exists","none","isNone","Mutation","__PRIVATE_SetMutation","precondition","fieldTransforms","getFieldMask","__PRIVATE_PatchMutation","fieldMask","__PRIVATE_DeleteMutation","__PRIVATE_VerifyMutation","__PRIVATE_DIRECTIONS","__PRIVATE_dirs","__PRIVATE_OPERATORS","__PRIVATE_ops","__PRIVATE_COMPOSITE_OPERATORS","JsonProtoSerializer","toISOString","__PRIVATE_toBytes","__PRIVATE_toVersion","__PRIVATE_fromVersion","__PRIVATE_toResourceName","__PRIVATE_toResourcePath","__PRIVATE_resourcePath","__PRIVATE_fullyQualifiedPrefixPath","__PRIVATE_toName","__PRIVATE_resource","__PRIVATE_fromResourceName","__PRIVATE_isValidResourceName","__PRIVATE_extractLocalPathFromResourceName","__PRIVATE_resourceName","__PRIVATE_toMutationDocument","__PRIVATE_fromBatchGetDocumentsResponse","__PRIVATE_fromFound","found","__PRIVATE_fromMissing","missing","toMutation","mutation","update","delete","updateMask","__PRIVATE_toDocumentMask","__PRIVATE_mutationType","verify","updateTransforms","__PRIVATE_toFieldTransform","__PRIVATE_fieldTransform","setToServerValue","appendMissingElements","removeAllFromArray","increment","currentDocument","__PRIVATE_toPrecondition","__PRIVATE_toQueryTarget","__PRIVATE_queryTarget","structuredQuery","from","allDescendants","__PRIVATE_toQueryPath","where","__PRIVATE_toFilters","__PRIVATE_toFilter","__PRIVATE_toOrder","order","__PRIVATE_toPropertyOrder","__PRIVATE_toFieldPathReference","direction","__PRIVATE_toDirection","__PRIVATE_toInt32Proto","__PRIVATE_toStartAtCursor","cursor","before","__PRIVATE_toEndAtCursor","__PRIVATE_toOperatorName","__PRIVATE_toCompositeOperatorName","__PRIVATE_toUnaryOrFieldFilter","unaryFilter","fieldFilter","__PRIVATE_toCompositeFilter","__PRIVATE_protos","__PRIVATE_canonicalFields","fieldPaths","__PRIVATE_newSerializer","__PRIVATE_ExponentialBackoff","__PRIVATE_queue","timerId","__PRIVATE_initialDelayMs","__PRIVATE_backoffFactor","__PRIVATE_maxDelayMs","__PRIVATE_currentBaseMs","__PRIVATE_timerPromise","reset","__PRIVATE_resetToMax","__PRIVATE_backoffAndRun","cancel","__PRIVATE_desiredDelayWithJitterMs","__PRIVATE_jitterDelayMs","__PRIVATE_delaySoFarMs","__PRIVATE_lastAttemptTime","__PRIVATE_remainingDelayMs","enqueueAfterDelay","__PRIVATE_skipBackoff","skipDelay","Datastore","__PRIVATE_DatastoreImpl","authCredentials","appCheckCredentials","connection","__PRIVATE_terminated","__PRIVATE_verifyInitialized","all","catch","async","__PRIVATE_invokeCommitRpc","datastore","mutations","__PRIVATE_datastoreImpl","writes","m","__PRIVATE_invokeBatchGetDocumentsRpc","documents","docs","__PRIVATE_invokeRunQueryRpc","M","document","__PRIVATE_fromDocument","__PRIVATE_invokeRunAggregationQueryRpc","__PRIVATE_aggregates","nt","__PRIVATE_aliasMap","__PRIVATE_toRunAggregationQueryRequest","__PRIVATE_skipAliasing","aggregations","__PRIVATE_aggregationNum","__PRIVATE_aggregate","__PRIVATE_serverAlias","avg","sum","structuredAggregationQuery","__PRIVATE_queryToAggregateTarget","__PRIVATE_filteredResult","__PRIVATE_unmappedAggregateFields","aggregateFields","__PRIVATE_accumulator","__PRIVATE_datastoreInstances","__PRIVATE_getDatastore","firestore","_terminated","__PRIVATE_newConnection","__PRIVATE_makeDatabaseInfo","experimentalForceLongPolling","experimentalAutoDetectLongPolling","experimentalLongPollingOptions","_databaseId","_persistenceKey","_freezeSettings","__PRIVATE_newDatastore","_authCredentials","_appCheckCredentials","__PRIVATE_LRU_MINIMUM_CACHE_SIZE_BYTES","__PRIVATE_DEFAULT_HOST","__PRIVATE_DEFAULT_SSL","FirestoreSettingsImpl","emulatorOptions","ignoreUndefinedProperties","localCache","cacheSizeBytes","__PRIVATE_validateIsNotUsedTogether","optionName1","argument1","optionName2","argument2","__PRIVATE_validateLongPollingOptions","__PRIVATE_longPollingOptionsEqual","__PRIVATE_options1","__PRIVATE_options2","Firestore","_app","_settings","_settingsFrozen","_emulatorOptions","_terminateTask","_initialized","_setSettings","__PRIVATE_makeAuthCredentialsProvider","_getSettings","_getEmulatorOptions","_delete","_terminate","_restart","__PRIVATE_removeComponents","initializeFirestore","provider","_getProvider","isInitialized","initialize","instanceIdentifier","getFirestore","__PRIVATE_appOrDatabaseId","__PRIVATE_optionalDatabaseId","getApp","db","getImmediate","identifier","__PRIVATE_emulator","getDefaultEmulatorHostnameAndPort","connectFirestoreEmulator","port","__PRIVATE_useSsl","__PRIVATE_existingConfig","__PRIVATE_newHostSetting","pingServer","updateEmulatorBanner","__PRIVATE_newConfig","deepEqual","mockUserToken","createMockUserToken","sub","user_id","_removeServiceInstance","AggregateField","_internalFieldPath","AggregateQuerySnapshot","_userDataWriter","_data","convertObjectMap","Query","converter","_query","withConverter","DocumentReference","_key","_path","CollectionReference","referencePath","__PRIVATE_newQueryForPath","parentPath","collection","pathSegments","getModularInstance","__PRIVATE_absolutePath","__PRIVATE_newQueryForCollectionGroup","arguments","refEqual","queryEqual","Bytes","byteString","_byteString","fieldNames","_internalPath","__PRIVATE_InternalFieldPath","documentId","FieldValue","_methodName","GeoPoint","isFinite","_lat","_long","VectorValue","_values","__PRIVATE_isPrimitiveArrayEqual","vectorValues","element","__PRIVATE_RESERVED_FIELD_REGEX","ParsedSetData","ParsedUpdateData","__PRIVATE_isWrite","__PRIVATE_dataSource","__PRIVATE_ParseContextImpl","__PRIVATE_validatePath","__PRIVATE_contextWith","configuration","__PRIVATE_childContextForField","__PRIVATE_childPath","__PRIVATE_arrayElement","__PRIVATE_validatePathSegment","__PRIVATE_childContextForFieldPath","__PRIVATE_childContextForArray","__PRIVATE_createError","reason","methodName","__PRIVATE_hasConverter","__PRIVATE_targetDoc","contains","__PRIVATE_UserDataReader","__PRIVATE_createContext","__PRIVATE_newUserDataReader","__PRIVATE_parseSetData","__PRIVATE_userDataReader","merge","mergeFields","__PRIVATE_validatePlainObject","__PRIVATE_updateData","__PRIVATE_parseObject","__PRIVATE_validatedFieldPaths","__PRIVATE_stringOrFieldPath","__PRIVATE_fieldPathFromArgument","__PRIVATE_fieldMaskContains","__PRIVATE_DeleteFieldValueImpl","_toFieldTransform","__PRIVATE_createSentinelChildContext","__PRIVATE_ServerTimestampFieldValueImpl","__PRIVATE_ArrayUnionFieldValueImpl","__PRIVATE__elements","__PRIVATE_parseContext","__PRIVATE_parsedElements","__PRIVATE_parseData","arrayUnion","__PRIVATE_ArrayRemoveFieldValueImpl","__PRIVATE_NumericIncrementFieldValueImpl","__PRIVATE__operand","__PRIVATE_numericIncrement","__PRIVATE_parseUpdateData","__PRIVATE_fieldMaskPaths","__PRIVATE_fieldPathFromDotSeparatedString","__PRIVATE_childContext","__PRIVATE_parsedValue","mask","__PRIVATE_parseUpdateVarargs","moreFieldsAndValues","__PRIVATE_parseQueryValue","__PRIVATE_allowArrays","__PRIVATE_looksLikeJsonObject","__PRIVATE_parseSentinelFieldValue","__PRIVATE_parseArray","__PRIVATE_entryIndex","entry","__PRIVATE_parsedEntry","__PRIVATE_parseScalarValue","__PRIVATE_thisDb","__PRIVATE_otherDb","__PRIVATE_parseVectorValue","__PRIVATE_FIELD_PATH_RESERVED","search","__PRIVATE_hasPath","__PRIVATE_hasDocument","DocumentSnapshot","_firestore","_document","_converter","ref","snapshot","QueryDocumentSnapshot","fromFirestore","convertValue","QuerySnapshot","_docs","callback","thisArg","snapshotEqual","arg","AppliableConstraint","QueryConstraint","__PRIVATE_queryConstraint","__PRIVATE_additionalQueryConstraints","queryConstraints","__PRIVATE_validateQueryConstraintArray","__PRIVATE_compositeFilterCount","QueryCompositeFilterConstraint","__PRIVATE_fieldFilterCount","QueryFieldFilterConstraint","constraint","_apply","_field","_op","_value","_create","_parse","__PRIVATE_validateNewFieldFilter","__PRIVATE_reader","__PRIVATE_newQueryFilter","__PRIVATE_dataReader","__PRIVATE_validateDisjunctiveFilterElements","__PRIVATE_referenceList","__PRIVATE_parseDocumentIdValue","opStr","_queryConstraints","__PRIVATE_parsedFilters","__PRIVATE_parsedFilter","_getOperator","__PRIVATE_validateNewFilter","__PRIVATE_testQuery","__PRIVATE_subFilters","__PRIVATE_subFilter","_getQueryConstraints","or","__PRIVATE_validateQueryFilterConstraint","and","QueryOrderByConstraint","_direction","__PRIVATE_newQueryOrderBy","__PRIVATE_queryWithAddedOrderBy","__PRIVATE_newOrderBy","directionStr","QueryLimitConstraint","_limit","_limitType","__PRIVATE_queryWithLimit","limitToLast","QueryStartAtConstraint","_docOrFields","_inclusive","bound","__PRIVATE_newQueryBoundFromDocOrFields","__PRIVATE_queryWithStartAt","__PRIVATE_docOrFields","startAfter","QueryEndAtConstraint","__PRIVATE_queryWithEndAt","endBefore","__PRIVATE_newQueryBoundFromDocument","components","__PRIVATE_newQueryBoundFromFields","__PRIVATE_rawValue","__PRIVATE_wrapped","__PRIVATE_documentIdValue","__PRIVATE_conflictingOp","__PRIVATE_findOpInsideFilters","__PRIVATE_operators","__PRIVATE_conflictingOps","AbstractUserDataWriter","serverTimestampBehavior","convertTimestamp","convertServerTimestamp","convertBytes","convertReference","convertGeoPoint","convertArray","convertObject","convertVectorValue","__PRIVATE_normalizedValue","convertDocumentKey","expectedDatabaseId","__PRIVATE_applyFirestoreDataConverter","__PRIVATE_convertedValue","toFirestore","__PRIVATE_LiteUserDataWriter","getDoc","reference","userDataWriter","getDocs","__PRIVATE_validateHasExplicitOrderByForLimitToLast","reverse","setDoc","__PRIVATE_parsed","updateDoc","__PRIVATE_fieldOrUpdateData","deleteDoc","addDoc","__PRIVATE_docRef","getCount","getAggregate","aggregateSpec","__PRIVATE_internalAggregates","__PRIVATE_mapToArray","__PRIVATE_aggregateResult","__PRIVATE_convertToAggregateQuerySnapshot","__PRIVATE_querySnapshot","average","aggregateFieldEqual","aggregateQuerySnapshotEqual","deleteField","serverTimestamp","arrayRemove","vector","WriteBatch","_commitHandler","_mutations","_committed","_dataReader","documentRef","_verifyNotCommitted","__PRIVATE_validateReference","commit","writeBatch","Transaction","readVersions","committed","lastTransactionError","writtenDocs","lookup","ensureCommitNotCalled","recordVersion","write","preconditionForUpdate","__PRIVATE_unwritten","__PRIVATE_docVersion","__PRIVATE_documentName","__PRIVATE_existingVersion","__PRIVATE_DEFAULT_TRANSACTION_OPTIONS","maxAttempts","__PRIVATE_TransactionRunner","updateFunction","deferred","__PRIVATE_attemptsRemaining","__PRIVATE_backoff","__PRIVATE_run","__PRIVATE_runWithBackOff","transaction","__PRIVATE_userPromise","__PRIVATE_tryRunUpdateFunction","enqueueAndForget","__PRIVATE_commitError","__PRIVATE_handleTransactionError","__PRIVATE_userPromiseError","__PRIVATE_isRetryableTransactionError","__PRIVATE_isPermanentError","getDocument","DelayedOperation","targetTimeMs","removalCallback","bind","createAndSchedule","delayMs","__PRIVATE_targetTime","__PRIVATE_delayedOp","timerHandle","setTimeout","handleDelayElapsed","clearTimeout","__PRIVATE_AsyncQueueImpl","__PRIVATE_tail","__PRIVATE_retryableOps","__PRIVATE__isShuttingDown","__PRIVATE_delayedOperations","__PRIVATE_operationInProgress","__PRIVATE_skipNonRestrictedTasks","__PRIVATE_timerIdsToSkip","__PRIVATE_visibilityHandler","visibilityState","addEventListener","isShuttingDown","enqueue","enqueueAndForgetEvenWhileRestricted","__PRIVATE_verifyNotFailed","__PRIVATE_enqueueInternal","enterRestrictedMode","purgeExistingTasks","removeEventListener","task","__PRIVATE_retryNextOp","shift","__PRIVATE_isIndexedDbTransactionError","__PRIVATE_newTail","__PRIVATE_getMessageOrStack","__PRIVATE_removedOp","__PRIVATE_removeDelayedOperation","__PRIVATE_messageOrStack","verifyOperationInProgress","__PRIVATE_drain","__PRIVATE_currentTail","__PRIVATE_containsDelayedOperation","__PRIVATE_runAllDelayedOperationsUntil","__PRIVATE_lastTimerId","a","b","__PRIVATE_skipDelaysForTimerId","splice","stack","includes","_transaction","runTransaction","__PRIVATE_optionsWithDefaults","__PRIVATE_validateTransactionOptions","__PRIVATE_newAsyncQueue","__PRIVATE_internalTransaction","__PRIVATE_registerFirestore","__PRIVATE_setSDKVersion","_registerComponent","Component","container","getProvider","__PRIVATE_firestoreInstance","__PRIVATE_databaseIdFromApp","apply","setMultipleInstances","registerVersion"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAqBaA,IAAAA,MAAAA,IAAAA,CAAAA;AAUX,IAAA,WAAAC,CAAqBC,CAAAA,EAAAA;AAAAC,QAAAA,IAAAA,CAAGD,GAAHA,GAAAA,CAAAA,CAAAA;AAAsB,KAAA;IAE3C,eAAAE,GAAAA;AACE,QAAA,OAAmB,QAAZD,IAAKD,CAAAA,GAAAA,CAAAA;AACb,KAAA;;;;WAMD,KAAAG,GAAAA;AACE,QAAA,OAAIF,IAAKC,CAAAA,eAAAA,EAAAA,GACA,MAASD,GAAAA,IAAAA,CAAKD,GAEd,GAAA,gBAAA,CAAA;AAEV,KAAA;AAED,IAAA,OAAAI,CAAQC,CAAAA,EAAAA;QACN,OAAOA,CAAAA,CAAUL,QAAQC,IAAKD,CAAAA,GAAAA,CAAAA;AAC/B,KAAA;;;+BA5BeM,IAAAA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7C,CCzCAioB,EAAAA;;;;"} \ No newline at end of file diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/index.cjs.js b/frontend-old/node_modules/@firebase/firestore/dist/lite/index.cjs.js new file mode 100644 index 0000000..e8ab979 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/index.cjs.js @@ -0,0 +1,7660 @@ +import { _registerComponent, registerVersion, _isFirebaseServerApp, _getProvider, getApp, _removeServiceInstance, SDK_VERSION } from '@firebase/app'; +import { Component } from '@firebase/component'; +import { Logger, LogLevel } from '@firebase/logger'; +import { FirebaseError, getDefaultEmulatorHostnameAndPort, isCloudWorkstation, pingServer, updateEmulatorBanner, deepEqual, createMockUserToken, getModularInstance } from '@firebase/util'; +import { Integer } from '@firebase/webchannel-wrapper/bloom-blob'; + +const P = "4.9.2"; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Simple wrapper around a nullable UID. Mostly exists to make code more + * readable. + */ class User { + constructor(t) { + this.uid = t; + } + isAuthenticated() { + return null != this.uid; + } + /** + * Returns a key representing this user, suitable for inclusion in a + * dictionary. + */ toKey() { + return this.isAuthenticated() ? "uid:" + this.uid : "anonymous-user"; + } + isEqual(t) { + return t.uid === this.uid; + } +} + +/** A user with a null UID. */ User.UNAUTHENTICATED = new User(null), +// TODO(mikelehen): Look into getting a proper uid-equivalent for +// non-FirebaseAuth providers. +User.GOOGLE_CREDENTIALS = new User("google-credentials-uid"), User.FIRST_PARTY = new User("first-party-uid"), +User.MOCK_USER = new User("mock-user"); + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +let A = "12.3.0"; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const R = new Logger("@firebase/firestore"); + +/** + * Sets the verbosity of Cloud Firestore logs (debug, error, or silent). + * + * @param logLevel - The verbosity you set for activity and error logging. Can + * be any of the following values: + * + *
    + *
  • `debug` for the most verbose logging level, primarily for + * debugging.
  • + *
  • `error` to log errors only.
  • + *
  • `silent` to turn off logging.
  • + *
+ */ function setLogLevel(t) { + R.setLogLevel(t); +} + +function __PRIVATE_logDebug(t, ...e) { + if (R.logLevel <= LogLevel.DEBUG) { + const r = e.map(__PRIVATE_argToString); + R.debug(`Firestore (${A}): ${t}`, ...r); + } +} + +function __PRIVATE_logError(t, ...e) { + if (R.logLevel <= LogLevel.ERROR) { + const r = e.map(__PRIVATE_argToString); + R.error(`Firestore (${A}): ${t}`, ...r); + } +} + +/** + * @internal + */ function __PRIVATE_logWarn(t, ...e) { + if (R.logLevel <= LogLevel.WARN) { + const r = e.map(__PRIVATE_argToString); + R.warn(`Firestore (${A}): ${t}`, ...r); + } +} + +/** + * Converts an additional log parameter to a string representation. + */ function __PRIVATE_argToString(t) { + if ("string" == typeof t) return t; + try { + /** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + /** Formats an object as a JSON string, suitable for logging. */ + return function __PRIVATE_formatJSON(t) { + return JSON.stringify(t); + }(t); + } catch (e) { + // Converting to JSON failed, just log the object directly + return t; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ function fail(t, e, r) { + let n = "Unexpected state"; + "string" == typeof e ? n = e : r = e, __PRIVATE__fail(t, n, r); +} + +function __PRIVATE__fail(t, e, r) { + // Log the failure in addition to throw an exception, just in case the + // exception is swallowed. + let n = `FIRESTORE (${A}) INTERNAL ASSERTION FAILED: ${e} (ID: ${t.toString(16)})`; + if (void 0 !== r) try { + n += " CONTEXT: " + JSON.stringify(r); + } catch (t) { + n += " CONTEXT: " + r; + } + // NOTE: We don't use FirestoreError here because these are internal failures + // that cannot be handled by the user. (Also it would create a circular + // dependency between the error and assert modules which doesn't work.) + throw __PRIVATE_logError(n), new Error(n); +} + +function __PRIVATE_hardAssert(t, e, r, n) { + let i = "Unexpected state"; + "string" == typeof r ? i = r : n = r, t || __PRIVATE__fail(e, i, n); +} + +/** + * Casts `obj` to `T`. In non-production builds, verifies that `obj` is an + * instance of `T` before casting. + */ function __PRIVATE_debugCast(t, +// eslint-disable-next-line @typescript-eslint/no-explicit-any +e) { + return t; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ const V = "ok", I = "cancelled", p = "unknown", y = "invalid-argument", g = "deadline-exceeded", w = "not-found", F = "already-exists", v = "permission-denied", D = "unauthenticated", b = "resource-exhausted", S = "failed-precondition", C = "aborted", N = "out-of-range", O = "unimplemented", q = "internal", B = "unavailable", $ = "data-loss"; + +/** An error returned by a Firestore operation. */ class FirestoreError extends FirebaseError { + /** @hideconstructor */ + constructor( + /** + * The backend error code associated with this error. + */ + t, + /** + * A custom error description. + */ + e) { + super(t, e), this.code = t, this.message = e, + // HACK: We write a toString property directly because Error is not a real + // class and so inheritance does not work correctly. We could alternatively + // do the same "back-door inheritance" trick that FirebaseError does. + this.toString = () => `${this.name}: [code=${this.code}]: ${this.message}`; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ class __PRIVATE_Deferred { + constructor() { + this.promise = new Promise(((t, e) => { + this.resolve = t, this.reject = e; + })); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ class __PRIVATE_OAuthToken { + constructor(t, e) { + this.user = e, this.type = "OAuth", this.headers = new Map, this.headers.set("Authorization", `Bearer ${t}`); + } +} + +/** + * A CredentialsProvider that always yields an empty token. + * @internal + */ class __PRIVATE_EmptyAuthCredentialsProvider { + getToken() { + return Promise.resolve(null); + } + invalidateToken() {} + start(t, e) { + // Fire with initial user. + t.enqueueRetryable((() => e(User.UNAUTHENTICATED))); + } + shutdown() {} +} + +/** + * A CredentialsProvider that always returns a constant token. Used for + * emulator token mocking. + */ class __PRIVATE_EmulatorAuthCredentialsProvider { + constructor(t) { + this.token = t, + /** + * Stores the listener registered with setChangeListener() + * This isn't actually necessary since the UID never changes, but we use this + * to verify the listen contract is adhered to in tests. + */ + this.changeListener = null; + } + getToken() { + return Promise.resolve(this.token); + } + invalidateToken() {} + start(t, e) { + this.changeListener = e, + // Fire with initial user. + t.enqueueRetryable((() => e(this.token.user))); + } + shutdown() { + this.changeListener = null; + } +} + +/** Credential provider for the Lite SDK. */ class __PRIVATE_LiteAuthCredentialsProvider { + constructor(t) { + this.auth = null, t.onInit((t => { + this.auth = t; + })); + } + getToken() { + return this.auth ? this.auth.getToken().then((t => t ? (__PRIVATE_hardAssert("string" == typeof t.accessToken, 42297, { + t: t + }), new __PRIVATE_OAuthToken(t.accessToken, new User(this.auth.getUid()))) : null)) : Promise.resolve(null); + } + invalidateToken() {} + start(t, e) {} + shutdown() {} +} + +/* + * FirstPartyToken provides a fresh token each time its value + * is requested, because if the token is too old, requests will be rejected. + * Technically this may no longer be necessary since the SDK should gracefully + * recover from unauthenticated errors (see b/33147818 for context), but it's + * safer to keep the implementation as-is. + */ class __PRIVATE_FirstPartyToken { + constructor(t, e, r) { + this.i = t, this.o = e, this.u = r, this.type = "FirstParty", this.user = User.FIRST_PARTY, + this.l = new Map; + } + /** + * Gets an authorization token, using a provided factory function, or return + * null. + */ h() { + return this.u ? this.u() : null; + } + get headers() { + this.l.set("X-Goog-AuthUser", this.i); + // Use array notation to prevent minification + const t = this.h(); + return t && this.l.set("Authorization", t), this.o && this.l.set("X-Goog-Iam-Authorization-Token", this.o), + this.l; + } +} + +/* + * Provides user credentials required for the Firestore JavaScript SDK + * to authenticate the user, using technique that is only available + * to applications hosted by Google. + */ class __PRIVATE_FirstPartyAuthCredentialsProvider { + constructor(t, e, r) { + this.i = t, this.o = e, this.u = r; + } + getToken() { + return Promise.resolve(new __PRIVATE_FirstPartyToken(this.i, this.o, this.u)); + } + start(t, e) { + // Fire with initial uid. + t.enqueueRetryable((() => e(User.FIRST_PARTY))); + } + shutdown() {} + invalidateToken() {} +} + +class AppCheckToken { + constructor(t) { + this.value = t, this.type = "AppCheck", this.headers = new Map, t && t.length > 0 && this.headers.set("x-firebase-appcheck", this.value); + } +} + +/** AppCheck token provider for the Lite SDK. */ class __PRIVATE_LiteAppCheckTokenProvider { + constructor(e, r) { + this.m = r, this.appCheck = null, this.T = null, _isFirebaseServerApp(e) && e.settings.appCheckToken && (this.T = e.settings.appCheckToken), + r.onInit((t => { + this.appCheck = t; + })); + } + getToken() { + return this.T ? Promise.resolve(new AppCheckToken(this.T)) : this.appCheck ? this.appCheck.getToken().then((t => t ? (__PRIVATE_hardAssert("string" == typeof t.token, 3470, { + tokenResult: t + }), new AppCheckToken(t.token)) : null)) : Promise.resolve(null); + } + invalidateToken() {} + start(t, e) {} + shutdown() {} +} + +/** + * Builds a CredentialsProvider depending on the type of + * the credentials passed in. + */ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class DatabaseInfo { + /** + * Constructs a DatabaseInfo using the provided host, databaseId and + * persistenceKey. + * + * @param databaseId - The database to use. + * @param appId - The Firebase App Id. + * @param persistenceKey - A unique identifier for this Firestore's local + * storage (used in conjunction with the databaseId). + * @param host - The Firestore backend host to connect to. + * @param ssl - Whether to use SSL when connecting. + * @param forceLongPolling - Whether to use the forceLongPolling option + * when using WebChannel as the network transport. + * @param autoDetectLongPolling - Whether to use the detectBufferingProxy + * option when using WebChannel as the network transport. + * @param longPollingOptions Options that configure long-polling. + * @param useFetchStreams Whether to use the Fetch API instead of + * XMLHTTPRequest + */ + constructor(t, e, r, n, i, s, o, a, u, _) { + this.databaseId = t, this.appId = e, this.persistenceKey = r, this.host = n, this.ssl = i, + this.forceLongPolling = s, this.autoDetectLongPolling = o, this.longPollingOptions = a, + this.useFetchStreams = u, this.isUsingEmulator = _; + } +} + +/** The default database name for a project. */ const Q = "(default)"; + +/** + * Represents the database ID a Firestore client is associated with. + * @internal + */ class DatabaseId { + constructor(t, e) { + this.projectId = t, this.database = e || Q; + } + static empty() { + return new DatabaseId("", ""); + } + get isDefaultDatabase() { + return this.database === Q; + } + isEqual(t) { + return t instanceof DatabaseId && t.projectId === this.projectId && t.database === this.database; + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Generates `nBytes` of random bytes. + * + * If `nBytes < 0` , an error will be thrown. + */ +function __PRIVATE_randomBytes(t) { + // Polyfills for IE and WebWorker by using `self` and `msCrypto` when `crypto` is not available. + const e = + // eslint-disable-next-line @typescript-eslint/no-explicit-any + "undefined" != typeof self && (self.crypto || self.msCrypto), r = new Uint8Array(t); + if (e && "function" == typeof e.getRandomValues) e.getRandomValues(r); else + // Falls back to Math.random + for (let e = 0; e < t; e++) r[e] = Math.floor(256 * Math.random()); + return r; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A utility class for generating unique alphanumeric IDs of a specified length. + * + * @internal + * Exported internally for testing purposes. + */ class __PRIVATE_AutoId { + static newId() { + // Alphanumeric characters + const t = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", e = 62 * Math.floor(256 / 62); + // The largest byte value that is a multiple of `char.length`. + let r = ""; + for (;r.length < 20; ) { + const n = __PRIVATE_randomBytes(40); + for (let i = 0; i < n.length; ++i) + // Only accept values that are [0, maxMultiple), this ensures they can + // be evenly mapped to indices of `chars` via a modulo operation. + r.length < 20 && n[i] < e && (r += t.charAt(n[i] % 62)); + } + return r; + } +} + +function __PRIVATE_primitiveComparator(t, e) { + return t < e ? -1 : t > e ? 1 : 0; +} + +/** Compare strings in UTF-8 encoded byte order */ function __PRIVATE_compareUtf8Strings(t, e) { + // Find the first differing character (a.k.a. "UTF-16 code unit") in the two strings and, + // if found, use that character to determine the relative ordering of the two strings as a + // whole. Comparing UTF-16 strings in UTF-8 byte order can be done simply and efficiently by + // comparing the UTF-16 code units (chars). This serendipitously works because of the way UTF-8 + // and UTF-16 happen to represent Unicode code points. + // After finding the first pair of differing characters, there are two cases: + // Case 1: Both characters are non-surrogates (code points less than or equal to 0xFFFF) or + // both are surrogates from a surrogate pair (that collectively represent code points greater + // than 0xFFFF). In this case their numeric order as UTF-16 code units is the same as the + // lexicographical order of their corresponding UTF-8 byte sequences. A direct comparison is + // sufficient. + // Case 2: One character is a surrogate and the other is not. In this case the surrogate- + // containing string is always ordered after the non-surrogate. This is because surrogates are + // used to represent code points greater than 0xFFFF which have 4-byte UTF-8 representations + // and are lexicographically greater than the 1, 2, or 3-byte representations of code points + // less than or equal to 0xFFFF. + // An example of why Case 2 is required is comparing the following two Unicode code points: + // |-----------------------|------------|---------------------|-----------------| + // | Name | Code Point | UTF-8 Encoding | UTF-16 Encoding | + // |-----------------------|------------|---------------------|-----------------| + // | Replacement Character | U+FFFD | 0xEF 0xBF 0xBD | 0xFFFD | + // | Grinning Face | U+1F600 | 0xF0 0x9F 0x98 0x80 | 0xD83D 0xDE00 | + // |-----------------------|------------|---------------------|-----------------| + // A lexicographical comparison of the UTF-8 encodings of these code points would order + // "Replacement Character" _before_ "Grinning Face" because 0xEF is less than 0xF0. However, a + // direct comparison of the UTF-16 code units, as would be done in case 1, would erroneously + // produce the _opposite_ ordering, because 0xFFFD is _greater than_ 0xD83D. As it turns out, + // this relative ordering holds for all comparisons of UTF-16 code points requiring a surrogate + // pair with those that do not. + const r = Math.min(t.length, e.length); + for (let n = 0; n < r; n++) { + const r = t.charAt(n), i = e.charAt(n); + if (r !== i) return __PRIVATE_isSurrogate(r) === __PRIVATE_isSurrogate(i) ? __PRIVATE_primitiveComparator(r, i) : __PRIVATE_isSurrogate(r) ? 1 : -1; + } + // Use the lengths of the strings to determine the overall comparison result since either the + // strings were equal or one is a prefix of the other. + return __PRIVATE_primitiveComparator(t.length, e.length); +} + +const k = 55296, L = 57343; + +function __PRIVATE_isSurrogate(t) { + const e = t.charCodeAt(0); + return e >= k && e <= L; +} + +/** Helper to compare arrays using isEqual(). */ function __PRIVATE_arrayEquals(t, e, r) { + return t.length === e.length && t.every(((t, n) => r(t, e[n]))); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ const M = "__name__"; + +/** + * Path represents an ordered sequence of string segments. + */ class BasePath { + constructor(t, e, r) { + void 0 === e ? e = 0 : e > t.length && fail(637, { + offset: e, + range: t.length + }), void 0 === r ? r = t.length - e : r > t.length - e && fail(1746, { + length: r, + range: t.length - e + }), this.segments = t, this.offset = e, this.len = r; + } + get length() { + return this.len; + } + isEqual(t) { + return 0 === BasePath.comparator(this, t); + } + child(t) { + const e = this.segments.slice(this.offset, this.limit()); + return t instanceof BasePath ? t.forEach((t => { + e.push(t); + })) : e.push(t), this.construct(e); + } + /** The index of one past the last segment of the path. */ limit() { + return this.offset + this.length; + } + popFirst(t) { + return t = void 0 === t ? 1 : t, this.construct(this.segments, this.offset + t, this.length - t); + } + popLast() { + return this.construct(this.segments, this.offset, this.length - 1); + } + firstSegment() { + return this.segments[this.offset]; + } + lastSegment() { + return this.get(this.length - 1); + } + get(t) { + return this.segments[this.offset + t]; + } + isEmpty() { + return 0 === this.length; + } + isPrefixOf(t) { + if (t.length < this.length) return !1; + for (let e = 0; e < this.length; e++) if (this.get(e) !== t.get(e)) return !1; + return !0; + } + isImmediateParentOf(t) { + if (this.length + 1 !== t.length) return !1; + for (let e = 0; e < this.length; e++) if (this.get(e) !== t.get(e)) return !1; + return !0; + } + forEach(t) { + for (let e = this.offset, r = this.limit(); e < r; e++) t(this.segments[e]); + } + toArray() { + return this.segments.slice(this.offset, this.limit()); + } + /** + * Compare 2 paths segment by segment, prioritizing numeric IDs + * (e.g., "__id123__") in numeric ascending order, followed by string + * segments in lexicographical order. + */ static comparator(t, e) { + const r = Math.min(t.length, e.length); + for (let n = 0; n < r; n++) { + const r = BasePath.compareSegments(t.get(n), e.get(n)); + if (0 !== r) return r; + } + return __PRIVATE_primitiveComparator(t.length, e.length); + } + static compareSegments(t, e) { + const r = BasePath.isNumericId(t), n = BasePath.isNumericId(e); + return r && !n ? -1 : !r && n ? 1 : r && n ? BasePath.extractNumericId(t).compare(BasePath.extractNumericId(e)) : __PRIVATE_compareUtf8Strings(t, e); + } + // Checks if a segment is a numeric ID (starts with "__id" and ends with "__"). + static isNumericId(t) { + return t.startsWith("__id") && t.endsWith("__"); + } + static extractNumericId(t) { + return Integer.fromString(t.substring(4, t.length - 2)); + } +} + +/** + * A slash-separated path for navigating resources (documents and collections) + * within Firestore. + * + * @internal + */ class ResourcePath extends BasePath { + construct(t, e, r) { + return new ResourcePath(t, e, r); + } + canonicalString() { + // NOTE: The client is ignorant of any path segments containing escape + // sequences (e.g. __id123__) and just passes them through raw (they exist + // for legacy reasons and should not be used frequently). + return this.toArray().join("/"); + } + toString() { + return this.canonicalString(); + } + /** + * Returns a string representation of this path + * where each path segment has been encoded with + * `encodeURIComponent`. + */ toUriEncodedString() { + return this.toArray().map(encodeURIComponent).join("/"); + } + /** + * Creates a resource path from the given slash-delimited string. If multiple + * arguments are provided, all components are combined. Leading and trailing + * slashes from all components are ignored. + */ static fromString(...t) { + // NOTE: The client is ignorant of any path segments containing escape + // sequences (e.g. __id123__) and just passes them through raw (they exist + // for legacy reasons and should not be used frequently). + const e = []; + for (const r of t) { + if (r.indexOf("//") >= 0) throw new FirestoreError(y, `Invalid segment (${r}). Paths must not contain // in them.`); + // Strip leading and trailing slashed. + e.push(...r.split("/").filter((t => t.length > 0))); + } + return new ResourcePath(e); + } + static emptyPath() { + return new ResourcePath([]); + } +} + +const x = /^[_a-zA-Z][_a-zA-Z0-9]*$/; + +/** + * A dot-separated path for navigating sub-objects within a document. + * @internal + */ class FieldPath$1 extends BasePath { + construct(t, e, r) { + return new FieldPath$1(t, e, r); + } + /** + * Returns true if the string could be used as a segment in a field path + * without escaping. + */ static isValidIdentifier(t) { + return x.test(t); + } + canonicalString() { + return this.toArray().map((t => (t = t.replace(/\\/g, "\\\\").replace(/`/g, "\\`"), + FieldPath$1.isValidIdentifier(t) || (t = "`" + t + "`"), t))).join("."); + } + toString() { + return this.canonicalString(); + } + /** + * Returns true if this field references the key of a document. + */ isKeyField() { + return 1 === this.length && this.get(0) === M; + } + /** + * The field designating the key of a document. + */ static keyField() { + return new FieldPath$1([ M ]); + } + /** + * Parses a field string from the given server-formatted string. + * + * - Splitting the empty string is not allowed (for now at least). + * - Empty segments within the string (e.g. if there are two consecutive + * separators) are not allowed. + * + * TODO(b/37244157): we should make this more strict. Right now, it allows + * non-identifier path components, even if they aren't escaped. + */ static fromServerFormat(t) { + const e = []; + let r = "", n = 0; + const __PRIVATE_addCurrentSegment = () => { + if (0 === r.length) throw new FirestoreError(y, `Invalid field path (${t}). Paths must not be empty, begin with '.', end with '.', or contain '..'`); + e.push(r), r = ""; + }; + let i = !1; + for (;n < t.length; ) { + const e = t[n]; + if ("\\" === e) { + if (n + 1 === t.length) throw new FirestoreError(y, "Path has trailing escape character: " + t); + const e = t[n + 1]; + if ("\\" !== e && "." !== e && "`" !== e) throw new FirestoreError(y, "Path has invalid escape sequence: " + t); + r += e, n += 2; + } else "`" === e ? (i = !i, n++) : "." !== e || i ? (r += e, n++) : (__PRIVATE_addCurrentSegment(), + n++); + } + if (__PRIVATE_addCurrentSegment(), i) throw new FirestoreError(y, "Unterminated ` in path: " + t); + return new FieldPath$1(e); + } + static emptyPath() { + return new FieldPath$1([]); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @internal + */ class DocumentKey { + constructor(t) { + this.path = t; + } + static fromPath(t) { + return new DocumentKey(ResourcePath.fromString(t)); + } + static fromName(t) { + return new DocumentKey(ResourcePath.fromString(t).popFirst(5)); + } + static empty() { + return new DocumentKey(ResourcePath.emptyPath()); + } + get collectionGroup() { + return this.path.popLast().lastSegment(); + } + /** Returns true if the document is in the specified collectionId. */ hasCollectionId(t) { + return this.path.length >= 2 && this.path.get(this.path.length - 2) === t; + } + /** Returns the collection group (i.e. the name of the parent collection) for this key. */ getCollectionGroup() { + return this.path.get(this.path.length - 2); + } + /** Returns the fully qualified path to the parent collection. */ getCollectionPath() { + return this.path.popLast(); + } + isEqual(t) { + return null !== t && 0 === ResourcePath.comparator(this.path, t.path); + } + toString() { + return this.path.toString(); + } + static comparator(t, e) { + return ResourcePath.comparator(t.path, e.path); + } + static isDocumentKey(t) { + return t.length % 2 == 0; + } + /** + * Creates and returns a new document key with the given segments. + * + * @param segments - The segments of the path to the document + * @returns A new instance of DocumentKey + */ static fromSegments(t) { + return new DocumentKey(new ResourcePath(t.slice())); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ function __PRIVATE_validateNonEmptyArgument(t, e, r) { + if (!r) throw new FirestoreError(y, `Function ${t}() cannot be called with an empty ${e}.`); +} + +/** + * Validates that two boolean options are not set at the same time. + * @internal + */ +/** + * Validates that `path` refers to a document (indicated by the fact it contains + * an even numbers of segments). + */ +function __PRIVATE_validateDocumentPath(t) { + if (!DocumentKey.isDocumentKey(t)) throw new FirestoreError(y, `Invalid document reference. Document references must have an even number of segments, but ${t} has ${t.length}.`); +} + +/** + * Validates that `path` refers to a collection (indicated by the fact it + * contains an odd numbers of segments). + */ function __PRIVATE_validateCollectionPath(t) { + if (DocumentKey.isDocumentKey(t)) throw new FirestoreError(y, `Invalid collection reference. Collection references must have an odd number of segments, but ${t} has ${t.length}.`); +} + +/** + * Returns true if it's a non-null object without a custom prototype + * (i.e. excludes Array, Date, etc.). + */ function __PRIVATE_isPlainObject(t) { + return "object" == typeof t && null !== t && (Object.getPrototypeOf(t) === Object.prototype || null === Object.getPrototypeOf(t)); +} + +/** Returns a string describing the type / value of the provided input. */ function __PRIVATE_valueDescription(t) { + if (void 0 === t) return "undefined"; + if (null === t) return "null"; + if ("string" == typeof t) return t.length > 20 && (t = `${t.substring(0, 20)}...`), + JSON.stringify(t); + if ("number" == typeof t || "boolean" == typeof t) return "" + t; + if ("object" == typeof t) { + if (t instanceof Array) return "an array"; + { + const e = + /** try to get the constructor name for an object. */ + function __PRIVATE_tryGetCustomObjectType(t) { + if (t.constructor) return t.constructor.name; + return null; + } + /** + * Casts `obj` to `T`, optionally unwrapping Compat types to expose the + * underlying instance. Throws if `obj` is not an instance of `T`. + * + * This cast is used in the Lite and Full SDK to verify instance types for + * arguments passed to the public API. + * @internal + */ (t); + return e ? `a custom ${e} object` : "an object"; + } + } + return "function" == typeof t ? "a function" : fail(12329, { + type: typeof t + }); +} + +function __PRIVATE_cast(t, +// eslint-disable-next-line @typescript-eslint/no-explicit-any +e) { + if ("_delegate" in t && ( + // Unwrap Compat types + // eslint-disable-next-line @typescript-eslint/no-explicit-any + t = t._delegate), !(t instanceof e)) { + if (e.name === t.constructor.name) throw new FirestoreError(y, "Type does not match the expected instance. Did you pass a reference from a different Firestore SDK?"); + { + const r = __PRIVATE_valueDescription(t); + throw new FirestoreError(y, `Expected type '${e.name}', but it was: ${r}`); + } + } + return t; +} + +function __PRIVATE_validatePositiveNumber(t, e) { + if (e <= 0) throw new FirestoreError(y, `Function ${t}() requires a positive number, but it was: ${e}.`); +} + +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Compares two `ExperimentalLongPollingOptions` objects for equality. + */ +/** + * Creates and returns a new `ExperimentalLongPollingOptions` with the same + * option values as the given instance. + */ +function __PRIVATE_cloneLongPollingOptions(t) { + const e = {}; + return void 0 !== t.timeoutSeconds && (e.timeoutSeconds = t.timeoutSeconds), e; +} + +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * The value returned from the most recent invocation of + * `generateUniqueDebugId()`, or null if it has never been invoked. + */ let U = null; + +/** + * Generates and returns an initial value for `lastUniqueDebugId`. + * + * The returned value is randomly selected from a range of integers that are + * represented as 8 hexadecimal digits. This means that (within reason) any + * numbers generated by incrementing the returned number by 1 will also be + * represented by 8 hexadecimal digits. This leads to all "IDs" having the same + * length when converted to a hexadecimal string, making reading logs containing + * these IDs easier to follow. And since the return value is randomly selected + * it will help to differentiate between logs from different executions. + */ +/** + * Generates and returns a unique ID as a hexadecimal string. + * + * The returned ID is intended to be used in debug logging messages to help + * correlate log messages that may be spatially separated in the logs, but + * logically related. For example, a network connection could include the same + * "debug ID" string in all of its log messages to help trace a specific + * connection over time. + * + * @return the 10-character generated ID (e.g. "0xa1b2c3d4"). + */ +function __PRIVATE_generateUniqueDebugId() { + return null === U ? U = function __PRIVATE_generateInitialUniqueDebugId() { + return 268435456 + Math.round(2147483648 * Math.random()); + }() : U++, "0x" + U.toString(16); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Returns whether a variable is either undefined or null. + */ function __PRIVATE_isNullOrUndefined(t) { + return null == t; +} + +/** Returns whether the value represents -0. */ function __PRIVATE_isNegativeZero(t) { + // Detect if the value is -0.0. Based on polyfill from + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is + return 0 === t && 1 / t == -1 / 0; +} + +/** + * Returns whether a value is an integer and in the safe integer range + * @param value - The value to test for being an integer and in the safe range + */ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const j = "RestConnection", z = { + BatchGetDocuments: "batchGet", + Commit: "commit", + RunQuery: "runQuery", + RunAggregationQuery: "runAggregationQuery" +}; + +/** + * Maps RPC names to the corresponding REST endpoint name. + * + * We use array notation to avoid mangling. + */ +/** + * Base class for all Rest-based connections to the backend (WebChannel and + * HTTP). + */ +class __PRIVATE_RestConnection { + get P() { + // Both `invokeRPC()` and `invokeStreamingRPC()` use their `path` arguments to determine + // where to run the query, and expect the `request` to NOT specify the "path". + return !1; + } + constructor(t) { + this.databaseInfo = t, this.databaseId = t.databaseId; + const e = t.ssl ? "https" : "http", r = encodeURIComponent(this.databaseId.projectId), n = encodeURIComponent(this.databaseId.database); + this.A = e + "://" + t.host, this.R = `projects/${r}/databases/${n}`, this.V = this.databaseId.database === Q ? `project_id=${r}` : `project_id=${r}&database_id=${n}`; + } + I(t, e, r, n, i) { + const s = __PRIVATE_generateUniqueDebugId(), o = this.p(t, e.toUriEncodedString()); + __PRIVATE_logDebug(j, `Sending RPC '${t}' ${s}:`, o, r); + const a = { + "google-cloud-resource-prefix": this.R, + "x-goog-request-params": this.V + }; + this.F(a, n, i); + const {host: u} = new URL(o), _ = isCloudWorkstation(u); + return this.v(t, o, a, r, _).then((e => (__PRIVATE_logDebug(j, `Received RPC '${t}' ${s}: `, e), + e)), (e => { + throw __PRIVATE_logWarn(j, `RPC '${t}' ${s} failed with error: `, e, "url: ", o, "request:", r), + e; + })); + } + D(t, e, r, n, i, s) { + // The REST API automatically aggregates all of the streamed results, so we + // can just use the normal invoke() method. + return this.I(t, e, r, n, i); + } + /** + * Modifies the headers for a request, adding any authorization token if + * present and any additional headers for the request. + */ F(t, e, r) { + t["X-Goog-Api-Client"] = + // SDK_VERSION is updated to different value at runtime depending on the entry point, + // so we need to get its value when we need it in a function. + function __PRIVATE_getGoogApiClientValue() { + return "gl-js/ fire/" + A; + }(), + // Content-Type: text/plain will avoid preflight requests which might + // mess with CORS and redirects by proxies. If we add custom headers + // we will need to change this code to potentially use the $httpOverwrite + // parameter supported by ESF to avoid triggering preflight requests. + t["Content-Type"] = "text/plain", this.databaseInfo.appId && (t["X-Firebase-GMPID"] = this.databaseInfo.appId), + e && e.headers.forEach(((e, r) => t[r] = e)), r && r.headers.forEach(((e, r) => t[r] = e)); + } + p(t, e) { + const r = z[t]; + return `${this.A}/v1/${e}:${r}`; + } + /** + * Closes and cleans up any resources associated with the connection. This + * implementation is a no-op because there are no resources associated + * with the RestConnection that need to be cleaned up. + */ terminate() { + // No-op + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Error Codes describing the different ways GRPC can fail. These are copied + * directly from GRPC's sources here: + * + * https://github.com/grpc/grpc/blob/bceec94ea4fc5f0085d81235d8e1c06798dc341a/include/grpc%2B%2B/impl/codegen/status_code_enum.h + * + * Important! The names of these identifiers matter because the string forms + * are used for reverse lookups from the webchannel stream. Do NOT change the + * names of these identifiers or change this into a const enum. + */ var W, K; + +/** + * Converts an HTTP Status Code to the equivalent error code. + * + * @param status - An HTTP Status Code, like 200, 404, 503, etc. + * @returns The equivalent Code. Unknown status codes are mapped to + * Code.UNKNOWN. + */ +function __PRIVATE_mapCodeFromHttpStatus(t) { + if (void 0 === t) return __PRIVATE_logError("RPC_ERROR", "HTTP error has no status"), + p; + // The canonical error codes for Google APIs [1] specify mapping onto HTTP + // status codes but the mapping is not bijective. In each case of ambiguity + // this function chooses a primary error. + + // [1] + // https://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto + switch (t) { + case 200: + // OK + return V; + + case 400: + // Bad Request + return S; + + // Other possibilities based on the forward mapping + // return Code.INVALID_ARGUMENT; + // return Code.OUT_OF_RANGE; + case 401: + // Unauthorized + return D; + + case 403: + // Forbidden + return v; + + case 404: + // Not Found + return w; + + case 409: + // Conflict + return C; + + // Other possibilities: + // return Code.ALREADY_EXISTS; + case 416: + // Range Not Satisfiable + return N; + + case 429: + // Too Many Requests + return b; + + case 499: + // Client Closed Request + return I; + + case 500: + // Internal Server Error + return p; + + // Other possibilities: + // return Code.INTERNAL; + // return Code.DATA_LOSS; + case 501: + // Unimplemented + return O; + + case 503: + // Service Unavailable + return B; + + case 504: + // Gateway Timeout + return g; + + default: + return t >= 200 && t < 300 ? V : t >= 400 && t < 500 ? S : t >= 500 && t < 600 ? q : p; + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A Rest-based connection that relies on the native HTTP stack + * (e.g. `fetch` or a polyfill). + */ (K = W || (W = {}))[K.OK = 0] = "OK", K[K.CANCELLED = 1] = "CANCELLED", K[K.UNKNOWN = 2] = "UNKNOWN", +K[K.INVALID_ARGUMENT = 3] = "INVALID_ARGUMENT", K[K.DEADLINE_EXCEEDED = 4] = "DEADLINE_EXCEEDED", +K[K.NOT_FOUND = 5] = "NOT_FOUND", K[K.ALREADY_EXISTS = 6] = "ALREADY_EXISTS", K[K.PERMISSION_DENIED = 7] = "PERMISSION_DENIED", +K[K.UNAUTHENTICATED = 16] = "UNAUTHENTICATED", K[K.RESOURCE_EXHAUSTED = 8] = "RESOURCE_EXHAUSTED", +K[K.FAILED_PRECONDITION = 9] = "FAILED_PRECONDITION", K[K.ABORTED = 10] = "ABORTED", +K[K.OUT_OF_RANGE = 11] = "OUT_OF_RANGE", K[K.UNIMPLEMENTED = 12] = "UNIMPLEMENTED", +K[K.INTERNAL = 13] = "INTERNAL", K[K.UNAVAILABLE = 14] = "UNAVAILABLE", K[K.DATA_LOSS = 15] = "DATA_LOSS"; + +class __PRIVATE_FetchConnection extends __PRIVATE_RestConnection { + S(t, e) { + throw new Error("Not supported by FetchConnection"); + } + async v(t, e, r, n, i) { + const s = JSON.stringify(n); + let o; + try { + const t = { + method: "POST", + headers: r, + body: s + }; + i && (t.credentials = "include"), o = await fetch(e, t); + } catch (t) { + const e = t; + throw new FirestoreError(__PRIVATE_mapCodeFromHttpStatus(e.status), "Request failed with error: " + e.statusText); + } + if (!o.ok) { + let t = await o.json(); + Array.isArray(t) && (t = t[0]); + const e = t?.error?.message; + throw new FirestoreError(__PRIVATE_mapCodeFromHttpStatus(o.status), `Request failed with error: ${e ?? o.statusText}`); + } + return o.json(); + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Initializes the HTTP connection for the REST API. */ +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Concrete implementation of the Aggregate type. + */ +class __PRIVATE_AggregateImpl { + constructor(t, e, r) { + this.alias = t, this.aggregateType = e, this.fieldPath = r; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ function __PRIVATE_objectSize(t) { + let e = 0; + for (const r in t) Object.prototype.hasOwnProperty.call(t, r) && e++; + return e; +} + +function forEach(t, e) { + for (const r in t) Object.prototype.hasOwnProperty.call(t, r) && e(r, t[r]); +} + +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An error encountered while decoding base64 string. + */ +class __PRIVATE_Base64DecodeError extends Error { + constructor() { + super(...arguments), this.name = "Base64DecodeError"; + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Converts a Base64 encoded string to a binary string. */ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Immutable class that represents a "proto" byte string. + * + * Proto byte strings can either be Base64-encoded strings or Uint8Arrays when + * sent on the wire. This class abstracts away this differentiation by holding + * the proto byte string in a common class that must be converted into a string + * before being sent as a proto. + * @internal + */ +class ByteString { + constructor(t) { + this.binaryString = t; + } + static fromBase64String(t) { + const e = function __PRIVATE_decodeBase64(t) { + try { + return atob(t); + } catch (t) { + // Check that `DOMException` is defined before using it to avoid + // "ReferenceError: Property 'DOMException' doesn't exist" in react-native. + // (https://github.com/firebase/firebase-js-sdk/issues/7115) + throw "undefined" != typeof DOMException && t instanceof DOMException ? new __PRIVATE_Base64DecodeError("Invalid base64 string: " + t) : t; + } + } + /** Converts a binary string to a Base64 encoded string. */ (t); + return new ByteString(e); + } + static fromUint8Array(t) { + // TODO(indexing); Remove the copy of the byte string here as this method + // is frequently called during indexing. + const e = + /** + * Helper function to convert an Uint8array to a binary string. + */ + function __PRIVATE_binaryStringFromUint8Array(t) { + let e = ""; + for (let r = 0; r < t.length; ++r) e += String.fromCharCode(t[r]); + return e; + } + /** + * Helper function to convert a binary string to an Uint8Array. + */ (t); + return new ByteString(e); + } + [Symbol.iterator]() { + let t = 0; + return { + next: () => t < this.binaryString.length ? { + value: this.binaryString.charCodeAt(t++), + done: !1 + } : { + value: void 0, + done: !0 + } + }; + } + toBase64() { + return function __PRIVATE_encodeBase64(t) { + return btoa(t); + }(this.binaryString); + } + toUint8Array() { + return function __PRIVATE_uint8ArrayFromBinaryString(t) { + const e = new Uint8Array(t.length); + for (let r = 0; r < t.length; r++) e[r] = t.charCodeAt(r); + return e; + } + /** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + // A RegExp matching ISO 8601 UTC timestamps with optional fraction. + (this.binaryString); + } + approximateByteSize() { + return 2 * this.binaryString.length; + } + compareTo(t) { + return __PRIVATE_primitiveComparator(this.binaryString, t.binaryString); + } + isEqual(t) { + return this.binaryString === t.binaryString; + } +} + +ByteString.EMPTY_BYTE_STRING = new ByteString(""); + +const G = new RegExp(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.(\d+))?Z$/); + +/** + * Converts the possible Proto values for a timestamp value into a "seconds and + * nanos" representation. + */ function __PRIVATE_normalizeTimestamp(t) { + // The json interface (for the browser) will return an iso timestamp string, + // while the proto js library (for node) will return a + // google.protobuf.Timestamp instance. + if (__PRIVATE_hardAssert(!!t, 39018), "string" == typeof t) { + // The date string can have higher precision (nanos) than the Date class + // (millis), so we do some custom parsing here. + // Parse the nanos right out of the string. + let e = 0; + const r = G.exec(t); + if (__PRIVATE_hardAssert(!!r, 46558, { + timestamp: t + }), r[1]) { + // Pad the fraction out to 9 digits (nanos). + let t = r[1]; + t = (t + "000000000").substr(0, 9), e = Number(t); + } + // Parse the date to get the seconds. + const n = new Date(t); + return { + seconds: Math.floor(n.getTime() / 1e3), + nanos: e + }; + } + return { + seconds: __PRIVATE_normalizeNumber(t.seconds), + nanos: __PRIVATE_normalizeNumber(t.nanos) + }; +} + +/** + * Converts the possible Proto types for numbers into a JavaScript number. + * Returns 0 if the value is not numeric. + */ function __PRIVATE_normalizeNumber(t) { + // TODO(bjornick): Handle int64 greater than 53 bits. + return "number" == typeof t ? t : "string" == typeof t ? Number(t) : 0; +} + +/** Converts the possible Proto types for Blobs into a ByteString. */ function __PRIVATE_normalizeByteString(t) { + return "string" == typeof t ? ByteString.fromBase64String(t) : ByteString.fromUint8Array(t); +} + +/** + * @license + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Helper function to define a JSON schema {@link Property}. + * @private + * @internal + */ function property(t, e) { + const r = { + typeString: t + }; + return e && (r.value = e), r; +} + +/** + * Validates the JSON object based on the provided schema, and narrows the type to the provided + * JSON schema. + * @private + * @internal + * + * @param json A JSON object to validate. + * @param scheme a {@link JsonSchema} that defines the properties to validate. + * @returns true if the JSON schema exists within the object. Throws a FirestoreError otherwise. + */ function __PRIVATE_validateJSON(t, e) { + if (!__PRIVATE_isPlainObject(t)) throw new FirestoreError(y, "JSON must be an object"); + let r; + for (const n in e) if (e[n]) { + const i = e[n].typeString, s = "value" in e[n] ? { + value: e[n].value + } : void 0; + if (!(n in t)) { + r = `JSON missing required field: '${n}'`; + break; + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const o = t[n]; + if (i && typeof o !== i) { + r = `JSON field '${n}' must be a ${i}.`; + break; + } + if (void 0 !== s && o !== s.value) { + r = `Expected '${n}' field to equal '${s.value}'`; + break; + } + } + if (r) throw new FirestoreError(y, r); + return !0; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// The earliest date supported by Firestore timestamps (0001-01-01T00:00:00Z). +const J = -62135596800, H = 1e6; + +// Number of nanoseconds in a millisecond. +/** + * A `Timestamp` represents a point in time independent of any time zone or + * calendar, represented as seconds and fractions of seconds at nanosecond + * resolution in UTC Epoch time. + * + * It is encoded using the Proleptic Gregorian Calendar which extends the + * Gregorian calendar backwards to year one. It is encoded assuming all minutes + * are 60 seconds long, i.e. leap seconds are "smeared" so that no leap second + * table is needed for interpretation. Range is from 0001-01-01T00:00:00Z to + * 9999-12-31T23:59:59.999999999Z. + * + * For examples and further specifications, refer to the + * {@link https://github.com/google/protobuf/blob/master/src/google/protobuf/timestamp.proto | Timestamp definition}. + */ +class Timestamp { + /** + * Creates a new timestamp with the current date, with millisecond precision. + * + * @returns a new timestamp representing the current date. + */ + static now() { + return Timestamp.fromMillis(Date.now()); + } + /** + * Creates a new timestamp from the given date. + * + * @param date - The date to initialize the `Timestamp` from. + * @returns A new `Timestamp` representing the same point in time as the given + * date. + */ static fromDate(t) { + return Timestamp.fromMillis(t.getTime()); + } + /** + * Creates a new timestamp from the given number of milliseconds. + * + * @param milliseconds - Number of milliseconds since Unix epoch + * 1970-01-01T00:00:00Z. + * @returns A new `Timestamp` representing the same point in time as the given + * number of milliseconds. + */ static fromMillis(t) { + const e = Math.floor(t / 1e3), r = Math.floor((t - 1e3 * e) * H); + return new Timestamp(e, r); + } + /** + * Creates a new timestamp. + * + * @param seconds - The number of seconds of UTC time since Unix epoch + * 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to + * 9999-12-31T23:59:59Z inclusive. + * @param nanoseconds - The non-negative fractions of a second at nanosecond + * resolution. Negative second values with fractions must still have + * non-negative nanoseconds values that count forward in time. Must be + * from 0 to 999,999,999 inclusive. + */ constructor( + /** + * The number of seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z. + */ + t, + /** + * The fractions of a second at nanosecond resolution.* + */ + e) { + if (this.seconds = t, this.nanoseconds = e, e < 0) throw new FirestoreError(y, "Timestamp nanoseconds out of range: " + e); + if (e >= 1e9) throw new FirestoreError(y, "Timestamp nanoseconds out of range: " + e); + if (t < J) throw new FirestoreError(y, "Timestamp seconds out of range: " + t); + // This will break in the year 10,000. + if (t >= 253402300800) throw new FirestoreError(y, "Timestamp seconds out of range: " + t); + } + /** + * Converts a `Timestamp` to a JavaScript `Date` object. This conversion + * causes a loss of precision since `Date` objects only support millisecond + * precision. + * + * @returns JavaScript `Date` object representing the same point in time as + * this `Timestamp`, with millisecond precision. + */ toDate() { + return new Date(this.toMillis()); + } + /** + * Converts a `Timestamp` to a numeric timestamp (in milliseconds since + * epoch). This operation causes a loss of precision. + * + * @returns The point in time corresponding to this timestamp, represented as + * the number of milliseconds since Unix epoch 1970-01-01T00:00:00Z. + */ toMillis() { + return 1e3 * this.seconds + this.nanoseconds / H; + } + _compareTo(t) { + return this.seconds === t.seconds ? __PRIVATE_primitiveComparator(this.nanoseconds, t.nanoseconds) : __PRIVATE_primitiveComparator(this.seconds, t.seconds); + } + /** + * Returns true if this `Timestamp` is equal to the provided one. + * + * @param other - The `Timestamp` to compare against. + * @returns true if this `Timestamp` is equal to the provided one. + */ isEqual(t) { + return t.seconds === this.seconds && t.nanoseconds === this.nanoseconds; + } + /** Returns a textual representation of this `Timestamp`. */ toString() { + return "Timestamp(seconds=" + this.seconds + ", nanoseconds=" + this.nanoseconds + ")"; + } + /** + * Returns a JSON-serializable representation of this `Timestamp`. + */ toJSON() { + return { + type: Timestamp._jsonSchemaVersion, + seconds: this.seconds, + nanoseconds: this.nanoseconds + }; + } + /** + * Builds a `Timestamp` instance from a JSON object created by {@link Timestamp.toJSON}. + */ static fromJSON(t) { + if (__PRIVATE_validateJSON(t, Timestamp._jsonSchema)) return new Timestamp(t.seconds, t.nanoseconds); + } + /** + * Converts this object to a primitive string, which allows `Timestamp` objects + * to be compared using the `>`, `<=`, `>=` and `>` operators. + */ valueOf() { + // This method returns a string of the form . where + // is translated to have a non-negative value and both + // and are left-padded with zeroes to be a consistent length. + // Strings with this format then have a lexicographical ordering that matches + // the expected ordering. The translation is done to avoid having + // a leading negative sign (i.e. a leading '-' character) in its string + // representation, which would affect its lexicographical ordering. + const t = this.seconds - J; + // Note: Up to 12 decimal digits are required to represent all valid + // 'seconds' values. + return String(t).padStart(12, "0") + "." + String(this.nanoseconds).padStart(9, "0"); + } +} + +Timestamp._jsonSchemaVersion = "firestore/timestamp/1.0", Timestamp._jsonSchema = { + type: property("string", Timestamp._jsonSchemaVersion), + seconds: property("number"), + nanoseconds: property("number") +}; + +function __PRIVATE_isServerTimestamp(t) { + const e = (t?.mapValue?.fields || {}).__type__?.stringValue; + return "server_timestamp" === e; +} + +/** + * Returns the value of the field before this ServerTimestamp was set. + * + * Preserving the previous values allows the user to display the last resoled + * value until the backend responds with the timestamp. + */ function __PRIVATE_getPreviousValue(t) { + const e = t.mapValue.fields.__previous_value__; + return __PRIVATE_isServerTimestamp(e) ? __PRIVATE_getPreviousValue(e) : e; +} + +/** + * Returns the local time at which this timestamp was first set. + */ function __PRIVATE_getLocalWriteTime(t) { + const e = __PRIVATE_normalizeTimestamp(t.mapValue.fields.__local_write_time__.timestampValue); + return new Timestamp(e.seconds, e.nanos); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ const Y = "__type__", Z = "__max__", X = { + fields: { + __type__: { + stringValue: Z + } + } +}, tt = "__vector__", et = "value"; + +/** Extracts the backend's type order for the provided value. */ +function __PRIVATE_typeOrder(t) { + return "nullValue" in t ? 0 /* TypeOrder.NullValue */ : "booleanValue" in t ? 1 /* TypeOrder.BooleanValue */ : "integerValue" in t || "doubleValue" in t ? 2 /* TypeOrder.NumberValue */ : "timestampValue" in t ? 3 /* TypeOrder.TimestampValue */ : "stringValue" in t ? 5 /* TypeOrder.StringValue */ : "bytesValue" in t ? 6 /* TypeOrder.BlobValue */ : "referenceValue" in t ? 7 /* TypeOrder.RefValue */ : "geoPointValue" in t ? 8 /* TypeOrder.GeoPointValue */ : "arrayValue" in t ? 9 /* TypeOrder.ArrayValue */ : "mapValue" in t ? __PRIVATE_isServerTimestamp(t) ? 4 /* TypeOrder.ServerTimestampValue */ : + /** Returns true if the Value represents the canonical {@link #MAX_VALUE} . */ + function __PRIVATE_isMaxValue(t) { + return (((t.mapValue || {}).fields || {}).__type__ || {}).stringValue === Z; + } + /** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + /** + * Represents a bound of a query. + * + * The bound is specified with the given components representing a position and + * whether it's just before or just after the position (relative to whatever the + * query order is). + * + * The position represents a logical index position for a query. It's a prefix + * of values for the (potentially implicit) order by clauses of a query. + * + * Bound provides a function to determine whether a document comes before or + * after a bound. This is influenced by whether the position is just before or + * just after the provided values. + */ (t) ? 9007199254740991 /* TypeOrder.MaxValue */ : + /** Returns true if `value` is a VetorValue. */ + function __PRIVATE_isVectorValue(t) { + const e = (t?.mapValue?.fields || {})[Y]?.stringValue; + return e === tt; + } + /** Creates a deep copy of `source`. */ (t) ? 10 /* TypeOrder.VectorValue */ : 11 /* TypeOrder.ObjectValue */ : fail(28295, { + value: t + }); +} + +/** Tests `left` and `right` for equality based on the backend semantics. */ function __PRIVATE_valueEquals(t, e) { + if (t === e) return !0; + const r = __PRIVATE_typeOrder(t); + if (r !== __PRIVATE_typeOrder(e)) return !1; + switch (r) { + case 0 /* TypeOrder.NullValue */ : + case 9007199254740991 /* TypeOrder.MaxValue */ : + return !0; + + case 1 /* TypeOrder.BooleanValue */ : + return t.booleanValue === e.booleanValue; + + case 4 /* TypeOrder.ServerTimestampValue */ : + return __PRIVATE_getLocalWriteTime(t).isEqual(__PRIVATE_getLocalWriteTime(e)); + + case 3 /* TypeOrder.TimestampValue */ : + return function __PRIVATE_timestampEquals(t, e) { + if ("string" == typeof t.timestampValue && "string" == typeof e.timestampValue && t.timestampValue.length === e.timestampValue.length) + // Use string equality for ISO 8601 timestamps + return t.timestampValue === e.timestampValue; + const r = __PRIVATE_normalizeTimestamp(t.timestampValue), n = __PRIVATE_normalizeTimestamp(e.timestampValue); + return r.seconds === n.seconds && r.nanos === n.nanos; + }(t, e); + + case 5 /* TypeOrder.StringValue */ : + return t.stringValue === e.stringValue; + + case 6 /* TypeOrder.BlobValue */ : + return function __PRIVATE_blobEquals(t, e) { + return __PRIVATE_normalizeByteString(t.bytesValue).isEqual(__PRIVATE_normalizeByteString(e.bytesValue)); + }(t, e); + + case 7 /* TypeOrder.RefValue */ : + return t.referenceValue === e.referenceValue; + + case 8 /* TypeOrder.GeoPointValue */ : + return function __PRIVATE_geoPointEquals(t, e) { + return __PRIVATE_normalizeNumber(t.geoPointValue.latitude) === __PRIVATE_normalizeNumber(e.geoPointValue.latitude) && __PRIVATE_normalizeNumber(t.geoPointValue.longitude) === __PRIVATE_normalizeNumber(e.geoPointValue.longitude); + }(t, e); + + case 2 /* TypeOrder.NumberValue */ : + return function __PRIVATE_numberEquals(t, e) { + if ("integerValue" in t && "integerValue" in e) return __PRIVATE_normalizeNumber(t.integerValue) === __PRIVATE_normalizeNumber(e.integerValue); + if ("doubleValue" in t && "doubleValue" in e) { + const r = __PRIVATE_normalizeNumber(t.doubleValue), n = __PRIVATE_normalizeNumber(e.doubleValue); + return r === n ? __PRIVATE_isNegativeZero(r) === __PRIVATE_isNegativeZero(n) : isNaN(r) && isNaN(n); + } + return !1; + }(t, e); + + case 9 /* TypeOrder.ArrayValue */ : + return __PRIVATE_arrayEquals(t.arrayValue.values || [], e.arrayValue.values || [], __PRIVATE_valueEquals); + + case 10 /* TypeOrder.VectorValue */ : + case 11 /* TypeOrder.ObjectValue */ : + return function __PRIVATE_objectEquals(t, e) { + const r = t.mapValue.fields || {}, n = e.mapValue.fields || {}; + if (__PRIVATE_objectSize(r) !== __PRIVATE_objectSize(n)) return !1; + for (const t in r) if (r.hasOwnProperty(t) && (void 0 === n[t] || !__PRIVATE_valueEquals(r[t], n[t]))) return !1; + return !0; + } + /** Returns true if the ArrayValue contains the specified element. */ (t, e); + + default: + return fail(52216, { + left: t + }); + } +} + +function __PRIVATE_arrayValueContains(t, e) { + return void 0 !== (t.values || []).find((t => __PRIVATE_valueEquals(t, e))); +} + +function __PRIVATE_valueCompare(t, e) { + if (t === e) return 0; + const r = __PRIVATE_typeOrder(t), n = __PRIVATE_typeOrder(e); + if (r !== n) return __PRIVATE_primitiveComparator(r, n); + switch (r) { + case 0 /* TypeOrder.NullValue */ : + case 9007199254740991 /* TypeOrder.MaxValue */ : + return 0; + + case 1 /* TypeOrder.BooleanValue */ : + return __PRIVATE_primitiveComparator(t.booleanValue, e.booleanValue); + + case 2 /* TypeOrder.NumberValue */ : + return function __PRIVATE_compareNumbers(t, e) { + const r = __PRIVATE_normalizeNumber(t.integerValue || t.doubleValue), n = __PRIVATE_normalizeNumber(e.integerValue || e.doubleValue); + return r < n ? -1 : r > n ? 1 : r === n ? 0 : + // one or both are NaN. + isNaN(r) ? isNaN(n) ? 0 : -1 : 1; + }(t, e); + + case 3 /* TypeOrder.TimestampValue */ : + return __PRIVATE_compareTimestamps(t.timestampValue, e.timestampValue); + + case 4 /* TypeOrder.ServerTimestampValue */ : + return __PRIVATE_compareTimestamps(__PRIVATE_getLocalWriteTime(t), __PRIVATE_getLocalWriteTime(e)); + + case 5 /* TypeOrder.StringValue */ : + return __PRIVATE_compareUtf8Strings(t.stringValue, e.stringValue); + + case 6 /* TypeOrder.BlobValue */ : + return function __PRIVATE_compareBlobs(t, e) { + const r = __PRIVATE_normalizeByteString(t), n = __PRIVATE_normalizeByteString(e); + return r.compareTo(n); + }(t.bytesValue, e.bytesValue); + + case 7 /* TypeOrder.RefValue */ : + return function __PRIVATE_compareReferences(t, e) { + const r = t.split("/"), n = e.split("/"); + for (let t = 0; t < r.length && t < n.length; t++) { + const e = __PRIVATE_primitiveComparator(r[t], n[t]); + if (0 !== e) return e; + } + return __PRIVATE_primitiveComparator(r.length, n.length); + }(t.referenceValue, e.referenceValue); + + case 8 /* TypeOrder.GeoPointValue */ : + return function __PRIVATE_compareGeoPoints(t, e) { + const r = __PRIVATE_primitiveComparator(__PRIVATE_normalizeNumber(t.latitude), __PRIVATE_normalizeNumber(e.latitude)); + if (0 !== r) return r; + return __PRIVATE_primitiveComparator(__PRIVATE_normalizeNumber(t.longitude), __PRIVATE_normalizeNumber(e.longitude)); + }(t.geoPointValue, e.geoPointValue); + + case 9 /* TypeOrder.ArrayValue */ : + return __PRIVATE_compareArrays(t.arrayValue, e.arrayValue); + + case 10 /* TypeOrder.VectorValue */ : + return function __PRIVATE_compareVectors(t, e) { + const r = t.fields || {}, n = e.fields || {}, i = r[et]?.arrayValue, s = n[et]?.arrayValue, o = __PRIVATE_primitiveComparator(i?.values?.length || 0, s?.values?.length || 0); + if (0 !== o) return o; + return __PRIVATE_compareArrays(i, s); + }(t.mapValue, e.mapValue); + + case 11 /* TypeOrder.ObjectValue */ : + return function __PRIVATE_compareMaps(t, e) { + if (t === X && e === X) return 0; + if (t === X) return 1; + if (e === X) return -1; + const r = t.fields || {}, n = Object.keys(r), i = e.fields || {}, s = Object.keys(i); + // Even though MapValues are likely sorted correctly based on their insertion + // order (e.g. when received from the backend), local modifications can bring + // elements out of order. We need to re-sort the elements to ensure that + // canonical IDs are independent of insertion order. + n.sort(), s.sort(); + for (let t = 0; t < n.length && t < s.length; ++t) { + const e = __PRIVATE_compareUtf8Strings(n[t], s[t]); + if (0 !== e) return e; + const o = __PRIVATE_valueCompare(r[n[t]], i[s[t]]); + if (0 !== o) return o; + } + return __PRIVATE_primitiveComparator(n.length, s.length); + } + /** Returns a reference value for the provided database and key. */ (t.mapValue, e.mapValue); + + default: + throw fail(23264, { + C: r + }); + } +} + +function __PRIVATE_compareTimestamps(t, e) { + if ("string" == typeof t && "string" == typeof e && t.length === e.length) return __PRIVATE_primitiveComparator(t, e); + const r = __PRIVATE_normalizeTimestamp(t), n = __PRIVATE_normalizeTimestamp(e), i = __PRIVATE_primitiveComparator(r.seconds, n.seconds); + return 0 !== i ? i : __PRIVATE_primitiveComparator(r.nanos, n.nanos); +} + +function __PRIVATE_compareArrays(t, e) { + const r = t.values || [], n = e.values || []; + for (let t = 0; t < r.length && t < n.length; ++t) { + const e = __PRIVATE_valueCompare(r[t], n[t]); + if (e) return e; + } + return __PRIVATE_primitiveComparator(r.length, n.length); +} + +function __PRIVATE_refValue(t, e) { + return { + referenceValue: `projects/${t.projectId}/databases/${t.database}/documents/${e.path.canonicalString()}` + }; +} + +/** Returns true if `value` is an ArrayValue. */ function isArray(t) { + return !!t && "arrayValue" in t; +} + +/** Returns true if `value` is a NullValue. */ function __PRIVATE_isNullValue(t) { + return !!t && "nullValue" in t; +} + +/** Returns true if `value` is NaN. */ function __PRIVATE_isNanValue(t) { + return !!t && "doubleValue" in t && isNaN(Number(t.doubleValue)); +} + +/** Returns true if `value` is a MapValue. */ function __PRIVATE_isMapValue(t) { + return !!t && "mapValue" in t; +} + +function __PRIVATE_deepClone(t) { + if (t.geoPointValue) return { + geoPointValue: { + ...t.geoPointValue + } + }; + if (t.timestampValue && "object" == typeof t.timestampValue) return { + timestampValue: { + ...t.timestampValue + } + }; + if (t.mapValue) { + const e = { + mapValue: { + fields: {} + } + }; + return forEach(t.mapValue.fields, ((t, r) => e.mapValue.fields[t] = __PRIVATE_deepClone(r))), + e; + } + if (t.arrayValue) { + const e = { + arrayValue: { + values: [] + } + }; + for (let r = 0; r < (t.arrayValue.values || []).length; ++r) e.arrayValue.values[r] = __PRIVATE_deepClone(t.arrayValue.values[r]); + return e; + } + return { + ...t + }; +} + +class Bound { + constructor(t, e) { + this.position = t, this.inclusive = e; + } +} + +function __PRIVATE_boundEquals(t, e) { + if (null === t) return null === e; + if (null === e) return !1; + if (t.inclusive !== e.inclusive || t.position.length !== e.position.length) return !1; + for (let r = 0; r < t.position.length; r++) { + if (!__PRIVATE_valueEquals(t.position[r], e.position[r])) return !1; + } + return !0; +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ class Filter {} + +class FieldFilter extends Filter { + constructor(t, e, r) { + super(), this.field = t, this.op = e, this.value = r; + } + /** + * Creates a filter based on the provided arguments. + */ static create(t, e, r) { + return t.isKeyField() ? "in" /* Operator.IN */ === e || "not-in" /* Operator.NOT_IN */ === e ? this.createKeyFieldInFilter(t, e, r) : new __PRIVATE_KeyFieldFilter(t, e, r) : "array-contains" /* Operator.ARRAY_CONTAINS */ === e ? new __PRIVATE_ArrayContainsFilter(t, r) : "in" /* Operator.IN */ === e ? new __PRIVATE_InFilter(t, r) : "not-in" /* Operator.NOT_IN */ === e ? new __PRIVATE_NotInFilter(t, r) : "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ === e ? new __PRIVATE_ArrayContainsAnyFilter(t, r) : new FieldFilter(t, e, r); + } + static createKeyFieldInFilter(t, e, r) { + return "in" /* Operator.IN */ === e ? new __PRIVATE_KeyFieldInFilter(t, r) : new __PRIVATE_KeyFieldNotInFilter(t, r); + } + matches(t) { + const e = t.data.field(this.field); + // Types do not have to match in NOT_EQUAL filters. + return "!=" /* Operator.NOT_EQUAL */ === this.op ? null !== e && void 0 === e.nullValue && this.matchesComparison(__PRIVATE_valueCompare(e, this.value)) : null !== e && __PRIVATE_typeOrder(this.value) === __PRIVATE_typeOrder(e) && this.matchesComparison(__PRIVATE_valueCompare(e, this.value)); + // Only compare types with matching backend order (such as double and int). + } + matchesComparison(t) { + switch (this.op) { + case "<" /* Operator.LESS_THAN */ : + return t < 0; + + case "<=" /* Operator.LESS_THAN_OR_EQUAL */ : + return t <= 0; + + case "==" /* Operator.EQUAL */ : + return 0 === t; + + case "!=" /* Operator.NOT_EQUAL */ : + return 0 !== t; + + case ">" /* Operator.GREATER_THAN */ : + return t > 0; + + case ">=" /* Operator.GREATER_THAN_OR_EQUAL */ : + return t >= 0; + + default: + return fail(47266, { + operator: this.op + }); + } + } + isInequality() { + return [ "<" /* Operator.LESS_THAN */ , "<=" /* Operator.LESS_THAN_OR_EQUAL */ , ">" /* Operator.GREATER_THAN */ , ">=" /* Operator.GREATER_THAN_OR_EQUAL */ , "!=" /* Operator.NOT_EQUAL */ , "not-in" /* Operator.NOT_IN */ ].indexOf(this.op) >= 0; + } + getFlattenedFilters() { + return [ this ]; + } + getFilters() { + return [ this ]; + } +} + +class CompositeFilter extends Filter { + constructor(t, e) { + super(), this.filters = t, this.op = e, this.N = null; + } + /** + * Creates a filter based on the provided arguments. + */ static create(t, e) { + return new CompositeFilter(t, e); + } + matches(t) { + return function __PRIVATE_compositeFilterIsConjunction(t) { + return "and" /* CompositeOperator.AND */ === t.op; + }(this) ? void 0 === this.filters.find((e => !e.matches(t))) : void 0 !== this.filters.find((e => e.matches(t))); + } + getFlattenedFilters() { + return null !== this.N || (this.N = this.filters.reduce(((t, e) => t.concat(e.getFlattenedFilters())), [])), + this.N; + } + // Returns a mutable copy of `this.filters` + getFilters() { + return Object.assign([], this.filters); + } +} + +function __PRIVATE_filterEquals(t, e) { + return t instanceof FieldFilter ? function __PRIVATE_fieldFilterEquals(t, e) { + return e instanceof FieldFilter && t.op === e.op && t.field.isEqual(e.field) && __PRIVATE_valueEquals(t.value, e.value); + }(t, e) : t instanceof CompositeFilter ? function __PRIVATE_compositeFilterEquals(t, e) { + if (e instanceof CompositeFilter && t.op === e.op && t.filters.length === e.filters.length) { + return t.filters.reduce(((t, r, n) => t && __PRIVATE_filterEquals(r, e.filters[n])), !0); + } + return !1; + } + /** Filter that matches on key fields (i.e. '__name__'). */ (t, e) : void fail(19439); +} + +class __PRIVATE_KeyFieldFilter extends FieldFilter { + constructor(t, e, r) { + super(t, e, r), this.key = DocumentKey.fromName(r.referenceValue); + } + matches(t) { + const e = DocumentKey.comparator(t.key, this.key); + return this.matchesComparison(e); + } +} + +/** Filter that matches on key fields within an array. */ class __PRIVATE_KeyFieldInFilter extends FieldFilter { + constructor(t, e) { + super(t, "in" /* Operator.IN */ , e), this.keys = __PRIVATE_extractDocumentKeysFromArrayValue("in" /* Operator.IN */ , e); + } + matches(t) { + return this.keys.some((e => e.isEqual(t.key))); + } +} + +/** Filter that matches on key fields not present within an array. */ class __PRIVATE_KeyFieldNotInFilter extends FieldFilter { + constructor(t, e) { + super(t, "not-in" /* Operator.NOT_IN */ , e), this.keys = __PRIVATE_extractDocumentKeysFromArrayValue("not-in" /* Operator.NOT_IN */ , e); + } + matches(t) { + return !this.keys.some((e => e.isEqual(t.key))); + } +} + +function __PRIVATE_extractDocumentKeysFromArrayValue(t, e) { + return (e.arrayValue?.values || []).map((t => DocumentKey.fromName(t.referenceValue))); +} + +/** A Filter that implements the array-contains operator. */ class __PRIVATE_ArrayContainsFilter extends FieldFilter { + constructor(t, e) { + super(t, "array-contains" /* Operator.ARRAY_CONTAINS */ , e); + } + matches(t) { + const e = t.data.field(this.field); + return isArray(e) && __PRIVATE_arrayValueContains(e.arrayValue, this.value); + } +} + +/** A Filter that implements the IN operator. */ class __PRIVATE_InFilter extends FieldFilter { + constructor(t, e) { + super(t, "in" /* Operator.IN */ , e); + } + matches(t) { + const e = t.data.field(this.field); + return null !== e && __PRIVATE_arrayValueContains(this.value.arrayValue, e); + } +} + +/** A Filter that implements the not-in operator. */ class __PRIVATE_NotInFilter extends FieldFilter { + constructor(t, e) { + super(t, "not-in" /* Operator.NOT_IN */ , e); + } + matches(t) { + if (__PRIVATE_arrayValueContains(this.value.arrayValue, { + nullValue: "NULL_VALUE" + })) return !1; + const e = t.data.field(this.field); + return null !== e && void 0 === e.nullValue && !__PRIVATE_arrayValueContains(this.value.arrayValue, e); + } +} + +/** A Filter that implements the array-contains-any operator. */ class __PRIVATE_ArrayContainsAnyFilter extends FieldFilter { + constructor(t, e) { + super(t, "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ , e); + } + matches(t) { + const e = t.data.field(this.field); + return !(!isArray(e) || !e.arrayValue.values) && e.arrayValue.values.some((t => __PRIVATE_arrayValueContains(this.value.arrayValue, t))); + } +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An ordering on a field, in some Direction. Direction defaults to ASCENDING. + */ class OrderBy { + constructor(t, e = "asc" /* Direction.ASCENDING */) { + this.field = t, this.dir = e; + } +} + +function __PRIVATE_orderByEquals(t, e) { + return t.dir === e.dir && t.field.isEqual(e.field); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A version of a document in Firestore. This corresponds to the version + * timestamp, such as update_time or read_time. + */ class SnapshotVersion { + static fromTimestamp(t) { + return new SnapshotVersion(t); + } + static min() { + return new SnapshotVersion(new Timestamp(0, 0)); + } + static max() { + return new SnapshotVersion(new Timestamp(253402300799, 999999999)); + } + constructor(t) { + this.timestamp = t; + } + compareTo(t) { + return this.timestamp._compareTo(t.timestamp); + } + isEqual(t) { + return this.timestamp.isEqual(t.timestamp); + } + /** Returns a number representation of the version for use in spec tests. */ toMicroseconds() { + // Convert to microseconds. + return 1e6 * this.timestamp.seconds + this.timestamp.nanoseconds / 1e3; + } + toString() { + return "SnapshotVersion(" + this.timestamp.toString() + ")"; + } + toTimestamp() { + return this.timestamp; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// An immutable sorted map implementation, based on a Left-leaning Red-Black +// tree. +class SortedMap { + constructor(t, e) { + this.comparator = t, this.root = e || LLRBNode.EMPTY; + } + // Returns a copy of the map, with the specified key/value added or replaced. + insert(t, e) { + return new SortedMap(this.comparator, this.root.insert(t, e, this.comparator).copy(null, null, LLRBNode.BLACK, null, null)); + } + // Returns a copy of the map, with the specified key removed. + remove(t) { + return new SortedMap(this.comparator, this.root.remove(t, this.comparator).copy(null, null, LLRBNode.BLACK, null, null)); + } + // Returns the value of the node with the given key, or null. + get(t) { + let e = this.root; + for (;!e.isEmpty(); ) { + const r = this.comparator(t, e.key); + if (0 === r) return e.value; + r < 0 ? e = e.left : r > 0 && (e = e.right); + } + return null; + } + // Returns the index of the element in this sorted map, or -1 if it doesn't + // exist. + indexOf(t) { + // Number of nodes that were pruned when descending right + let e = 0, r = this.root; + for (;!r.isEmpty(); ) { + const n = this.comparator(t, r.key); + if (0 === n) return e + r.left.size; + n < 0 ? r = r.left : ( + // Count all nodes left of the node plus the node itself + e += r.left.size + 1, r = r.right); + } + // Node not found + return -1; + } + isEmpty() { + return this.root.isEmpty(); + } + // Returns the total number of nodes in the map. + get size() { + return this.root.size; + } + // Returns the minimum key in the map. + minKey() { + return this.root.minKey(); + } + // Returns the maximum key in the map. + maxKey() { + return this.root.maxKey(); + } + // Traverses the map in key order and calls the specified action function + // for each key/value pair. If action returns true, traversal is aborted. + // Returns the first truthy value returned by action, or the last falsey + // value returned by action. + inorderTraversal(t) { + return this.root.inorderTraversal(t); + } + forEach(t) { + this.inorderTraversal(((e, r) => (t(e, r), !1))); + } + toString() { + const t = []; + return this.inorderTraversal(((e, r) => (t.push(`${e}:${r}`), !1))), `{${t.join(", ")}}`; + } + // Traverses the map in reverse key order and calls the specified action + // function for each key/value pair. If action returns true, traversal is + // aborted. + // Returns the first truthy value returned by action, or the last falsey + // value returned by action. + reverseTraversal(t) { + return this.root.reverseTraversal(t); + } + // Returns an iterator over the SortedMap. + getIterator() { + return new SortedMapIterator(this.root, null, this.comparator, !1); + } + getIteratorFrom(t) { + return new SortedMapIterator(this.root, t, this.comparator, !1); + } + getReverseIterator() { + return new SortedMapIterator(this.root, null, this.comparator, !0); + } + getReverseIteratorFrom(t) { + return new SortedMapIterator(this.root, t, this.comparator, !0); + } +} + + // end SortedMap +// An iterator over an LLRBNode. +class SortedMapIterator { + constructor(t, e, r, n) { + this.isReverse = n, this.nodeStack = []; + let i = 1; + for (;!t.isEmpty(); ) if (i = e ? r(t.key, e) : 1, + // flip the comparison if we're going in reverse + e && n && (i *= -1), i < 0) + // This node is less than our start key. ignore it + t = this.isReverse ? t.left : t.right; else { + if (0 === i) { + // This node is exactly equal to our start key. Push it on the stack, + // but stop iterating; + this.nodeStack.push(t); + break; + } + // This node is greater than our start key, add it to the stack and move + // to the next one + this.nodeStack.push(t), t = this.isReverse ? t.right : t.left; + } + } + getNext() { + let t = this.nodeStack.pop(); + const e = { + key: t.key, + value: t.value + }; + if (this.isReverse) for (t = t.left; !t.isEmpty(); ) this.nodeStack.push(t), t = t.right; else for (t = t.right; !t.isEmpty(); ) this.nodeStack.push(t), + t = t.left; + return e; + } + hasNext() { + return this.nodeStack.length > 0; + } + peek() { + if (0 === this.nodeStack.length) return null; + const t = this.nodeStack[this.nodeStack.length - 1]; + return { + key: t.key, + value: t.value + }; + } +} + + // end SortedMapIterator +// Represents a node in a Left-leaning Red-Black tree. +class LLRBNode { + constructor(t, e, r, n, i) { + this.key = t, this.value = e, this.color = null != r ? r : LLRBNode.RED, this.left = null != n ? n : LLRBNode.EMPTY, + this.right = null != i ? i : LLRBNode.EMPTY, this.size = this.left.size + 1 + this.right.size; + } + // Returns a copy of the current node, optionally replacing pieces of it. + copy(t, e, r, n, i) { + return new LLRBNode(null != t ? t : this.key, null != e ? e : this.value, null != r ? r : this.color, null != n ? n : this.left, null != i ? i : this.right); + } + isEmpty() { + return !1; + } + // Traverses the tree in key order and calls the specified action function + // for each node. If action returns true, traversal is aborted. + // Returns the first truthy value returned by action, or the last falsey + // value returned by action. + inorderTraversal(t) { + return this.left.inorderTraversal(t) || t(this.key, this.value) || this.right.inorderTraversal(t); + } + // Traverses the tree in reverse key order and calls the specified action + // function for each node. If action returns true, traversal is aborted. + // Returns the first truthy value returned by action, or the last falsey + // value returned by action. + reverseTraversal(t) { + return this.right.reverseTraversal(t) || t(this.key, this.value) || this.left.reverseTraversal(t); + } + // Returns the minimum node in the tree. + min() { + return this.left.isEmpty() ? this : this.left.min(); + } + // Returns the maximum key in the tree. + minKey() { + return this.min().key; + } + // Returns the maximum key in the tree. + maxKey() { + return this.right.isEmpty() ? this.key : this.right.maxKey(); + } + // Returns new tree, with the key/value added. + insert(t, e, r) { + let n = this; + const i = r(t, n.key); + return n = i < 0 ? n.copy(null, null, null, n.left.insert(t, e, r), null) : 0 === i ? n.copy(null, e, null, null, null) : n.copy(null, null, null, null, n.right.insert(t, e, r)), + n.fixUp(); + } + removeMin() { + if (this.left.isEmpty()) return LLRBNode.EMPTY; + let t = this; + return t.left.isRed() || t.left.left.isRed() || (t = t.moveRedLeft()), t = t.copy(null, null, null, t.left.removeMin(), null), + t.fixUp(); + } + // Returns new tree, with the specified item removed. + remove(t, e) { + let r, n = this; + if (e(t, n.key) < 0) n.left.isEmpty() || n.left.isRed() || n.left.left.isRed() || (n = n.moveRedLeft()), + n = n.copy(null, null, null, n.left.remove(t, e), null); else { + if (n.left.isRed() && (n = n.rotateRight()), n.right.isEmpty() || n.right.isRed() || n.right.left.isRed() || (n = n.moveRedRight()), + 0 === e(t, n.key)) { + if (n.right.isEmpty()) return LLRBNode.EMPTY; + r = n.right.min(), n = n.copy(r.key, r.value, null, null, n.right.removeMin()); + } + n = n.copy(null, null, null, null, n.right.remove(t, e)); + } + return n.fixUp(); + } + isRed() { + return this.color; + } + // Returns new tree after performing any needed rotations. + fixUp() { + let t = this; + return t.right.isRed() && !t.left.isRed() && (t = t.rotateLeft()), t.left.isRed() && t.left.left.isRed() && (t = t.rotateRight()), + t.left.isRed() && t.right.isRed() && (t = t.colorFlip()), t; + } + moveRedLeft() { + let t = this.colorFlip(); + return t.right.left.isRed() && (t = t.copy(null, null, null, null, t.right.rotateRight()), + t = t.rotateLeft(), t = t.colorFlip()), t; + } + moveRedRight() { + let t = this.colorFlip(); + return t.left.left.isRed() && (t = t.rotateRight(), t = t.colorFlip()), t; + } + rotateLeft() { + const t = this.copy(null, null, LLRBNode.RED, null, this.right.left); + return this.right.copy(null, null, this.color, t, null); + } + rotateRight() { + const t = this.copy(null, null, LLRBNode.RED, this.left.right, null); + return this.left.copy(null, null, this.color, null, t); + } + colorFlip() { + const t = this.left.copy(null, null, !this.left.color, null, null), e = this.right.copy(null, null, !this.right.color, null, null); + return this.copy(null, null, !this.color, t, e); + } + // For testing. + checkMaxDepth() { + const t = this.check(); + return Math.pow(2, t) <= this.size + 1; + } + // In a balanced RB tree, the black-depth (number of black nodes) from root to + // leaves is equal on both sides. This function verifies that or asserts. + check() { + if (this.isRed() && this.left.isRed()) throw fail(43730, { + key: this.key, + value: this.value + }); + if (this.right.isRed()) throw fail(14113, { + key: this.key, + value: this.value + }); + const t = this.left.check(); + if (t !== this.right.check()) throw fail(27949); + return t + (this.isRed() ? 0 : 1); + } +} + + // end LLRBNode +// Empty node is shared between all LLRB trees. +// eslint-disable-next-line @typescript-eslint/no-explicit-any +LLRBNode.EMPTY = null, LLRBNode.RED = !0, LLRBNode.BLACK = !1; + +// end LLRBEmptyNode +LLRBNode.EMPTY = new +// Represents an empty node (a leaf node in the Red-Black Tree). +class LLRBEmptyNode { + constructor() { + this.size = 0; + } + get key() { + throw fail(57766); + } + get value() { + throw fail(16141); + } + get color() { + throw fail(16727); + } + get left() { + throw fail(29726); + } + get right() { + throw fail(36894); + } + // Returns a copy of the current node. + copy(t, e, r, n, i) { + return this; + } + // Returns a copy of the tree, with the specified key/value added. + insert(t, e, r) { + return new LLRBNode(t, e); + } + // Returns a copy of the tree, with the specified key removed. + remove(t, e) { + return this; + } + isEmpty() { + return !0; + } + inorderTraversal(t) { + return !1; + } + reverseTraversal(t) { + return !1; + } + minKey() { + return null; + } + maxKey() { + return null; + } + isRed() { + return !1; + } + // For testing. + checkMaxDepth() { + return !0; + } + check() { + return 0; + } +}; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * SortedSet is an immutable (copy-on-write) collection that holds elements + * in order specified by the provided comparator. + * + * NOTE: if provided comparator returns 0 for two elements, we consider them to + * be equal! + */ +class SortedSet { + constructor(t) { + this.comparator = t, this.data = new SortedMap(this.comparator); + } + has(t) { + return null !== this.data.get(t); + } + first() { + return this.data.minKey(); + } + last() { + return this.data.maxKey(); + } + get size() { + return this.data.size; + } + indexOf(t) { + return this.data.indexOf(t); + } + /** Iterates elements in order defined by "comparator" */ forEach(t) { + this.data.inorderTraversal(((e, r) => (t(e), !1))); + } + /** Iterates over `elem`s such that: range[0] <= elem < range[1]. */ forEachInRange(t, e) { + const r = this.data.getIteratorFrom(t[0]); + for (;r.hasNext(); ) { + const n = r.getNext(); + if (this.comparator(n.key, t[1]) >= 0) return; + e(n.key); + } + } + /** + * Iterates over `elem`s such that: start <= elem until false is returned. + */ forEachWhile(t, e) { + let r; + for (r = void 0 !== e ? this.data.getIteratorFrom(e) : this.data.getIterator(); r.hasNext(); ) { + if (!t(r.getNext().key)) return; + } + } + /** Finds the least element greater than or equal to `elem`. */ firstAfterOrEqual(t) { + const e = this.data.getIteratorFrom(t); + return e.hasNext() ? e.getNext().key : null; + } + getIterator() { + return new SortedSetIterator(this.data.getIterator()); + } + getIteratorFrom(t) { + return new SortedSetIterator(this.data.getIteratorFrom(t)); + } + /** Inserts or updates an element */ add(t) { + return this.copy(this.data.remove(t).insert(t, !0)); + } + /** Deletes an element */ delete(t) { + return this.has(t) ? this.copy(this.data.remove(t)) : this; + } + isEmpty() { + return this.data.isEmpty(); + } + unionWith(t) { + let e = this; + // Make sure `result` always refers to the larger one of the two sets. + return e.size < t.size && (e = t, t = this), t.forEach((t => { + e = e.add(t); + })), e; + } + isEqual(t) { + if (!(t instanceof SortedSet)) return !1; + if (this.size !== t.size) return !1; + const e = this.data.getIterator(), r = t.data.getIterator(); + for (;e.hasNext(); ) { + const t = e.getNext().key, n = r.getNext().key; + if (0 !== this.comparator(t, n)) return !1; + } + return !0; + } + toArray() { + const t = []; + return this.forEach((e => { + t.push(e); + })), t; + } + toString() { + const t = []; + return this.forEach((e => t.push(e))), "SortedSet(" + t.toString() + ")"; + } + copy(t) { + const e = new SortedSet(this.comparator); + return e.data = t, e; + } +} + +class SortedSetIterator { + constructor(t) { + this.iter = t; + } + getNext() { + return this.iter.getNext().key; + } + hasNext() { + return this.iter.hasNext(); + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Provides a set of fields that can be used to partially patch a document. + * FieldMask is used in conjunction with ObjectValue. + * Examples: + * foo - Overwrites foo entirely with the provided value. If foo is not + * present in the companion ObjectValue, the field is deleted. + * foo.bar - Overwrites only the field bar of the object foo. + * If foo is not an object, foo is replaced with an object + * containing foo + */ class FieldMask { + constructor(t) { + this.fields = t, + // TODO(dimond): validation of FieldMask + // Sort the field mask to support `FieldMask.isEqual()` and assert below. + t.sort(FieldPath$1.comparator); + } + static empty() { + return new FieldMask([]); + } + /** + * Returns a new FieldMask object that is the result of adding all the given + * fields paths to this field mask. + */ unionWith(t) { + let e = new SortedSet(FieldPath$1.comparator); + for (const t of this.fields) e = e.add(t); + for (const r of t) e = e.add(r); + return new FieldMask(e.toArray()); + } + /** + * Verifies that `fieldPath` is included by at least one field in this field + * mask. + * + * This is an O(n) operation, where `n` is the size of the field mask. + */ covers(t) { + for (const e of this.fields) if (e.isPrefixOf(t)) return !0; + return !1; + } + isEqual(t) { + return __PRIVATE_arrayEquals(this.fields, t.fields, ((t, e) => t.isEqual(e))); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An ObjectValue represents a MapValue in the Firestore Proto and offers the + * ability to add and remove fields (via the ObjectValueBuilder). + */ class ObjectValue { + constructor(t) { + this.value = t; + } + static empty() { + return new ObjectValue({ + mapValue: {} + }); + } + /** + * Returns the value at the given path or null. + * + * @param path - the path to search + * @returns The value at the path or null if the path is not set. + */ field(t) { + if (t.isEmpty()) return this.value; + { + let e = this.value; + for (let r = 0; r < t.length - 1; ++r) if (e = (e.mapValue.fields || {})[t.get(r)], + !__PRIVATE_isMapValue(e)) return null; + return e = (e.mapValue.fields || {})[t.lastSegment()], e || null; + } + } + /** + * Sets the field to the provided value. + * + * @param path - The field path to set. + * @param value - The value to set. + */ set(t, e) { + this.getFieldsMap(t.popLast())[t.lastSegment()] = __PRIVATE_deepClone(e); + } + /** + * Sets the provided fields to the provided values. + * + * @param data - A map of fields to values (or null for deletes). + */ setAll(t) { + let e = FieldPath$1.emptyPath(), r = {}, n = []; + t.forEach(((t, i) => { + if (!e.isImmediateParentOf(i)) { + // Insert the accumulated changes at this parent location + const t = this.getFieldsMap(e); + this.applyChanges(t, r, n), r = {}, n = [], e = i.popLast(); + } + t ? r[i.lastSegment()] = __PRIVATE_deepClone(t) : n.push(i.lastSegment()); + })); + const i = this.getFieldsMap(e); + this.applyChanges(i, r, n); + } + /** + * Removes the field at the specified path. If there is no field at the + * specified path, nothing is changed. + * + * @param path - The field path to remove. + */ delete(t) { + const e = this.field(t.popLast()); + __PRIVATE_isMapValue(e) && e.mapValue.fields && delete e.mapValue.fields[t.lastSegment()]; + } + isEqual(t) { + return __PRIVATE_valueEquals(this.value, t.value); + } + /** + * Returns the map that contains the leaf element of `path`. If the parent + * entry does not yet exist, or if it is not a map, a new map will be created. + */ getFieldsMap(t) { + let e = this.value; + e.mapValue.fields || (e.mapValue = { + fields: {} + }); + for (let r = 0; r < t.length; ++r) { + let n = e.mapValue.fields[t.get(r)]; + __PRIVATE_isMapValue(n) && n.mapValue.fields || (n = { + mapValue: { + fields: {} + } + }, e.mapValue.fields[t.get(r)] = n), e = n; + } + return e.mapValue.fields; + } + /** + * Modifies `fieldsMap` by adding, replacing or deleting the specified + * entries. + */ applyChanges(t, e, r) { + forEach(e, ((e, r) => t[e] = r)); + for (const e of r) delete t[e]; + } + clone() { + return new ObjectValue(__PRIVATE_deepClone(this.value)); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Represents a document in Firestore with a key, version, data and whether it + * has local mutations applied to it. + * + * Documents can transition between states via `convertToFoundDocument()`, + * `convertToNoDocument()` and `convertToUnknownDocument()`. If a document does + * not transition to one of these states even after all mutations have been + * applied, `isValidDocument()` returns false and the document should be removed + * from all views. + */ class MutableDocument { + constructor(t, e, r, n, i, s, o) { + this.key = t, this.documentType = e, this.version = r, this.readTime = n, this.createTime = i, + this.data = s, this.documentState = o; + } + /** + * Creates a document with no known version or data, but which can serve as + * base document for mutations. + */ static newInvalidDocument(t) { + return new MutableDocument(t, 0 /* DocumentType.INVALID */ , + /* version */ SnapshotVersion.min(), + /* readTime */ SnapshotVersion.min(), + /* createTime */ SnapshotVersion.min(), ObjectValue.empty(), 0 /* DocumentState.SYNCED */); + } + /** + * Creates a new document that is known to exist with the given data at the + * given version. + */ static newFoundDocument(t, e, r, n) { + return new MutableDocument(t, 1 /* DocumentType.FOUND_DOCUMENT */ , + /* version */ e, + /* readTime */ SnapshotVersion.min(), + /* createTime */ r, n, 0 /* DocumentState.SYNCED */); + } + /** Creates a new document that is known to not exist at the given version. */ static newNoDocument(t, e) { + return new MutableDocument(t, 2 /* DocumentType.NO_DOCUMENT */ , + /* version */ e, + /* readTime */ SnapshotVersion.min(), + /* createTime */ SnapshotVersion.min(), ObjectValue.empty(), 0 /* DocumentState.SYNCED */); + } + /** + * Creates a new document that is known to exist at the given version but + * whose data is not known (e.g. a document that was updated without a known + * base document). + */ static newUnknownDocument(t, e) { + return new MutableDocument(t, 3 /* DocumentType.UNKNOWN_DOCUMENT */ , + /* version */ e, + /* readTime */ SnapshotVersion.min(), + /* createTime */ SnapshotVersion.min(), ObjectValue.empty(), 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */); + } + /** + * Changes the document type to indicate that it exists and that its version + * and data are known. + */ convertToFoundDocument(t, e) { + // If a document is switching state from being an invalid or deleted + // document to a valid (FOUND_DOCUMENT) document, either due to receiving an + // update from Watch or due to applying a local set mutation on top + // of a deleted document, our best guess about its createTime would be the + // version at which the document transitioned to a FOUND_DOCUMENT. + return !this.createTime.isEqual(SnapshotVersion.min()) || 2 /* DocumentType.NO_DOCUMENT */ !== this.documentType && 0 /* DocumentType.INVALID */ !== this.documentType || (this.createTime = t), + this.version = t, this.documentType = 1 /* DocumentType.FOUND_DOCUMENT */ , this.data = e, + this.documentState = 0 /* DocumentState.SYNCED */ , this; + } + /** + * Changes the document type to indicate that it doesn't exist at the given + * version. + */ convertToNoDocument(t) { + return this.version = t, this.documentType = 2 /* DocumentType.NO_DOCUMENT */ , + this.data = ObjectValue.empty(), this.documentState = 0 /* DocumentState.SYNCED */ , + this; + } + /** + * Changes the document type to indicate that it exists at a given version but + * that its data is not known (e.g. a document that was updated without a known + * base document). + */ convertToUnknownDocument(t) { + return this.version = t, this.documentType = 3 /* DocumentType.UNKNOWN_DOCUMENT */ , + this.data = ObjectValue.empty(), this.documentState = 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */ , + this; + } + setHasCommittedMutations() { + return this.documentState = 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */ , this; + } + setHasLocalMutations() { + return this.documentState = 1 /* DocumentState.HAS_LOCAL_MUTATIONS */ , this.version = SnapshotVersion.min(), + this; + } + setReadTime(t) { + return this.readTime = t, this; + } + get hasLocalMutations() { + return 1 /* DocumentState.HAS_LOCAL_MUTATIONS */ === this.documentState; + } + get hasCommittedMutations() { + return 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */ === this.documentState; + } + get hasPendingWrites() { + return this.hasLocalMutations || this.hasCommittedMutations; + } + isValidDocument() { + return 0 /* DocumentType.INVALID */ !== this.documentType; + } + isFoundDocument() { + return 1 /* DocumentType.FOUND_DOCUMENT */ === this.documentType; + } + isNoDocument() { + return 2 /* DocumentType.NO_DOCUMENT */ === this.documentType; + } + isUnknownDocument() { + return 3 /* DocumentType.UNKNOWN_DOCUMENT */ === this.documentType; + } + isEqual(t) { + return t instanceof MutableDocument && this.key.isEqual(t.key) && this.version.isEqual(t.version) && this.documentType === t.documentType && this.documentState === t.documentState && this.data.isEqual(t.data); + } + mutableCopy() { + return new MutableDocument(this.key, this.documentType, this.version, this.readTime, this.createTime, this.data.clone(), this.documentState); + } + toString() { + return `Document(${this.key}, ${this.version}, ${JSON.stringify(this.data.value)}, {createTime: ${this.createTime}}), {documentType: ${this.documentType}}), {documentState: ${this.documentState}})`; + } +} + +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// Visible for testing +class __PRIVATE_TargetImpl { + constructor(t, e = null, r = [], n = [], i = null, s = null, o = null) { + this.path = t, this.collectionGroup = e, this.orderBy = r, this.filters = n, this.limit = i, + this.startAt = s, this.endAt = o, this.O = null; + } +} + +/** + * Initializes a Target with a path and optional additional query constraints. + * Path must currently be empty if this is a collection group query. + * + * NOTE: you should always construct `Target` from `Query.toTarget` instead of + * using this factory method, because `Query` provides an implicit `orderBy` + * property. + */ function __PRIVATE_newTarget(t, e = null, r = [], n = [], i = null, s = null, o = null) { + return new __PRIVATE_TargetImpl(t, e, r, n, i, s, o); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Query encapsulates all the query attributes we support in the SDK. It can + * be run against the LocalStore, as well as be converted to a `Target` to + * query the RemoteStore results. + * + * Visible for testing. + */ +class __PRIVATE_QueryImpl { + /** + * Initializes a Query with a path and optional additional query constraints. + * Path must currently be empty if this is a collection group query. + */ + constructor(t, e = null, r = [], n = [], i = null, s = "F" /* LimitType.First */ , o = null, a = null) { + this.path = t, this.collectionGroup = e, this.explicitOrderBy = r, this.filters = n, + this.limit = i, this.limitType = s, this.startAt = o, this.endAt = a, this.q = null, + // The corresponding `Target` of this `Query` instance, for use with + // non-aggregate queries. + this.B = null, + // The corresponding `Target` of this `Query` instance, for use with + // aggregate queries. Unlike targets for non-aggregate queries, + // aggregate query targets do not contain normalized order-bys, they only + // contain explicit order-bys. + this.$ = null, this.startAt, this.endAt; + } +} + +/** Creates a new Query for a query that matches all documents at `path` */ +/** + * Returns whether the query matches a collection group rather than a specific + * collection. + */ +function __PRIVATE_isCollectionGroupQuery(t) { + return null !== t.collectionGroup; +} + +/** + * Returns the normalized order-by constraint that is used to execute the Query, + * which can be different from the order-by constraints the user provided (e.g. + * the SDK and backend always orders by `__name__`). The normalized order-by + * includes implicit order-bys in addition to the explicit user provided + * order-bys. + */ function __PRIVATE_queryNormalizedOrderBy(t) { + const e = __PRIVATE_debugCast(t); + if (null === e.q) { + e.q = []; + const t = new Set; + // Any explicit order by fields should be added as is. + for (const r of e.explicitOrderBy) e.q.push(r), t.add(r.field.canonicalString()); + // The order of the implicit ordering always matches the last explicit order by. + const r = e.explicitOrderBy.length > 0 ? e.explicitOrderBy[e.explicitOrderBy.length - 1].dir : "asc" /* Direction.ASCENDING */ , n = + // Returns the sorted set of inequality filter fields used in this query. + function __PRIVATE_getInequalityFilterFields(t) { + let e = new SortedSet(FieldPath$1.comparator); + return t.filters.forEach((t => { + t.getFlattenedFilters().forEach((t => { + t.isInequality() && (e = e.add(t.field)); + })); + })), e; + } + /** + * Creates a new Query for a collection group query that matches all documents + * within the provided collection group. + */ (e); + // Any inequality fields not explicitly ordered should be implicitly ordered in a lexicographical + // order. When there are multiple inequality filters on the same field, the field should be added + // only once. + // Note: `SortedSet` sorts the key field before other fields. However, we want the key + // field to be sorted last. + n.forEach((n => { + t.has(n.canonicalString()) || n.isKeyField() || e.q.push(new OrderBy(n, r)); + })), + // Add the document key field to the last if it is not explicitly ordered. + t.has(FieldPath$1.keyField().canonicalString()) || e.q.push(new OrderBy(FieldPath$1.keyField(), r)); + } + return e.q; +} + +/** + * Converts this `Query` instance to its corresponding `Target` representation. + */ function __PRIVATE_queryToTarget(t) { + const e = __PRIVATE_debugCast(t); + return e.B || (e.B = __PRIVATE__queryToTarget(e, __PRIVATE_queryNormalizedOrderBy(t))), + e.B; +} + +/** + * Converts this `Query` instance to its corresponding `Target` representation, + * for use within an aggregate query. Unlike targets for non-aggregate queries, + * aggregate query targets do not contain normalized order-bys, they only + * contain explicit order-bys. + */ function __PRIVATE__queryToTarget(t, e) { + if ("F" /* LimitType.First */ === t.limitType) return __PRIVATE_newTarget(t.path, t.collectionGroup, e, t.filters, t.limit, t.startAt, t.endAt); + { + // Flip the orderBy directions since we want the last results + e = e.map((t => { + const e = "desc" /* Direction.DESCENDING */ === t.dir ? "asc" /* Direction.ASCENDING */ : "desc" /* Direction.DESCENDING */; + return new OrderBy(t.field, e); + })); + // We need to swap the cursors to match the now-flipped query ordering. + const r = t.endAt ? new Bound(t.endAt.position, t.endAt.inclusive) : null, n = t.startAt ? new Bound(t.startAt.position, t.startAt.inclusive) : null; + // Now return as a LimitType.First query. + return __PRIVATE_newTarget(t.path, t.collectionGroup, e, t.filters, t.limit, r, n); + } +} + +function __PRIVATE_queryWithAddedFilter(t, e) { + const r = t.filters.concat([ e ]); + return new __PRIVATE_QueryImpl(t.path, t.collectionGroup, t.explicitOrderBy.slice(), r, t.limit, t.limitType, t.startAt, t.endAt); +} + +function __PRIVATE_queryEquals(t, e) { + return function __PRIVATE_targetEquals(t, e) { + if (t.limit !== e.limit) return !1; + if (t.orderBy.length !== e.orderBy.length) return !1; + for (let r = 0; r < t.orderBy.length; r++) if (!__PRIVATE_orderByEquals(t.orderBy[r], e.orderBy[r])) return !1; + if (t.filters.length !== e.filters.length) return !1; + for (let r = 0; r < t.filters.length; r++) if (!__PRIVATE_filterEquals(t.filters[r], e.filters[r])) return !1; + return t.collectionGroup === e.collectionGroup && !!t.path.isEqual(e.path) && !!__PRIVATE_boundEquals(t.startAt, e.startAt) && __PRIVATE_boundEquals(t.endAt, e.endAt); + }(__PRIVATE_queryToTarget(t), __PRIVATE_queryToTarget(e)) && t.limitType === e.limitType; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Returns an DoubleValue for `value` that is encoded based the serializer's + * `useProto3Json` setting. + */ function __PRIVATE_toDouble(t, e) { + if (t.useProto3Json) { + if (isNaN(e)) return { + doubleValue: "NaN" + }; + if (e === 1 / 0) return { + doubleValue: "Infinity" + }; + if (e === -1 / 0) return { + doubleValue: "-Infinity" + }; + } + return { + doubleValue: __PRIVATE_isNegativeZero(e) ? "-0" : e + }; +} + +/** + * Returns an IntegerValue for `value`. + */ +/** + * Returns a value for a number that's appropriate to put into a proto. + * The return value is an IntegerValue if it can safely represent the value, + * otherwise a DoubleValue is returned. + */ +function toNumber(t, e) { + return function isSafeInteger(t) { + return "number" == typeof t && Number.isInteger(t) && !__PRIVATE_isNegativeZero(t) && t <= Number.MAX_SAFE_INTEGER && t >= Number.MIN_SAFE_INTEGER; + }(e) ? function __PRIVATE_toInteger(t) { + return { + integerValue: "" + t + }; + }(e) : __PRIVATE_toDouble(t, e); +} + +/** + * @license + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Used to represent a field transform on a mutation. */ class TransformOperation { + constructor() { + // Make sure that the structural type of `TransformOperation` is unique. + // See https://github.com/microsoft/TypeScript/issues/5451 + this._ = void 0; + } +} + +/** Transforms a value into a server-generated timestamp. */ class __PRIVATE_ServerTimestampTransform extends TransformOperation {} + +/** Transforms an array value via a union operation. */ class __PRIVATE_ArrayUnionTransformOperation extends TransformOperation { + constructor(t) { + super(), this.elements = t; + } +} + +/** Transforms an array value via a remove operation. */ class __PRIVATE_ArrayRemoveTransformOperation extends TransformOperation { + constructor(t) { + super(), this.elements = t; + } +} + +/** + * Implements the backend semantics for locally computed NUMERIC_ADD (increment) + * transforms. Converts all field values to integers or doubles, but unlike the + * backend does not cap integer values at 2^63. Instead, JavaScript number + * arithmetic is used and precision loss can occur for values greater than 2^53. + */ class __PRIVATE_NumericIncrementTransformOperation extends TransformOperation { + constructor(t, e) { + super(), this.serializer = t, this.k = e; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** A field path and the TransformOperation to perform upon it. */ class FieldTransform { + constructor(t, e) { + this.field = t, this.transform = e; + } +} + +/** + * Encodes a precondition for a mutation. This follows the model that the + * backend accepts with the special case of an explicit "empty" precondition + * (meaning no precondition). + */ class Precondition { + constructor(t, e) { + this.updateTime = t, this.exists = e; + } + /** Creates a new empty Precondition. */ static none() { + return new Precondition; + } + /** Creates a new Precondition with an exists flag. */ static exists(t) { + return new Precondition(void 0, t); + } + /** Creates a new Precondition based on a version a document exists at. */ static updateTime(t) { + return new Precondition(t); + } + /** Returns whether this Precondition is empty. */ get isNone() { + return void 0 === this.updateTime && void 0 === this.exists; + } + isEqual(t) { + return this.exists === t.exists && (this.updateTime ? !!t.updateTime && this.updateTime.isEqual(t.updateTime) : !t.updateTime); + } +} + +/** + * A mutation describes a self-contained change to a document. Mutations can + * create, replace, delete, and update subsets of documents. + * + * Mutations not only act on the value of the document but also its version. + * + * For local mutations (mutations that haven't been committed yet), we preserve + * the existing version for Set and Patch mutations. For Delete mutations, we + * reset the version to 0. + * + * Here's the expected transition table. + * + * MUTATION APPLIED TO RESULTS IN + * + * SetMutation Document(v3) Document(v3) + * SetMutation NoDocument(v3) Document(v0) + * SetMutation InvalidDocument(v0) Document(v0) + * PatchMutation Document(v3) Document(v3) + * PatchMutation NoDocument(v3) NoDocument(v3) + * PatchMutation InvalidDocument(v0) UnknownDocument(v3) + * DeleteMutation Document(v3) NoDocument(v0) + * DeleteMutation NoDocument(v3) NoDocument(v0) + * DeleteMutation InvalidDocument(v0) NoDocument(v0) + * + * For acknowledged mutations, we use the updateTime of the WriteResponse as + * the resulting version for Set and Patch mutations. As deletes have no + * explicit update time, we use the commitTime of the WriteResponse for + * Delete mutations. + * + * If a mutation is acknowledged by the backend but fails the precondition check + * locally, we transition to an `UnknownDocument` and rely on Watch to send us + * the updated version. + * + * Field transforms are used only with Patch and Set Mutations. We use the + * `updateTransforms` message to store transforms, rather than the `transforms`s + * messages. + * + * ## Subclassing Notes + * + * Every type of mutation needs to implement its own applyToRemoteDocument() and + * applyToLocalView() to implement the actual behavior of applying the mutation + * to some source document (see `setMutationApplyToRemoteDocument()` for an + * example). + */ class Mutation {} + +/** + * A mutation that creates or replaces the document at the given key with the + * object value contents. + */ class __PRIVATE_SetMutation extends Mutation { + constructor(t, e, r, n = []) { + super(), this.key = t, this.value = e, this.precondition = r, this.fieldTransforms = n, + this.type = 0 /* MutationType.Set */; + } + getFieldMask() { + return null; + } +} + +/** + * A mutation that modifies fields of the document at the given key with the + * given values. The values are applied through a field mask: + * + * * When a field is in both the mask and the values, the corresponding field + * is updated. + * * When a field is in neither the mask nor the values, the corresponding + * field is unmodified. + * * When a field is in the mask but not in the values, the corresponding field + * is deleted. + * * When a field is not in the mask but is in the values, the values map is + * ignored. + */ class __PRIVATE_PatchMutation extends Mutation { + constructor(t, e, r, n, i = []) { + super(), this.key = t, this.data = e, this.fieldMask = r, this.precondition = n, + this.fieldTransforms = i, this.type = 1 /* MutationType.Patch */; + } + getFieldMask() { + return this.fieldMask; + } +} + +/** A mutation that deletes the document at the given key. */ class __PRIVATE_DeleteMutation extends Mutation { + constructor(t, e) { + super(), this.key = t, this.precondition = e, this.type = 2 /* MutationType.Delete */ , + this.fieldTransforms = []; + } + getFieldMask() { + return null; + } +} + +/** + * A mutation that verifies the existence of the document at the given key with + * the provided precondition. + * + * The `verify` operation is only used in Transactions, and this class serves + * primarily to facilitate serialization into protos. + */ class __PRIVATE_VerifyMutation extends Mutation { + constructor(t, e) { + super(), this.key = t, this.precondition = e, this.type = 3 /* MutationType.Verify */ , + this.fieldTransforms = []; + } + getFieldMask() { + return null; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ const rt = (() => { + const t = { + asc: "ASCENDING", + desc: "DESCENDING" + }; + return t; +})(), nt = (() => { + const t = { + "<": "LESS_THAN", + "<=": "LESS_THAN_OR_EQUAL", + ">": "GREATER_THAN", + ">=": "GREATER_THAN_OR_EQUAL", + "==": "EQUAL", + "!=": "NOT_EQUAL", + "array-contains": "ARRAY_CONTAINS", + in: "IN", + "not-in": "NOT_IN", + "array-contains-any": "ARRAY_CONTAINS_ANY" + }; + return t; +})(), it = (() => { + const t = { + and: "AND", + or: "OR" + }; + return t; +})(); + +/** + * This class generates JsonObject values for the Datastore API suitable for + * sending to either GRPC stub methods or via the JSON/HTTP REST API. + * + * The serializer supports both Protobuf.js and Proto3 JSON formats. By + * setting `useProto3Json` to true, the serializer will use the Proto3 JSON + * format. + * + * For a description of the Proto3 JSON format check + * https://developers.google.com/protocol-buffers/docs/proto3#json + * + * TODO(klimt): We can remove the databaseId argument if we keep the full + * resource name in documents. + */ +class JsonProtoSerializer { + constructor(t, e) { + this.databaseId = t, this.useProto3Json = e; + } +} + +/** + * Returns a value for a number (or null) that's appropriate to put into + * a google.protobuf.Int32Value proto. + * DO NOT USE THIS FOR ANYTHING ELSE. + * This method cheats. It's typed as returning "number" because that's what + * our generated proto interfaces say Int32Value must be. But GRPC actually + * expects a { value: } struct. + */ +/** + * Returns a value for a Date that's appropriate to put into a proto. + */ +function toTimestamp(t, e) { + if (t.useProto3Json) { + return `${new Date(1e3 * e.seconds).toISOString().replace(/\.\d*/, "").replace("Z", "")}.${("000000000" + e.nanoseconds).slice(-9)}Z`; + } + return { + seconds: "" + e.seconds, + nanos: e.nanoseconds + }; +} + +/** + * Returns a Timestamp typed object given protobuf timestamp value. + */ +/** + * Returns a value for bytes that's appropriate to put in a proto. + * + * Visible for testing. + */ +function __PRIVATE_toBytes(t, e) { + return t.useProto3Json ? e.toBase64() : e.toUint8Array(); +} + +function __PRIVATE_toVersion(t, e) { + return toTimestamp(t, e.toTimestamp()); +} + +function __PRIVATE_fromVersion(t) { + return __PRIVATE_hardAssert(!!t, 49232), SnapshotVersion.fromTimestamp(function fromTimestamp(t) { + const e = __PRIVATE_normalizeTimestamp(t); + return new Timestamp(e.seconds, e.nanos); + }(t)); +} + +function __PRIVATE_toResourceName(t, e) { + return __PRIVATE_toResourcePath(t, e).canonicalString(); +} + +function __PRIVATE_toResourcePath(t, e) { + const r = function __PRIVATE_fullyQualifiedPrefixPath(t) { + return new ResourcePath([ "projects", t.projectId, "databases", t.database ]); + }(t).child("documents"); + return void 0 === e ? r : r.child(e); +} + +function __PRIVATE_toName(t, e) { + return __PRIVATE_toResourceName(t.databaseId, e.path); +} + +function fromName(t, e) { + const r = function __PRIVATE_fromResourceName(t) { + const e = ResourcePath.fromString(t); + return __PRIVATE_hardAssert(__PRIVATE_isValidResourceName(e), 10190, { + key: e.toString() + }), e; + }(e); + if (r.get(1) !== t.databaseId.projectId) throw new FirestoreError(y, "Tried to deserialize key from different project: " + r.get(1) + " vs " + t.databaseId.projectId); + if (r.get(3) !== t.databaseId.database) throw new FirestoreError(y, "Tried to deserialize key from different database: " + r.get(3) + " vs " + t.databaseId.database); + return new DocumentKey(function __PRIVATE_extractLocalPathFromResourceName(t) { + return __PRIVATE_hardAssert(t.length > 4 && "documents" === t.get(4), 29091, { + key: t.toString() + }), t.popFirst(5); + } + /** Creates a Document proto from key and fields (but no create/update time) */ (r)); +} + +function __PRIVATE_toMutationDocument(t, e, r) { + return { + name: __PRIVATE_toName(t, e), + fields: r.value.mapValue.fields + }; +} + +function __PRIVATE_fromBatchGetDocumentsResponse(t, e) { + return "found" in e ? function __PRIVATE_fromFound(t, e) { + __PRIVATE_hardAssert(!!e.found, 43571), e.found.name, e.found.updateTime; + const r = fromName(t, e.found.name), n = __PRIVATE_fromVersion(e.found.updateTime), i = e.found.createTime ? __PRIVATE_fromVersion(e.found.createTime) : SnapshotVersion.min(), s = new ObjectValue({ + mapValue: { + fields: e.found.fields + } + }); + return MutableDocument.newFoundDocument(r, n, i, s); + }(t, e) : "missing" in e ? function __PRIVATE_fromMissing(t, e) { + __PRIVATE_hardAssert(!!e.missing, 3894), __PRIVATE_hardAssert(!!e.readTime, 22933); + const r = fromName(t, e.missing), n = __PRIVATE_fromVersion(e.readTime); + return MutableDocument.newNoDocument(r, n); + }(t, e) : fail(7234, { + result: e + }); +} + +function toMutation(t, e) { + let r; + if (e instanceof __PRIVATE_SetMutation) r = { + update: __PRIVATE_toMutationDocument(t, e.key, e.value) + }; else if (e instanceof __PRIVATE_DeleteMutation) r = { + delete: __PRIVATE_toName(t, e.key) + }; else if (e instanceof __PRIVATE_PatchMutation) r = { + update: __PRIVATE_toMutationDocument(t, e.key, e.data), + updateMask: __PRIVATE_toDocumentMask(e.fieldMask) + }; else { + if (!(e instanceof __PRIVATE_VerifyMutation)) return fail(16599, { + L: e.type + }); + r = { + verify: __PRIVATE_toName(t, e.key) + }; + } + return e.fieldTransforms.length > 0 && (r.updateTransforms = e.fieldTransforms.map((t => function __PRIVATE_toFieldTransform(t, e) { + const r = e.transform; + if (r instanceof __PRIVATE_ServerTimestampTransform) return { + fieldPath: e.field.canonicalString(), + setToServerValue: "REQUEST_TIME" + }; + if (r instanceof __PRIVATE_ArrayUnionTransformOperation) return { + fieldPath: e.field.canonicalString(), + appendMissingElements: { + values: r.elements + } + }; + if (r instanceof __PRIVATE_ArrayRemoveTransformOperation) return { + fieldPath: e.field.canonicalString(), + removeAllFromArray: { + values: r.elements + } + }; + if (r instanceof __PRIVATE_NumericIncrementTransformOperation) return { + fieldPath: e.field.canonicalString(), + increment: r.k + }; + throw fail(20930, { + transform: e.transform + }); + }(0, t)))), e.precondition.isNone || (r.currentDocument = function __PRIVATE_toPrecondition(t, e) { + return void 0 !== e.updateTime ? { + updateTime: __PRIVATE_toVersion(t, e.updateTime) + } : void 0 !== e.exists ? { + exists: e.exists + } : fail(27497); + }(t, e.precondition)), r; +} + +function __PRIVATE_toQueryTarget(t, e) { + // Dissect the path into parent, collectionId, and optional key filter. + const r = { + structuredQuery: {} + }, n = e.path; + let i; + null !== e.collectionGroup ? (i = n, r.structuredQuery.from = [ { + collectionId: e.collectionGroup, + allDescendants: !0 + } ]) : (i = n.popLast(), r.structuredQuery.from = [ { + collectionId: n.lastSegment() + } ]), r.parent = function __PRIVATE_toQueryPath(t, e) { + return __PRIVATE_toResourceName(t.databaseId, e); + }(t, i); + const s = function __PRIVATE_toFilters(t) { + if (0 === t.length) return; + return __PRIVATE_toFilter(CompositeFilter.create(t, "and" /* CompositeOperator.AND */)); + }(e.filters); + s && (r.structuredQuery.where = s); + const o = function __PRIVATE_toOrder(t) { + if (0 === t.length) return; + return t.map((t => + // visible for testing + function __PRIVATE_toPropertyOrder(t) { + return { + field: __PRIVATE_toFieldPathReference(t.field), + direction: __PRIVATE_toDirection(t.dir) + }; + } + // visible for testing + (t))); + }(e.orderBy); + o && (r.structuredQuery.orderBy = o); + const a = function __PRIVATE_toInt32Proto(t, e) { + return t.useProto3Json || __PRIVATE_isNullOrUndefined(e) ? e : { + value: e + }; + }(t, e.limit); + return null !== a && (r.structuredQuery.limit = a), e.startAt && (r.structuredQuery.startAt = function __PRIVATE_toStartAtCursor(t) { + return { + before: t.inclusive, + values: t.position + }; + }(e.startAt)), e.endAt && (r.structuredQuery.endAt = function __PRIVATE_toEndAtCursor(t) { + return { + before: !t.inclusive, + values: t.position + }; + } + // visible for testing + (e.endAt)), { + M: r, + parent: i + }; +} + +function __PRIVATE_toDirection(t) { + return rt[t]; +} + +// visible for testing +function __PRIVATE_toOperatorName(t) { + return nt[t]; +} + +function __PRIVATE_toCompositeOperatorName(t) { + return it[t]; +} + +function __PRIVATE_toFieldPathReference(t) { + return { + fieldPath: t.canonicalString() + }; +} + +function __PRIVATE_toFilter(t) { + return t instanceof FieldFilter ? function __PRIVATE_toUnaryOrFieldFilter(t) { + if ("==" /* Operator.EQUAL */ === t.op) { + if (__PRIVATE_isNanValue(t.value)) return { + unaryFilter: { + field: __PRIVATE_toFieldPathReference(t.field), + op: "IS_NAN" + } + }; + if (__PRIVATE_isNullValue(t.value)) return { + unaryFilter: { + field: __PRIVATE_toFieldPathReference(t.field), + op: "IS_NULL" + } + }; + } else if ("!=" /* Operator.NOT_EQUAL */ === t.op) { + if (__PRIVATE_isNanValue(t.value)) return { + unaryFilter: { + field: __PRIVATE_toFieldPathReference(t.field), + op: "IS_NOT_NAN" + } + }; + if (__PRIVATE_isNullValue(t.value)) return { + unaryFilter: { + field: __PRIVATE_toFieldPathReference(t.field), + op: "IS_NOT_NULL" + } + }; + } + return { + fieldFilter: { + field: __PRIVATE_toFieldPathReference(t.field), + op: __PRIVATE_toOperatorName(t.op), + value: t.value + } + }; + }(t) : t instanceof CompositeFilter ? function __PRIVATE_toCompositeFilter(t) { + const e = t.getFilters().map((t => __PRIVATE_toFilter(t))); + if (1 === e.length) return e[0]; + return { + compositeFilter: { + op: __PRIVATE_toCompositeOperatorName(t.op), + filters: e + } + }; + }(t) : fail(54877, { + filter: t + }); +} + +function __PRIVATE_toDocumentMask(t) { + const e = []; + return t.fields.forEach((t => e.push(t.canonicalString()))), { + fieldPaths: e + }; +} + +function __PRIVATE_isValidResourceName(t) { + // Resource names have at least 4 components (project ID, database ID) + return t.length >= 4 && "projects" === t.get(0) && "databases" === t.get(2); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ function __PRIVATE_newSerializer(t) { + return new JsonProtoSerializer(t, /* useProto3Json= */ !0); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A helper for running delayed tasks following an exponential backoff curve + * between attempts. + * + * Each delay is made up of a "base" delay which follows the exponential + * backoff curve, and a +/- 50% "jitter" that is calculated and added to the + * base delay. This prevents clients from accidentally synchronizing their + * delays causing spikes of load to the backend. + */ +class __PRIVATE_ExponentialBackoff { + constructor( + /** + * The AsyncQueue to run backoff operations on. + */ + t, + /** + * The ID to use when scheduling backoff operations on the AsyncQueue. + */ + e, + /** + * The initial delay (used as the base delay on the first retry attempt). + * Note that jitter will still be applied, so the actual delay could be as + * little as 0.5*initialDelayMs. + */ + r = 1e3 + /** + * The multiplier to use to determine the extended base delay after each + * attempt. + */ , n = 1.5 + /** + * The maximum base delay after which no further backoff is performed. + * Note that jitter will still be applied, so the actual delay could be as + * much as 1.5*maxDelayMs. + */ , i = 6e4) { + this.U = t, this.timerId = e, this.j = r, this.W = n, this.K = i, this.G = 0, this.J = null, + /** The last backoff attempt, as epoch milliseconds. */ + this.H = Date.now(), this.reset(); + } + /** + * Resets the backoff delay. + * + * The very next backoffAndWait() will have no delay. If it is called again + * (i.e. due to an error), initialDelayMs (plus jitter) will be used, and + * subsequent ones will increase according to the backoffFactor. + */ reset() { + this.G = 0; + } + /** + * Resets the backoff delay to the maximum delay (e.g. for use after a + * RESOURCE_EXHAUSTED error). + */ Y() { + this.G = this.K; + } + /** + * Returns a promise that resolves after currentDelayMs, and increases the + * delay for any subsequent attempts. If there was a pending backoff operation + * already, it will be canceled. + */ Z(t) { + // Cancel any pending backoff operation. + this.cancel(); + // First schedule using the current base (which may be 0 and should be + // honored as such). + const e = Math.floor(this.G + this.X()), r = Math.max(0, Date.now() - this.H), n = Math.max(0, e - r); + // Guard against lastAttemptTime being in the future due to a clock change. + n > 0 && __PRIVATE_logDebug("ExponentialBackoff", `Backing off for ${n} ms (base delay: ${this.G} ms, delay with jitter: ${e} ms, last attempt: ${r} ms ago)`), + this.J = this.U.enqueueAfterDelay(this.timerId, n, (() => (this.H = Date.now(), + t()))), + // Apply backoff factor to determine next delay and ensure it is within + // bounds. + this.G *= this.W, this.G < this.j && (this.G = this.j), this.G > this.K && (this.G = this.K); + } + tt() { + null !== this.J && (this.J.skipDelay(), this.J = null); + } + cancel() { + null !== this.J && (this.J.cancel(), this.J = null); + } + /** Returns a random value in the range [-currentBaseMs/2, currentBaseMs/2] */ X() { + return (Math.random() - .5) * this.G; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Datastore and its related methods are a wrapper around the external Google + * Cloud Datastore grpc API, which provides an interface that is more convenient + * for the rest of the client SDK architecture to consume. + */ class Datastore {} + +/** + * An implementation of Datastore that exposes additional state for internal + * consumption. + */ class __PRIVATE_DatastoreImpl extends Datastore { + constructor(t, e, r, n) { + super(), this.authCredentials = t, this.appCheckCredentials = e, this.connection = r, + this.serializer = n, this.et = !1; + } + rt() { + if (this.et) throw new FirestoreError(S, "The client has already been terminated."); + } + /** Invokes the provided RPC with auth and AppCheck tokens. */ I(t, e, r, n) { + return this.rt(), Promise.all([ this.authCredentials.getToken(), this.appCheckCredentials.getToken() ]).then((([i, s]) => this.connection.I(t, __PRIVATE_toResourcePath(e, r), n, i, s))).catch((t => { + throw "FirebaseError" === t.name ? (t.code === D && (this.authCredentials.invalidateToken(), + this.appCheckCredentials.invalidateToken()), t) : new FirestoreError(p, t.toString()); + })); + } + /** Invokes the provided RPC with streamed results with auth and AppCheck tokens. */ D(t, e, r, n, i) { + return this.rt(), Promise.all([ this.authCredentials.getToken(), this.appCheckCredentials.getToken() ]).then((([s, o]) => this.connection.D(t, __PRIVATE_toResourcePath(e, r), n, s, o, i))).catch((t => { + throw "FirebaseError" === t.name ? (t.code === D && (this.authCredentials.invalidateToken(), + this.appCheckCredentials.invalidateToken()), t) : new FirestoreError(p, t.toString()); + })); + } + terminate() { + this.et = !0, this.connection.terminate(); + } +} + +// TODO(firestorexp): Make sure there is only one Datastore instance per +// firestore-exp client. +async function __PRIVATE_invokeCommitRpc(t, e) { + const r = __PRIVATE_debugCast(t), n = { + writes: e.map((t => toMutation(r.serializer, t))) + }; + await r.I("Commit", r.serializer.databaseId, ResourcePath.emptyPath(), n); +} + +async function __PRIVATE_invokeBatchGetDocumentsRpc(t, e) { + const r = __PRIVATE_debugCast(t), n = { + documents: e.map((t => __PRIVATE_toName(r.serializer, t))) + }, i = await r.D("BatchGetDocuments", r.serializer.databaseId, ResourcePath.emptyPath(), n, e.length), s = new Map; + i.forEach((t => { + const e = __PRIVATE_fromBatchGetDocumentsResponse(r.serializer, t); + s.set(e.key.toString(), e); + })); + const o = []; + return e.forEach((t => { + const e = s.get(t.toString()); + __PRIVATE_hardAssert(!!e, 55234, { + key: t + }), o.push(e); + })), o; +} + +async function __PRIVATE_invokeRunQueryRpc(t, e) { + const r = __PRIVATE_debugCast(t), {M: n, parent: i} = __PRIVATE_toQueryTarget(r.serializer, __PRIVATE_queryToTarget(e)); + return (await r.D("RunQuery", r.serializer.databaseId, i, { + structuredQuery: n.structuredQuery + })).filter((t => !!t.document)).map((t => function __PRIVATE_fromDocument(t, e, r) { + const n = fromName(t, e.name), i = __PRIVATE_fromVersion(e.updateTime), s = e.createTime ? __PRIVATE_fromVersion(e.createTime) : SnapshotVersion.min(), o = new ObjectValue({ + mapValue: { + fields: e.fields + } + }), a = MutableDocument.newFoundDocument(n, i, s, o); + return r && a.setHasCommittedMutations(), r ? a.setHasCommittedMutations() : a; + }(r.serializer, t.document, void 0))); +} + +async function __PRIVATE_invokeRunAggregationQueryRpc(t, e, r) { + const n = __PRIVATE_debugCast(t), {request: i, nt: s, parent: o} = function __PRIVATE_toRunAggregationQueryRequest(t, e, r, n) { + const {M: i, parent: s} = __PRIVATE_toQueryTarget(t, e), o = {}, a = []; + let u = 0; + return r.forEach((t => { + // Map all client-side aliases to a unique short-form + // alias. This avoids issues with client-side aliases that + // exceed the 1500-byte string size limit. + const e = n ? t.alias : "aggregate_" + u++; + o[e] = t.alias, "count" === t.aggregateType ? a.push({ + alias: e, + count: {} + }) : "avg" === t.aggregateType ? a.push({ + alias: e, + avg: { + field: __PRIVATE_toFieldPathReference(t.fieldPath) + } + }) : "sum" === t.aggregateType && a.push({ + alias: e, + sum: { + field: __PRIVATE_toFieldPathReference(t.fieldPath) + } + }); + })), { + request: { + structuredAggregationQuery: { + aggregations: a, + structuredQuery: i.structuredQuery + }, + parent: i.parent + }, + nt: o, + parent: s + }; + }(n.serializer, function __PRIVATE_queryToAggregateTarget(t) { + const e = __PRIVATE_debugCast(t); + return e.$ || ( + // Do not include implicit order-bys for aggregate queries. + e.$ = __PRIVATE__queryToTarget(e, t.explicitOrderBy)), e.$; + }(e), r); + n.connection.P || delete i.parent; + const a = (await n.D("RunAggregationQuery", n.serializer.databaseId, o, i, + /*expectedResponseCount=*/ 1)).filter((t => !!t.result)); + // Omit RunAggregationQueryResponse that only contain readTimes. + __PRIVATE_hardAssert(1 === a.length, 64727); + // Remap the short-form aliases that were sent to the server + // to the client-side aliases. Users will access the results + // using the client-side alias. + const u = a[0].result?.aggregateFields; + return Object.keys(u).reduce(((t, e) => (t[s[e]] = u[e], t)), {}); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ const st = "ComponentProvider", ot = new Map; + +/** + * An instance map that ensures only one Datastore exists per Firestore + * instance. + */ +/** + * Returns an initialized and started Datastore for the given Firestore + * instance. Callers must invoke removeComponents() when the Firestore + * instance is terminated. + */ +function __PRIVATE_getDatastore(t) { + if (t._terminated) throw new FirestoreError(S, "The client has already been terminated."); + if (!ot.has(t)) { + __PRIVATE_logDebug(st, "Initializing Datastore"); + const e = function __PRIVATE_newConnection(t) { + return new __PRIVATE_FetchConnection(t); + }(function __PRIVATE_makeDatabaseInfo(t, e, r, n) { + return new DatabaseInfo(t, e, r, n.host, n.ssl, n.experimentalForceLongPolling, n.experimentalAutoDetectLongPolling, __PRIVATE_cloneLongPollingOptions(n.experimentalLongPollingOptions), n.useFetchStreams, n.isUsingEmulator); + } + /** + * @license + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ (t._databaseId, t.app.options.appId || "", t._persistenceKey, t._freezeSettings())), r = __PRIVATE_newSerializer(t._databaseId), n = function __PRIVATE_newDatastore(t, e, r, n) { + return new __PRIVATE_DatastoreImpl(t, e, r, n); + }(t._authCredentials, t._appCheckCredentials, e, r); + ot.set(t, n); + } + return ot.get(t); +} + +/** + * Removes all components associated with the provided instance. Must be called + * when the `Firestore` instance is terminated. + */ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const at = 1048576, ut = "firestore.googleapis.com", _t = !0; + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// settings() defaults: +/** + * A concrete type describing all the values that can be applied via a + * user-supplied `FirestoreSettings` object. This is a separate type so that + * defaults can be supplied and the value can be checked for equality. + */ +class FirestoreSettingsImpl { + constructor(t) { + if (void 0 === t.host) { + if (void 0 !== t.ssl) throw new FirestoreError(y, "Can't provide ssl option if host option is not set"); + this.host = ut, this.ssl = _t; + } else this.host = t.host, this.ssl = t.ssl ?? _t; + if (this.isUsingEmulator = void 0 !== t.emulatorOptions, this.credentials = t.credentials, + this.ignoreUndefinedProperties = !!t.ignoreUndefinedProperties, this.localCache = t.localCache, + void 0 === t.cacheSizeBytes) this.cacheSizeBytes = 41943040; else { + if (-1 !== t.cacheSizeBytes && t.cacheSizeBytes < at) throw new FirestoreError(y, "cacheSizeBytes must be at least 1048576"); + this.cacheSizeBytes = t.cacheSizeBytes; + } + !function __PRIVATE_validateIsNotUsedTogether(t, e, r, n) { + if (!0 === e && !0 === n) throw new FirestoreError(y, `${t} and ${r} cannot be used together.`); + }("experimentalForceLongPolling", t.experimentalForceLongPolling, "experimentalAutoDetectLongPolling", t.experimentalAutoDetectLongPolling), + this.experimentalForceLongPolling = !!t.experimentalForceLongPolling, this.experimentalForceLongPolling ? this.experimentalAutoDetectLongPolling = !1 : void 0 === t.experimentalAutoDetectLongPolling ? this.experimentalAutoDetectLongPolling = true : + // For backwards compatibility, coerce the value to boolean even though + // the TypeScript compiler has narrowed the type to boolean already. + // noinspection PointlessBooleanExpressionJS + this.experimentalAutoDetectLongPolling = !!t.experimentalAutoDetectLongPolling, + this.experimentalLongPollingOptions = __PRIVATE_cloneLongPollingOptions(t.experimentalLongPollingOptions ?? {}), + function __PRIVATE_validateLongPollingOptions(t) { + if (void 0 !== t.timeoutSeconds) { + if (isNaN(t.timeoutSeconds)) throw new FirestoreError(y, `invalid long polling timeout: ${t.timeoutSeconds} (must not be NaN)`); + if (t.timeoutSeconds < 5) throw new FirestoreError(y, `invalid long polling timeout: ${t.timeoutSeconds} (minimum allowed value is 5)`); + if (t.timeoutSeconds > 30) throw new FirestoreError(y, `invalid long polling timeout: ${t.timeoutSeconds} (maximum allowed value is 30)`); + } + } + /** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + /** + * The Cloud Firestore service interface. + * + * Do not call this constructor directly. Instead, use {@link (getFirestore:1)}. + */ (this.experimentalLongPollingOptions), this.useFetchStreams = !!t.useFetchStreams; + } + isEqual(t) { + return this.host === t.host && this.ssl === t.ssl && this.credentials === t.credentials && this.cacheSizeBytes === t.cacheSizeBytes && this.experimentalForceLongPolling === t.experimentalForceLongPolling && this.experimentalAutoDetectLongPolling === t.experimentalAutoDetectLongPolling && function __PRIVATE_longPollingOptionsEqual(t, e) { + return t.timeoutSeconds === e.timeoutSeconds; + }(this.experimentalLongPollingOptions, t.experimentalLongPollingOptions) && this.ignoreUndefinedProperties === t.ignoreUndefinedProperties && this.useFetchStreams === t.useFetchStreams; + } +} + +class Firestore { + /** @hideconstructor */ + constructor(t, e, r, n) { + this._authCredentials = t, this._appCheckCredentials = e, this._databaseId = r, + this._app = n, + /** + * Whether it's a Firestore or Firestore Lite instance. + */ + this.type = "firestore-lite", this._persistenceKey = "(lite)", this._settings = new FirestoreSettingsImpl({}), + this._settingsFrozen = !1, this._emulatorOptions = {}, + // A task that is assigned when the terminate() is invoked and resolved when + // all components have shut down. Otherwise, Firestore is not terminated, + // which can mean either the FirestoreClient is in the process of starting, + // or restarting. + this._terminateTask = "notTerminated"; + } + /** + * The {@link @firebase/app#FirebaseApp} associated with this `Firestore` service + * instance. + */ get app() { + if (!this._app) throw new FirestoreError(S, "Firestore was not initialized using the Firebase SDK. 'app' is not available"); + return this._app; + } + get _initialized() { + return this._settingsFrozen; + } + get _terminated() { + return "notTerminated" !== this._terminateTask; + } + _setSettings(t) { + if (this._settingsFrozen) throw new FirestoreError(S, "Firestore has already been started and its settings can no longer be changed. You can only modify settings before calling any other methods on a Firestore object."); + this._settings = new FirestoreSettingsImpl(t), this._emulatorOptions = t.emulatorOptions || {}, + void 0 !== t.credentials && (this._authCredentials = function __PRIVATE_makeAuthCredentialsProvider(t) { + if (!t) return new __PRIVATE_EmptyAuthCredentialsProvider; + switch (t.type) { + case "firstParty": + return new __PRIVATE_FirstPartyAuthCredentialsProvider(t.sessionIndex || "0", t.iamToken || null, t.authTokenFactory || null); + + case "provider": + return t.client; + + default: + throw new FirestoreError(y, "makeAuthCredentialsProvider failed due to invalid credential type"); + } + }(t.credentials)); + } + _getSettings() { + return this._settings; + } + _getEmulatorOptions() { + return this._emulatorOptions; + } + _freezeSettings() { + return this._settingsFrozen = !0, this._settings; + } + _delete() { + // The `_terminateTask` must be assigned future that completes when + // terminate is complete. The existence of this future puts SDK in state + // that will not accept further API interaction. + return "notTerminated" === this._terminateTask && (this._terminateTask = this._terminate()), + this._terminateTask; + } + async _restart() { + // The `_terminateTask` must equal 'notTerminated' after restart to + // signal that client is in a state that accepts API calls. + "notTerminated" === this._terminateTask ? await this._terminate() : this._terminateTask = "notTerminated"; + } + /** Returns a JSON-serializable representation of this `Firestore` instance. */ toJSON() { + return { + app: this._app, + databaseId: this._databaseId, + settings: this._settings + }; + } + /** + * Terminates all components used by this client. Subclasses can override + * this method to clean up their own dependencies, but must also call this + * method. + * + * Only ever called once. + */ _terminate() { + return function __PRIVATE_removeComponents(t) { + const e = ot.get(t); + e && (__PRIVATE_logDebug(st, "Removing Datastore"), ot.delete(t), e.terminate()); + }(this), Promise.resolve(); + } +} + +function initializeFirestore(t, e, r) { + r || (r = Q); + const n = _getProvider(t, "firestore/lite"); + if (n.isInitialized(r)) throw new FirestoreError(S, "Firestore can only be initialized once per app."); + return n.initialize({ + options: e, + instanceIdentifier: r + }); +} + +function getFirestore(t, r) { + const n = "object" == typeof t ? t : getApp(), i = "string" == typeof t ? t : r || "(default)", s = _getProvider(n, "firestore/lite").getImmediate({ + identifier: i + }); + if (!s._initialized) { + const t = getDefaultEmulatorHostnameAndPort("firestore"); + t && connectFirestoreEmulator(s, ...t); + } + return s; +} + +/** + * Modify this instance to communicate with the Cloud Firestore emulator. + * + * Note: This must be called before this instance has been used to do any + * operations. + * + * @param firestore - The `Firestore` instance to configure to connect to the + * emulator. + * @param host - the emulator host (ex: localhost). + * @param port - the emulator port (ex: 9000). + * @param options.mockUserToken - the mock auth token to use for unit testing + * Security Rules. + */ function connectFirestoreEmulator(t, e, r, n = {}) { + t = __PRIVATE_cast(t, Firestore); + const i = isCloudWorkstation(e), s = t._getSettings(), o = { + ...s, + emulatorOptions: t._getEmulatorOptions() + }, a = `${e}:${r}`; + i && (pingServer(`https://${a}`), updateEmulatorBanner("Firestore", !0)), s.host !== ut && s.host !== a && __PRIVATE_logWarn("Host has been set in both settings() and connectFirestoreEmulator(), emulator host will be used."); + const u = { + ...s, + host: a, + ssl: i, + emulatorOptions: n + }; + // No-op if the new configuration matches the current configuration. This supports SSR + // enviornments which might call `connectFirestoreEmulator` multiple times as a standard practice. + if (!deepEqual(u, o) && (t._setSettings(u), n.mockUserToken)) { + let e, r; + if ("string" == typeof n.mockUserToken) e = n.mockUserToken, r = User.MOCK_USER; else { + // Let createMockUserToken validate first (catches common mistakes like + // invalid field "uid" and missing field "sub" / "user_id".) + e = createMockUserToken(n.mockUserToken, t._app?.options.projectId); + const i = n.mockUserToken.sub || n.mockUserToken.user_id; + if (!i) throw new FirestoreError(y, "mockUserToken must contain 'sub' or 'user_id' field!"); + r = new User(i); + } + t._authCredentials = new __PRIVATE_EmulatorAuthCredentialsProvider(new __PRIVATE_OAuthToken(e, r)); + } +} + +/** + * Terminates the provided `Firestore` instance. + * + * After calling `terminate()` only the `clearIndexedDbPersistence()` functions + * may be used. Any other function will throw a `FirestoreError`. Termination + * does not cancel any pending writes, and any promises that are awaiting a + * response from the server will not be resolved. + * + * To restart after termination, create a new instance of `Firestore` with + * {@link (getFirestore:1)}. + * + * Note: Under normal circumstances, calling `terminate()` is not required. This + * function is useful only when you want to force this instance to release all of + * its resources or in combination with {@link clearIndexedDbPersistence} to + * ensure that all local state is destroyed between test runs. + * + * @param firestore - The `Firestore` instance to terminate. + * @returns A `Promise` that is resolved when the instance has been successfully + * terminated. + */ function terminate(t) { + return t = __PRIVATE_cast(t, Firestore), _removeServiceInstance(t.app, "firestore/lite"), t._delete(); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Represents an aggregation that can be performed by Firestore. + */ +// eslint-disable-next-line @typescript-eslint/no-unused-vars +class AggregateField { + /** + * Create a new AggregateField + * @param aggregateType Specifies the type of aggregation operation to perform. + * @param _internalFieldPath Optionally specifies the field that is aggregated. + * @internal + */ + constructor(t = "count", e) { + this._internalFieldPath = e, + /** A type string to uniquely identify instances of this class. */ + this.type = "AggregateField", this.aggregateType = t; + } +} + +/** + * The results of executing an aggregation query. + */ class AggregateQuerySnapshot { + /** @hideconstructor */ + constructor(t, e, r) { + this._userDataWriter = e, this._data = r, + /** A type string to uniquely identify instances of this class. */ + this.type = "AggregateQuerySnapshot", this.query = t; + } + /** + * Returns the results of the aggregations performed over the underlying + * query. + * + * The keys of the returned object will be the same as those of the + * `AggregateSpec` object specified to the aggregation method, and the values + * will be the corresponding aggregation result. + * + * @returns The results of the aggregations performed over the underlying + * query. + */ data() { + return this._userDataWriter.convertObjectMap(this._data); + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A `Query` refers to a query which you can read or listen to. You can also + * construct refined `Query` objects by adding filters and ordering. + */ class Query { + // This is the lite version of the Query class in the main SDK. + /** @hideconstructor protected */ + constructor(t, + /** + * If provided, the `FirestoreDataConverter` associated with this instance. + */ + e, r) { + this.converter = e, this._query = r, + /** The type of this Firestore reference. */ + this.type = "query", this.firestore = t; + } + withConverter(t) { + return new Query(this.firestore, t, this._query); + } +} + +/** + * A `DocumentReference` refers to a document location in a Firestore database + * and can be used to write, read, or listen to the location. The document at + * the referenced location may or may not exist. + */ class DocumentReference { + /** @hideconstructor */ + constructor(t, + /** + * If provided, the `FirestoreDataConverter` associated with this instance. + */ + e, r) { + this.converter = e, this._key = r, + /** The type of this Firestore reference. */ + this.type = "document", this.firestore = t; + } + get _path() { + return this._key.path; + } + /** + * The document's identifier within its collection. + */ get id() { + return this._key.path.lastSegment(); + } + /** + * A string representing the path of the referenced document (relative + * to the root of the database). + */ get path() { + return this._key.path.canonicalString(); + } + /** + * The collection this `DocumentReference` belongs to. + */ get parent() { + return new CollectionReference(this.firestore, this.converter, this._key.path.popLast()); + } + withConverter(t) { + return new DocumentReference(this.firestore, t, this._key); + } + /** + * Returns a JSON-serializable representation of this `DocumentReference` instance. + * + * @returns a JSON representation of this object. + */ toJSON() { + return { + type: DocumentReference._jsonSchemaVersion, + referencePath: this._key.toString() + }; + } + static fromJSON(t, e, r) { + if (__PRIVATE_validateJSON(e, DocumentReference._jsonSchema)) return new DocumentReference(t, r || null, new DocumentKey(ResourcePath.fromString(e.referencePath))); + } +} + +DocumentReference._jsonSchemaVersion = "firestore/documentReference/1.0", DocumentReference._jsonSchema = { + type: property("string", DocumentReference._jsonSchemaVersion), + referencePath: property("string") +}; + +/** + * A `CollectionReference` object can be used for adding documents, getting + * document references, and querying for documents (using {@link (query:1)}). + */ +class CollectionReference extends Query { + /** @hideconstructor */ + constructor(t, e, r) { + super(t, e, function __PRIVATE_newQueryForPath(t) { + return new __PRIVATE_QueryImpl(t); + }(r)), this._path = r, + /** The type of this Firestore reference. */ + this.type = "collection"; + } + /** The collection's identifier. */ get id() { + return this._query.path.lastSegment(); + } + /** + * A string representing the path of the referenced collection (relative + * to the root of the database). + */ get path() { + return this._query.path.canonicalString(); + } + /** + * A reference to the containing `DocumentReference` if this is a + * subcollection. If this isn't a subcollection, the reference is null. + */ get parent() { + const t = this._path.popLast(); + return t.isEmpty() ? null : new DocumentReference(this.firestore, + /* converter= */ null, new DocumentKey(t)); + } + withConverter(t) { + return new CollectionReference(this.firestore, t, this._path); + } +} + +function collection(t, e, ...r) { + if (t = getModularInstance(t), __PRIVATE_validateNonEmptyArgument("collection", "path", e), t instanceof Firestore) { + const n = ResourcePath.fromString(e, ...r); + return __PRIVATE_validateCollectionPath(n), new CollectionReference(t, /* converter= */ null, n); + } + { + if (!(t instanceof DocumentReference || t instanceof CollectionReference)) throw new FirestoreError(y, "Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore"); + const n = t._path.child(ResourcePath.fromString(e, ...r)); + return __PRIVATE_validateCollectionPath(n), new CollectionReference(t.firestore, + /* converter= */ null, n); + } +} + +// TODO(firestorelite): Consider using ErrorFactory - +// https://github.com/firebase/firebase-js-sdk/blob/0131e1f/packages/util/src/errors.ts#L106 +/** + * Creates and returns a new `Query` instance that includes all documents in the + * database that are contained in a collection or subcollection with the + * given `collectionId`. + * + * @param firestore - A reference to the root `Firestore` instance. + * @param collectionId - Identifies the collections to query over. Every + * collection or subcollection with this ID as the last segment of its path + * will be included. Cannot contain a slash. + * @returns The created `Query`. + */ function collectionGroup(t, e) { + if (t = __PRIVATE_cast(t, Firestore), __PRIVATE_validateNonEmptyArgument("collectionGroup", "collection id", e), + e.indexOf("/") >= 0) throw new FirestoreError(y, `Invalid collection ID '${e}' passed to function collectionGroup(). Collection IDs must not contain '/'.`); + return new Query(t, + /* converter= */ null, function __PRIVATE_newQueryForCollectionGroup(t) { + return new __PRIVATE_QueryImpl(ResourcePath.emptyPath(), t); + }(e)); +} + +function doc(t, e, ...r) { + if (t = getModularInstance(t), + // We allow omission of 'pathString' but explicitly prohibit passing in both + // 'undefined' and 'null'. + 1 === arguments.length && (e = __PRIVATE_AutoId.newId()), __PRIVATE_validateNonEmptyArgument("doc", "path", e), + t instanceof Firestore) { + const n = ResourcePath.fromString(e, ...r); + return __PRIVATE_validateDocumentPath(n), new DocumentReference(t, + /* converter= */ null, new DocumentKey(n)); + } + { + if (!(t instanceof DocumentReference || t instanceof CollectionReference)) throw new FirestoreError(y, "Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore"); + const n = t._path.child(ResourcePath.fromString(e, ...r)); + return __PRIVATE_validateDocumentPath(n), new DocumentReference(t.firestore, t instanceof CollectionReference ? t.converter : null, new DocumentKey(n)); + } +} + +/** + * Returns true if the provided references are equal. + * + * @param left - A reference to compare. + * @param right - A reference to compare. + * @returns true if the references point to the same location in the same + * Firestore database. + */ function refEqual(t, e) { + return t = getModularInstance(t), e = getModularInstance(e), (t instanceof DocumentReference || t instanceof CollectionReference) && (e instanceof DocumentReference || e instanceof CollectionReference) && (t.firestore === e.firestore && t.path === e.path && t.converter === e.converter); +} + +/** + * Returns true if the provided queries point to the same collection and apply + * the same constraints. + * + * @param left - A `Query` to compare. + * @param right - A `Query` to compare. + * @returns true if the references point to the same location in the same + * Firestore database. + */ function queryEqual(t, e) { + return t = getModularInstance(t), e = getModularInstance(e), t instanceof Query && e instanceof Query && (t.firestore === e.firestore && __PRIVATE_queryEquals(t._query, e._query) && t.converter === e.converter); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An immutable object representing an array of bytes. + */ class Bytes { + /** @hideconstructor */ + constructor(t) { + this._byteString = t; + } + /** + * Creates a new `Bytes` object from the given Base64 string, converting it to + * bytes. + * + * @param base64 - The Base64 string used to create the `Bytes` object. + */ static fromBase64String(t) { + try { + return new Bytes(ByteString.fromBase64String(t)); + } catch (t) { + throw new FirestoreError(y, "Failed to construct data from Base64 string: " + t); + } + } + /** + * Creates a new `Bytes` object from the given Uint8Array. + * + * @param array - The Uint8Array used to create the `Bytes` object. + */ static fromUint8Array(t) { + return new Bytes(ByteString.fromUint8Array(t)); + } + /** + * Returns the underlying bytes as a Base64-encoded string. + * + * @returns The Base64-encoded string created from the `Bytes` object. + */ toBase64() { + return this._byteString.toBase64(); + } + /** + * Returns the underlying bytes in a new `Uint8Array`. + * + * @returns The Uint8Array created from the `Bytes` object. + */ toUint8Array() { + return this._byteString.toUint8Array(); + } + /** + * Returns a string representation of the `Bytes` object. + * + * @returns A string representation of the `Bytes` object. + */ toString() { + return "Bytes(base64: " + this.toBase64() + ")"; + } + /** + * Returns true if this `Bytes` object is equal to the provided one. + * + * @param other - The `Bytes` object to compare against. + * @returns true if this `Bytes` object is equal to the provided one. + */ isEqual(t) { + return this._byteString.isEqual(t._byteString); + } + /** + * Returns a JSON-serializable representation of this `Bytes` instance. + * + * @returns a JSON representation of this object. + */ toJSON() { + return { + type: Bytes._jsonSchemaVersion, + bytes: this.toBase64() + }; + } + /** + * Builds a `Bytes` instance from a JSON object created by {@link Bytes.toJSON}. + * + * @param json a JSON object represention of a `Bytes` instance + * @returns an instance of {@link Bytes} if the JSON object could be parsed. Throws a + * {@link FirestoreError} if an error occurs. + */ static fromJSON(t) { + if (__PRIVATE_validateJSON(t, Bytes._jsonSchema)) return Bytes.fromBase64String(t.bytes); + } +} + +Bytes._jsonSchemaVersion = "firestore/bytes/1.0", Bytes._jsonSchema = { + type: property("string", Bytes._jsonSchemaVersion), + bytes: property("string") +}; + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A `FieldPath` refers to a field in a document. The path may consist of a + * single field name (referring to a top-level field in the document), or a + * list of field names (referring to a nested field in the document). + * + * Create a `FieldPath` by providing field names. If more than one field + * name is provided, the path will point to a nested field in a document. + */ +class FieldPath { + /** + * Creates a `FieldPath` from the provided field names. If more than one field + * name is provided, the path will point to a nested field in a document. + * + * @param fieldNames - A list of field names. + */ + constructor(...t) { + for (let e = 0; e < t.length; ++e) if (0 === t[e].length) throw new FirestoreError(y, "Invalid field name at argument $(i + 1). Field names must not be empty."); + this._internalPath = new FieldPath$1(t); + } + /** + * Returns true if this `FieldPath` is equal to the provided one. + * + * @param other - The `FieldPath` to compare against. + * @returns true if this `FieldPath` is equal to the provided one. + */ isEqual(t) { + return this._internalPath.isEqual(t._internalPath); + } +} + +/** + * Returns a special sentinel `FieldPath` to refer to the ID of a document. + * It can be used in queries to sort or filter by the document ID. + */ function documentId() { + return new FieldPath(M); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Sentinel values that can be used when writing document fields with `set()` + * or `update()`. + */ class FieldValue { + /** + * @param _methodName - The public API endpoint that returns this class. + * @hideconstructor + */ + constructor(t) { + this._methodName = t; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An immutable object representing a geographic location in Firestore. The + * location is represented as latitude/longitude pair. + * + * Latitude values are in the range of [-90, 90]. + * Longitude values are in the range of [-180, 180]. + */ class GeoPoint { + /** + * Creates a new immutable `GeoPoint` object with the provided latitude and + * longitude values. + * @param latitude - The latitude as number between -90 and 90. + * @param longitude - The longitude as number between -180 and 180. + */ + constructor(t, e) { + if (!isFinite(t) || t < -90 || t > 90) throw new FirestoreError(y, "Latitude must be a number between -90 and 90, but was: " + t); + if (!isFinite(e) || e < -180 || e > 180) throw new FirestoreError(y, "Longitude must be a number between -180 and 180, but was: " + e); + this._lat = t, this._long = e; + } + /** + * The latitude of this `GeoPoint` instance. + */ get latitude() { + return this._lat; + } + /** + * The longitude of this `GeoPoint` instance. + */ get longitude() { + return this._long; + } + /** + * Returns true if this `GeoPoint` is equal to the provided one. + * + * @param other - The `GeoPoint` to compare against. + * @returns true if this `GeoPoint` is equal to the provided one. + */ isEqual(t) { + return this._lat === t._lat && this._long === t._long; + } + /** + * Actually private to JS consumers of our API, so this function is prefixed + * with an underscore. + */ _compareTo(t) { + return __PRIVATE_primitiveComparator(this._lat, t._lat) || __PRIVATE_primitiveComparator(this._long, t._long); + } + /** + * Returns a JSON-serializable representation of this `GeoPoint` instance. + * + * @returns a JSON representation of this object. + */ toJSON() { + return { + latitude: this._lat, + longitude: this._long, + type: GeoPoint._jsonSchemaVersion + }; + } + /** + * Builds a `GeoPoint` instance from a JSON object created by {@link GeoPoint.toJSON}. + * + * @param json a JSON object represention of a `GeoPoint` instance + * @returns an instance of {@link GeoPoint} if the JSON object could be parsed. Throws a + * {@link FirestoreError} if an error occurs. + */ static fromJSON(t) { + if (__PRIVATE_validateJSON(t, GeoPoint._jsonSchema)) return new GeoPoint(t.latitude, t.longitude); + } +} + +GeoPoint._jsonSchemaVersion = "firestore/geoPoint/1.0", GeoPoint._jsonSchema = { + type: property("string", GeoPoint._jsonSchemaVersion), + latitude: property("number"), + longitude: property("number") +}; + +/** + * @license + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Represents a vector type in Firestore documents. + * Create an instance with {@link vector}. + * + * @class VectorValue + */ +class VectorValue { + /** + * @private + * @internal + */ + constructor(t) { + // Making a copy of the parameter. + this._values = (t || []).map((t => t)); + } + /** + * Returns a copy of the raw number array form of the vector. + */ toArray() { + return this._values.map((t => t)); + } + /** + * Returns `true` if the two `VectorValue` values have the same raw number arrays, returns `false` otherwise. + */ isEqual(t) { + /** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + /** + * Verifies equality for an array of primitives. + * + * @private + * @internal + * @param left Array of primitives. + * @param right Array of primitives. + * @return True if arrays are equal. + */ + return function __PRIVATE_isPrimitiveArrayEqual(t, e) { + if (t.length !== e.length) return !1; + for (let r = 0; r < t.length; ++r) if (t[r] !== e[r]) return !1; + return !0; + }(this._values, t._values); + } + /** + * Returns a JSON-serializable representation of this `VectorValue` instance. + * + * @returns a JSON representation of this object. + */ toJSON() { + return { + type: VectorValue._jsonSchemaVersion, + vectorValues: this._values + }; + } + /** + * Builds a `VectorValue` instance from a JSON object created by {@link VectorValue.toJSON}. + * + * @param json a JSON object represention of a `VectorValue` instance. + * @returns an instance of {@link VectorValue} if the JSON object could be parsed. Throws a + * {@link FirestoreError} if an error occurs. + */ static fromJSON(t) { + if (__PRIVATE_validateJSON(t, VectorValue._jsonSchema)) { + if (Array.isArray(t.vectorValues) && t.vectorValues.every((t => "number" == typeof t))) return new VectorValue(t.vectorValues); + throw new FirestoreError(y, "Expected 'vectorValues' field to be a number array"); + } + } +} + +VectorValue._jsonSchemaVersion = "firestore/vectorValue/1.0", VectorValue._jsonSchema = { + type: property("string", VectorValue._jsonSchemaVersion), + vectorValues: property("object") +}; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const ct = /^__.*__$/; + +/** The result of parsing document data (e.g. for a setData call). */ class ParsedSetData { + constructor(t, e, r) { + this.data = t, this.fieldMask = e, this.fieldTransforms = r; + } + toMutation(t, e) { + return null !== this.fieldMask ? new __PRIVATE_PatchMutation(t, this.data, this.fieldMask, e, this.fieldTransforms) : new __PRIVATE_SetMutation(t, this.data, e, this.fieldTransforms); + } +} + +/** The result of parsing "update" data (i.e. for an updateData call). */ class ParsedUpdateData { + constructor(t, + // The fieldMask does not include document transforms. + e, r) { + this.data = t, this.fieldMask = e, this.fieldTransforms = r; + } + toMutation(t, e) { + return new __PRIVATE_PatchMutation(t, this.data, this.fieldMask, e, this.fieldTransforms); + } +} + +function __PRIVATE_isWrite(t) { + switch (t) { + case 0 /* UserDataSource.Set */ : + // fall through + case 2 /* UserDataSource.MergeSet */ : + // fall through + case 1 /* UserDataSource.Update */ : + return !0; + + case 3 /* UserDataSource.Argument */ : + case 4 /* UserDataSource.ArrayArgument */ : + return !1; + + default: + throw fail(40011, { + it: t + }); + } +} + +/** A "context" object passed around while parsing user data. */ class __PRIVATE_ParseContextImpl { + /** + * Initializes a ParseContext with the given source and path. + * + * @param settings - The settings for the parser. + * @param databaseId - The database ID of the Firestore instance. + * @param serializer - The serializer to use to generate the Value proto. + * @param ignoreUndefinedProperties - Whether to ignore undefined properties + * rather than throw. + * @param fieldTransforms - A mutable list of field transforms encountered + * while parsing the data. + * @param fieldMask - A mutable list of field paths encountered while parsing + * the data. + * + * TODO(b/34871131): We don't support array paths right now, so path can be + * null to indicate the context represents any location within an array (in + * which case certain features will not work and errors will be somewhat + * compromised). + */ + constructor(t, e, r, n, i, s) { + this.settings = t, this.databaseId = e, this.serializer = r, this.ignoreUndefinedProperties = n, + // Minor hack: If fieldTransforms is undefined, we assume this is an + // external call and we need to validate the entire path. + void 0 === i && this.st(), this.fieldTransforms = i || [], this.fieldMask = s || []; + } + get path() { + return this.settings.path; + } + get it() { + return this.settings.it; + } + /** Returns a new context with the specified settings overwritten. */ ot(t) { + return new __PRIVATE_ParseContextImpl({ + ...this.settings, + ...t + }, this.databaseId, this.serializer, this.ignoreUndefinedProperties, this.fieldTransforms, this.fieldMask); + } + ut(t) { + const e = this.path?.child(t), r = this.ot({ + path: e, + _t: !1 + }); + return r.ct(t), r; + } + lt(t) { + const e = this.path?.child(t), r = this.ot({ + path: e, + _t: !1 + }); + return r.st(), r; + } + ht(t) { + // TODO(b/34871131): We don't support array paths right now; so make path + // undefined. + return this.ot({ + path: void 0, + _t: !0 + }); + } + ft(t) { + return __PRIVATE_createError(t, this.settings.methodName, this.settings.dt || !1, this.path, this.settings.Et); + } + /** Returns 'true' if 'fieldPath' was traversed when creating this context. */ contains(t) { + return void 0 !== this.fieldMask.find((e => t.isPrefixOf(e))) || void 0 !== this.fieldTransforms.find((e => t.isPrefixOf(e.field))); + } + st() { + // TODO(b/34871131): Remove null check once we have proper paths for fields + // within arrays. + if (this.path) for (let t = 0; t < this.path.length; t++) this.ct(this.path.get(t)); + } + ct(t) { + if (0 === t.length) throw this.ft("Document fields must not be empty"); + if (__PRIVATE_isWrite(this.it) && ct.test(t)) throw this.ft('Document fields cannot begin and end with "__"'); + } +} + +/** + * Helper for parsing raw user input (provided via the API) into internal model + * classes. + */ class __PRIVATE_UserDataReader { + constructor(t, e, r) { + this.databaseId = t, this.ignoreUndefinedProperties = e, this.serializer = r || __PRIVATE_newSerializer(t); + } + /** Creates a new top-level parse context. */ Tt(t, e, r, n = !1) { + return new __PRIVATE_ParseContextImpl({ + it: t, + methodName: e, + Et: r, + path: FieldPath$1.emptyPath(), + _t: !1, + dt: n + }, this.databaseId, this.serializer, this.ignoreUndefinedProperties); + } +} + +function __PRIVATE_newUserDataReader(t) { + const e = t._freezeSettings(), r = __PRIVATE_newSerializer(t._databaseId); + return new __PRIVATE_UserDataReader(t._databaseId, !!e.ignoreUndefinedProperties, r); +} + +/** Parse document data from a set() call. */ function __PRIVATE_parseSetData(t, e, r, n, i, s = {}) { + const o = t.Tt(s.merge || s.mergeFields ? 2 /* UserDataSource.MergeSet */ : 0 /* UserDataSource.Set */ , e, r, i); + __PRIVATE_validatePlainObject("Data must be an object, but it was:", o, n); + const a = __PRIVATE_parseObject(n, o); + let u, _; + if (s.merge) u = new FieldMask(o.fieldMask), _ = o.fieldTransforms; else if (s.mergeFields) { + const t = []; + for (const n of s.mergeFields) { + const i = __PRIVATE_fieldPathFromArgument$1(e, n, r); + if (!o.contains(i)) throw new FirestoreError(y, `Field '${i}' is specified in your field mask but missing from your input data.`); + __PRIVATE_fieldMaskContains(t, i) || t.push(i); + } + u = new FieldMask(t), _ = o.fieldTransforms.filter((t => u.covers(t.field))); + } else u = null, _ = o.fieldTransforms; + return new ParsedSetData(new ObjectValue(a), u, _); +} + +class __PRIVATE_DeleteFieldValueImpl extends FieldValue { + _toFieldTransform(t) { + if (2 /* UserDataSource.MergeSet */ !== t.it) throw 1 /* UserDataSource.Update */ === t.it ? t.ft(`${this._methodName}() can only appear at the top level of your update data`) : t.ft(`${this._methodName}() cannot be used with set() unless you pass {merge:true}`); + // No transform to add for a delete, but we need to add it to our + // fieldMask so it gets deleted. + return t.fieldMask.push(t.path), null; + } + isEqual(t) { + return t instanceof __PRIVATE_DeleteFieldValueImpl; + } +} + +/** + * Creates a child context for parsing SerializableFieldValues. + * + * This is different than calling `ParseContext.contextWith` because it keeps + * the fieldTransforms and fieldMask separate. + * + * The created context has its `dataSource` set to `UserDataSource.Argument`. + * Although these values are used with writes, any elements in these FieldValues + * are not considered writes since they cannot contain any FieldValue sentinels, + * etc. + * + * @param fieldValue - The sentinel FieldValue for which to create a child + * context. + * @param context - The parent context. + * @param arrayElement - Whether or not the FieldValue has an array. + */ function __PRIVATE_createSentinelChildContext(t, e, r) { + return new __PRIVATE_ParseContextImpl({ + it: 3 /* UserDataSource.Argument */ , + Et: e.settings.Et, + methodName: t._methodName, + _t: r + }, e.databaseId, e.serializer, e.ignoreUndefinedProperties); +} + +class __PRIVATE_ServerTimestampFieldValueImpl extends FieldValue { + _toFieldTransform(t) { + return new FieldTransform(t.path, new __PRIVATE_ServerTimestampTransform); + } + isEqual(t) { + return t instanceof __PRIVATE_ServerTimestampFieldValueImpl; + } +} + +class __PRIVATE_ArrayUnionFieldValueImpl extends FieldValue { + constructor(t, e) { + super(t), this.Pt = e; + } + _toFieldTransform(t) { + const e = __PRIVATE_createSentinelChildContext(this, t, + /*array=*/ !0), r = this.Pt.map((t => __PRIVATE_parseData(t, e))), n = new __PRIVATE_ArrayUnionTransformOperation(r); + return new FieldTransform(t.path, n); + } + isEqual(t) { + return t instanceof __PRIVATE_ArrayUnionFieldValueImpl && deepEqual(this.Pt, t.Pt); + } +} + +class __PRIVATE_ArrayRemoveFieldValueImpl extends FieldValue { + constructor(t, e) { + super(t), this.Pt = e; + } + _toFieldTransform(t) { + const e = __PRIVATE_createSentinelChildContext(this, t, + /*array=*/ !0), r = this.Pt.map((t => __PRIVATE_parseData(t, e))), n = new __PRIVATE_ArrayRemoveTransformOperation(r); + return new FieldTransform(t.path, n); + } + isEqual(t) { + return t instanceof __PRIVATE_ArrayRemoveFieldValueImpl && deepEqual(this.Pt, t.Pt); + } +} + +class __PRIVATE_NumericIncrementFieldValueImpl extends FieldValue { + constructor(t, e) { + super(t), this.At = e; + } + _toFieldTransform(t) { + const e = new __PRIVATE_NumericIncrementTransformOperation(t.serializer, toNumber(t.serializer, this.At)); + return new FieldTransform(t.path, e); + } + isEqual(t) { + return t instanceof __PRIVATE_NumericIncrementFieldValueImpl && this.At === t.At; + } +} + +/** Parse update data from an update() call. */ function __PRIVATE_parseUpdateData(t, e, r, n) { + const i = t.Tt(1 /* UserDataSource.Update */ , e, r); + __PRIVATE_validatePlainObject("Data must be an object, but it was:", i, n); + const s = [], o = ObjectValue.empty(); + forEach(n, ((t, n) => { + const a = __PRIVATE_fieldPathFromDotSeparatedString(e, t, r); + // For Compat types, we have to "extract" the underlying types before + // performing validation. + n = getModularInstance(n); + const u = i.lt(a); + if (n instanceof __PRIVATE_DeleteFieldValueImpl) + // Add it to the field mask, but don't add anything to updateData. + s.push(a); else { + const t = __PRIVATE_parseData(n, u); + null != t && (s.push(a), o.set(a, t)); + } + })); + const a = new FieldMask(s); + return new ParsedUpdateData(o, a, i.fieldTransforms); +} + +/** Parse update data from a list of field/value arguments. */ function __PRIVATE_parseUpdateVarargs(t, e, r, n, i, s) { + const o = t.Tt(1 /* UserDataSource.Update */ , e, r), a = [ __PRIVATE_fieldPathFromArgument$1(e, n, r) ], u = [ i ]; + if (s.length % 2 != 0) throw new FirestoreError(y, `Function ${e}() needs to be called with an even number of arguments that alternate between field names and values.`); + for (let t = 0; t < s.length; t += 2) a.push(__PRIVATE_fieldPathFromArgument$1(e, s[t])), + u.push(s[t + 1]); + const _ = [], c = ObjectValue.empty(); + // We iterate in reverse order to pick the last value for a field if the + // user specified the field multiple times. + for (let t = a.length - 1; t >= 0; --t) if (!__PRIVATE_fieldMaskContains(_, a[t])) { + const e = a[t]; + let r = u[t]; + // For Compat types, we have to "extract" the underlying types before + // performing validation. + r = getModularInstance(r); + const n = o.lt(e); + if (r instanceof __PRIVATE_DeleteFieldValueImpl) + // Add it to the field mask, but don't add anything to updateData. + _.push(e); else { + const t = __PRIVATE_parseData(r, n); + null != t && (_.push(e), c.set(e, t)); + } + } + const l = new FieldMask(_); + return new ParsedUpdateData(c, l, o.fieldTransforms); +} + +/** + * Parse a "query value" (e.g. value in a where filter or a value in a cursor + * bound). + * + * @param allowArrays - Whether the query value is an array that may directly + * contain additional arrays (e.g. the operand of an `in` query). + */ function __PRIVATE_parseQueryValue(t, e, r, n = !1) { + return __PRIVATE_parseData(r, t.Tt(n ? 4 /* UserDataSource.ArrayArgument */ : 3 /* UserDataSource.Argument */ , e)); +} + +/** + * Parses user data to Protobuf Values. + * + * @param input - Data to be parsed. + * @param context - A context object representing the current path being parsed, + * the source of the data being parsed, etc. + * @returns The parsed value, or null if the value was a FieldValue sentinel + * that should not be included in the resulting parsed data. + */ function __PRIVATE_parseData(t, e) { + if (__PRIVATE_looksLikeJsonObject( + // Unwrap the API type from the Compat SDK. This will return the API type + // from firestore-exp. + t = getModularInstance(t))) return __PRIVATE_validatePlainObject("Unsupported field value:", e, t), + __PRIVATE_parseObject(t, e); + if (t instanceof FieldValue) + // FieldValues usually parse into transforms (except deleteField()) + // in which case we do not want to include this field in our parsed data + // (as doing so will overwrite the field directly prior to the transform + // trying to transform it). So we don't add this location to + // context.fieldMask and we return null as our parsing result. + /** + * "Parses" the provided FieldValueImpl, adding any necessary transforms to + * context.fieldTransforms. + */ + return function __PRIVATE_parseSentinelFieldValue(t, e) { + // Sentinels are only supported with writes, and not within arrays. + if (!__PRIVATE_isWrite(e.it)) throw e.ft(`${t._methodName}() can only be used with update() and set()`); + if (!e.path) throw e.ft(`${t._methodName}() is not currently supported inside arrays`); + const r = t._toFieldTransform(e); + r && e.fieldTransforms.push(r); + } + /** + * Helper to parse a scalar value (i.e. not an Object, Array, or FieldValue) + * + * @returns The parsed value + */ (t, e), null; + if (void 0 === t && e.ignoreUndefinedProperties) + // If the input is undefined it can never participate in the fieldMask, so + // don't handle this below. If `ignoreUndefinedProperties` is false, + // `parseScalarValue` will reject an undefined value. + return null; + if ( + // If context.path is null we are inside an array and we don't support + // field mask paths more granular than the top-level array. + e.path && e.fieldMask.push(e.path), t instanceof Array) { + // TODO(b/34871131): Include the path containing the array in the error + // message. + // In the case of IN queries, the parsed data is an array (representing + // the set of values to be included for the IN query) that may directly + // contain additional arrays (each representing an individual field + // value), so we disable this validation. + if (e.settings._t && 4 /* UserDataSource.ArrayArgument */ !== e.it) throw e.ft("Nested arrays are not supported"); + return function __PRIVATE_parseArray(t, e) { + const r = []; + let n = 0; + for (const i of t) { + let t = __PRIVATE_parseData(i, e.ht(n)); + null == t && ( + // Just include nulls in the array for fields being replaced with a + // sentinel. + t = { + nullValue: "NULL_VALUE" + }), r.push(t), n++; + } + return { + arrayValue: { + values: r + } + }; + }(t, e); + } + return function __PRIVATE_parseScalarValue(t, e) { + if (null === (t = getModularInstance(t))) return { + nullValue: "NULL_VALUE" + }; + if ("number" == typeof t) return toNumber(e.serializer, t); + if ("boolean" == typeof t) return { + booleanValue: t + }; + if ("string" == typeof t) return { + stringValue: t + }; + if (t instanceof Date) { + const r = Timestamp.fromDate(t); + return { + timestampValue: toTimestamp(e.serializer, r) + }; + } + if (t instanceof Timestamp) { + // Firestore backend truncates precision down to microseconds. To ensure + // offline mode works the same with regards to truncation, perform the + // truncation immediately without waiting for the backend to do that. + const r = new Timestamp(t.seconds, 1e3 * Math.floor(t.nanoseconds / 1e3)); + return { + timestampValue: toTimestamp(e.serializer, r) + }; + } + if (t instanceof GeoPoint) return { + geoPointValue: { + latitude: t.latitude, + longitude: t.longitude + } + }; + if (t instanceof Bytes) return { + bytesValue: __PRIVATE_toBytes(e.serializer, t._byteString) + }; + if (t instanceof DocumentReference) { + const r = e.databaseId, n = t.firestore._databaseId; + if (!n.isEqual(r)) throw e.ft(`Document reference is for database ${n.projectId}/${n.database} but should be for database ${r.projectId}/${r.database}`); + return { + referenceValue: __PRIVATE_toResourceName(t.firestore._databaseId || e.databaseId, t._key.path) + }; + } + if (t instanceof VectorValue) + /** + * Creates a new VectorValue proto value (using the internal format). + */ + return function __PRIVATE_parseVectorValue(t, e) { + const r = { + fields: { + [Y]: { + stringValue: tt + }, + [et]: { + arrayValue: { + values: t.toArray().map((t => { + if ("number" != typeof t) throw e.ft("VectorValues must only contain numeric values."); + return __PRIVATE_toDouble(e.serializer, t); + })) + } + } + } + }; + return { + mapValue: r + }; + } + /** + * Checks whether an object looks like a JSON object that should be converted + * into a struct. Normal class/prototype instances are considered to look like + * JSON objects since they should be converted to a struct value. Arrays, Dates, + * GeoPoints, etc. are not considered to look like JSON objects since they map + * to specific FieldValue types other than ObjectValue. + */ (t, e); + throw e.ft(`Unsupported field value: ${__PRIVATE_valueDescription(t)}`); + }(t, e); +} + +function __PRIVATE_parseObject(t, e) { + const r = {}; + return !function isEmpty(t) { + for (const e in t) if (Object.prototype.hasOwnProperty.call(t, e)) return !1; + return !0; + }(t) ? forEach(t, ((t, n) => { + const i = __PRIVATE_parseData(n, e.ut(t)); + null != i && (r[t] = i); + })) : + // If we encounter an empty object, we explicitly add it to the update + // mask to ensure that the server creates a map entry. + e.path && e.path.length > 0 && e.fieldMask.push(e.path), { + mapValue: { + fields: r + } + }; +} + +function __PRIVATE_looksLikeJsonObject(t) { + return !("object" != typeof t || null === t || t instanceof Array || t instanceof Date || t instanceof Timestamp || t instanceof GeoPoint || t instanceof Bytes || t instanceof DocumentReference || t instanceof FieldValue || t instanceof VectorValue); +} + +function __PRIVATE_validatePlainObject(t, e, r) { + if (!__PRIVATE_looksLikeJsonObject(r) || !__PRIVATE_isPlainObject(r)) { + const n = __PRIVATE_valueDescription(r); + throw "an object" === n ? e.ft(t + " a custom object") : e.ft(t + " " + n); + } +} + +/** + * Helper that calls fromDotSeparatedString() but wraps any error thrown. + */ function __PRIVATE_fieldPathFromArgument$1(t, e, r) { + if (( + // If required, replace the FieldPath Compat class with the firestore-exp + // FieldPath. + e = getModularInstance(e)) instanceof FieldPath) return e._internalPath; + if ("string" == typeof e) return __PRIVATE_fieldPathFromDotSeparatedString(t, e); + throw __PRIVATE_createError("Field path arguments must be of type string or ", t, + /* hasConverter= */ !1, + /* path= */ void 0, r); +} + +/** + * Matches any characters in a field path string that are reserved. + */ const lt = new RegExp("[~\\*/\\[\\]]"); + +/** + * Wraps fromDotSeparatedString with an error message about the method that + * was thrown. + * @param methodName - The publicly visible method name + * @param path - The dot-separated string form of a field path which will be + * split on dots. + * @param targetDoc - The document against which the field path will be + * evaluated. + */ function __PRIVATE_fieldPathFromDotSeparatedString(t, e, r) { + if (e.search(lt) >= 0) throw __PRIVATE_createError(`Invalid field path (${e}). Paths must not contain '~', '*', '/', '[', or ']'`, t, + /* hasConverter= */ !1, + /* path= */ void 0, r); + try { + return new FieldPath(...e.split("."))._internalPath; + } catch (n) { + throw __PRIVATE_createError(`Invalid field path (${e}). Paths must not be empty, begin with '.', end with '.', or contain '..'`, t, + /* hasConverter= */ !1, + /* path= */ void 0, r); + } +} + +function __PRIVATE_createError(t, e, r, n, i) { + const s = n && !n.isEmpty(), o = void 0 !== i; + let a = `Function ${e}() called with invalid data`; + r && (a += " (via `toFirestore()`)"), a += ". "; + let u = ""; + return (s || o) && (u += " (found", s && (u += ` in field ${n}`), o && (u += ` in document ${i}`), + u += ")"), new FirestoreError(y, a + t + u); +} + +/** Checks `haystack` if FieldPath `needle` is present. Runs in O(n). */ function __PRIVATE_fieldMaskContains(t, e) { + return t.some((t => t.isEqual(e))); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A `DocumentSnapshot` contains data read from a document in your Firestore + * database. The data can be extracted with `.data()` or `.get()` to + * get a specific field. + * + * For a `DocumentSnapshot` that points to a non-existing document, any data + * access will return 'undefined'. You can use the `exists()` method to + * explicitly verify a document's existence. + */ class DocumentSnapshot { + // Note: This class is stripped down version of the DocumentSnapshot in + // the legacy SDK. The changes are: + // - No support for SnapshotMetadata. + // - No support for SnapshotOptions. + /** @hideconstructor protected */ + constructor(t, e, r, n, i) { + this._firestore = t, this._userDataWriter = e, this._key = r, this._document = n, + this._converter = i; + } + /** Property of the `DocumentSnapshot` that provides the document's ID. */ get id() { + return this._key.path.lastSegment(); + } + /** + * The `DocumentReference` for the document included in the `DocumentSnapshot`. + */ get ref() { + return new DocumentReference(this._firestore, this._converter, this._key); + } + /** + * Signals whether or not the document at the snapshot's location exists. + * + * @returns true if the document exists. + */ exists() { + return null !== this._document; + } + /** + * Retrieves all fields in the document as an `Object`. Returns `undefined` if + * the document doesn't exist. + * + * @returns An `Object` containing all fields in the document or `undefined` + * if the document doesn't exist. + */ data() { + if (this._document) { + if (this._converter) { + // We only want to use the converter and create a new DocumentSnapshot + // if a converter has been provided. + const t = new QueryDocumentSnapshot(this._firestore, this._userDataWriter, this._key, this._document, + /* converter= */ null); + return this._converter.fromFirestore(t); + } + return this._userDataWriter.convertValue(this._document.data.value); + } + } + /** + * Retrieves the field specified by `fieldPath`. Returns `undefined` if the + * document or field doesn't exist. + * + * @param fieldPath - The path (for example 'foo' or 'foo.bar') to a specific + * field. + * @returns The data at the specified field location or undefined if no such + * field exists in the document. + */ + // We are using `any` here to avoid an explicit cast by our users. + // eslint-disable-next-line @typescript-eslint/no-explicit-any + get(t) { + if (this._document) { + const e = this._document.data.field(__PRIVATE_fieldPathFromArgument("DocumentSnapshot.get", t)); + if (null !== e) return this._userDataWriter.convertValue(e); + } + } +} + +/** + * A `QueryDocumentSnapshot` contains data read from a document in your + * Firestore database as part of a query. The document is guaranteed to exist + * and its data can be extracted with `.data()` or `.get()` to get a + * specific field. + * + * A `QueryDocumentSnapshot` offers the same API surface as a + * `DocumentSnapshot`. Since query results contain only existing documents, the + * `exists` property will always be true and `data()` will never return + * 'undefined'. + */ class QueryDocumentSnapshot extends DocumentSnapshot { + /** + * Retrieves all fields in the document as an `Object`. + * + * @override + * @returns An `Object` containing all fields in the document. + */ + data() { + return super.data(); + } +} + +/** + * A `QuerySnapshot` contains zero or more `DocumentSnapshot` objects + * representing the results of a query. The documents can be accessed as an + * array via the `docs` property or enumerated using the `forEach` method. The + * number of documents can be determined via the `empty` and `size` + * properties. + */ class QuerySnapshot { + /** @hideconstructor */ + constructor(t, e) { + this._docs = e, this.query = t; + } + /** An array of all the documents in the `QuerySnapshot`. */ get docs() { + return [ ...this._docs ]; + } + /** The number of documents in the `QuerySnapshot`. */ get size() { + return this.docs.length; + } + /** True if there are no documents in the `QuerySnapshot`. */ get empty() { + return 0 === this.docs.length; + } + /** + * Enumerates all of the documents in the `QuerySnapshot`. + * + * @param callback - A callback to be called with a `QueryDocumentSnapshot` for + * each document in the snapshot. + * @param thisArg - The `this` binding for the callback. + */ forEach(t, e) { + this._docs.forEach(t, e); + } +} + +/** + * Returns true if the provided snapshots are equal. + * + * @param left - A snapshot to compare. + * @param right - A snapshot to compare. + * @returns true if the snapshots are equal. + */ function snapshotEqual(t, e) { + return t = getModularInstance(t), e = getModularInstance(e), t instanceof DocumentSnapshot && e instanceof DocumentSnapshot ? t._firestore === e._firestore && t._key.isEqual(e._key) && (null === t._document ? null === e._document : t._document.isEqual(e._document)) && t._converter === e._converter : t instanceof QuerySnapshot && e instanceof QuerySnapshot && (queryEqual(t.query, e.query) && __PRIVATE_arrayEquals(t.docs, e.docs, snapshotEqual)); +} + +/** + * Helper that calls `fromDotSeparatedString()` but wraps any error thrown. + */ function __PRIVATE_fieldPathFromArgument(t, e) { + return "string" == typeof e ? __PRIVATE_fieldPathFromDotSeparatedString(t, e) : e instanceof FieldPath ? e._internalPath : e._delegate._internalPath; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An `AppliableConstraint` is an abstraction of a constraint that can be applied + * to a Firestore query. + */ +class AppliableConstraint {} + +/** + * A `QueryConstraint` is used to narrow the set of documents returned by a + * Firestore query. `QueryConstraint`s are created by invoking {@link where}, + * {@link orderBy}, {@link (startAt:1)}, {@link (startAfter:1)}, {@link + * (endBefore:1)}, {@link (endAt:1)}, {@link limit}, {@link limitToLast} and + * can then be passed to {@link (query:1)} to create a new query instance that + * also contains this `QueryConstraint`. + */ class QueryConstraint extends AppliableConstraint {} + +function query(t, e, ...r) { + let n = []; + e instanceof AppliableConstraint && n.push(e), n = n.concat(r), function __PRIVATE_validateQueryConstraintArray(t) { + const e = t.filter((t => t instanceof QueryCompositeFilterConstraint)).length, r = t.filter((t => t instanceof QueryFieldFilterConstraint)).length; + if (e > 1 || e > 0 && r > 0) throw new FirestoreError(y, "InvalidQuery. When using composite filters, you cannot use more than one filter at the top level. Consider nesting the multiple filters within an `and(...)` statement. For example: change `query(query, where(...), or(...))` to `query(query, and(where(...), or(...)))`."); + } + /** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + /** + * Converts Firestore's internal types to the JavaScript types that we expose + * to the user. + * + * @internal + */ (n); + for (const e of n) t = e._apply(t); + return t; +} + +/** + * A `QueryFieldFilterConstraint` is used to narrow the set of documents returned by + * a Firestore query by filtering on one or more document fields. + * `QueryFieldFilterConstraint`s are created by invoking {@link where} and can then + * be passed to {@link (query:1)} to create a new query instance that also contains + * this `QueryFieldFilterConstraint`. + */ class QueryFieldFilterConstraint extends QueryConstraint { + /** + * @internal + */ + constructor(t, e, r) { + super(), this._field = t, this._op = e, this._value = r, + /** The type of this query constraint */ + this.type = "where"; + } + static _create(t, e, r) { + return new QueryFieldFilterConstraint(t, e, r); + } + _apply(t) { + const e = this._parse(t); + return __PRIVATE_validateNewFieldFilter(t._query, e), new Query(t.firestore, t.converter, __PRIVATE_queryWithAddedFilter(t._query, e)); + } + _parse(t) { + const e = __PRIVATE_newUserDataReader(t.firestore), r = function __PRIVATE_newQueryFilter(t, e, r, n, i, s, o) { + let a; + if (i.isKeyField()) { + if ("array-contains" /* Operator.ARRAY_CONTAINS */ === s || "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ === s) throw new FirestoreError(y, `Invalid Query. You can't perform '${s}' queries on documentId().`); + if ("in" /* Operator.IN */ === s || "not-in" /* Operator.NOT_IN */ === s) { + __PRIVATE_validateDisjunctiveFilterElements(o, s); + const e = []; + for (const r of o) e.push(__PRIVATE_parseDocumentIdValue(n, t, r)); + a = { + arrayValue: { + values: e + } + }; + } else a = __PRIVATE_parseDocumentIdValue(n, t, o); + } else "in" /* Operator.IN */ !== s && "not-in" /* Operator.NOT_IN */ !== s && "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ !== s || __PRIVATE_validateDisjunctiveFilterElements(o, s), + a = __PRIVATE_parseQueryValue(r, e, o, + /* allowArrays= */ "in" /* Operator.IN */ === s || "not-in" /* Operator.NOT_IN */ === s); + const u = FieldFilter.create(i, s, a); + return u; + }(t._query, "where", e, t.firestore._databaseId, this._field, this._op, this._value); + return r; + } +} + +/** + * Creates a {@link QueryFieldFilterConstraint} that enforces that documents + * must contain the specified field and that the value should satisfy the + * relation constraint provided. + * + * @param fieldPath - The path to compare + * @param opStr - The operation string (e.g "<", "<=", "==", "<", + * "<=", "!="). + * @param value - The value for comparison + * @returns The created {@link QueryFieldFilterConstraint}. + */ function where(t, e, r) { + const n = e, i = __PRIVATE_fieldPathFromArgument("where", t); + return QueryFieldFilterConstraint._create(i, n, r); +} + +/** + * A `QueryCompositeFilterConstraint` is used to narrow the set of documents + * returned by a Firestore query by performing the logical OR or AND of multiple + * {@link QueryFieldFilterConstraint}s or {@link QueryCompositeFilterConstraint}s. + * `QueryCompositeFilterConstraint`s are created by invoking {@link or} or + * {@link and} and can then be passed to {@link (query:1)} to create a new query + * instance that also contains the `QueryCompositeFilterConstraint`. + */ class QueryCompositeFilterConstraint extends AppliableConstraint { + /** + * @internal + */ + constructor( + /** The type of this query constraint */ + t, e) { + super(), this.type = t, this._queryConstraints = e; + } + static _create(t, e) { + return new QueryCompositeFilterConstraint(t, e); + } + _parse(t) { + const e = this._queryConstraints.map((e => e._parse(t))).filter((t => t.getFilters().length > 0)); + return 1 === e.length ? e[0] : CompositeFilter.create(e, this._getOperator()); + } + _apply(t) { + const e = this._parse(t); + return 0 === e.getFilters().length ? t : (function __PRIVATE_validateNewFilter(t, e) { + let r = t; + const n = e.getFlattenedFilters(); + for (const t of n) __PRIVATE_validateNewFieldFilter(r, t), r = __PRIVATE_queryWithAddedFilter(r, t); + } + // Checks if any of the provided filter operators are included in the given list of filters and + // returns the first one that is, or null if none are. + (t._query, e), new Query(t.firestore, t.converter, __PRIVATE_queryWithAddedFilter(t._query, e))); + } + _getQueryConstraints() { + return this._queryConstraints; + } + _getOperator() { + return "and" === this.type ? "and" /* CompositeOperator.AND */ : "or" /* CompositeOperator.OR */; + } +} + +/** + * Creates a new {@link QueryCompositeFilterConstraint} that is a disjunction of + * the given filter constraints. A disjunction filter includes a document if it + * satisfies any of the given filters. + * + * @param queryConstraints - Optional. The list of + * {@link QueryFilterConstraint}s to perform a disjunction for. These must be + * created with calls to {@link where}, {@link or}, or {@link and}. + * @returns The newly created {@link QueryCompositeFilterConstraint}. + */ function or(...t) { + // Only support QueryFilterConstraints + return t.forEach((t => __PRIVATE_validateQueryFilterConstraint("or", t))), QueryCompositeFilterConstraint._create("or" /* CompositeOperator.OR */ , t); +} + +/** + * Creates a new {@link QueryCompositeFilterConstraint} that is a conjunction of + * the given filter constraints. A conjunction filter includes a document if it + * satisfies all of the given filters. + * + * @param queryConstraints - Optional. The list of + * {@link QueryFilterConstraint}s to perform a conjunction for. These must be + * created with calls to {@link where}, {@link or}, or {@link and}. + * @returns The newly created {@link QueryCompositeFilterConstraint}. + */ function and(...t) { + // Only support QueryFilterConstraints + return t.forEach((t => __PRIVATE_validateQueryFilterConstraint("and", t))), QueryCompositeFilterConstraint._create("and" /* CompositeOperator.AND */ , t); +} + +/** + * A `QueryOrderByConstraint` is used to sort the set of documents returned by a + * Firestore query. `QueryOrderByConstraint`s are created by invoking + * {@link orderBy} and can then be passed to {@link (query:1)} to create a new query + * instance that also contains this `QueryOrderByConstraint`. + * + * Note: Documents that do not contain the orderBy field will not be present in + * the query result. + */ class QueryOrderByConstraint extends QueryConstraint { + /** + * @internal + */ + constructor(t, e) { + super(), this._field = t, this._direction = e, + /** The type of this query constraint */ + this.type = "orderBy"; + } + static _create(t, e) { + return new QueryOrderByConstraint(t, e); + } + _apply(t) { + const e = function __PRIVATE_newQueryOrderBy(t, e, r) { + if (null !== t.startAt) throw new FirestoreError(y, "Invalid query. You must not call startAt() or startAfter() before calling orderBy()."); + if (null !== t.endAt) throw new FirestoreError(y, "Invalid query. You must not call endAt() or endBefore() before calling orderBy()."); + const n = new OrderBy(e, r); + return n; + } + /** + * Create a `Bound` from a query and a document. + * + * Note that the `Bound` will always include the key of the document + * and so only the provided document will compare equal to the returned + * position. + * + * Will throw if the document does not contain all fields of the order by + * of the query or if any of the fields in the order by are an uncommitted + * server timestamp. + */ (t._query, this._field, this._direction); + return new Query(t.firestore, t.converter, function __PRIVATE_queryWithAddedOrderBy(t, e) { + // TODO(dimond): validate that orderBy does not list the same key twice. + const r = t.explicitOrderBy.concat([ e ]); + return new __PRIVATE_QueryImpl(t.path, t.collectionGroup, r, t.filters.slice(), t.limit, t.limitType, t.startAt, t.endAt); + }(t._query, e)); + } +} + +/** + * Creates a {@link QueryOrderByConstraint} that sorts the query result by the + * specified field, optionally in descending order instead of ascending. + * + * Note: Documents that do not contain the specified field will not be present + * in the query result. + * + * @param fieldPath - The field to sort by. + * @param directionStr - Optional direction to sort by ('asc' or 'desc'). If + * not specified, order will be ascending. + * @returns The created {@link QueryOrderByConstraint}. + */ function orderBy(t, e = "asc") { + const r = e, n = __PRIVATE_fieldPathFromArgument("orderBy", t); + return QueryOrderByConstraint._create(n, r); +} + +/** + * A `QueryLimitConstraint` is used to limit the number of documents returned by + * a Firestore query. + * `QueryLimitConstraint`s are created by invoking {@link limit} or + * {@link limitToLast} and can then be passed to {@link (query:1)} to create a new + * query instance that also contains this `QueryLimitConstraint`. + */ class QueryLimitConstraint extends QueryConstraint { + /** + * @internal + */ + constructor( + /** The type of this query constraint */ + t, e, r) { + super(), this.type = t, this._limit = e, this._limitType = r; + } + static _create(t, e, r) { + return new QueryLimitConstraint(t, e, r); + } + _apply(t) { + return new Query(t.firestore, t.converter, function __PRIVATE_queryWithLimit(t, e, r) { + return new __PRIVATE_QueryImpl(t.path, t.collectionGroup, t.explicitOrderBy.slice(), t.filters.slice(), e, r, t.startAt, t.endAt); + }(t._query, this._limit, this._limitType)); + } +} + +/** + * Creates a {@link QueryLimitConstraint} that only returns the first matching + * documents. + * + * @param limit - The maximum number of items to return. + * @returns The created {@link QueryLimitConstraint}. + */ function limit(t) { + return __PRIVATE_validatePositiveNumber("limit", t), QueryLimitConstraint._create("limit", t, "F" /* LimitType.First */); +} + +/** + * Creates a {@link QueryLimitConstraint} that only returns the last matching + * documents. + * + * You must specify at least one `orderBy` clause for `limitToLast` queries, + * otherwise an exception will be thrown during execution. + * + * @param limit - The maximum number of items to return. + * @returns The created {@link QueryLimitConstraint}. + */ function limitToLast(t) { + return __PRIVATE_validatePositiveNumber("limitToLast", t), QueryLimitConstraint._create("limitToLast", t, "L" /* LimitType.Last */); +} + +/** + * A `QueryStartAtConstraint` is used to exclude documents from the start of a + * result set returned by a Firestore query. + * `QueryStartAtConstraint`s are created by invoking {@link (startAt:1)} or + * {@link (startAfter:1)} and can then be passed to {@link (query:1)} to create a + * new query instance that also contains this `QueryStartAtConstraint`. + */ class QueryStartAtConstraint extends QueryConstraint { + /** + * @internal + */ + constructor( + /** The type of this query constraint */ + t, e, r) { + super(), this.type = t, this._docOrFields = e, this._inclusive = r; + } + static _create(t, e, r) { + return new QueryStartAtConstraint(t, e, r); + } + _apply(t) { + const e = __PRIVATE_newQueryBoundFromDocOrFields(t, this.type, this._docOrFields, this._inclusive); + return new Query(t.firestore, t.converter, function __PRIVATE_queryWithStartAt(t, e) { + return new __PRIVATE_QueryImpl(t.path, t.collectionGroup, t.explicitOrderBy.slice(), t.filters.slice(), t.limit, t.limitType, e, t.endAt); + }(t._query, e)); + } +} + +function startAt(...t) { + return QueryStartAtConstraint._create("startAt", t, + /*inclusive=*/ !0); +} + +function startAfter(...t) { + return QueryStartAtConstraint._create("startAfter", t, + /*inclusive=*/ !1); +} + +/** + * A `QueryEndAtConstraint` is used to exclude documents from the end of a + * result set returned by a Firestore query. + * `QueryEndAtConstraint`s are created by invoking {@link (endAt:1)} or + * {@link (endBefore:1)} and can then be passed to {@link (query:1)} to create a new + * query instance that also contains this `QueryEndAtConstraint`. + */ class QueryEndAtConstraint extends QueryConstraint { + /** + * @internal + */ + constructor( + /** The type of this query constraint */ + t, e, r) { + super(), this.type = t, this._docOrFields = e, this._inclusive = r; + } + static _create(t, e, r) { + return new QueryEndAtConstraint(t, e, r); + } + _apply(t) { + const e = __PRIVATE_newQueryBoundFromDocOrFields(t, this.type, this._docOrFields, this._inclusive); + return new Query(t.firestore, t.converter, function __PRIVATE_queryWithEndAt(t, e) { + return new __PRIVATE_QueryImpl(t.path, t.collectionGroup, t.explicitOrderBy.slice(), t.filters.slice(), t.limit, t.limitType, t.startAt, e); + }(t._query, e)); + } +} + +function endBefore(...t) { + return QueryEndAtConstraint._create("endBefore", t, + /*inclusive=*/ !1); +} + +function endAt(...t) { + return QueryEndAtConstraint._create("endAt", t, + /*inclusive=*/ !0); +} + +/** Helper function to create a bound from a document or fields */ function __PRIVATE_newQueryBoundFromDocOrFields(t, e, r, n) { + if (r[0] = getModularInstance(r[0]), r[0] instanceof DocumentSnapshot) return function __PRIVATE_newQueryBoundFromDocument(t, e, r, n, i) { + if (!n) throw new FirestoreError(w, `Can't use a DocumentSnapshot that doesn't exist for ${r}().`); + const s = []; + // Because people expect to continue/end a query at the exact document + // provided, we need to use the implicit sort order rather than the explicit + // sort order, because it's guaranteed to contain the document key. That way + // the position becomes unambiguous and the query continues/ends exactly at + // the provided document. Without the key (by using the explicit sort + // orders), multiple documents could match the position, yielding duplicate + // results. + for (const r of __PRIVATE_queryNormalizedOrderBy(t)) if (r.field.isKeyField()) s.push(__PRIVATE_refValue(e, n.key)); else { + const t = n.data.field(r.field); + if (__PRIVATE_isServerTimestamp(t)) throw new FirestoreError(y, 'Invalid query. You are trying to start or end a query using a document for which the field "' + r.field + '" is an uncommitted server timestamp. (Since the value of this field is unknown, you cannot start/end a query with it.)'); + if (null === t) { + const t = r.field.canonicalString(); + throw new FirestoreError(y, `Invalid query. You are trying to start or end a query using a document for which the field '${t}' (used as the orderBy) does not exist.`); + } + s.push(t); + } + return new Bound(s, i); + } + /** + * Converts a list of field values to a `Bound` for the given query. + */ (t._query, t.firestore._databaseId, e, r[0]._document, n); + { + const i = __PRIVATE_newUserDataReader(t.firestore); + return function __PRIVATE_newQueryBoundFromFields(t, e, r, n, i, s) { + // Use explicit order by's because it has to match the query the user made + const o = t.explicitOrderBy; + if (i.length > o.length) throw new FirestoreError(y, `Too many arguments provided to ${n}(). The number of arguments must be less than or equal to the number of orderBy() clauses`); + const a = []; + for (let s = 0; s < i.length; s++) { + const u = i[s]; + if (o[s].field.isKeyField()) { + if ("string" != typeof u) throw new FirestoreError(y, `Invalid query. Expected a string for document ID in ${n}(), but got a ${typeof u}`); + if (!__PRIVATE_isCollectionGroupQuery(t) && -1 !== u.indexOf("/")) throw new FirestoreError(y, `Invalid query. When querying a collection and ordering by documentId(), the value passed to ${n}() must be a plain document ID, but '${u}' contains a slash.`); + const r = t.path.child(ResourcePath.fromString(u)); + if (!DocumentKey.isDocumentKey(r)) throw new FirestoreError(y, `Invalid query. When querying a collection group and ordering by documentId(), the value passed to ${n}() must result in a valid document path, but '${r}' is not because it contains an odd number of segments.`); + const i = new DocumentKey(r); + a.push(__PRIVATE_refValue(e, i)); + } else { + const t = __PRIVATE_parseQueryValue(r, n, u); + a.push(t); + } + } + return new Bound(a, s); + } + /** + * Parses the given `documentIdValue` into a `ReferenceValue`, throwing + * appropriate errors if the value is anything other than a `DocumentReference` + * or `string`, or if the string is malformed. + */ (t._query, t.firestore._databaseId, i, e, r, n); + } +} + +function __PRIVATE_parseDocumentIdValue(t, e, r) { + if ("string" == typeof (r = getModularInstance(r))) { + if ("" === r) throw new FirestoreError(y, "Invalid query. When querying with documentId(), you must provide a valid document ID, but it was an empty string."); + if (!__PRIVATE_isCollectionGroupQuery(e) && -1 !== r.indexOf("/")) throw new FirestoreError(y, `Invalid query. When querying a collection by documentId(), you must provide a plain document ID, but '${r}' contains a '/' character.`); + const n = e.path.child(ResourcePath.fromString(r)); + if (!DocumentKey.isDocumentKey(n)) throw new FirestoreError(y, `Invalid query. When querying a collection group by documentId(), the value provided must result in a valid document path, but '${n}' is not because it has an odd number of segments (${n.length}).`); + return __PRIVATE_refValue(t, new DocumentKey(n)); + } + if (r instanceof DocumentReference) return __PRIVATE_refValue(t, r._key); + throw new FirestoreError(y, `Invalid query. When querying with documentId(), you must provide a valid string or a DocumentReference, but it was: ${__PRIVATE_valueDescription(r)}.`); +} + +/** + * Validates that the value passed into a disjunctive filter satisfies all + * array requirements. + */ function __PRIVATE_validateDisjunctiveFilterElements(t, e) { + if (!Array.isArray(t) || 0 === t.length) throw new FirestoreError(y, `Invalid Query. A non-empty array is required for '${e.toString()}' filters.`); +} + +/** + * Given an operator, returns the set of operators that cannot be used with it. + * + * This is not a comprehensive check, and this function should be removed in the + * long term. Validations should occur in the Firestore backend. + * + * Operators in a query must adhere to the following set of rules: + * 1. Only one inequality per query. + * 2. `NOT_IN` cannot be used with array, disjunctive, or `NOT_EQUAL` operators. + */ function __PRIVATE_validateNewFieldFilter(t, e) { + const r = function __PRIVATE_findOpInsideFilters(t, e) { + for (const r of t) for (const t of r.getFlattenedFilters()) if (e.indexOf(t.op) >= 0) return t.op; + return null; + }(t.filters, function __PRIVATE_conflictingOps(t) { + switch (t) { + case "!=" /* Operator.NOT_EQUAL */ : + return [ "!=" /* Operator.NOT_EQUAL */ , "not-in" /* Operator.NOT_IN */ ]; + + case "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ : + case "in" /* Operator.IN */ : + return [ "not-in" /* Operator.NOT_IN */ ]; + + case "not-in" /* Operator.NOT_IN */ : + return [ "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ , "in" /* Operator.IN */ , "not-in" /* Operator.NOT_IN */ , "!=" /* Operator.NOT_EQUAL */ ]; + + default: + return []; + } + }(e.op)); + if (null !== r) + // Special case when it's a duplicate op to give a slightly clearer error message. + throw r === e.op ? new FirestoreError(y, `Invalid query. You cannot use more than one '${e.op.toString()}' filter.`) : new FirestoreError(y, `Invalid query. You cannot use '${e.op.toString()}' filters with '${r.toString()}' filters.`); +} + +function __PRIVATE_validateQueryFilterConstraint(t, e) { + if (!(e instanceof QueryFieldFilterConstraint || e instanceof QueryCompositeFilterConstraint)) throw new FirestoreError(y, `Function ${t}() requires AppliableConstraints created with a call to 'where(...)', 'or(...)', or 'and(...)'.`); +} + +class AbstractUserDataWriter { + convertValue(t, e = "none") { + switch (__PRIVATE_typeOrder(t)) { + case 0 /* TypeOrder.NullValue */ : + return null; + + case 1 /* TypeOrder.BooleanValue */ : + return t.booleanValue; + + case 2 /* TypeOrder.NumberValue */ : + return __PRIVATE_normalizeNumber(t.integerValue || t.doubleValue); + + case 3 /* TypeOrder.TimestampValue */ : + return this.convertTimestamp(t.timestampValue); + + case 4 /* TypeOrder.ServerTimestampValue */ : + return this.convertServerTimestamp(t, e); + + case 5 /* TypeOrder.StringValue */ : + return t.stringValue; + + case 6 /* TypeOrder.BlobValue */ : + return this.convertBytes(__PRIVATE_normalizeByteString(t.bytesValue)); + + case 7 /* TypeOrder.RefValue */ : + return this.convertReference(t.referenceValue); + + case 8 /* TypeOrder.GeoPointValue */ : + return this.convertGeoPoint(t.geoPointValue); + + case 9 /* TypeOrder.ArrayValue */ : + return this.convertArray(t.arrayValue, e); + + case 11 /* TypeOrder.ObjectValue */ : + return this.convertObject(t.mapValue, e); + + case 10 /* TypeOrder.VectorValue */ : + return this.convertVectorValue(t.mapValue); + + default: + throw fail(62114, { + value: t + }); + } + } + convertObject(t, e) { + return this.convertObjectMap(t.fields, e); + } + /** + * @internal + */ convertObjectMap(t, e = "none") { + const r = {}; + return forEach(t, ((t, n) => { + r[t] = this.convertValue(n, e); + })), r; + } + /** + * @internal + */ convertVectorValue(t) { + const e = t.fields?.[et].arrayValue?.values?.map((t => __PRIVATE_normalizeNumber(t.doubleValue))); + return new VectorValue(e); + } + convertGeoPoint(t) { + return new GeoPoint(__PRIVATE_normalizeNumber(t.latitude), __PRIVATE_normalizeNumber(t.longitude)); + } + convertArray(t, e) { + return (t.values || []).map((t => this.convertValue(t, e))); + } + convertServerTimestamp(t, e) { + switch (e) { + case "previous": + const r = __PRIVATE_getPreviousValue(t); + return null == r ? null : this.convertValue(r, e); + + case "estimate": + return this.convertTimestamp(__PRIVATE_getLocalWriteTime(t)); + + default: + return null; + } + } + convertTimestamp(t) { + const e = __PRIVATE_normalizeTimestamp(t); + return new Timestamp(e.seconds, e.nanos); + } + convertDocumentKey(t, e) { + const r = ResourcePath.fromString(t); + __PRIVATE_hardAssert(__PRIVATE_isValidResourceName(r), 9688, { + name: t + }); + const n = new DatabaseId(r.get(1), r.get(3)), i = new DocumentKey(r.popFirst(5)); + return n.isEqual(e) || + // TODO(b/64130202): Somehow support foreign references. + __PRIVATE_logError(`Document ${i} contains a document reference within a different database (${n.projectId}/${n.database}) which is not supported. It will be treated as a reference in the current database (${e.projectId}/${e.database}) instead.`), + i; + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Converts custom model object of type T into `DocumentData` by applying the + * converter if it exists. + * + * This function is used when converting user objects to `DocumentData` + * because we want to provide the user with a more specific error message if + * their `set()` or fails due to invalid data originating from a `toFirestore()` + * call. + */ function __PRIVATE_applyFirestoreDataConverter(t, e, r) { + let n; + // Cast to `any` in order to satisfy the union type constraint on + // toFirestore(). + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return n = t ? r && (r.merge || r.mergeFields) ? t.toFirestore(e, r) : t.toFirestore(e) : e, + n; +} + +class __PRIVATE_LiteUserDataWriter extends AbstractUserDataWriter { + constructor(t) { + super(), this.firestore = t; + } + convertBytes(t) { + return new Bytes(t); + } + convertReference(t) { + const e = this.convertDocumentKey(t, this.firestore._databaseId); + return new DocumentReference(this.firestore, /* converter= */ null, e); + } +} + +/** + * Reads the document referred to by the specified document reference. + * + * All documents are directly fetched from the server, even if the document was + * previously read or modified. Recent modifications are only reflected in the + * retrieved `DocumentSnapshot` if they have already been applied by the + * backend. If the client is offline, the read fails. If you like to use + * caching or see local modifications, please use the full Firestore SDK. + * + * @param reference - The reference of the document to fetch. + * @returns A Promise resolved with a `DocumentSnapshot` containing the current + * document contents. + */ function getDoc(t) { + const e = __PRIVATE_getDatastore((t = __PRIVATE_cast(t, DocumentReference)).firestore), r = new __PRIVATE_LiteUserDataWriter(t.firestore); + return __PRIVATE_invokeBatchGetDocumentsRpc(e, [ t._key ]).then((e => { + __PRIVATE_hardAssert(1 === e.length, 15618); + const n = e[0]; + return new DocumentSnapshot(t.firestore, r, t._key, n.isFoundDocument() ? n : null, t.converter); + })); +} + +/** + * Executes the query and returns the results as a {@link QuerySnapshot}. + * + * All queries are executed directly by the server, even if the query was + * previously executed. Recent modifications are only reflected in the retrieved + * results if they have already been applied by the backend. If the client is + * offline, the operation fails. To see previously cached result and local + * modifications, use the full Firestore SDK. + * + * @param query - The `Query` to execute. + * @returns A Promise that will be resolved with the results of the query. + */ function getDocs(t) { + (function __PRIVATE_validateHasExplicitOrderByForLimitToLast(t) { + if ("L" /* LimitType.Last */ === t.limitType && 0 === t.explicitOrderBy.length) throw new FirestoreError(O, "limitToLast() queries require specifying at least one orderBy() clause"); + })((t = __PRIVATE_cast(t, Query))._query); + const e = __PRIVATE_getDatastore(t.firestore), r = new __PRIVATE_LiteUserDataWriter(t.firestore); + return __PRIVATE_invokeRunQueryRpc(e, t._query).then((e => { + const n = e.map((e => new QueryDocumentSnapshot(t.firestore, r, e.key, e, t.converter))); + return "L" /* LimitType.Last */ === t._query.limitType && + // Limit to last queries reverse the orderBy constraint that was + // specified by the user. As such, we need to reverse the order of the + // results to return the documents in the expected order. + n.reverse(), new QuerySnapshot(t, n); + })); +} + +function setDoc(t, e, r) { + const n = __PRIVATE_applyFirestoreDataConverter((t = __PRIVATE_cast(t, DocumentReference)).converter, e, r), i = __PRIVATE_parseSetData(__PRIVATE_newUserDataReader(t.firestore), "setDoc", t._key, n, null !== t.converter, r); + return __PRIVATE_invokeCommitRpc(__PRIVATE_getDatastore(t.firestore), [ i.toMutation(t._key, Precondition.none()) ]); +} + +function updateDoc(t, e, r, ...n) { + const i = __PRIVATE_newUserDataReader((t = __PRIVATE_cast(t, DocumentReference)).firestore); + // For Compat types, we have to "extract" the underlying types before + // performing validation. + let s; + s = "string" == typeof (e = getModularInstance(e)) || e instanceof FieldPath ? __PRIVATE_parseUpdateVarargs(i, "updateDoc", t._key, e, r, n) : __PRIVATE_parseUpdateData(i, "updateDoc", t._key, e); + return __PRIVATE_invokeCommitRpc(__PRIVATE_getDatastore(t.firestore), [ s.toMutation(t._key, Precondition.exists(!0)) ]); +} + +/** + * Deletes the document referred to by the specified `DocumentReference`. + * + * The deletion will only be reflected in document reads that occur after the + * returned promise resolves. If the client is offline, the + * delete fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @param reference - A reference to the document to delete. + * @returns A `Promise` resolved once the document has been successfully + * deleted from the backend. + */ function deleteDoc(t) { + return __PRIVATE_invokeCommitRpc(__PRIVATE_getDatastore((t = __PRIVATE_cast(t, DocumentReference)).firestore), [ new __PRIVATE_DeleteMutation(t._key, Precondition.none()) ]); +} + +/** + * Add a new document to specified `CollectionReference` with the given data, + * assigning it a document ID automatically. + * + * The result of this write will only be reflected in document reads that occur + * after the returned promise resolves. If the client is offline, the + * write fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @param reference - A reference to the collection to add this document to. + * @param data - An Object containing the data for the new document. + * @throws Error - If the provided input is not a valid Firestore document. + * @returns A `Promise` resolved with a `DocumentReference` pointing to the + * newly created document after it has been written to the backend. + */ function addDoc(t, e) { + const r = doc(t = __PRIVATE_cast(t, CollectionReference)), n = __PRIVATE_applyFirestoreDataConverter(t.converter, e), i = __PRIVATE_parseSetData(__PRIVATE_newUserDataReader(t.firestore), "addDoc", r._key, n, null !== r.converter, {}); + return __PRIVATE_invokeCommitRpc(__PRIVATE_getDatastore(t.firestore), [ i.toMutation(r._key, Precondition.exists(!1)) ]).then((() => r)); +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Calculates the number of documents in the result set of the given query + * without actually downloading the documents. + * + * Using this function to count the documents is efficient because only the + * final count, not the documents' data, is downloaded. This function can + * count the documents in cases where the result set is prohibitively large to + * download entirely (thousands of documents). + * + * @param query The query whose result set size is calculated. + * @returns A Promise that will be resolved with the count; the count can be + * retrieved from `snapshot.data().count`, where `snapshot` is the + * `AggregateQuerySnapshot` to which the returned Promise resolves. + */ function getCount(t) { + return getAggregate(t, { + count: count() + }); +} + +/** + * Calculates the specified aggregations over the documents in the result + * set of the given query without actually downloading the documents. + * + * Using this function to perform aggregations is efficient because only the + * final aggregation values, not the documents' data, are downloaded. This + * function can perform aggregations of the documents in cases where the result + * set is prohibitively large to download entirely (thousands of documents). + * + * @param query The query whose result set is aggregated over. + * @param aggregateSpec An `AggregateSpec` object that specifies the aggregates + * to perform over the result set. The AggregateSpec specifies aliases for each + * aggregate, which can be used to retrieve the aggregate result. + * @example + * ```typescript + * const aggregateSnapshot = await getAggregate(query, { + * countOfDocs: count(), + * totalHours: sum('hours'), + * averageScore: average('score') + * }); + * + * const countOfDocs: number = aggregateSnapshot.data().countOfDocs; + * const totalHours: number = aggregateSnapshot.data().totalHours; + * const averageScore: number | null = aggregateSnapshot.data().averageScore; + * ``` + */ function getAggregate(t, e) { + const r = __PRIVATE_cast(t.firestore, Firestore), n = __PRIVATE_getDatastore(r), i = function __PRIVATE_mapToArray(t, e) { + const r = []; + for (const n in t) Object.prototype.hasOwnProperty.call(t, n) && r.push(e(t[n], n, t)); + return r; + }(e, ((t, e) => new __PRIVATE_AggregateImpl(e, t.aggregateType, t._internalFieldPath))); + // Run the aggregation and convert the results + return __PRIVATE_invokeRunAggregationQueryRpc(n, t._query, i).then((e => function __PRIVATE_convertToAggregateQuerySnapshot(t, e, r) { + const n = new __PRIVATE_LiteUserDataWriter(t), i = new AggregateQuerySnapshot(e, n, r); + return i; + } + /** + * Create an AggregateField object that can be used to compute the sum of + * a specified field over a range of documents in the result set of a query. + * @param field Specifies the field to sum across the result set. + */ (r, t, e))); +} + +function sum(t) { + return new AggregateField("sum", __PRIVATE_fieldPathFromArgument$1("sum", t)); +} + +/** + * Create an AggregateField object that can be used to compute the average of + * a specified field over a range of documents in the result set of a query. + * @param field Specifies the field to average across the result set. + */ function average(t) { + return new AggregateField("avg", __PRIVATE_fieldPathFromArgument$1("average", t)); +} + +/** + * Create an AggregateField object that can be used to compute the count of + * documents in the result set of a query. + */ function count() { + return new AggregateField("count"); +} + +/** + * Compares two 'AggregateField` instances for equality. + * + * @param left Compare this AggregateField to the `right`. + * @param right Compare this AggregateField to the `left`. + */ function aggregateFieldEqual(t, e) { + return t instanceof AggregateField && e instanceof AggregateField && t.aggregateType === e.aggregateType && t._internalFieldPath?.canonicalString() === e._internalFieldPath?.canonicalString(); +} + +/** + * Compares two `AggregateQuerySnapshot` instances for equality. + * + * Two `AggregateQuerySnapshot` instances are considered "equal" if they have + * underlying queries that compare equal, and the same data. + * + * @param left - The first `AggregateQuerySnapshot` to compare. + * @param right - The second `AggregateQuerySnapshot` to compare. + * + * @returns `true` if the objects are "equal", as defined above, or `false` + * otherwise. + */ function aggregateQuerySnapshotEqual(t, e) { + return queryEqual(t.query, e.query) && deepEqual(t.data(), e.data()); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Returns a sentinel for use with {@link @firebase/firestore/lite#(updateDoc:1)} or + * {@link @firebase/firestore/lite#(setDoc:1)} with `{merge: true}` to mark a field for deletion. + */ function deleteField() { + return new __PRIVATE_DeleteFieldValueImpl("deleteField"); +} + +/** + * Returns a sentinel used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link @firebase/firestore/lite#(updateDoc:1)} to + * include a server-generated timestamp in the written data. + */ function serverTimestamp() { + return new __PRIVATE_ServerTimestampFieldValueImpl("serverTimestamp"); +} + +/** + * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link + * @firebase/firestore/lite#(updateDoc:1)} that tells the server to union the given elements with any array + * value that already exists on the server. Each specified element that doesn't + * already exist in the array will be added to the end. If the field being + * modified is not already an array it will be overwritten with an array + * containing exactly the specified elements. + * + * @param elements - The elements to union into the array. + * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or + * `updateDoc()`. + */ function arrayUnion(...t) { + // NOTE: We don't actually parse the data until it's used in set() or + // update() since we'd need the Firestore instance to do this. + return new __PRIVATE_ArrayUnionFieldValueImpl("arrayUnion", t); +} + +/** + * Returns a special value that can be used with {@link (setDoc:1)} or {@link + * updateDoc:1} that tells the server to remove the given elements from any + * array value that already exists on the server. All instances of each element + * specified will be removed from the array. If the field being modified is not + * already an array it will be overwritten with an empty array. + * + * @param elements - The elements to remove from the array. + * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or + * `updateDoc()` + */ function arrayRemove(...t) { + // NOTE: We don't actually parse the data until it's used in set() or + // update() since we'd need the Firestore instance to do this. + return new __PRIVATE_ArrayRemoveFieldValueImpl("arrayRemove", t); +} + +/** + * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link + * @firebase/firestore/lite#(updateDoc:1)} that tells the server to increment the field's current value by + * the given value. + * + * If either the operand or the current field value uses floating point + * precision, all arithmetic follows IEEE 754 semantics. If both values are + * integers, values outside of JavaScript's safe number range + * (`Number.MIN_SAFE_INTEGER` to `Number.MAX_SAFE_INTEGER`) are also subject to + * precision loss. Furthermore, once processed by the Firestore backend, all + * integer operations are capped between -2^63 and 2^63-1. + * + * If the current field value is not of type `number`, or if the field does not + * yet exist, the transformation sets the field to the given value. + * + * @param n - The value to increment by. + * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or + * `updateDoc()` + */ function increment(t) { + return new __PRIVATE_NumericIncrementFieldValueImpl("increment", t); +} + +/** + * Creates a new `VectorValue` constructed with a copy of the given array of numbers. + * + * @param values - Create a `VectorValue` instance with a copy of this array of numbers. + * + * @returns A new `VectorValue` constructed with a copy of the given array of numbers. + */ function vector(t) { + return new VectorValue(t); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A write batch, used to perform multiple writes as a single atomic unit. + * + * A `WriteBatch` object can be acquired by calling {@link writeBatch}. It + * provides methods for adding writes to the write batch. None of the writes + * will be committed (or visible locally) until {@link WriteBatch.commit} is + * called. + */ class WriteBatch { + /** @hideconstructor */ + constructor(t, e) { + this._firestore = t, this._commitHandler = e, this._mutations = [], this._committed = !1, + this._dataReader = __PRIVATE_newUserDataReader(t); + } + set(t, e, r) { + this._verifyNotCommitted(); + const n = __PRIVATE_validateReference(t, this._firestore), i = __PRIVATE_applyFirestoreDataConverter(n.converter, e, r), s = __PRIVATE_parseSetData(this._dataReader, "WriteBatch.set", n._key, i, null !== n.converter, r); + return this._mutations.push(s.toMutation(n._key, Precondition.none())), this; + } + update(t, e, r, ...n) { + this._verifyNotCommitted(); + const i = __PRIVATE_validateReference(t, this._firestore); + // For Compat types, we have to "extract" the underlying types before + // performing validation. + let s; + return s = "string" == typeof (e = getModularInstance(e)) || e instanceof FieldPath ? __PRIVATE_parseUpdateVarargs(this._dataReader, "WriteBatch.update", i._key, e, r, n) : __PRIVATE_parseUpdateData(this._dataReader, "WriteBatch.update", i._key, e), + this._mutations.push(s.toMutation(i._key, Precondition.exists(!0))), this; + } + /** + * Deletes the document referred to by the provided {@link DocumentReference}. + * + * @param documentRef - A reference to the document to be deleted. + * @returns This `WriteBatch` instance. Used for chaining method calls. + */ delete(t) { + this._verifyNotCommitted(); + const e = __PRIVATE_validateReference(t, this._firestore); + return this._mutations = this._mutations.concat(new __PRIVATE_DeleteMutation(e._key, Precondition.none())), + this; + } + /** + * Commits all of the writes in this write batch as a single atomic unit. + * + * The result of these writes will only be reflected in document reads that + * occur after the returned promise resolves. If the client is offline, the + * write fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @returns A `Promise` resolved once all of the writes in the batch have been + * successfully written to the backend as an atomic unit (note that it won't + * resolve while you're offline). + */ commit() { + return this._verifyNotCommitted(), this._committed = !0, this._mutations.length > 0 ? this._commitHandler(this._mutations) : Promise.resolve(); + } + _verifyNotCommitted() { + if (this._committed) throw new FirestoreError(S, "A write batch can no longer be used after commit() has been called."); + } +} + +function __PRIVATE_validateReference(t, e) { + if ((t = getModularInstance(t)).firestore !== e) throw new FirestoreError(y, "Provided document reference is from a different Firestore instance."); + return t; +} + +/** + * Creates a write batch, used for performing multiple writes as a single + * atomic operation. The maximum number of writes allowed in a single WriteBatch + * is 500. + * + * The result of these writes will only be reflected in document reads that + * occur after the returned promise resolves. If the client is offline, the + * write fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @returns A `WriteBatch` that can be used to atomically execute multiple + * writes. + */ function writeBatch(t) { + const e = __PRIVATE_getDatastore(t = __PRIVATE_cast(t, Firestore)); + return new WriteBatch(t, (t => __PRIVATE_invokeCommitRpc(e, t))); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Internal transaction object responsible for accumulating the mutations to + * perform and the base versions for any documents read. + */ class Transaction$1 { + constructor(t) { + this.datastore = t, + // The version of each document that was read during this transaction. + this.readVersions = new Map, this.mutations = [], this.committed = !1, + /** + * A deferred usage error that occurred previously in this transaction that + * will cause the transaction to fail once it actually commits. + */ + this.lastTransactionError = null, + /** + * Set of documents that have been written in the transaction. + * + * When there's more than one write to the same key in a transaction, any + * writes after the first are handled differently. + */ + this.writtenDocs = new Set; + } + async lookup(t) { + if (this.ensureCommitNotCalled(), this.mutations.length > 0) throw this.lastTransactionError = new FirestoreError(y, "Firestore transactions require all reads to be executed before all writes."), + this.lastTransactionError; + const e = await __PRIVATE_invokeBatchGetDocumentsRpc(this.datastore, t); + return e.forEach((t => this.recordVersion(t))), e; + } + set(t, e) { + this.write(e.toMutation(t, this.precondition(t))), this.writtenDocs.add(t.toString()); + } + update(t, e) { + try { + this.write(e.toMutation(t, this.preconditionForUpdate(t))); + } catch (t) { + this.lastTransactionError = t; + } + this.writtenDocs.add(t.toString()); + } + delete(t) { + this.write(new __PRIVATE_DeleteMutation(t, this.precondition(t))), this.writtenDocs.add(t.toString()); + } + async commit() { + if (this.ensureCommitNotCalled(), this.lastTransactionError) throw this.lastTransactionError; + const t = this.readVersions; + // For each mutation, note that the doc was written. + this.mutations.forEach((e => { + t.delete(e.key.toString()); + })), + // For each document that was read but not written to, we want to perform + // a `verify` operation. + t.forEach(((t, e) => { + const r = DocumentKey.fromPath(e); + this.mutations.push(new __PRIVATE_VerifyMutation(r, this.precondition(r))); + })), await __PRIVATE_invokeCommitRpc(this.datastore, this.mutations), this.committed = !0; + } + recordVersion(t) { + let e; + if (t.isFoundDocument()) e = t.version; else { + if (!t.isNoDocument()) throw fail(50498, { + Rt: t.constructor.name + }); + // Represent a deleted doc using SnapshotVersion.min(). + e = SnapshotVersion.min(); + } + const r = this.readVersions.get(t.key.toString()); + if (r) { + if (!e.isEqual(r)) + // This transaction will fail no matter what. + throw new FirestoreError(C, "Document version changed between two reads."); + } else this.readVersions.set(t.key.toString(), e); + } + /** + * Returns the version of this document when it was read in this transaction, + * as a precondition, or no precondition if it was not read. + */ precondition(t) { + const e = this.readVersions.get(t.toString()); + return !this.writtenDocs.has(t.toString()) && e ? e.isEqual(SnapshotVersion.min()) ? Precondition.exists(!1) : Precondition.updateTime(e) : Precondition.none(); + } + /** + * Returns the precondition for a document if the operation is an update. + */ preconditionForUpdate(t) { + const e = this.readVersions.get(t.toString()); + // The first time a document is written, we want to take into account the + // read time and existence + if (!this.writtenDocs.has(t.toString()) && e) { + if (e.isEqual(SnapshotVersion.min())) + // The document doesn't exist, so fail the transaction. + // This has to be validated locally because you can't send a + // precondition that a document does not exist without changing the + // semantics of the backend write to be an insert. This is the reverse + // of what we want, since we want to assert that the document doesn't + // exist but then send the update and have it fail. Since we can't + // express that to the backend, we have to validate locally. + // Note: this can change once we can send separate verify writes in the + // transaction. + throw new FirestoreError(y, "Can't update a document that doesn't exist."); + // Document exists, base precondition on document update time. + return Precondition.updateTime(e); + } + // Document was not read, so we just use the preconditions for a blind + // update. + return Precondition.exists(!0); + } + write(t) { + this.ensureCommitNotCalled(), this.mutations.push(t); + } + ensureCommitNotCalled() {} +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ const ht = { + maxAttempts: 5 +}; + +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * TransactionRunner encapsulates the logic needed to run and retry transactions + * with backoff. + */ +class __PRIVATE_TransactionRunner { + constructor(t, e, r, n, i) { + this.asyncQueue = t, this.datastore = e, this.options = r, this.updateFunction = n, + this.deferred = i, this.Vt = r.maxAttempts, this.It = new __PRIVATE_ExponentialBackoff(this.asyncQueue, "transaction_retry" /* TimerId.TransactionRetry */); + } + /** Runs the transaction and sets the result on deferred. */ yt() { + this.Vt -= 1, this.gt(); + } + gt() { + this.It.Z((async () => { + const t = new Transaction$1(this.datastore), e = this.wt(t); + e && e.then((e => { + this.asyncQueue.enqueueAndForget((() => t.commit().then((() => { + this.deferred.resolve(e); + })).catch((t => { + this.Ft(t); + })))); + })).catch((t => { + this.Ft(t); + })); + })); + } + wt(t) { + try { + const e = this.updateFunction(t); + return !__PRIVATE_isNullOrUndefined(e) && e.catch && e.then ? e : (this.deferred.reject(Error("Transaction callback must return a Promise")), + null); + } catch (t) { + // Do not retry errors thrown by user provided updateFunction. + return this.deferred.reject(t), null; + } + } + Ft(t) { + this.Vt > 0 && this.vt(t) ? (this.Vt -= 1, this.asyncQueue.enqueueAndForget((() => (this.gt(), + Promise.resolve())))) : this.deferred.reject(t); + } + vt(t) { + if ("FirebaseError" === t?.name) { + // In transactions, the backend will fail outdated reads with FAILED_PRECONDITION and + // non-matching document versions with ABORTED. These errors should be retried. + const e = t.code; + return "aborted" === e || "failed-precondition" === e || "already-exists" === e || ! + /** + * Determines whether an error code represents a permanent error when received + * in response to a non-write operation. + * + * See isPermanentWriteError for classifying write errors. + */ + function __PRIVATE_isPermanentError(t) { + switch (t) { + case V: + return fail(64938); + + case I: + case p: + case g: + case b: + case q: + case B: + // Unauthenticated means something went wrong with our token and we need + // to retry with new credentials which will happen automatically. + case D: + return !1; + + case y: + case w: + case F: + case v: + case S: + // Aborted might be retried in some scenarios, but that is dependent on + // the context and should handled individually by the calling code. + // See https://cloud.google.com/apis/design/errors. + case C: + case N: + case O: + case $: + return !0; + + default: + return fail(15467, { + code: t + }); + } + }(e); + } + return !1; + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** The Platform's 'document' implementation or null if not available. */ function getDocument() { + // `document` is not always available, e.g. in ReactNative and WebWorkers. + // eslint-disable-next-line no-restricted-globals + return "undefined" != typeof document ? document : null; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Represents an operation scheduled to be run in the future on an AsyncQueue. + * + * It is created via DelayedOperation.createAndSchedule(). + * + * Supports cancellation (via cancel()) and early execution (via skipDelay()). + * + * Note: We implement `PromiseLike` instead of `Promise`, as the `Promise` type + * in newer versions of TypeScript defines `finally`, which is not available in + * IE. + */ class DelayedOperation { + constructor(t, e, r, n, i) { + this.asyncQueue = t, this.timerId = e, this.targetTimeMs = r, this.op = n, this.removalCallback = i, + this.deferred = new __PRIVATE_Deferred, this.then = this.deferred.promise.then.bind(this.deferred.promise), + // It's normal for the deferred promise to be canceled (due to cancellation) + // and so we attach a dummy catch callback to avoid + // 'UnhandledPromiseRejectionWarning' log spam. + this.deferred.promise.catch((t => {})); + } + get promise() { + return this.deferred.promise; + } + /** + * Creates and returns a DelayedOperation that has been scheduled to be + * executed on the provided asyncQueue after the provided delayMs. + * + * @param asyncQueue - The queue to schedule the operation on. + * @param id - A Timer ID identifying the type of operation this is. + * @param delayMs - The delay (ms) before the operation should be scheduled. + * @param op - The operation to run. + * @param removalCallback - A callback to be called synchronously once the + * operation is executed or canceled, notifying the AsyncQueue to remove it + * from its delayedOperations list. + * PORTING NOTE: This exists to prevent making removeDelayedOperation() and + * the DelayedOperation class public. + */ static createAndSchedule(t, e, r, n, i) { + const s = Date.now() + r, o = new DelayedOperation(t, e, s, n, i); + return o.start(r), o; + } + /** + * Starts the timer. This is called immediately after construction by + * createAndSchedule(). + */ start(t) { + this.timerHandle = setTimeout((() => this.handleDelayElapsed()), t); + } + /** + * Queues the operation to run immediately (if it hasn't already been run or + * canceled). + */ skipDelay() { + return this.handleDelayElapsed(); + } + /** + * Cancels the operation if it hasn't already been executed or canceled. The + * promise will be rejected. + * + * As long as the operation has not yet been run, calling cancel() provides a + * guarantee that the operation will not be run. + */ cancel(t) { + null !== this.timerHandle && (this.clearTimeout(), this.deferred.reject(new FirestoreError(I, "Operation cancelled" + (t ? ": " + t : "")))); + } + handleDelayElapsed() { + this.asyncQueue.enqueueAndForget((() => null !== this.timerHandle ? (this.clearTimeout(), + this.op().then((t => this.deferred.resolve(t)))) : Promise.resolve())); + } + clearTimeout() { + null !== this.timerHandle && (this.removalCallback(this), clearTimeout(this.timerHandle), + this.timerHandle = null); + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ const ft = "AsyncQueue"; + +class __PRIVATE_AsyncQueueImpl { + constructor(t = Promise.resolve()) { + // A list of retryable operations. Retryable operations are run in order and + // retried with backoff. + this.Dt = [], + // Is this AsyncQueue being shut down? Once it is set to true, it will not + // be changed again. + this.bt = !1, + // Operations scheduled to be queued in the future. Operations are + // automatically removed after they are run or canceled. + this.St = [], + // visible for testing + this.Ct = null, + // Flag set while there's an outstanding AsyncQueue operation, used for + // assertion sanity-checks. + this.Nt = !1, + // Enabled during shutdown on Safari to prevent future access to IndexedDB. + this.Ot = !1, + // List of TimerIds to fast-forward delays for. + this.qt = [], + // Backoff timer used to schedule retries for retryable operations + this.It = new __PRIVATE_ExponentialBackoff(this, "async_queue_retry" /* TimerId.AsyncQueueRetry */), + // Visibility handler that triggers an immediate retry of all retryable + // operations. Meant to speed up recovery when we regain file system access + // after page comes into foreground. + this.Bt = () => { + const t = getDocument(); + t && __PRIVATE_logDebug(ft, "Visibility state changed to " + t.visibilityState), + this.It.tt(); + }, this.$t = t; + const e = getDocument(); + e && "function" == typeof e.addEventListener && e.addEventListener("visibilitychange", this.Bt); + } + get isShuttingDown() { + return this.bt; + } + /** + * Adds a new operation to the queue without waiting for it to complete (i.e. + * we ignore the Promise result). + */ enqueueAndForget(t) { + // eslint-disable-next-line @typescript-eslint/no-floating-promises + this.enqueue(t); + } + enqueueAndForgetEvenWhileRestricted(t) { + this.Qt(), + // eslint-disable-next-line @typescript-eslint/no-floating-promises + this.kt(t); + } + enterRestrictedMode(t) { + if (!this.bt) { + this.bt = !0, this.Ot = t || !1; + const e = getDocument(); + e && "function" == typeof e.removeEventListener && e.removeEventListener("visibilitychange", this.Bt); + } + } + enqueue(t) { + if (this.Qt(), this.bt) + // Return a Promise which never resolves. + return new Promise((() => {})); + // Create a deferred Promise that we can return to the callee. This + // allows us to return a "hanging Promise" only to the callee and still + // advance the queue even when the operation is not run. + const e = new __PRIVATE_Deferred; + return this.kt((() => this.bt && this.Ot ? Promise.resolve() : (t().then(e.resolve, e.reject), + e.promise))).then((() => e.promise)); + } + enqueueRetryable(t) { + this.enqueueAndForget((() => (this.Dt.push(t), this.Lt()))); + } + /** + * Runs the next operation from the retryable queue. If the operation fails, + * reschedules with backoff. + */ async Lt() { + if (0 !== this.Dt.length) { + try { + await this.Dt[0](), this.Dt.shift(), this.It.reset(); + } catch (t) { + if (! + /** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + /** Verifies whether `e` is an IndexedDbTransactionError. */ + function __PRIVATE_isIndexedDbTransactionError(t) { + // Use name equality, as instanceof checks on errors don't work with errors + // that wrap other errors. + return "IndexedDbTransactionError" === t.name; + }(t)) throw t; + // Failure will be handled by AsyncQueue + __PRIVATE_logDebug(ft, "Operation failed with retryable error: " + t); + } + this.Dt.length > 0 && + // If there are additional operations, we re-schedule `retryNextOp()`. + // This is necessary to run retryable operations that failed during + // their initial attempt since we don't know whether they are already + // enqueued. If, for example, `op1`, `op2`, `op3` are enqueued and `op1` + // needs to be re-run, we will run `op1`, `op1`, `op2` using the + // already enqueued calls to `retryNextOp()`. `op3()` will then run in the + // call scheduled here. + // Since `backoffAndRun()` cancels an existing backoff and schedules a + // new backoff on every call, there is only ever a single additional + // operation in the queue. + this.It.Z((() => this.Lt())); + } + } + kt(t) { + const e = this.$t.then((() => (this.Nt = !0, t().catch((t => { + this.Ct = t, this.Nt = !1; + // Re-throw the error so that this.tail becomes a rejected Promise and + // all further attempts to chain (via .then) will just short-circuit + // and return the rejected Promise. + throw __PRIVATE_logError("INTERNAL UNHANDLED ERROR: ", __PRIVATE_getMessageOrStack(t)), + t; + })).then((t => (this.Nt = !1, t)))))); + return this.$t = e, e; + } + enqueueAfterDelay(t, e, r) { + this.Qt(), + // Fast-forward delays for timerIds that have been overridden. + this.qt.indexOf(t) > -1 && (e = 0); + const n = DelayedOperation.createAndSchedule(this, t, e, r, (t => this.Mt(t))); + return this.St.push(n), n; + } + Qt() { + this.Ct && fail(47125, { + xt: __PRIVATE_getMessageOrStack(this.Ct) + }); + } + verifyOperationInProgress() {} + /** + * Waits until all currently queued tasks are finished executing. Delayed + * operations are not run. + */ async Ut() { + // Operations in the queue prior to draining may have enqueued additional + // operations. Keep draining the queue until the tail is no longer advanced, + // which indicates that no more new operations were enqueued and that all + // operations were executed. + let t; + do { + t = this.$t, await t; + } while (t !== this.$t); + } + /** + * For Tests: Determine if a delayed operation with a particular TimerId + * exists. + */ jt(t) { + for (const e of this.St) if (e.timerId === t) return !0; + return !1; + } + /** + * For Tests: Runs some or all delayed operations early. + * + * @param lastTimerId - Delayed operations up to and including this TimerId + * will be drained. Pass TimerId.All to run all delayed operations. + * @returns a Promise that resolves once all operations have been run. + */ zt(t) { + // Note that draining may generate more delayed ops, so we do that first. + return this.Ut().then((() => { + // Run ops in the same order they'd run if they ran naturally. + /* eslint-disable-next-line @typescript-eslint/no-floating-promises */ + this.St.sort(((t, e) => t.targetTimeMs - e.targetTimeMs)); + for (const e of this.St) if (e.skipDelay(), "all" /* TimerId.All */ !== t && e.timerId === t) break; + return this.Ut(); + })); + } + /** + * For Tests: Skip all subsequent delays for a timer id. + */ Wt(t) { + this.qt.push(t); + } + /** Called once a DelayedOperation is run or canceled. */ Mt(t) { + // NOTE: indexOf / slice are O(n), but delayedOperations is expected to be small. + const e = this.St.indexOf(t); + /* eslint-disable-next-line @typescript-eslint/no-floating-promises */ this.St.splice(e, 1); + } +} + +/** + * Chrome includes Error.message in Error.stack. Other browsers do not. + * This returns expected output of message + stack when available. + * @param error - Error or FirestoreError + */ +function __PRIVATE_getMessageOrStack(t) { + let e = t.message || ""; + return t.stack && (e = t.stack.includes(t.message) ? t.stack : t.message + "\n" + t.stack), + e; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// TODO(mrschmidt) Consider using `BaseTransaction` as the base class in the +// legacy SDK. +/** + * A reference to a transaction. + * + * The `Transaction` object passed to a transaction's `updateFunction` provides + * the methods to read and write data within the transaction context. See + * {@link runTransaction}. + */ class Transaction { + /** @hideconstructor */ + constructor(t, e) { + this._firestore = t, this._transaction = e, this._dataReader = __PRIVATE_newUserDataReader(t); + } + /** + * Reads the document referenced by the provided {@link DocumentReference}. + * + * @param documentRef - A reference to the document to be read. + * @returns A `DocumentSnapshot` with the read data. + */ get(t) { + const e = __PRIVATE_validateReference(t, this._firestore), r = new __PRIVATE_LiteUserDataWriter(this._firestore); + return this._transaction.lookup([ e._key ]).then((t => { + if (!t || 1 !== t.length) return fail(24041); + const n = t[0]; + if (n.isFoundDocument()) return new DocumentSnapshot(this._firestore, r, n.key, n, e.converter); + if (n.isNoDocument()) return new DocumentSnapshot(this._firestore, r, e._key, null, e.converter); + throw fail(18433, { + doc: n + }); + })); + } + set(t, e, r) { + const n = __PRIVATE_validateReference(t, this._firestore), i = __PRIVATE_applyFirestoreDataConverter(n.converter, e, r), s = __PRIVATE_parseSetData(this._dataReader, "Transaction.set", n._key, i, null !== n.converter, r); + return this._transaction.set(n._key, s), this; + } + update(t, e, r, ...n) { + const i = __PRIVATE_validateReference(t, this._firestore); + // For Compat types, we have to "extract" the underlying types before + // performing validation. + let s; + return s = "string" == typeof (e = getModularInstance(e)) || e instanceof FieldPath ? __PRIVATE_parseUpdateVarargs(this._dataReader, "Transaction.update", i._key, e, r, n) : __PRIVATE_parseUpdateData(this._dataReader, "Transaction.update", i._key, e), + this._transaction.update(i._key, s), this; + } + /** + * Deletes the document referred to by the provided {@link DocumentReference}. + * + * @param documentRef - A reference to the document to be deleted. + * @returns This `Transaction` instance. Used for chaining method calls. + */ delete(t) { + const e = __PRIVATE_validateReference(t, this._firestore); + return this._transaction.delete(e._key), this; + } +} + +/** + * Executes the given `updateFunction` and then attempts to commit the changes + * applied within the transaction. If any document read within the transaction + * has changed, Cloud Firestore retries the `updateFunction`. If it fails to + * commit after 5 attempts, the transaction fails. + * + * The maximum number of writes allowed in a single transaction is 500. + * + * @param firestore - A reference to the Firestore database to run this + * transaction against. + * @param updateFunction - The function to execute within the transaction + * context. + * @param options - An options object to configure maximum number of attempts to + * commit. + * @returns If the transaction completed successfully or was explicitly aborted + * (the `updateFunction` returned a failed promise), the promise returned by the + * `updateFunction `is returned here. Otherwise, if the transaction failed, a + * rejected promise with the corresponding failure error is returned. + */ function runTransaction(t, e, r) { + const n = __PRIVATE_getDatastore(t = __PRIVATE_cast(t, Firestore)), i = { + ...ht, + ...r + }; + !function __PRIVATE_validateTransactionOptions(t) { + if (t.maxAttempts < 1) throw new FirestoreError(y, "Max attempts must be at least 1"); + }(i); + const s = new __PRIVATE_Deferred; + return new __PRIVATE_TransactionRunner(function __PRIVATE_newAsyncQueue() { + return new __PRIVATE_AsyncQueueImpl; + }(), n, i, (r => e(new Transaction(t, r))), s).yt(), s.promise; +} + +/** + * Firestore Lite + * + * @remarks Firestore Lite is a small online-only SDK that allows read + * and write access to your Firestore database. All operations connect + * directly to the backend, and `onSnapshot()` APIs are not supported. + * @packageDocumentation + */ !function __PRIVATE_registerFirestore() { + !function __PRIVATE_setSDKVersion(t) { + A = t; + }(`${SDK_VERSION}_lite`), _registerComponent(new Component("firestore/lite", ((t, {instanceIdentifier: e, options: r}) => { + const n = t.getProvider("app").getImmediate(), i = new Firestore(new __PRIVATE_LiteAuthCredentialsProvider(t.getProvider("auth-internal")), new __PRIVATE_LiteAppCheckTokenProvider(n, t.getProvider("app-check-internal")), function __PRIVATE_databaseIdFromApp(t, e) { + if (!Object.prototype.hasOwnProperty.apply(t.options, [ "projectId" ])) throw new FirestoreError(y, '"projectId" not provided in firebase.initializeApp.'); + return new DatabaseId(t.options.projectId, e); + }(n, e), n); + return r && i._setSettings(r), i; + }), "PUBLIC").setMultipleInstances(!0)), + // RUNTIME_ENV and BUILD_TARGET are replaced by real values during the compilation + registerVersion("firestore-lite", P, ""), registerVersion("firestore-lite", P, "cjs2020"); +}(); + +export { AggregateField, AggregateQuerySnapshot, Bytes, CollectionReference, DocumentReference, DocumentSnapshot, FieldPath, FieldValue, Firestore, FirestoreError, GeoPoint, Query, QueryCompositeFilterConstraint, QueryConstraint, QueryDocumentSnapshot, QueryEndAtConstraint, QueryFieldFilterConstraint, QueryLimitConstraint, QueryOrderByConstraint, QuerySnapshot, QueryStartAtConstraint, Timestamp, Transaction, VectorValue, WriteBatch, addDoc, aggregateFieldEqual, aggregateQuerySnapshotEqual, and, arrayRemove, arrayUnion, average, collection, collectionGroup, connectFirestoreEmulator, count, deleteDoc, deleteField, doc, documentId, endAt, endBefore, getAggregate, getCount, getDoc, getDocs, getFirestore, increment, initializeFirestore, limit, limitToLast, or, orderBy, query, queryEqual, refEqual, runTransaction, serverTimestamp, setDoc, setLogLevel, snapshotEqual, startAfter, startAt, sum, terminate, updateDoc, vector, where, writeBatch }; +//# sourceMappingURL=index.cjs.js.map diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/index.cjs.js.map b/frontend-old/node_modules/@firebase/firestore/dist/lite/index.cjs.js.map new file mode 100644 index 0000000..2820a3b --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/index.cjs.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.cjs.js","sources":["../../src/auth/user.ts","../../src/core/version.ts","../../src/util/log.ts","../../src/platform/browser/format_json.ts","../../src/util/assert.ts","../../src/util/error.ts","../../src/util/promise.ts","../../src/api/credentials.ts","../../src/core/database_info.ts","../../src/platform/browser/random_bytes.ts","../../src/util/misc.ts","../../src/model/path.ts","../../src/model/document_key.ts","../../src/util/input_validation.ts","../../src/api/long_polling_options.ts","../../src/util/debug_uid.ts","../../src/util/types.ts","../../src/remote/rest_connection.ts","../../src/remote/rpc_error.ts","../../src/platform/browser_lite/fetch_connection.ts","../../src/core/aggregate.ts","../../src/util/obj.ts","../../src/util/base64_decode_error.ts","../../src/util/byte_string.ts","../../src/platform/browser/base64.ts","../../src/model/normalize.ts","../../src/util/json_validation.ts","../../src/lite-api/timestamp.ts","../../src/model/server_timestamps.ts","../../src/model/values.ts","../../src/core/bound.ts","../../src/core/filter.ts","../../src/core/order_by.ts","../../src/core/snapshot_version.ts","../../src/util/sorted_map.ts","../../src/util/sorted_set.ts","../../src/model/field_mask.ts","../../src/model/object_value.ts","../../src/model/document.ts","../../src/core/target.ts","../../src/core/query.ts","../../src/remote/number_serializer.ts","../../src/model/transform_operation.ts","../../src/model/mutation.ts","../../src/remote/serializer.ts","../../src/platform/browser/serializer.ts","../../src/remote/backoff.ts","../../src/remote/datastore.ts","../../src/lite-api/components.ts","../../src/platform/browser_lite/connection.ts","../../src/local/lru_garbage_collector_impl.ts","../../src/lite-api/settings.ts","../../src/local/lru_garbage_collector.ts","../../src/lite-api/database.ts","../../src/lite-api/aggregate_types.ts","../../src/lite-api/reference.ts","../../src/lite-api/bytes.ts","../../src/lite-api/field_path.ts","../../src/lite-api/field_value.ts","../../src/lite-api/geo_point.ts","../../src/lite-api/vector_value.ts","../../src/util/array.ts","../../src/lite-api/user_data_reader.ts","../../src/lite-api/snapshot.ts","../../src/lite-api/query.ts","../../src/lite-api/user_data_writer.ts","../../src/lite-api/reference_impl.ts","../../src/lite-api/aggregate.ts","../../src/lite-api/field_value_impl.ts","../../src/lite-api/write_batch.ts","../../src/core/transaction.ts","../../src/core/transaction_options.ts","../../src/core/transaction_runner.ts","../../src/platform/browser/dom.ts","../../src/util/async_queue.ts","../../src/util/async_queue_impl.ts","../../src/local/simple_db.ts","../../src/lite-api/transaction.ts","../../lite/register.ts","../../lite/index.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Simple wrapper around a nullable UID. Mostly exists to make code more\n * readable.\n */\nexport class User {\n /** A user with a null UID. */\n static readonly UNAUTHENTICATED = new User(null);\n\n // TODO(mikelehen): Look into getting a proper uid-equivalent for\n // non-FirebaseAuth providers.\n static readonly GOOGLE_CREDENTIALS = new User('google-credentials-uid');\n static readonly FIRST_PARTY = new User('first-party-uid');\n static readonly MOCK_USER = new User('mock-user');\n\n constructor(readonly uid: string | null) {}\n\n isAuthenticated(): boolean {\n return this.uid != null;\n }\n\n /**\n * Returns a key representing this user, suitable for inclusion in a\n * dictionary.\n */\n toKey(): string {\n if (this.isAuthenticated()) {\n return 'uid:' + this.uid;\n } else {\n return 'anonymous-user';\n }\n }\n\n isEqual(otherUser: User): boolean {\n return otherUser.uid === this.uid;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** The semver (www.semver.org) version of the SDK. */\nimport { version } from '../../../firebase/package.json';\nexport let SDK_VERSION = version;\nexport function setSDKVersion(version: string): void {\n SDK_VERSION = version;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Logger, LogLevel, LogLevelString } from '@firebase/logger';\n\nimport { SDK_VERSION } from '../core/version';\nimport { formatJSON } from '../platform/format_json';\n\nexport { LogLevel, LogLevelString };\n\nconst logClient = new Logger('@firebase/firestore');\n\n// Helper methods are needed because variables can't be exported as read/write\nexport function getLogLevel(): LogLevel {\n return logClient.logLevel;\n}\n\n/**\n * Sets the verbosity of Cloud Firestore logs (debug, error, or silent).\n *\n * @param logLevel - The verbosity you set for activity and error logging. Can\n * be any of the following values:\n *\n *
    \n *
  • `debug` for the most verbose logging level, primarily for\n * debugging.
  • \n *
  • `error` to log errors only.
  • \n *
  • `silent` to turn off logging.
  • \n *
\n */\nexport function setLogLevel(logLevel: LogLevelString): void {\n logClient.setLogLevel(logLevel);\n}\n\nexport function logDebug(msg: string, ...obj: unknown[]): void {\n if (logClient.logLevel <= LogLevel.DEBUG) {\n const args = obj.map(argToString);\n logClient.debug(`Firestore (${SDK_VERSION}): ${msg}`, ...args);\n }\n}\n\nexport function logError(msg: string, ...obj: unknown[]): void {\n if (logClient.logLevel <= LogLevel.ERROR) {\n const args = obj.map(argToString);\n logClient.error(`Firestore (${SDK_VERSION}): ${msg}`, ...args);\n }\n}\n\n/**\n * @internal\n */\nexport function logWarn(msg: string, ...obj: unknown[]): void {\n if (logClient.logLevel <= LogLevel.WARN) {\n const args = obj.map(argToString);\n logClient.warn(`Firestore (${SDK_VERSION}): ${msg}`, ...args);\n }\n}\n\n/**\n * Converts an additional log parameter to a string representation.\n */\nfunction argToString(obj: unknown): string | unknown {\n if (typeof obj === 'string') {\n return obj;\n } else {\n try {\n return formatJSON(obj);\n } catch (e) {\n // Converting to JSON failed, just log the object directly\n return obj;\n }\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** Formats an object as a JSON string, suitable for logging. */\nexport function formatJSON(value: unknown): string {\n return JSON.stringify(value);\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SDK_VERSION } from '../core/version';\n\nimport { logError } from './log';\n\n/**\n * Unconditionally fails, throwing an Error with the given message.\n * Messages are stripped in production builds.\n *\n * Returns `never` and can be used in expressions:\n * @example\n * let futureVar = fail('not implemented yet');\n *\n * @param code generate a new unique value with `yarn assertion-id:generate`\n * Search for an existing value using `yarn assertion-id:find X`\n */\nexport function fail(\n code: number,\n message: string,\n context?: Record\n): never;\n\n/**\n * Unconditionally fails, throwing an Error with the given message.\n * Messages are stripped in production builds.\n *\n * Returns `never` and can be used in expressions:\n * @example\n * let futureVar = fail('not implemented yet');\n *\n * @param id generate a new unique value with `yarn assertion-id:generate`\n * Search for an existing value using `yarn assertion-id:find X`\n */\nexport function fail(id: number, context?: Record): never;\n\nexport function fail(\n id: number,\n messageOrContext?: string | Record,\n context?: Record\n): never {\n let message = 'Unexpected state';\n if (typeof messageOrContext === 'string') {\n message = messageOrContext;\n } else {\n context = messageOrContext;\n }\n _fail(id, message, context);\n}\n\nfunction _fail(\n id: number,\n failure: string,\n context?: Record\n): never {\n // Log the failure in addition to throw an exception, just in case the\n // exception is swallowed.\n let message = `FIRESTORE (${SDK_VERSION}) INTERNAL ASSERTION FAILED: ${failure} (ID: ${id.toString(\n 16\n )})`;\n if (context !== undefined) {\n try {\n const stringContext = JSON.stringify(context);\n message += ' CONTEXT: ' + stringContext;\n } catch (e) {\n message += ' CONTEXT: ' + context;\n }\n }\n logError(message);\n\n // NOTE: We don't use FirestoreError here because these are internal failures\n // that cannot be handled by the user. (Also it would create a circular\n // dependency between the error and assert modules which doesn't work.)\n throw new Error(message);\n}\n\n/**\n * Fails if the given assertion condition is false, throwing an Error with the\n * given message if it did.\n *\n * Messages are stripped in production builds.\n *\n * @param id generate a new unique value with `yarn assertion-idgenerate`.\n * Search for an existing value using `yarn assertion-id:find X`\n */\nexport function hardAssert(\n assertion: boolean,\n id: number,\n message: string,\n context?: Record\n): asserts assertion;\n\n/**\n * Fails if the given assertion condition is false, throwing an Error with the\n * given message if it did.\n *\n * Messages are stripped in production builds.\n *\n * @param id generate a new unique value with `yarn assertion-id:generate`.\n * Search for an existing value using `yarn assertion-id:find X`\n */\nexport function hardAssert(\n assertion: boolean,\n id: number,\n context?: Record\n): asserts assertion;\n\nexport function hardAssert(\n assertion: boolean,\n id: number,\n messageOrContext?: string | Record,\n context?: Record\n): asserts assertion {\n let message = 'Unexpected state';\n if (typeof messageOrContext === 'string') {\n message = messageOrContext;\n } else {\n context = messageOrContext;\n }\n\n if (!assertion) {\n _fail(id, message, context);\n }\n}\n\n/**\n * Fails if the given assertion condition is false, throwing an Error with the\n * given message if it did.\n *\n * The code of callsites invoking this function are stripped out in production\n * builds. Any side-effects of code within the debugAssert() invocation will not\n * happen in this case.\n *\n * @internal\n */\nexport function debugAssert(\n assertion: boolean,\n message: string\n): asserts assertion {\n if (!assertion) {\n fail(0xdeb6, message);\n }\n}\n\n/**\n * Casts `obj` to `T`. In non-production builds, verifies that `obj` is an\n * instance of `T` before casting.\n */\nexport function debugCast(\n obj: object,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n constructor: { new (...args: any[]): T }\n): T | never {\n debugAssert(\n obj instanceof constructor,\n `Expected type '${constructor.name}', but was '${obj.constructor.name}'`\n );\n return obj as T;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseError } from '@firebase/util';\n\n/**\n * The set of Firestore status codes. The codes are the same at the ones\n * exposed by gRPC here:\n * https://github.com/grpc/grpc/blob/master/doc/statuscodes.md\n *\n * Possible values:\n * - 'cancelled': The operation was cancelled (typically by the caller).\n * - 'unknown': Unknown error or an error from a different error domain.\n * - 'invalid-argument': Client specified an invalid argument. Note that this\n * differs from 'failed-precondition'. 'invalid-argument' indicates\n * arguments that are problematic regardless of the state of the system\n * (e.g. an invalid field name).\n * - 'deadline-exceeded': Deadline expired before operation could complete.\n * For operations that change the state of the system, this error may be\n * returned even if the operation has completed successfully. For example,\n * a successful response from a server could have been delayed long enough\n * for the deadline to expire.\n * - 'not-found': Some requested document was not found.\n * - 'already-exists': Some document that we attempted to create already\n * exists.\n * - 'permission-denied': The caller does not have permission to execute the\n * specified operation.\n * - 'resource-exhausted': Some resource has been exhausted, perhaps a\n * per-user quota, or perhaps the entire file system is out of space.\n * - 'failed-precondition': Operation was rejected because the system is not\n * in a state required for the operation's execution.\n * - 'aborted': The operation was aborted, typically due to a concurrency\n * issue like transaction aborts, etc.\n * - 'out-of-range': Operation was attempted past the valid range.\n * - 'unimplemented': Operation is not implemented or not supported/enabled.\n * - 'internal': Internal errors. Means some invariants expected by\n * underlying system has been broken. If you see one of these errors,\n * something is very broken.\n * - 'unavailable': The service is currently unavailable. This is most likely\n * a transient condition and may be corrected by retrying with a backoff.\n * - 'data-loss': Unrecoverable data loss or corruption.\n * - 'unauthenticated': The request does not have valid authentication\n * credentials for the operation.\n */\nexport type FirestoreErrorCode =\n | 'cancelled'\n | 'unknown'\n | 'invalid-argument'\n | 'deadline-exceeded'\n | 'not-found'\n | 'already-exists'\n | 'permission-denied'\n | 'resource-exhausted'\n | 'failed-precondition'\n | 'aborted'\n | 'out-of-range'\n | 'unimplemented'\n | 'internal'\n | 'unavailable'\n | 'data-loss'\n | 'unauthenticated';\n\n/**\n * Error Codes describing the different ways Firestore can fail. These come\n * directly from GRPC.\n */\nexport type Code = FirestoreErrorCode;\n\nexport const Code = {\n // Causes are copied from:\n // https://github.com/grpc/grpc/blob/bceec94ea4fc5f0085d81235d8e1c06798dc341a/include/grpc%2B%2B/impl/codegen/status_code_enum.h\n /** Not an error; returned on success. */\n OK: 'ok' as FirestoreErrorCode,\n\n /** The operation was cancelled (typically by the caller). */\n CANCELLED: 'cancelled' as FirestoreErrorCode,\n\n /** Unknown error or an error from a different error domain. */\n UNKNOWN: 'unknown' as FirestoreErrorCode,\n\n /**\n * Client specified an invalid argument. Note that this differs from\n * FAILED_PRECONDITION. INVALID_ARGUMENT indicates arguments that are\n * problematic regardless of the state of the system (e.g., a malformed file\n * name).\n */\n INVALID_ARGUMENT: 'invalid-argument' as FirestoreErrorCode,\n\n /**\n * Deadline expired before operation could complete. For operations that\n * change the state of the system, this error may be returned even if the\n * operation has completed successfully. For example, a successful response\n * from a server could have been delayed long enough for the deadline to\n * expire.\n */\n DEADLINE_EXCEEDED: 'deadline-exceeded' as FirestoreErrorCode,\n\n /** Some requested entity (e.g., file or directory) was not found. */\n NOT_FOUND: 'not-found' as FirestoreErrorCode,\n\n /**\n * Some entity that we attempted to create (e.g., file or directory) already\n * exists.\n */\n ALREADY_EXISTS: 'already-exists' as FirestoreErrorCode,\n\n /**\n * The caller does not have permission to execute the specified operation.\n * PERMISSION_DENIED must not be used for rejections caused by exhausting\n * some resource (use RESOURCE_EXHAUSTED instead for those errors).\n * PERMISSION_DENIED must not be used if the caller cannot be identified\n * (use UNAUTHENTICATED instead for those errors).\n */\n PERMISSION_DENIED: 'permission-denied' as FirestoreErrorCode,\n\n /**\n * The request does not have valid authentication credentials for the\n * operation.\n */\n UNAUTHENTICATED: 'unauthenticated' as FirestoreErrorCode,\n\n /**\n * Some resource has been exhausted, perhaps a per-user quota, or perhaps the\n * entire file system is out of space.\n */\n RESOURCE_EXHAUSTED: 'resource-exhausted' as FirestoreErrorCode,\n\n /**\n * Operation was rejected because the system is not in a state required for\n * the operation's execution. For example, directory to be deleted may be\n * non-empty, an rmdir operation is applied to a non-directory, etc.\n *\n * A litmus test that may help a service implementor in deciding\n * between FAILED_PRECONDITION, ABORTED, and UNAVAILABLE:\n * (a) Use UNAVAILABLE if the client can retry just the failing call.\n * (b) Use ABORTED if the client should retry at a higher-level\n * (e.g., restarting a read-modify-write sequence).\n * (c) Use FAILED_PRECONDITION if the client should not retry until\n * the system state has been explicitly fixed. E.g., if an \"rmdir\"\n * fails because the directory is non-empty, FAILED_PRECONDITION\n * should be returned since the client should not retry unless\n * they have first fixed up the directory by deleting files from it.\n * (d) Use FAILED_PRECONDITION if the client performs conditional\n * REST Get/Update/Delete on a resource and the resource on the\n * server does not match the condition. E.g., conflicting\n * read-modify-write on the same resource.\n */\n FAILED_PRECONDITION: 'failed-precondition' as FirestoreErrorCode,\n\n /**\n * The operation was aborted, typically due to a concurrency issue like\n * sequencer check failures, transaction aborts, etc.\n *\n * See litmus test above for deciding between FAILED_PRECONDITION, ABORTED,\n * and UNAVAILABLE.\n */\n ABORTED: 'aborted' as FirestoreErrorCode,\n\n /**\n * Operation was attempted past the valid range. E.g., seeking or reading\n * past end of file.\n *\n * Unlike INVALID_ARGUMENT, this error indicates a problem that may be fixed\n * if the system state changes. For example, a 32-bit file system will\n * generate INVALID_ARGUMENT if asked to read at an offset that is not in the\n * range [0,2^32-1], but it will generate OUT_OF_RANGE if asked to read from\n * an offset past the current file size.\n *\n * There is a fair bit of overlap between FAILED_PRECONDITION and\n * OUT_OF_RANGE. We recommend using OUT_OF_RANGE (the more specific error)\n * when it applies so that callers who are iterating through a space can\n * easily look for an OUT_OF_RANGE error to detect when they are done.\n */\n OUT_OF_RANGE: 'out-of-range' as FirestoreErrorCode,\n\n /** Operation is not implemented or not supported/enabled in this service. */\n UNIMPLEMENTED: 'unimplemented' as FirestoreErrorCode,\n\n /**\n * Internal errors. Means some invariants expected by underlying System has\n * been broken. If you see one of these errors, Something is very broken.\n */\n INTERNAL: 'internal' as FirestoreErrorCode,\n\n /**\n * The service is currently unavailable. This is a most likely a transient\n * condition and may be corrected by retrying with a backoff.\n *\n * See litmus test above for deciding between FAILED_PRECONDITION, ABORTED,\n * and UNAVAILABLE.\n */\n UNAVAILABLE: 'unavailable' as FirestoreErrorCode,\n\n /** Unrecoverable data loss or corruption. */\n DATA_LOSS: 'data-loss' as FirestoreErrorCode\n};\n\n/** An error returned by a Firestore operation. */\nexport class FirestoreError extends FirebaseError {\n /** The stack of the error. */\n readonly stack?: string;\n\n /** @hideconstructor */\n constructor(\n /**\n * The backend error code associated with this error.\n */\n readonly code: FirestoreErrorCode,\n /**\n * A custom error description.\n */\n readonly message: string\n ) {\n super(code, message);\n\n // HACK: We write a toString property directly because Error is not a real\n // class and so inheritance does not work correctly. We could alternatively\n // do the same \"back-door inheritance\" trick that FirebaseError does.\n this.toString = () => `${this.name}: [code=${this.code}]: ${this.message}`;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport interface Resolver {\n (value: R | Promise): void;\n}\n\nexport interface Rejecter {\n (reason?: Error): void;\n}\n\nexport class Deferred {\n promise: Promise;\n // Assigned synchronously in constructor by Promise constructor callback.\n resolve!: Resolver;\n reject!: Rejecter;\n\n constructor() {\n this.promise = new Promise((resolve: Resolver, reject: Rejecter) => {\n this.resolve = resolve;\n this.reject = reject;\n });\n }\n}\n\n/**\n * Takes an array of values and a function from a value to a Promise. The function is run on each\n * value sequentially, waiting for the previous promise to resolve before starting the next one.\n * The returned promise resolves once the function has been run on all values.\n */\nexport function sequence(\n values: T[],\n fn: (value: T) => Promise\n): Promise {\n let p = Promise.resolve();\n for (const value of values) {\n p = p.then(() => fn(value));\n }\n return p;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseApp, _isFirebaseServerApp } from '@firebase/app';\nimport {\n AppCheckInternalComponentName,\n AppCheckTokenListener,\n AppCheckTokenResult,\n FirebaseAppCheckInternal\n} from '@firebase/app-check-interop-types';\nimport {\n FirebaseAuthInternal,\n FirebaseAuthInternalName\n} from '@firebase/auth-interop-types';\nimport { Provider } from '@firebase/component';\n\nimport { User } from '../auth/user';\nimport { debugAssert, hardAssert } from '../util/assert';\nimport { AsyncQueue } from '../util/async_queue';\nimport { Code, FirestoreError } from '../util/error';\nimport { logDebug } from '../util/log';\nimport { Deferred } from '../util/promise';\n\n// TODO(mikelehen): This should be split into multiple files and probably\n// moved to an auth/ folder to match other platforms.\n\n/**\n * @internal\n */\nexport type AuthTokenFactory = () => string;\n\n/**\n * @internal\n */\nexport interface FirstPartyCredentialsSettings {\n // These are external types. Prevent minification.\n ['type']: 'firstParty';\n ['sessionIndex']: string;\n ['iamToken']: string | null;\n ['authTokenFactory']: AuthTokenFactory | null;\n}\n\nexport interface ProviderCredentialsSettings {\n // These are external types. Prevent minification.\n ['type']: 'provider';\n ['client']: CredentialsProvider;\n}\n\n/** Settings for private credentials */\nexport type CredentialsSettings =\n | FirstPartyCredentialsSettings\n | ProviderCredentialsSettings;\n\nexport type TokenType = 'OAuth' | 'FirstParty' | 'AppCheck';\nexport interface Token {\n /** Type of token. */\n type: TokenType;\n\n /**\n * The user with which the token is associated (used for persisting user\n * state on disk, etc.).\n * This will be null for Tokens of the type 'AppCheck'.\n */\n user?: User;\n\n /** Header values to set for this token */\n headers: Map;\n}\n\nexport class OAuthToken implements Token {\n type = 'OAuth' as TokenType;\n headers = new Map();\n\n constructor(value: string, public user: User) {\n this.headers.set('Authorization', `Bearer ${value}`);\n }\n}\n\n/**\n * A Listener for credential change events. The listener should fetch a new\n * token and may need to invalidate other state if the current user has also\n * changed.\n */\nexport type CredentialChangeListener = (credential: T) => Promise;\n\n/**\n * Provides methods for getting the uid and token for the current user and\n * listening for changes.\n */\nexport interface CredentialsProvider {\n /**\n * Starts the credentials provider and specifies a listener to be notified of\n * credential changes (sign-in / sign-out, token changes). It is immediately\n * called once with the initial user.\n *\n * The change listener is invoked on the provided AsyncQueue.\n */\n start(\n asyncQueue: AsyncQueue,\n changeListener: CredentialChangeListener\n ): void;\n\n /** Requests a token for the current user. */\n getToken(): Promise;\n\n /**\n * Marks the last retrieved token as invalid, making the next GetToken request\n * force-refresh the token.\n */\n invalidateToken(): void;\n\n shutdown(): void;\n}\n\n/**\n * A CredentialsProvider that always yields an empty token.\n * @internal\n */\nexport class EmptyAuthCredentialsProvider implements CredentialsProvider {\n getToken(): Promise {\n return Promise.resolve(null);\n }\n\n invalidateToken(): void {}\n\n start(\n asyncQueue: AsyncQueue,\n changeListener: CredentialChangeListener\n ): void {\n // Fire with initial user.\n asyncQueue.enqueueRetryable(() => changeListener(User.UNAUTHENTICATED));\n }\n\n shutdown(): void {}\n}\n\n/**\n * A CredentialsProvider that always returns a constant token. Used for\n * emulator token mocking.\n */\nexport class EmulatorAuthCredentialsProvider\n implements CredentialsProvider\n{\n constructor(private token: Token) {}\n\n /**\n * Stores the listener registered with setChangeListener()\n * This isn't actually necessary since the UID never changes, but we use this\n * to verify the listen contract is adhered to in tests.\n */\n private changeListener: CredentialChangeListener | null = null;\n\n getToken(): Promise {\n return Promise.resolve(this.token);\n }\n\n invalidateToken(): void {}\n\n start(\n asyncQueue: AsyncQueue,\n changeListener: CredentialChangeListener\n ): void {\n debugAssert(\n !this.changeListener,\n 'Can only call setChangeListener() once.'\n );\n this.changeListener = changeListener;\n // Fire with initial user.\n asyncQueue.enqueueRetryable(() => changeListener(this.token.user!));\n }\n\n shutdown(): void {\n this.changeListener = null;\n }\n}\n\n/** Credential provider for the Lite SDK. */\nexport class LiteAuthCredentialsProvider implements CredentialsProvider {\n private auth: FirebaseAuthInternal | null = null;\n\n constructor(authProvider: Provider) {\n authProvider.onInit(auth => {\n this.auth = auth;\n });\n }\n\n getToken(): Promise {\n if (!this.auth) {\n return Promise.resolve(null);\n }\n\n return this.auth.getToken().then(tokenData => {\n if (tokenData) {\n hardAssert(\n typeof tokenData.accessToken === 'string',\n 0xa539,\n 'Invalid tokenData returned from getToken()',\n { tokenData }\n );\n return new OAuthToken(\n tokenData.accessToken,\n new User(this.auth!.getUid())\n );\n } else {\n return null;\n }\n });\n }\n\n invalidateToken(): void {}\n\n start(\n asyncQueue: AsyncQueue,\n changeListener: CredentialChangeListener\n ): void {}\n\n shutdown(): void {}\n}\n\nexport class FirebaseAuthCredentialsProvider\n implements CredentialsProvider\n{\n /**\n * The auth token listener registered with FirebaseApp, retained here so we\n * can unregister it.\n */\n private tokenListener: (() => void) | undefined;\n\n /** Tracks the current User. */\n private currentUser: User = User.UNAUTHENTICATED;\n\n /**\n * Counter used to detect if the token changed while a getToken request was\n * outstanding.\n */\n private tokenCounter = 0;\n\n private forceRefresh = false;\n\n private auth: FirebaseAuthInternal | null = null;\n\n constructor(private authProvider: Provider) {}\n\n start(\n asyncQueue: AsyncQueue,\n changeListener: CredentialChangeListener\n ): void {\n hardAssert(\n this.tokenListener === undefined,\n 0xa540,\n 'Token listener already added'\n );\n let lastTokenId = this.tokenCounter;\n\n // A change listener that prevents double-firing for the same token change.\n const guardedChangeListener: (user: User) => Promise = user => {\n if (this.tokenCounter !== lastTokenId) {\n lastTokenId = this.tokenCounter;\n return changeListener(user);\n } else {\n return Promise.resolve();\n }\n };\n\n // A promise that can be waited on to block on the next token change.\n // This promise is re-created after each change.\n let nextToken = new Deferred();\n\n this.tokenListener = () => {\n this.tokenCounter++;\n this.currentUser = this.getUser();\n nextToken.resolve();\n nextToken = new Deferred();\n asyncQueue.enqueueRetryable(() =>\n guardedChangeListener(this.currentUser)\n );\n };\n\n const awaitNextToken: () => void = () => {\n const currentTokenAttempt = nextToken;\n asyncQueue.enqueueRetryable(async () => {\n await currentTokenAttempt.promise;\n await guardedChangeListener(this.currentUser);\n });\n };\n\n const registerAuth = (auth: FirebaseAuthInternal): void => {\n logDebug('FirebaseAuthCredentialsProvider', 'Auth detected');\n this.auth = auth;\n if (this.tokenListener) {\n this.auth.addAuthTokenListener(this.tokenListener);\n awaitNextToken();\n }\n };\n\n this.authProvider.onInit(auth => registerAuth(auth));\n\n // Our users can initialize Auth right after Firestore, so we give it\n // a chance to register itself with the component framework before we\n // determine whether to start up in unauthenticated mode.\n setTimeout(() => {\n if (!this.auth) {\n const auth = this.authProvider.getImmediate({ optional: true });\n if (auth) {\n registerAuth(auth);\n } else {\n // If auth is still not available, proceed with `null` user\n logDebug('FirebaseAuthCredentialsProvider', 'Auth not yet detected');\n nextToken.resolve();\n nextToken = new Deferred();\n }\n }\n }, 0);\n\n awaitNextToken();\n }\n\n getToken(): Promise {\n debugAssert(\n this.tokenListener != null,\n 'FirebaseAuthCredentialsProvider not started.'\n );\n\n // Take note of the current value of the tokenCounter so that this method\n // can fail (with an ABORTED error) if there is a token change while the\n // request is outstanding.\n const initialTokenCounter = this.tokenCounter;\n const forceRefresh = this.forceRefresh;\n this.forceRefresh = false;\n\n if (!this.auth) {\n return Promise.resolve(null);\n }\n\n return this.auth.getToken(forceRefresh).then(tokenData => {\n // Cancel the request since the token changed while the request was\n // outstanding so the response is potentially for a previous user (which\n // user, we can't be sure).\n if (this.tokenCounter !== initialTokenCounter) {\n logDebug(\n 'FirebaseAuthCredentialsProvider',\n 'getToken aborted due to token change.'\n );\n return this.getToken();\n } else {\n if (tokenData) {\n hardAssert(\n typeof tokenData.accessToken === 'string',\n 0x7c5d,\n 'Invalid tokenData returned from getToken()',\n { tokenData }\n );\n return new OAuthToken(tokenData.accessToken, this.currentUser);\n } else {\n return null;\n }\n }\n });\n }\n\n invalidateToken(): void {\n this.forceRefresh = true;\n }\n\n shutdown(): void {\n if (this.auth && this.tokenListener) {\n this.auth.removeAuthTokenListener(this.tokenListener);\n }\n this.tokenListener = undefined;\n }\n\n // Auth.getUid() can return null even with a user logged in. It is because\n // getUid() is synchronous, but the auth code populating Uid is asynchronous.\n // This method should only be called in the AuthTokenListener callback\n // to guarantee to get the actual user.\n private getUser(): User {\n const currentUid = this.auth && this.auth.getUid();\n hardAssert(\n currentUid === null || typeof currentUid === 'string',\n 0x0807,\n 'Received invalid UID',\n { currentUid }\n );\n return new User(currentUid);\n }\n}\n\n/*\n * FirstPartyToken provides a fresh token each time its value\n * is requested, because if the token is too old, requests will be rejected.\n * Technically this may no longer be necessary since the SDK should gracefully\n * recover from unauthenticated errors (see b/33147818 for context), but it's\n * safer to keep the implementation as-is.\n */\nexport class FirstPartyToken implements Token {\n type = 'FirstParty' as TokenType;\n user = User.FIRST_PARTY;\n private _headers = new Map();\n\n constructor(\n private readonly sessionIndex: string,\n private readonly iamToken: string | null,\n private readonly authTokenFactory: AuthTokenFactory | null\n ) {}\n\n /**\n * Gets an authorization token, using a provided factory function, or return\n * null.\n */\n private getAuthToken(): string | null {\n if (this.authTokenFactory) {\n return this.authTokenFactory();\n } else {\n return null;\n }\n }\n\n get headers(): Map {\n this._headers.set('X-Goog-AuthUser', this.sessionIndex);\n // Use array notation to prevent minification\n const authHeaderTokenValue = this.getAuthToken();\n if (authHeaderTokenValue) {\n this._headers.set('Authorization', authHeaderTokenValue);\n }\n if (this.iamToken) {\n this._headers.set('X-Goog-Iam-Authorization-Token', this.iamToken);\n }\n\n return this._headers;\n }\n}\n\n/*\n * Provides user credentials required for the Firestore JavaScript SDK\n * to authenticate the user, using technique that is only available\n * to applications hosted by Google.\n */\nexport class FirstPartyAuthCredentialsProvider\n implements CredentialsProvider\n{\n constructor(\n private sessionIndex: string,\n private iamToken: string | null,\n private authTokenFactory: AuthTokenFactory | null\n ) {}\n\n getToken(): Promise {\n return Promise.resolve(\n new FirstPartyToken(\n this.sessionIndex,\n this.iamToken,\n this.authTokenFactory\n )\n );\n }\n\n start(\n asyncQueue: AsyncQueue,\n changeListener: CredentialChangeListener\n ): void {\n // Fire with initial uid.\n asyncQueue.enqueueRetryable(() => changeListener(User.FIRST_PARTY));\n }\n\n shutdown(): void {}\n\n invalidateToken(): void {}\n}\n\nexport class AppCheckToken implements Token {\n type = 'AppCheck' as TokenType;\n headers = new Map();\n\n constructor(private value: string) {\n if (value && value.length > 0) {\n this.headers.set('x-firebase-appcheck', this.value);\n }\n }\n}\n\nexport class FirebaseAppCheckTokenProvider\n implements CredentialsProvider\n{\n /**\n * The AppCheck token listener registered with FirebaseApp, retained here so\n * we can unregister it.\n */\n private tokenListener: AppCheckTokenListener | undefined;\n private forceRefresh = false;\n private appCheck: FirebaseAppCheckInternal | null = null;\n private latestAppCheckToken: string | null = null;\n private serverAppAppCheckToken: string | null = null;\n\n constructor(\n app: FirebaseApp,\n private appCheckProvider: Provider\n ) {\n if (_isFirebaseServerApp(app) && app.settings.appCheckToken) {\n this.serverAppAppCheckToken = app.settings.appCheckToken;\n }\n }\n\n start(\n asyncQueue: AsyncQueue,\n changeListener: CredentialChangeListener\n ): void {\n hardAssert(\n this.tokenListener === undefined,\n 0x0db8,\n 'Token listener already added'\n );\n\n const onTokenChanged: (\n tokenResult: AppCheckTokenResult\n ) => Promise = tokenResult => {\n if (tokenResult.error != null) {\n logDebug(\n 'FirebaseAppCheckTokenProvider',\n `Error getting App Check token; using placeholder token instead. Error: ${tokenResult.error.message}`\n );\n }\n const tokenUpdated = tokenResult.token !== this.latestAppCheckToken;\n this.latestAppCheckToken = tokenResult.token;\n logDebug(\n 'FirebaseAppCheckTokenProvider',\n `Received ${tokenUpdated ? 'new' : 'existing'} token.`\n );\n return tokenUpdated\n ? changeListener(tokenResult.token)\n : Promise.resolve();\n };\n\n this.tokenListener = (tokenResult: AppCheckTokenResult) => {\n asyncQueue.enqueueRetryable(() => onTokenChanged(tokenResult));\n };\n\n const registerAppCheck = (appCheck: FirebaseAppCheckInternal): void => {\n logDebug('FirebaseAppCheckTokenProvider', 'AppCheck detected');\n this.appCheck = appCheck;\n if (this.tokenListener) {\n this.appCheck.addTokenListener(this.tokenListener);\n }\n };\n\n this.appCheckProvider.onInit(appCheck => registerAppCheck(appCheck));\n\n // Our users can initialize AppCheck after Firestore, so we give it\n // a chance to register itself with the component framework.\n setTimeout(() => {\n if (!this.appCheck) {\n const appCheck = this.appCheckProvider.getImmediate({ optional: true });\n if (appCheck) {\n registerAppCheck(appCheck);\n } else {\n // If AppCheck is still not available, proceed without it.\n logDebug(\n 'FirebaseAppCheckTokenProvider',\n 'AppCheck not yet detected'\n );\n }\n }\n }, 0);\n }\n\n getToken(): Promise {\n if (this.serverAppAppCheckToken) {\n return Promise.resolve(new AppCheckToken(this.serverAppAppCheckToken));\n }\n debugAssert(\n this.tokenListener != null,\n 'FirebaseAppCheckTokenProvider not started.'\n );\n\n const forceRefresh = this.forceRefresh;\n this.forceRefresh = false;\n\n if (!this.appCheck) {\n return Promise.resolve(null);\n }\n\n return this.appCheck.getToken(forceRefresh).then(tokenResult => {\n if (tokenResult) {\n hardAssert(\n typeof tokenResult.token === 'string',\n 0xae0e,\n 'Invalid tokenResult returned from getToken()',\n { tokenResult }\n );\n this.latestAppCheckToken = tokenResult.token;\n return new AppCheckToken(tokenResult.token);\n } else {\n return null;\n }\n });\n }\n\n invalidateToken(): void {\n this.forceRefresh = true;\n }\n\n shutdown(): void {\n if (this.appCheck && this.tokenListener) {\n this.appCheck.removeTokenListener(this.tokenListener);\n }\n this.tokenListener = undefined;\n }\n}\n\n/**\n * An AppCheck token provider that always yields an empty token.\n * @internal\n */\nexport class EmptyAppCheckTokenProvider implements CredentialsProvider {\n getToken(): Promise {\n return Promise.resolve(new AppCheckToken(''));\n }\n\n invalidateToken(): void {}\n\n start(\n asyncQueue: AsyncQueue,\n changeListener: CredentialChangeListener\n ): void {}\n\n shutdown(): void {}\n}\n\n/** AppCheck token provider for the Lite SDK. */\nexport class LiteAppCheckTokenProvider implements CredentialsProvider {\n private appCheck: FirebaseAppCheckInternal | null = null;\n private serverAppAppCheckToken: string | null = null;\n\n constructor(\n app: FirebaseApp,\n private appCheckProvider: Provider\n ) {\n if (_isFirebaseServerApp(app) && app.settings.appCheckToken) {\n this.serverAppAppCheckToken = app.settings.appCheckToken;\n }\n appCheckProvider.onInit(appCheck => {\n this.appCheck = appCheck;\n });\n }\n\n getToken(): Promise {\n if (this.serverAppAppCheckToken) {\n return Promise.resolve(new AppCheckToken(this.serverAppAppCheckToken));\n }\n\n if (!this.appCheck) {\n return Promise.resolve(null);\n }\n\n return this.appCheck.getToken().then(tokenResult => {\n if (tokenResult) {\n hardAssert(\n typeof tokenResult.token === 'string',\n 0x0d8e,\n 'Invalid tokenResult returned from getToken()',\n { tokenResult }\n );\n return new AppCheckToken(tokenResult.token);\n } else {\n return null;\n }\n });\n }\n\n invalidateToken(): void {}\n\n start(\n asyncQueue: AsyncQueue,\n changeListener: CredentialChangeListener\n ): void {}\n\n shutdown(): void {}\n}\n\n/**\n * Builds a CredentialsProvider depending on the type of\n * the credentials passed in.\n */\nexport function makeAuthCredentialsProvider(\n credentials?: CredentialsSettings\n): CredentialsProvider {\n if (!credentials) {\n return new EmptyAuthCredentialsProvider();\n }\n switch (credentials['type']) {\n case 'firstParty':\n return new FirstPartyAuthCredentialsProvider(\n credentials['sessionIndex'] || '0',\n credentials['iamToken'] || null,\n credentials['authTokenFactory'] || null\n );\n\n case 'provider':\n return credentials['client'];\n\n default:\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'makeAuthCredentialsProvider failed due to invalid credential type'\n );\n }\n}\n","import { FirebaseApp } from '@firebase/app';\n\nimport { ExperimentalLongPollingOptions } from '../api/long_polling_options';\nimport { Code, FirestoreError } from '../util/error';\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport class DatabaseInfo {\n /**\n * Constructs a DatabaseInfo using the provided host, databaseId and\n * persistenceKey.\n *\n * @param databaseId - The database to use.\n * @param appId - The Firebase App Id.\n * @param persistenceKey - A unique identifier for this Firestore's local\n * storage (used in conjunction with the databaseId).\n * @param host - The Firestore backend host to connect to.\n * @param ssl - Whether to use SSL when connecting.\n * @param forceLongPolling - Whether to use the forceLongPolling option\n * when using WebChannel as the network transport.\n * @param autoDetectLongPolling - Whether to use the detectBufferingProxy\n * option when using WebChannel as the network transport.\n * @param longPollingOptions Options that configure long-polling.\n * @param useFetchStreams Whether to use the Fetch API instead of\n * XMLHTTPRequest\n */\n constructor(\n readonly databaseId: DatabaseId,\n readonly appId: string,\n readonly persistenceKey: string,\n readonly host: string,\n readonly ssl: boolean,\n readonly forceLongPolling: boolean,\n readonly autoDetectLongPolling: boolean,\n readonly longPollingOptions: ExperimentalLongPollingOptions,\n readonly useFetchStreams: boolean,\n readonly isUsingEmulator: boolean\n ) {}\n}\n\n/** The default database name for a project. */\nexport const DEFAULT_DATABASE_NAME = '(default)';\n\n/**\n * Represents the database ID a Firestore client is associated with.\n * @internal\n */\nexport class DatabaseId {\n readonly database: string;\n constructor(readonly projectId: string, database?: string) {\n this.database = database ? database : DEFAULT_DATABASE_NAME;\n }\n\n static empty(): DatabaseId {\n return new DatabaseId('', '');\n }\n\n get isDefaultDatabase(): boolean {\n return this.database === DEFAULT_DATABASE_NAME;\n }\n\n isEqual(other: {}): boolean {\n return (\n other instanceof DatabaseId &&\n other.projectId === this.projectId &&\n other.database === this.database\n );\n }\n}\n\nexport function databaseIdFromApp(\n app: FirebaseApp,\n database?: string\n): DatabaseId {\n if (!Object.prototype.hasOwnProperty.apply(app.options, ['projectId'])) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n '\"projectId\" not provided in firebase.initializeApp.'\n );\n }\n\n return new DatabaseId(app.options.projectId!, database);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { debugAssert } from '../../util/assert';\n\n/**\n * Generates `nBytes` of random bytes.\n *\n * If `nBytes < 0` , an error will be thrown.\n */\nexport function randomBytes(nBytes: number): Uint8Array {\n debugAssert(nBytes >= 0, `Expecting non-negative nBytes, got: ${nBytes}`);\n\n // Polyfills for IE and WebWorker by using `self` and `msCrypto` when `crypto` is not available.\n const crypto =\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n typeof self !== 'undefined' && (self.crypto || (self as any)['msCrypto']);\n const bytes = new Uint8Array(nBytes);\n if (crypto && typeof crypto.getRandomValues === 'function') {\n crypto.getRandomValues(bytes);\n } else {\n // Falls back to Math.random\n for (let i = 0; i < nBytes; i++) {\n bytes[i] = Math.floor(Math.random() * 256);\n }\n }\n return bytes;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { randomBytes } from '../platform/random_bytes';\n\nimport { debugAssert } from './assert';\n\nexport type EventHandler = (value: E) => void;\nexport interface Indexable {\n [k: string]: unknown;\n}\n\n/**\n * A utility class for generating unique alphanumeric IDs of a specified length.\n *\n * @internal\n * Exported internally for testing purposes.\n */\nexport class AutoId {\n static newId(): string {\n // Alphanumeric characters\n const chars =\n 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';\n // The largest byte value that is a multiple of `char.length`.\n const maxMultiple = Math.floor(256 / chars.length) * chars.length;\n debugAssert(\n 0 < maxMultiple && maxMultiple < 256,\n `Expect maxMultiple to be (0, 256), but got ${maxMultiple}`\n );\n\n let autoId = '';\n const targetLength = 20;\n while (autoId.length < targetLength) {\n const bytes = randomBytes(40);\n for (let i = 0; i < bytes.length; ++i) {\n // Only accept values that are [0, maxMultiple), this ensures they can\n // be evenly mapped to indices of `chars` via a modulo operation.\n if (autoId.length < targetLength && bytes[i] < maxMultiple) {\n autoId += chars.charAt(bytes[i] % chars.length);\n }\n }\n }\n debugAssert(autoId.length === targetLength, 'Invalid auto ID: ' + autoId);\n\n return autoId;\n }\n}\n\nexport function primitiveComparator(left: T, right: T): number {\n if (left < right) {\n return -1;\n }\n if (left > right) {\n return 1;\n }\n return 0;\n}\n\nexport interface Equatable {\n isEqual(other: T): boolean;\n}\n\n/** Compare strings in UTF-8 encoded byte order */\nexport function compareUtf8Strings(left: string, right: string): number {\n // Find the first differing character (a.k.a. \"UTF-16 code unit\") in the two strings and,\n // if found, use that character to determine the relative ordering of the two strings as a\n // whole. Comparing UTF-16 strings in UTF-8 byte order can be done simply and efficiently by\n // comparing the UTF-16 code units (chars). This serendipitously works because of the way UTF-8\n // and UTF-16 happen to represent Unicode code points.\n //\n // After finding the first pair of differing characters, there are two cases:\n //\n // Case 1: Both characters are non-surrogates (code points less than or equal to 0xFFFF) or\n // both are surrogates from a surrogate pair (that collectively represent code points greater\n // than 0xFFFF). In this case their numeric order as UTF-16 code units is the same as the\n // lexicographical order of their corresponding UTF-8 byte sequences. A direct comparison is\n // sufficient.\n //\n // Case 2: One character is a surrogate and the other is not. In this case the surrogate-\n // containing string is always ordered after the non-surrogate. This is because surrogates are\n // used to represent code points greater than 0xFFFF which have 4-byte UTF-8 representations\n // and are lexicographically greater than the 1, 2, or 3-byte representations of code points\n // less than or equal to 0xFFFF.\n //\n // An example of why Case 2 is required is comparing the following two Unicode code points:\n //\n // |-----------------------|------------|---------------------|-----------------|\n // | Name | Code Point | UTF-8 Encoding | UTF-16 Encoding |\n // |-----------------------|------------|---------------------|-----------------|\n // | Replacement Character | U+FFFD | 0xEF 0xBF 0xBD | 0xFFFD |\n // | Grinning Face | U+1F600 | 0xF0 0x9F 0x98 0x80 | 0xD83D 0xDE00 |\n // |-----------------------|------------|---------------------|-----------------|\n //\n // A lexicographical comparison of the UTF-8 encodings of these code points would order\n // \"Replacement Character\" _before_ \"Grinning Face\" because 0xEF is less than 0xF0. However, a\n // direct comparison of the UTF-16 code units, as would be done in case 1, would erroneously\n // produce the _opposite_ ordering, because 0xFFFD is _greater than_ 0xD83D. As it turns out,\n // this relative ordering holds for all comparisons of UTF-16 code points requiring a surrogate\n // pair with those that do not.\n const length = Math.min(left.length, right.length);\n for (let i = 0; i < length; i++) {\n const leftChar = left.charAt(i);\n const rightChar = right.charAt(i);\n if (leftChar !== rightChar) {\n return isSurrogate(leftChar) === isSurrogate(rightChar)\n ? primitiveComparator(leftChar, rightChar)\n : isSurrogate(leftChar)\n ? 1\n : -1;\n }\n }\n\n // Use the lengths of the strings to determine the overall comparison result since either the\n // strings were equal or one is a prefix of the other.\n return primitiveComparator(left.length, right.length);\n}\n\nconst MIN_SURROGATE = 0xd800;\nconst MAX_SURROGATE = 0xdfff;\n\nexport function isSurrogate(s: string): boolean {\n debugAssert(s.length === 1, `s.length == ${s.length}, but expected 1`);\n const c = s.charCodeAt(0);\n return c >= MIN_SURROGATE && c <= MAX_SURROGATE;\n}\n\nexport interface Iterable {\n forEach: (cb: (v: V) => void) => void;\n}\n\n/** Helper to compare arrays using isEqual(). */\nexport function arrayEquals(\n left: T[],\n right: T[],\n comparator: (l: T, r: T) => boolean\n): boolean {\n if (left.length !== right.length) {\n return false;\n }\n return left.every((value, index) => comparator(value, right[index]));\n}\n/**\n * Returns the immediate lexicographically-following string. This is useful to\n * construct an inclusive range for indexeddb iterators.\n */\nexport function immediateSuccessor(s: string): string {\n // Return the input string, with an additional NUL byte appended.\n return s + '\\0';\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Integer } from '@firebase/webchannel-wrapper/bloom-blob';\n\nimport { debugAssert, fail } from '../util/assert';\nimport { Code, FirestoreError } from '../util/error';\nimport { compareUtf8Strings, primitiveComparator } from '../util/misc';\n\nexport const DOCUMENT_KEY_NAME = '__name__';\n\n/**\n * Path represents an ordered sequence of string segments.\n */\nabstract class BasePath> {\n private segments: string[];\n private offset: number;\n private len: number;\n\n constructor(segments: string[], offset?: number, length?: number) {\n if (offset === undefined) {\n offset = 0;\n } else if (offset > segments.length) {\n fail(0x027d, 'offset out of range', {\n offset,\n range: segments.length\n });\n }\n\n if (length === undefined) {\n length = segments.length - offset;\n } else if (length > segments.length - offset) {\n fail(0x06d2, 'length out of range', {\n length,\n range: segments.length - offset\n });\n }\n this.segments = segments;\n this.offset = offset;\n this.len = length;\n }\n\n /**\n * Abstract constructor method to construct an instance of B with the given\n * parameters.\n */\n protected abstract construct(\n segments: string[],\n offset?: number,\n length?: number\n ): B;\n\n /**\n * Returns a String representation.\n *\n * Implementing classes are required to provide deterministic implementations as\n * the String representation is used to obtain canonical Query IDs.\n */\n abstract toString(): string;\n\n get length(): number {\n return this.len;\n }\n\n isEqual(other: B): boolean {\n return BasePath.comparator(this, other) === 0;\n }\n\n child(nameOrPath: string | B): B {\n const segments = this.segments.slice(this.offset, this.limit());\n if (nameOrPath instanceof BasePath) {\n nameOrPath.forEach(segment => {\n segments.push(segment);\n });\n } else {\n segments.push(nameOrPath);\n }\n return this.construct(segments);\n }\n\n /** The index of one past the last segment of the path. */\n private limit(): number {\n return this.offset + this.length;\n }\n\n popFirst(size?: number): B {\n size = size === undefined ? 1 : size;\n debugAssert(\n this.length >= size,\n \"Can't call popFirst() with less segments\"\n );\n return this.construct(\n this.segments,\n this.offset + size,\n this.length - size\n );\n }\n\n popLast(): B {\n debugAssert(!this.isEmpty(), \"Can't call popLast() on empty path\");\n return this.construct(this.segments, this.offset, this.length - 1);\n }\n\n firstSegment(): string {\n debugAssert(!this.isEmpty(), \"Can't call firstSegment() on empty path\");\n return this.segments[this.offset];\n }\n\n lastSegment(): string {\n debugAssert(!this.isEmpty(), \"Can't call lastSegment() on empty path\");\n return this.get(this.length - 1);\n }\n\n get(index: number): string {\n debugAssert(index < this.length, 'Index out of range');\n return this.segments[this.offset + index];\n }\n\n isEmpty(): boolean {\n return this.length === 0;\n }\n\n isPrefixOf(other: this): boolean {\n if (other.length < this.length) {\n return false;\n }\n\n for (let i = 0; i < this.length; i++) {\n if (this.get(i) !== other.get(i)) {\n return false;\n }\n }\n\n return true;\n }\n\n isImmediateParentOf(potentialChild: this): boolean {\n if (this.length + 1 !== potentialChild.length) {\n return false;\n }\n\n for (let i = 0; i < this.length; i++) {\n if (this.get(i) !== potentialChild.get(i)) {\n return false;\n }\n }\n\n return true;\n }\n\n forEach(fn: (segment: string) => void): void {\n for (let i = this.offset, end = this.limit(); i < end; i++) {\n fn(this.segments[i]);\n }\n }\n\n toArray(): string[] {\n return this.segments.slice(this.offset, this.limit());\n }\n\n /**\n * Compare 2 paths segment by segment, prioritizing numeric IDs\n * (e.g., \"__id123__\") in numeric ascending order, followed by string\n * segments in lexicographical order.\n */\n static comparator>(\n p1: BasePath,\n p2: BasePath\n ): number {\n const len = Math.min(p1.length, p2.length);\n for (let i = 0; i < len; i++) {\n const comparison = BasePath.compareSegments(p1.get(i), p2.get(i));\n if (comparison !== 0) {\n return comparison;\n }\n }\n return primitiveComparator(p1.length, p2.length);\n }\n\n private static compareSegments(lhs: string, rhs: string): number {\n const isLhsNumeric = BasePath.isNumericId(lhs);\n const isRhsNumeric = BasePath.isNumericId(rhs);\n\n if (isLhsNumeric && !isRhsNumeric) {\n // Only lhs is numeric\n return -1;\n } else if (!isLhsNumeric && isRhsNumeric) {\n // Only rhs is numeric\n return 1;\n } else if (isLhsNumeric && isRhsNumeric) {\n // both numeric\n return BasePath.extractNumericId(lhs).compare(\n BasePath.extractNumericId(rhs)\n );\n } else {\n // both non-numeric\n return compareUtf8Strings(lhs, rhs);\n }\n }\n\n // Checks if a segment is a numeric ID (starts with \"__id\" and ends with \"__\").\n private static isNumericId(segment: string): boolean {\n return segment.startsWith('__id') && segment.endsWith('__');\n }\n\n private static extractNumericId(segment: string): Integer {\n return Integer.fromString(segment.substring(4, segment.length - 2));\n }\n}\n\n/**\n * A slash-separated path for navigating resources (documents and collections)\n * within Firestore.\n *\n * @internal\n */\nexport class ResourcePath extends BasePath {\n protected construct(\n segments: string[],\n offset?: number,\n length?: number\n ): ResourcePath {\n return new ResourcePath(segments, offset, length);\n }\n\n canonicalString(): string {\n // NOTE: The client is ignorant of any path segments containing escape\n // sequences (e.g. __id123__) and just passes them through raw (they exist\n // for legacy reasons and should not be used frequently).\n\n return this.toArray().join('/');\n }\n\n toString(): string {\n return this.canonicalString();\n }\n\n /**\n * Returns a string representation of this path\n * where each path segment has been encoded with\n * `encodeURIComponent`.\n */\n toUriEncodedString(): string {\n return this.toArray().map(encodeURIComponent).join('/');\n }\n\n /**\n * Creates a resource path from the given slash-delimited string. If multiple\n * arguments are provided, all components are combined. Leading and trailing\n * slashes from all components are ignored.\n */\n static fromString(...pathComponents: string[]): ResourcePath {\n // NOTE: The client is ignorant of any path segments containing escape\n // sequences (e.g. __id123__) and just passes them through raw (they exist\n // for legacy reasons and should not be used frequently).\n\n const segments: string[] = [];\n for (const path of pathComponents) {\n if (path.indexOf('//') >= 0) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid segment (${path}). Paths must not contain // in them.`\n );\n }\n // Strip leading and trailing slashed.\n segments.push(...path.split('/').filter(segment => segment.length > 0));\n }\n\n return new ResourcePath(segments);\n }\n\n static emptyPath(): ResourcePath {\n return new ResourcePath([]);\n }\n}\n\nconst identifierRegExp = /^[_a-zA-Z][_a-zA-Z0-9]*$/;\n\n/**\n * A dot-separated path for navigating sub-objects within a document.\n * @internal\n */\nexport class FieldPath extends BasePath {\n protected construct(\n segments: string[],\n offset?: number,\n length?: number\n ): FieldPath {\n return new FieldPath(segments, offset, length);\n }\n\n /**\n * Returns true if the string could be used as a segment in a field path\n * without escaping.\n */\n private static isValidIdentifier(segment: string): boolean {\n return identifierRegExp.test(segment);\n }\n\n canonicalString(): string {\n return this.toArray()\n .map(str => {\n str = str.replace(/\\\\/g, '\\\\\\\\').replace(/`/g, '\\\\`');\n if (!FieldPath.isValidIdentifier(str)) {\n str = '`' + str + '`';\n }\n return str;\n })\n .join('.');\n }\n\n toString(): string {\n return this.canonicalString();\n }\n\n /**\n * Returns true if this field references the key of a document.\n */\n isKeyField(): boolean {\n return this.length === 1 && this.get(0) === DOCUMENT_KEY_NAME;\n }\n\n /**\n * The field designating the key of a document.\n */\n static keyField(): FieldPath {\n return new FieldPath([DOCUMENT_KEY_NAME]);\n }\n\n /**\n * Parses a field string from the given server-formatted string.\n *\n * - Splitting the empty string is not allowed (for now at least).\n * - Empty segments within the string (e.g. if there are two consecutive\n * separators) are not allowed.\n *\n * TODO(b/37244157): we should make this more strict. Right now, it allows\n * non-identifier path components, even if they aren't escaped.\n */\n static fromServerFormat(path: string): FieldPath {\n const segments: string[] = [];\n let current = '';\n let i = 0;\n\n const addCurrentSegment = (): void => {\n if (current.length === 0) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid field path (${path}). Paths must not be empty, begin ` +\n `with '.', end with '.', or contain '..'`\n );\n }\n segments.push(current);\n current = '';\n };\n\n let inBackticks = false;\n\n while (i < path.length) {\n const c = path[i];\n if (c === '\\\\') {\n if (i + 1 === path.length) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Path has trailing escape character: ' + path\n );\n }\n const next = path[i + 1];\n if (!(next === '\\\\' || next === '.' || next === '`')) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Path has invalid escape sequence: ' + path\n );\n }\n current += next;\n i += 2;\n } else if (c === '`') {\n inBackticks = !inBackticks;\n i++;\n } else if (c === '.' && !inBackticks) {\n addCurrentSegment();\n i++;\n } else {\n current += c;\n i++;\n }\n }\n addCurrentSegment();\n\n if (inBackticks) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Unterminated ` in path: ' + path\n );\n }\n\n return new FieldPath(segments);\n }\n\n static emptyPath(): FieldPath {\n return new FieldPath([]);\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { debugAssert } from '../util/assert';\n\nimport { ResourcePath } from './path';\n\n/**\n * @internal\n */\nexport class DocumentKey {\n constructor(readonly path: ResourcePath) {\n debugAssert(\n DocumentKey.isDocumentKey(path),\n 'Invalid DocumentKey with an odd number of segments: ' +\n path.toArray().join('/')\n );\n }\n\n static fromPath(path: string): DocumentKey {\n return new DocumentKey(ResourcePath.fromString(path));\n }\n\n static fromName(name: string): DocumentKey {\n return new DocumentKey(ResourcePath.fromString(name).popFirst(5));\n }\n\n static empty(): DocumentKey {\n return new DocumentKey(ResourcePath.emptyPath());\n }\n\n get collectionGroup(): string {\n debugAssert(\n !this.path.isEmpty(),\n 'Cannot get collection group for empty key'\n );\n return this.path.popLast().lastSegment();\n }\n\n /** Returns true if the document is in the specified collectionId. */\n hasCollectionId(collectionId: string): boolean {\n return (\n this.path.length >= 2 &&\n this.path.get(this.path.length - 2) === collectionId\n );\n }\n\n /** Returns the collection group (i.e. the name of the parent collection) for this key. */\n getCollectionGroup(): string {\n debugAssert(\n !this.path.isEmpty(),\n 'Cannot get collection group for empty key'\n );\n return this.path.get(this.path.length - 2);\n }\n\n /** Returns the fully qualified path to the parent collection. */\n getCollectionPath(): ResourcePath {\n return this.path.popLast();\n }\n\n isEqual(other: DocumentKey | null): boolean {\n return (\n other !== null && ResourcePath.comparator(this.path, other.path) === 0\n );\n }\n\n toString(): string {\n return this.path.toString();\n }\n\n static comparator(k1: DocumentKey, k2: DocumentKey): number {\n return ResourcePath.comparator(k1.path, k2.path);\n }\n\n static isDocumentKey(path: ResourcePath): boolean {\n return path.length % 2 === 0;\n }\n\n /**\n * Creates and returns a new document key with the given segments.\n *\n * @param segments - The segments of the path to the document\n * @returns A new instance of DocumentKey\n */\n static fromSegments(segments: string[]): DocumentKey {\n return new DocumentKey(new ResourcePath(segments.slice()));\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DocumentKey } from '../model/document_key';\nimport { ResourcePath } from '../model/path';\n\nimport { fail } from './assert';\nimport { Code, FirestoreError } from './error';\n\n/** Types accepted by validateType() and related methods for validation. */\nexport type ValidationType =\n | 'undefined'\n | 'object'\n | 'function'\n | 'boolean'\n | 'number'\n | 'string'\n | 'non-empty string';\n\nexport function validateNonEmptyArgument(\n functionName: string,\n argumentName: string,\n argument?: string\n): asserts argument is string {\n if (!argument) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Function ${functionName}() cannot be called with an empty ${argumentName}.`\n );\n }\n}\n\n/**\n * Validates that two boolean options are not set at the same time.\n * @internal\n */\nexport function validateIsNotUsedTogether(\n optionName1: string,\n argument1: boolean | undefined,\n optionName2: string,\n argument2: boolean | undefined\n): void {\n if (argument1 === true && argument2 === true) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `${optionName1} and ${optionName2} cannot be used together.`\n );\n }\n}\n\n/**\n * Validates that `path` refers to a document (indicated by the fact it contains\n * an even numbers of segments).\n */\nexport function validateDocumentPath(path: ResourcePath): void {\n if (!DocumentKey.isDocumentKey(path)) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid document reference. Document references must have an even number of segments, but ${path} has ${path.length}.`\n );\n }\n}\n\n/**\n * Validates that `path` refers to a collection (indicated by the fact it\n * contains an odd numbers of segments).\n */\nexport function validateCollectionPath(path: ResourcePath): void {\n if (DocumentKey.isDocumentKey(path)) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid collection reference. Collection references must have an odd number of segments, but ${path} has ${path.length}.`\n );\n }\n}\n\n/**\n * Returns true if it's a non-null object without a custom prototype\n * (i.e. excludes Array, Date, etc.).\n */\nexport function isPlainObject(input: unknown): boolean {\n return (\n typeof input === 'object' &&\n input !== null &&\n (Object.getPrototypeOf(input) === Object.prototype ||\n Object.getPrototypeOf(input) === null)\n );\n}\n\n/** Returns a string describing the type / value of the provided input. */\nexport function valueDescription(input: unknown): string {\n if (input === undefined) {\n return 'undefined';\n } else if (input === null) {\n return 'null';\n } else if (typeof input === 'string') {\n if (input.length > 20) {\n input = `${input.substring(0, 20)}...`;\n }\n return JSON.stringify(input);\n } else if (typeof input === 'number' || typeof input === 'boolean') {\n return '' + input;\n } else if (typeof input === 'object') {\n if (input instanceof Array) {\n return 'an array';\n } else {\n const customObjectName = tryGetCustomObjectType(input!);\n if (customObjectName) {\n return `a custom ${customObjectName} object`;\n } else {\n return 'an object';\n }\n }\n } else if (typeof input === 'function') {\n return 'a function';\n } else {\n return fail(0x3029, 'Unknown wrong type', { type: typeof input });\n }\n}\n\n/** try to get the constructor name for an object. */\nexport function tryGetCustomObjectType(input: object): string | null {\n if (input.constructor) {\n return input.constructor.name;\n }\n return null;\n}\n\n/**\n * Casts `obj` to `T`, optionally unwrapping Compat types to expose the\n * underlying instance. Throws if `obj` is not an instance of `T`.\n *\n * This cast is used in the Lite and Full SDK to verify instance types for\n * arguments passed to the public API.\n * @internal\n */\nexport function cast(\n obj: object,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n constructor: { new (...args: any[]): T }\n): T | never {\n if ('_delegate' in obj) {\n // Unwrap Compat types\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n obj = (obj as any)._delegate;\n }\n\n if (!(obj instanceof constructor)) {\n if (constructor.name === obj.constructor.name) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Type does not match the expected instance. Did you pass a ' +\n `reference from a different Firestore SDK?`\n );\n } else {\n const description = valueDescription(obj);\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Expected type '${constructor.name}', but it was: ${description}`\n );\n }\n }\n return obj as T;\n}\n\nexport function validatePositiveNumber(functionName: string, n: number): void {\n if (n <= 0) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Function ${functionName}() requires a positive number, but it was: ${n}.`\n );\n }\n}\n","/**\n * @license\n * Copyright 2023 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Options that configure the SDK’s underlying network transport (WebChannel)\n * when long-polling is used.\n *\n * Note: This interface is \"experimental\" and is subject to change.\n *\n * See `FirestoreSettings.experimentalAutoDetectLongPolling`,\n * `FirestoreSettings.experimentalForceLongPolling`, and\n * `FirestoreSettings.experimentalLongPollingOptions`.\n */\nexport interface ExperimentalLongPollingOptions {\n /**\n * The desired maximum timeout interval, in seconds, to complete a\n * long-polling GET response. Valid values are between 5 and 30, inclusive.\n * Floating point values are allowed and will be rounded to the nearest\n * millisecond.\n *\n * By default, when long-polling is used the \"hanging GET\" request sent by\n * the client times out after 30 seconds. To request a different timeout\n * from the server, set this setting with the desired timeout.\n *\n * Changing the default timeout may be useful, for example, if the buffering\n * proxy that necessitated enabling long-polling in the first place has a\n * shorter timeout for hanging GET requests, in which case setting the\n * long-polling timeout to a shorter value, such as 25 seconds, may fix\n * prematurely-closed hanging GET requests.\n * For example, see https://github.com/firebase/firebase-js-sdk/issues/6987.\n */\n timeoutSeconds?: number;\n}\n\n/**\n * Compares two `ExperimentalLongPollingOptions` objects for equality.\n */\nexport function longPollingOptionsEqual(\n options1: ExperimentalLongPollingOptions,\n options2: ExperimentalLongPollingOptions\n): boolean {\n return options1.timeoutSeconds === options2.timeoutSeconds;\n}\n\n/**\n * Creates and returns a new `ExperimentalLongPollingOptions` with the same\n * option values as the given instance.\n */\nexport function cloneLongPollingOptions(\n options: ExperimentalLongPollingOptions\n): ExperimentalLongPollingOptions {\n const clone: ExperimentalLongPollingOptions = {};\n\n if (options.timeoutSeconds !== undefined) {\n clone.timeoutSeconds = options.timeoutSeconds;\n }\n\n return clone;\n}\n","/**\n * @license\n * Copyright 2023 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * The value returned from the most recent invocation of\n * `generateUniqueDebugId()`, or null if it has never been invoked.\n */\nlet lastUniqueDebugId: number | null = null;\n\n/**\n * Generates and returns an initial value for `lastUniqueDebugId`.\n *\n * The returned value is randomly selected from a range of integers that are\n * represented as 8 hexadecimal digits. This means that (within reason) any\n * numbers generated by incrementing the returned number by 1 will also be\n * represented by 8 hexadecimal digits. This leads to all \"IDs\" having the same\n * length when converted to a hexadecimal string, making reading logs containing\n * these IDs easier to follow. And since the return value is randomly selected\n * it will help to differentiate between logs from different executions.\n */\nfunction generateInitialUniqueDebugId(): number {\n const minResult = 0x10000000;\n const maxResult = 0x90000000;\n const resultRange = maxResult - minResult;\n const resultOffset = Math.round(resultRange * Math.random());\n return minResult + resultOffset;\n}\n\n/**\n * Generates and returns a unique ID as a hexadecimal string.\n *\n * The returned ID is intended to be used in debug logging messages to help\n * correlate log messages that may be spatially separated in the logs, but\n * logically related. For example, a network connection could include the same\n * \"debug ID\" string in all of its log messages to help trace a specific\n * connection over time.\n *\n * @return the 10-character generated ID (e.g. \"0xa1b2c3d4\").\n */\nexport function generateUniqueDebugId(): string {\n if (lastUniqueDebugId === null) {\n lastUniqueDebugId = generateInitialUniqueDebugId();\n } else {\n lastUniqueDebugId++;\n }\n return '0x' + lastUniqueDebugId.toString(16);\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** Sentinel value that sorts before any Mutation Batch ID. */\nexport const BATCHID_UNKNOWN = -1;\n\n// An Object whose keys and values are strings.\nexport interface StringMap {\n [key: string]: string;\n}\n\n/**\n * Returns whether a variable is either undefined or null.\n */\nexport function isNullOrUndefined(value: unknown): value is null | undefined {\n return value === null || value === undefined;\n}\n\n/** Returns whether the value represents -0. */\nexport function isNegativeZero(value: number): boolean {\n // Detect if the value is -0.0. Based on polyfill from\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is\n return value === 0 && 1 / value === 1 / -0;\n}\n\n/**\n * Returns whether a value is an integer and in the safe integer range\n * @param value - The value to test for being an integer and in the safe range\n */\nexport function isSafeInteger(value: unknown): boolean {\n return (\n typeof value === 'number' &&\n Number.isInteger(value) &&\n !isNegativeZero(value) &&\n value <= Number.MAX_SAFE_INTEGER &&\n value >= Number.MIN_SAFE_INTEGER\n );\n}\n\n/** The subset of the browser's Window interface used by the SDK. */\nexport interface WindowLike {\n readonly localStorage: Storage;\n readonly indexedDB: IDBFactory | null;\n addEventListener(type: string, listener: EventListener): void;\n removeEventListener(type: string, listener: EventListener): void;\n}\n\n/** The subset of the browser's Document interface used by the SDK. */\nexport interface DocumentLike {\n readonly visibilityState: DocumentVisibilityState;\n addEventListener(type: string, listener: EventListener): void;\n removeEventListener(type: string, listener: EventListener): void;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isCloudWorkstation } from '@firebase/util';\n\nimport { SDK_VERSION } from '../../src/core/version';\nimport { Token } from '../api/credentials';\nimport {\n DatabaseId,\n DatabaseInfo,\n DEFAULT_DATABASE_NAME\n} from '../core/database_info';\nimport { ResourcePath } from '../model/path';\nimport { debugAssert } from '../util/assert';\nimport { generateUniqueDebugId } from '../util/debug_uid';\nimport { FirestoreError } from '../util/error';\nimport { logDebug, logWarn } from '../util/log';\nimport { StringMap } from '../util/types';\n\nimport { Connection, Stream } from './connection';\n\nconst LOG_TAG = 'RestConnection';\n\n/**\n * Maps RPC names to the corresponding REST endpoint name.\n *\n * We use array notation to avoid mangling.\n */\nconst RPC_NAME_URL_MAPPING: StringMap = {};\n\nRPC_NAME_URL_MAPPING['BatchGetDocuments'] = 'batchGet';\nRPC_NAME_URL_MAPPING['Commit'] = 'commit';\nRPC_NAME_URL_MAPPING['RunQuery'] = 'runQuery';\nRPC_NAME_URL_MAPPING['RunAggregationQuery'] = 'runAggregationQuery';\n\nconst RPC_URL_VERSION = 'v1';\n\n// SDK_VERSION is updated to different value at runtime depending on the entry point,\n// so we need to get its value when we need it in a function.\nfunction getGoogApiClientValue(): string {\n return 'gl-js/ fire/' + SDK_VERSION;\n}\n/**\n * Base class for all Rest-based connections to the backend (WebChannel and\n * HTTP).\n */\nexport abstract class RestConnection implements Connection {\n protected readonly databaseId: DatabaseId;\n protected readonly baseUrl: string;\n private readonly databasePath: string;\n private readonly requestParams: string;\n\n get shouldResourcePathBeIncludedInRequest(): boolean {\n // Both `invokeRPC()` and `invokeStreamingRPC()` use their `path` arguments to determine\n // where to run the query, and expect the `request` to NOT specify the \"path\".\n return false;\n }\n\n constructor(private readonly databaseInfo: DatabaseInfo) {\n this.databaseId = databaseInfo.databaseId;\n const proto = databaseInfo.ssl ? 'https' : 'http';\n const projectId = encodeURIComponent(this.databaseId.projectId);\n const databaseId = encodeURIComponent(this.databaseId.database);\n this.baseUrl = proto + '://' + databaseInfo.host;\n this.databasePath = `projects/${projectId}/databases/${databaseId}`;\n this.requestParams =\n this.databaseId.database === DEFAULT_DATABASE_NAME\n ? `project_id=${projectId}`\n : `project_id=${projectId}&database_id=${databaseId}`;\n }\n\n invokeRPC(\n rpcName: string,\n path: ResourcePath,\n req: Req,\n authToken: Token | null,\n appCheckToken: Token | null\n ): Promise {\n const streamId = generateUniqueDebugId();\n const url = this.makeUrl(rpcName, path.toUriEncodedString());\n logDebug(LOG_TAG, `Sending RPC '${rpcName}' ${streamId}:`, url, req);\n\n const headers: StringMap = {\n 'google-cloud-resource-prefix': this.databasePath,\n 'x-goog-request-params': this.requestParams\n };\n this.modifyHeadersForRequest(headers, authToken, appCheckToken);\n\n const { host } = new URL(url);\n const forwardCredentials = isCloudWorkstation(host);\n return this.performRPCRequest(\n rpcName,\n url,\n headers,\n req,\n forwardCredentials\n ).then(\n response => {\n logDebug(LOG_TAG, `Received RPC '${rpcName}' ${streamId}: `, response);\n return response;\n },\n (err: FirestoreError) => {\n logWarn(\n LOG_TAG,\n `RPC '${rpcName}' ${streamId} failed with error: `,\n err,\n 'url: ',\n url,\n 'request:',\n req\n );\n throw err;\n }\n );\n }\n\n invokeStreamingRPC(\n rpcName: string,\n path: ResourcePath,\n request: Req,\n authToken: Token | null,\n appCheckToken: Token | null,\n expectedResponseCount?: number\n ): Promise {\n // The REST API automatically aggregates all of the streamed results, so we\n // can just use the normal invoke() method.\n return this.invokeRPC(\n rpcName,\n path,\n request,\n authToken,\n appCheckToken\n );\n }\n\n abstract openStream(\n rpcName: string,\n authToken: Token | null,\n appCheckToken: Token | null\n ): Stream;\n\n /**\n * Modifies the headers for a request, adding any authorization token if\n * present and any additional headers for the request.\n */\n protected modifyHeadersForRequest(\n headers: StringMap,\n authToken: Token | null,\n appCheckToken: Token | null\n ): void {\n headers['X-Goog-Api-Client'] = getGoogApiClientValue();\n\n // Content-Type: text/plain will avoid preflight requests which might\n // mess with CORS and redirects by proxies. If we add custom headers\n // we will need to change this code to potentially use the $httpOverwrite\n // parameter supported by ESF to avoid triggering preflight requests.\n headers['Content-Type'] = 'text/plain';\n\n if (this.databaseInfo.appId) {\n headers['X-Firebase-GMPID'] = this.databaseInfo.appId;\n }\n\n if (authToken) {\n authToken.headers.forEach((value, key) => (headers[key] = value));\n }\n if (appCheckToken) {\n appCheckToken.headers.forEach((value, key) => (headers[key] = value));\n }\n }\n\n /**\n * Performs an RPC request using an implementation specific networking layer.\n */\n protected abstract performRPCRequest(\n rpcName: string,\n url: string,\n headers: StringMap,\n body: Req,\n _forwardCredentials: boolean\n ): Promise;\n\n private makeUrl(rpcName: string, path: string): string {\n const urlRpcName = RPC_NAME_URL_MAPPING[rpcName];\n debugAssert(\n urlRpcName !== undefined,\n 'Unknown REST mapping for: ' + rpcName\n );\n return `${this.baseUrl}/${RPC_URL_VERSION}/${path}:${urlRpcName}`;\n }\n\n /**\n * Closes and cleans up any resources associated with the connection. This\n * implementation is a no-op because there are no resources associated\n * with the RestConnection that need to be cleaned up.\n */\n terminate(): void {\n // No-op\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { fail } from '../util/assert';\nimport { Code } from '../util/error';\nimport { logError } from '../util/log';\n\n/**\n * Error Codes describing the different ways GRPC can fail. These are copied\n * directly from GRPC's sources here:\n *\n * https://github.com/grpc/grpc/blob/bceec94ea4fc5f0085d81235d8e1c06798dc341a/include/grpc%2B%2B/impl/codegen/status_code_enum.h\n *\n * Important! The names of these identifiers matter because the string forms\n * are used for reverse lookups from the webchannel stream. Do NOT change the\n * names of these identifiers or change this into a const enum.\n */\nenum RpcCode {\n OK = 0,\n CANCELLED = 1,\n UNKNOWN = 2,\n INVALID_ARGUMENT = 3,\n DEADLINE_EXCEEDED = 4,\n NOT_FOUND = 5,\n ALREADY_EXISTS = 6,\n PERMISSION_DENIED = 7,\n UNAUTHENTICATED = 16,\n RESOURCE_EXHAUSTED = 8,\n FAILED_PRECONDITION = 9,\n ABORTED = 10,\n OUT_OF_RANGE = 11,\n UNIMPLEMENTED = 12,\n INTERNAL = 13,\n UNAVAILABLE = 14,\n DATA_LOSS = 15\n}\n\n/**\n * Determines whether an error code represents a permanent error when received\n * in response to a non-write operation.\n *\n * See isPermanentWriteError for classifying write errors.\n */\nexport function isPermanentError(code: Code): boolean {\n switch (code) {\n case Code.OK:\n return fail(0xfdaa, 'Treated status OK as error');\n case Code.CANCELLED:\n case Code.UNKNOWN:\n case Code.DEADLINE_EXCEEDED:\n case Code.RESOURCE_EXHAUSTED:\n case Code.INTERNAL:\n case Code.UNAVAILABLE:\n // Unauthenticated means something went wrong with our token and we need\n // to retry with new credentials which will happen automatically.\n case Code.UNAUTHENTICATED:\n return false;\n case Code.INVALID_ARGUMENT:\n case Code.NOT_FOUND:\n case Code.ALREADY_EXISTS:\n case Code.PERMISSION_DENIED:\n case Code.FAILED_PRECONDITION:\n // Aborted might be retried in some scenarios, but that is dependent on\n // the context and should handled individually by the calling code.\n // See https://cloud.google.com/apis/design/errors.\n case Code.ABORTED:\n case Code.OUT_OF_RANGE:\n case Code.UNIMPLEMENTED:\n case Code.DATA_LOSS:\n return true;\n default:\n return fail(0x3c6b, 'Unknown status code', { code });\n }\n}\n\n/**\n * Determines whether an error code represents a permanent error when received\n * in response to a write operation.\n *\n * Write operations must be handled specially because as of b/119437764, ABORTED\n * errors on the write stream should be retried too (even though ABORTED errors\n * are not generally retryable).\n *\n * Note that during the initial handshake on the write stream an ABORTED error\n * signals that we should discard our stream token (i.e. it is permanent). This\n * means a handshake error should be classified with isPermanentError, above.\n */\nexport function isPermanentWriteError(code: Code): boolean {\n return isPermanentError(code) && code !== Code.ABORTED;\n}\n\n/**\n * Maps an error Code from a GRPC status identifier like 'NOT_FOUND'.\n *\n * @returns The Code equivalent to the given status string or undefined if\n * there is no match.\n */\nexport function mapCodeFromRpcStatus(status: string): Code | undefined {\n // lookup by string\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const code: RpcCode = RpcCode[status as any] as any;\n if (code === undefined) {\n return undefined;\n }\n\n return mapCodeFromRpcCode(code);\n}\n\n/**\n * Maps an error Code from GRPC status code number, like 0, 1, or 14. These\n * are not the same as HTTP status codes.\n *\n * @returns The Code equivalent to the given GRPC status code. Fails if there\n * is no match.\n */\nexport function mapCodeFromRpcCode(code: number | undefined): Code {\n if (code === undefined) {\n // This shouldn't normally happen, but in certain error cases (like trying\n // to send invalid proto messages) we may get an error with no GRPC code.\n logError('GRPC error has no .code');\n return Code.UNKNOWN;\n }\n\n switch (code) {\n case RpcCode.OK:\n return Code.OK;\n case RpcCode.CANCELLED:\n return Code.CANCELLED;\n case RpcCode.UNKNOWN:\n return Code.UNKNOWN;\n case RpcCode.DEADLINE_EXCEEDED:\n return Code.DEADLINE_EXCEEDED;\n case RpcCode.RESOURCE_EXHAUSTED:\n return Code.RESOURCE_EXHAUSTED;\n case RpcCode.INTERNAL:\n return Code.INTERNAL;\n case RpcCode.UNAVAILABLE:\n return Code.UNAVAILABLE;\n case RpcCode.UNAUTHENTICATED:\n return Code.UNAUTHENTICATED;\n case RpcCode.INVALID_ARGUMENT:\n return Code.INVALID_ARGUMENT;\n case RpcCode.NOT_FOUND:\n return Code.NOT_FOUND;\n case RpcCode.ALREADY_EXISTS:\n return Code.ALREADY_EXISTS;\n case RpcCode.PERMISSION_DENIED:\n return Code.PERMISSION_DENIED;\n case RpcCode.FAILED_PRECONDITION:\n return Code.FAILED_PRECONDITION;\n case RpcCode.ABORTED:\n return Code.ABORTED;\n case RpcCode.OUT_OF_RANGE:\n return Code.OUT_OF_RANGE;\n case RpcCode.UNIMPLEMENTED:\n return Code.UNIMPLEMENTED;\n case RpcCode.DATA_LOSS:\n return Code.DATA_LOSS;\n default:\n return fail(0x999b, 'Unknown status code', { code });\n }\n}\n\n/**\n * Maps an RPC code from a Code. This is the reverse operation from\n * mapCodeFromRpcCode and should really only be used in tests.\n */\nexport function mapRpcCodeFromCode(code: Code | undefined): number {\n if (code === undefined) {\n return RpcCode.OK;\n }\n\n switch (code) {\n case Code.OK:\n return RpcCode.OK;\n case Code.CANCELLED:\n return RpcCode.CANCELLED;\n case Code.UNKNOWN:\n return RpcCode.UNKNOWN;\n case Code.DEADLINE_EXCEEDED:\n return RpcCode.DEADLINE_EXCEEDED;\n case Code.RESOURCE_EXHAUSTED:\n return RpcCode.RESOURCE_EXHAUSTED;\n case Code.INTERNAL:\n return RpcCode.INTERNAL;\n case Code.UNAVAILABLE:\n return RpcCode.UNAVAILABLE;\n case Code.UNAUTHENTICATED:\n return RpcCode.UNAUTHENTICATED;\n case Code.INVALID_ARGUMENT:\n return RpcCode.INVALID_ARGUMENT;\n case Code.NOT_FOUND:\n return RpcCode.NOT_FOUND;\n case Code.ALREADY_EXISTS:\n return RpcCode.ALREADY_EXISTS;\n case Code.PERMISSION_DENIED:\n return RpcCode.PERMISSION_DENIED;\n case Code.FAILED_PRECONDITION:\n return RpcCode.FAILED_PRECONDITION;\n case Code.ABORTED:\n return RpcCode.ABORTED;\n case Code.OUT_OF_RANGE:\n return RpcCode.OUT_OF_RANGE;\n case Code.UNIMPLEMENTED:\n return RpcCode.UNIMPLEMENTED;\n case Code.DATA_LOSS:\n return RpcCode.DATA_LOSS;\n default:\n return fail(0x3019, 'Unknown status code', { code });\n }\n}\n\n/**\n * Converts an HTTP Status Code to the equivalent error code.\n *\n * @param status - An HTTP Status Code, like 200, 404, 503, etc.\n * @returns The equivalent Code. Unknown status codes are mapped to\n * Code.UNKNOWN.\n */\nexport function mapCodeFromHttpStatus(status?: number): Code {\n if (status === undefined) {\n logError('RPC_ERROR', 'HTTP error has no status');\n return Code.UNKNOWN;\n }\n\n // The canonical error codes for Google APIs [1] specify mapping onto HTTP\n // status codes but the mapping is not bijective. In each case of ambiguity\n // this function chooses a primary error.\n //\n // [1]\n // https://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto\n switch (status) {\n case 200: // OK\n return Code.OK;\n\n case 400: // Bad Request\n return Code.FAILED_PRECONDITION;\n // Other possibilities based on the forward mapping\n // return Code.INVALID_ARGUMENT;\n // return Code.OUT_OF_RANGE;\n\n case 401: // Unauthorized\n return Code.UNAUTHENTICATED;\n\n case 403: // Forbidden\n return Code.PERMISSION_DENIED;\n\n case 404: // Not Found\n return Code.NOT_FOUND;\n\n case 409: // Conflict\n return Code.ABORTED;\n // Other possibilities:\n // return Code.ALREADY_EXISTS;\n\n case 416: // Range Not Satisfiable\n return Code.OUT_OF_RANGE;\n\n case 429: // Too Many Requests\n return Code.RESOURCE_EXHAUSTED;\n\n case 499: // Client Closed Request\n return Code.CANCELLED;\n\n case 500: // Internal Server Error\n return Code.UNKNOWN;\n // Other possibilities:\n // return Code.INTERNAL;\n // return Code.DATA_LOSS;\n\n case 501: // Unimplemented\n return Code.UNIMPLEMENTED;\n\n case 503: // Service Unavailable\n return Code.UNAVAILABLE;\n\n case 504: // Gateway Timeout\n return Code.DEADLINE_EXCEEDED;\n\n default:\n if (status >= 200 && status < 300) {\n return Code.OK;\n }\n if (status >= 400 && status < 500) {\n return Code.FAILED_PRECONDITION;\n }\n if (status >= 500 && status < 600) {\n return Code.INTERNAL;\n }\n return Code.UNKNOWN;\n }\n}\n\n/**\n * Converts an HTTP response's error status to the equivalent error code.\n *\n * @param status - An HTTP error response status (\"FAILED_PRECONDITION\",\n * \"UNKNOWN\", etc.)\n * @returns The equivalent Code. Non-matching responses are mapped to\n * Code.UNKNOWN.\n */\nexport function mapCodeFromHttpResponseErrorStatus(status: string): Code {\n const serverError = status.toLowerCase().replace(/_/g, '-');\n return Object.values(Code).indexOf(serverError as Code) >= 0\n ? (serverError as Code)\n : Code.UNKNOWN;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Token } from '../../api/credentials';\nimport { Stream } from '../../remote/connection';\nimport { RestConnection } from '../../remote/rest_connection';\nimport { mapCodeFromHttpStatus } from '../../remote/rpc_error';\nimport { FirestoreError } from '../../util/error';\nimport { StringMap } from '../../util/types';\n\n/**\n * A Rest-based connection that relies on the native HTTP stack\n * (e.g. `fetch` or a polyfill).\n */\nexport class FetchConnection extends RestConnection {\n openStream(\n rpcName: string,\n token: Token | null\n ): Stream {\n throw new Error('Not supported by FetchConnection');\n }\n\n protected async performRPCRequest(\n rpcName: string,\n url: string,\n headers: StringMap,\n body: Req,\n forwardCredentials: boolean\n ): Promise {\n const requestJson = JSON.stringify(body);\n let response: Response;\n\n try {\n const fetchArgs: RequestInit = {\n method: 'POST',\n headers,\n body: requestJson\n };\n if (forwardCredentials) {\n fetchArgs.credentials = 'include';\n }\n response = await fetch(url, fetchArgs);\n } catch (e) {\n const err = e as { status: number | undefined; statusText: string };\n throw new FirestoreError(\n mapCodeFromHttpStatus(err.status),\n 'Request failed with error: ' + err.statusText\n );\n }\n\n if (!response.ok) {\n let errorResponse = await response.json();\n if (Array.isArray(errorResponse)) {\n errorResponse = errorResponse[0];\n }\n const errorMessage = errorResponse?.error?.message;\n throw new FirestoreError(\n mapCodeFromHttpStatus(response.status),\n `Request failed with error: ${errorMessage ?? response.statusText}`\n );\n }\n\n return response.json();\n }\n}\n","/**\n * @license\n * Copyright 2023 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FieldPath } from '../model/path';\n\n/**\n * Union type representing the aggregate type to be performed.\n */\nexport type AggregateType = 'count' | 'avg' | 'sum';\n\n/**\n * Represents an Aggregate to be performed over a query result set.\n */\nexport interface Aggregate {\n readonly fieldPath?: FieldPath;\n readonly alias: string;\n readonly aggregateType: AggregateType;\n}\n\n/**\n * Concrete implementation of the Aggregate type.\n */\nexport class AggregateImpl implements Aggregate {\n constructor(\n readonly alias: string,\n readonly aggregateType: AggregateType,\n readonly fieldPath?: FieldPath\n ) {}\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { debugAssert } from './assert';\n\nexport interface Dict {\n [stringKey: string]: V;\n}\n\nexport function objectSize(obj: object): number {\n let count = 0;\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n count++;\n }\n }\n return count;\n}\n\nexport function forEach(\n obj: Dict | undefined,\n fn: (key: string, val: V) => void\n): void {\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n fn(key, obj[key]);\n }\n }\n}\n\nexport function mapToArray(\n obj: Dict,\n fn: (element: V, key: string, obj: Dict) => R\n): R[] {\n const result: R[] = [];\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n result.push(fn(obj[key], key, obj));\n }\n }\n return result;\n}\n\nexport function isEmpty(obj: Dict): boolean {\n debugAssert(\n obj != null && typeof obj === 'object',\n 'isEmpty() expects object parameter.'\n );\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n return false;\n }\n }\n return true;\n}\n","/**\n * @license\n * Copyright 2023 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * An error encountered while decoding base64 string.\n */\nexport class Base64DecodeError extends Error {\n readonly name = 'Base64DecodeError';\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { decodeBase64, encodeBase64 } from '../platform/base64';\n\nimport { primitiveComparator } from './misc';\n\n/**\n * Immutable class that represents a \"proto\" byte string.\n *\n * Proto byte strings can either be Base64-encoded strings or Uint8Arrays when\n * sent on the wire. This class abstracts away this differentiation by holding\n * the proto byte string in a common class that must be converted into a string\n * before being sent as a proto.\n * @internal\n */\nexport class ByteString {\n static readonly EMPTY_BYTE_STRING = new ByteString('');\n\n private constructor(private readonly binaryString: string) {}\n\n static fromBase64String(base64: string): ByteString {\n const binaryString = decodeBase64(base64);\n return new ByteString(binaryString);\n }\n\n static fromUint8Array(array: Uint8Array): ByteString {\n // TODO(indexing); Remove the copy of the byte string here as this method\n // is frequently called during indexing.\n const binaryString = binaryStringFromUint8Array(array);\n return new ByteString(binaryString);\n }\n\n [Symbol.iterator](): Iterator {\n let i = 0;\n return {\n next: () => {\n if (i < this.binaryString.length) {\n return { value: this.binaryString.charCodeAt(i++), done: false };\n } else {\n return { value: undefined, done: true };\n }\n }\n };\n }\n\n toBase64(): string {\n return encodeBase64(this.binaryString);\n }\n\n toUint8Array(): Uint8Array {\n return uint8ArrayFromBinaryString(this.binaryString);\n }\n\n approximateByteSize(): number {\n return this.binaryString.length * 2;\n }\n\n compareTo(other: ByteString): number {\n return primitiveComparator(this.binaryString, other.binaryString);\n }\n\n isEqual(other: ByteString): boolean {\n return this.binaryString === other.binaryString;\n }\n}\n\n/**\n * Helper function to convert an Uint8array to a binary string.\n */\nexport function binaryStringFromUint8Array(array: Uint8Array): string {\n let binaryString = '';\n for (let i = 0; i < array.length; ++i) {\n binaryString += String.fromCharCode(array[i]);\n }\n return binaryString;\n}\n\n/**\n * Helper function to convert a binary string to an Uint8Array.\n */\nexport function uint8ArrayFromBinaryString(binaryString: string): Uint8Array {\n const buffer = new Uint8Array(binaryString.length);\n for (let i = 0; i < binaryString.length; i++) {\n buffer[i] = binaryString.charCodeAt(i);\n }\n return buffer;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Base64DecodeError } from '../../util/base64_decode_error';\n\n/** Converts a Base64 encoded string to a binary string. */\nexport function decodeBase64(encoded: string): string {\n try {\n return atob(encoded);\n } catch (e) {\n // Check that `DOMException` is defined before using it to avoid\n // \"ReferenceError: Property 'DOMException' doesn't exist\" in react-native.\n // (https://github.com/firebase/firebase-js-sdk/issues/7115)\n if (typeof DOMException !== 'undefined' && e instanceof DOMException) {\n throw new Base64DecodeError('Invalid base64 string: ' + e);\n } else {\n throw e;\n }\n }\n}\n\n/** Converts a binary string to a Base64 encoded string. */\nexport function encodeBase64(raw: string): string {\n return btoa(raw);\n}\n\n/** True if and only if the Base64 conversion functions are available. */\nexport function isBase64Available(): boolean {\n return typeof atob !== 'undefined';\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Timestamp } from '../protos/firestore_proto_api';\nimport { hardAssert } from '../util/assert';\nimport { ByteString } from '../util/byte_string';\n\n// A RegExp matching ISO 8601 UTC timestamps with optional fraction.\nconst ISO_TIMESTAMP_REG_EXP = new RegExp(\n /^\\d{4}-\\d\\d-\\d\\dT\\d\\d:\\d\\d:\\d\\d(?:\\.(\\d+))?Z$/\n);\n\n/**\n * Converts the possible Proto values for a timestamp value into a \"seconds and\n * nanos\" representation.\n */\nexport function normalizeTimestamp(date: Timestamp): {\n seconds: number;\n nanos: number;\n} {\n hardAssert(!!date, 0x986a, 'Cannot normalize null or undefined timestamp.');\n\n // The json interface (for the browser) will return an iso timestamp string,\n // while the proto js library (for node) will return a\n // google.protobuf.Timestamp instance.\n if (typeof date === 'string') {\n // The date string can have higher precision (nanos) than the Date class\n // (millis), so we do some custom parsing here.\n\n // Parse the nanos right out of the string.\n let nanos = 0;\n const fraction = ISO_TIMESTAMP_REG_EXP.exec(date);\n hardAssert(!!fraction, 0xb5de, 'invalid timestamp', {\n timestamp: date\n });\n if (fraction[1]) {\n // Pad the fraction out to 9 digits (nanos).\n let nanoStr = fraction[1];\n nanoStr = (nanoStr + '000000000').substr(0, 9);\n nanos = Number(nanoStr);\n }\n\n // Parse the date to get the seconds.\n const parsedDate = new Date(date);\n const seconds = Math.floor(parsedDate.getTime() / 1000);\n\n return { seconds, nanos };\n } else {\n // TODO(b/37282237): Use strings for Proto3 timestamps\n // assert(!this.options.useProto3Json,\n // 'The timestamp instance format requires Proto JS.');\n const seconds = normalizeNumber(date.seconds);\n const nanos = normalizeNumber(date.nanos);\n return { seconds, nanos };\n }\n}\n\n/**\n * Converts the possible Proto types for numbers into a JavaScript number.\n * Returns 0 if the value is not numeric.\n */\nexport function normalizeNumber(value: number | string | undefined): number {\n // TODO(bjornick): Handle int64 greater than 53 bits.\n if (typeof value === 'number') {\n return value;\n } else if (typeof value === 'string') {\n return Number(value);\n } else {\n return 0;\n }\n}\n\n/** Converts the possible Proto types for Blobs into a ByteString. */\nexport function normalizeByteString(blob: string | Uint8Array): ByteString {\n if (typeof blob === 'string') {\n return ByteString.fromBase64String(blob);\n } else {\n return ByteString.fromUint8Array(blob);\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isPlainObject } from '../util/input_validation';\n\nimport { Code, FirestoreError } from './error';\n\n/**\n * A list of data types Firestore objects may serialize in their toJSON implemenetations.\n * @private\n * @internal\n */\nexport type JsonTypeDesc =\n | 'object'\n | 'string'\n | 'number'\n | 'boolean'\n | 'null'\n | 'undefined';\n\n/**\n * An association of JsonTypeDesc values to their native types.\n * @private\n * @internal\n */\nexport type TSType = T extends 'object'\n ? object\n : T extends 'string'\n ? string\n : T extends 'number'\n ? number\n : T extends 'boolean'\n ? boolean\n : T extends 'null'\n ? null\n : T extends 'undefined'\n ? undefined\n : never;\n\n/**\n * The representation of a JSON object property name and its type value.\n * @private\n * @internal\n */\nexport interface Property {\n value?: TSType;\n typeString: JsonTypeDesc;\n}\n\n/**\n * A type Firestore data types may use to define the fields used in their JSON serialization.\n * @private\n * @internal\n */\nexport interface JsonSchema {\n [key: string]: Property;\n}\n\n/**\n * Associates the JSON property type to the native type and sets them to be Required.\n * @private\n * @internal\n */\nexport type Json = {\n [K in keyof T]: Required['value'];\n};\n\n/**\n * Helper function to define a JSON schema {@link Property}.\n * @private\n * @internal\n */\nexport function property(\n typeString: T,\n optionalValue?: TSType\n): Property {\n const result: Property = {\n typeString\n };\n if (optionalValue) {\n result.value = optionalValue;\n }\n return result;\n}\n\n/**\n * Validates the JSON object based on the provided schema, and narrows the type to the provided\n * JSON schema.\n * @private\n * @internal\n *\n * @param json A JSON object to validate.\n * @param scheme a {@link JsonSchema} that defines the properties to validate.\n * @returns true if the JSON schema exists within the object. Throws a FirestoreError otherwise.\n */\nexport function validateJSON(\n json: object,\n schema: S\n): json is Json {\n if (!isPlainObject(json)) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'JSON must be an object');\n }\n let error: string | undefined = undefined;\n for (const key in schema) {\n if (schema[key]) {\n const typeString = schema[key].typeString;\n const value: { value: unknown } | undefined =\n 'value' in schema[key] ? { value: schema[key].value } : undefined;\n if (!(key in json)) {\n error = `JSON missing required field: '${key}'`;\n break;\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const fieldValue = (json as any)[key];\n if (typeString && typeof fieldValue !== typeString) {\n error = `JSON field '${key}' must be a ${typeString}.`;\n break;\n } else if (value !== undefined && fieldValue !== value.value) {\n error = `Expected '${key}' field to equal '${value.value}'`;\n break;\n }\n }\n }\n if (error) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, error);\n }\n return true;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Code, FirestoreError } from '../util/error';\n// API extractor fails importing 'property' unless we also explicitly import 'Property'.\n// eslint-disable-next-line @typescript-eslint/no-unused-vars, unused-imports/no-unused-imports-ts\nimport { Property, property, validateJSON } from '../util/json_validation';\nimport { primitiveComparator } from '../util/misc';\n\n// The earliest date supported by Firestore timestamps (0001-01-01T00:00:00Z).\nconst MIN_SECONDS = -62135596800;\n\n// Number of nanoseconds in a millisecond.\nconst MS_TO_NANOS = 1e6;\n\n/**\n * A `Timestamp` represents a point in time independent of any time zone or\n * calendar, represented as seconds and fractions of seconds at nanosecond\n * resolution in UTC Epoch time.\n *\n * It is encoded using the Proleptic Gregorian Calendar which extends the\n * Gregorian calendar backwards to year one. It is encoded assuming all minutes\n * are 60 seconds long, i.e. leap seconds are \"smeared\" so that no leap second\n * table is needed for interpretation. Range is from 0001-01-01T00:00:00Z to\n * 9999-12-31T23:59:59.999999999Z.\n *\n * For examples and further specifications, refer to the\n * {@link https://github.com/google/protobuf/blob/master/src/google/protobuf/timestamp.proto | Timestamp definition}.\n */\nexport class Timestamp {\n /**\n * Creates a new timestamp with the current date, with millisecond precision.\n *\n * @returns a new timestamp representing the current date.\n */\n static now(): Timestamp {\n return Timestamp.fromMillis(Date.now());\n }\n\n /**\n * Creates a new timestamp from the given date.\n *\n * @param date - The date to initialize the `Timestamp` from.\n * @returns A new `Timestamp` representing the same point in time as the given\n * date.\n */\n static fromDate(date: Date): Timestamp {\n return Timestamp.fromMillis(date.getTime());\n }\n\n /**\n * Creates a new timestamp from the given number of milliseconds.\n *\n * @param milliseconds - Number of milliseconds since Unix epoch\n * 1970-01-01T00:00:00Z.\n * @returns A new `Timestamp` representing the same point in time as the given\n * number of milliseconds.\n */\n static fromMillis(milliseconds: number): Timestamp {\n const seconds = Math.floor(milliseconds / 1000);\n const nanos = Math.floor((milliseconds - seconds * 1000) * MS_TO_NANOS);\n return new Timestamp(seconds, nanos);\n }\n\n /**\n * Creates a new timestamp.\n *\n * @param seconds - The number of seconds of UTC time since Unix epoch\n * 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to\n * 9999-12-31T23:59:59Z inclusive.\n * @param nanoseconds - The non-negative fractions of a second at nanosecond\n * resolution. Negative second values with fractions must still have\n * non-negative nanoseconds values that count forward in time. Must be\n * from 0 to 999,999,999 inclusive.\n */\n constructor(\n /**\n * The number of seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z.\n */\n readonly seconds: number,\n /**\n * The fractions of a second at nanosecond resolution.*\n */\n readonly nanoseconds: number\n ) {\n if (nanoseconds < 0) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Timestamp nanoseconds out of range: ' + nanoseconds\n );\n }\n if (nanoseconds >= 1e9) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Timestamp nanoseconds out of range: ' + nanoseconds\n );\n }\n if (seconds < MIN_SECONDS) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Timestamp seconds out of range: ' + seconds\n );\n }\n // This will break in the year 10,000.\n if (seconds >= 253402300800) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Timestamp seconds out of range: ' + seconds\n );\n }\n }\n\n /**\n * Converts a `Timestamp` to a JavaScript `Date` object. This conversion\n * causes a loss of precision since `Date` objects only support millisecond\n * precision.\n *\n * @returns JavaScript `Date` object representing the same point in time as\n * this `Timestamp`, with millisecond precision.\n */\n toDate(): Date {\n return new Date(this.toMillis());\n }\n\n /**\n * Converts a `Timestamp` to a numeric timestamp (in milliseconds since\n * epoch). This operation causes a loss of precision.\n *\n * @returns The point in time corresponding to this timestamp, represented as\n * the number of milliseconds since Unix epoch 1970-01-01T00:00:00Z.\n */\n toMillis(): number {\n return this.seconds * 1000 + this.nanoseconds / MS_TO_NANOS;\n }\n\n _compareTo(other: Timestamp): number {\n if (this.seconds === other.seconds) {\n return primitiveComparator(this.nanoseconds, other.nanoseconds);\n }\n return primitiveComparator(this.seconds, other.seconds);\n }\n\n /**\n * Returns true if this `Timestamp` is equal to the provided one.\n *\n * @param other - The `Timestamp` to compare against.\n * @returns true if this `Timestamp` is equal to the provided one.\n */\n isEqual(other: Timestamp): boolean {\n return (\n other.seconds === this.seconds && other.nanoseconds === this.nanoseconds\n );\n }\n\n /** Returns a textual representation of this `Timestamp`. */\n toString(): string {\n return (\n 'Timestamp(seconds=' +\n this.seconds +\n ', nanoseconds=' +\n this.nanoseconds +\n ')'\n );\n }\n\n static _jsonSchemaVersion: string = 'firestore/timestamp/1.0';\n static _jsonSchema = {\n type: property('string', Timestamp._jsonSchemaVersion),\n seconds: property('number'),\n nanoseconds: property('number')\n };\n\n /**\n * Returns a JSON-serializable representation of this `Timestamp`.\n */\n toJSON(): { seconds: number; nanoseconds: number; type: string } {\n return {\n type: Timestamp._jsonSchemaVersion,\n seconds: this.seconds,\n nanoseconds: this.nanoseconds\n };\n }\n\n /**\n * Builds a `Timestamp` instance from a JSON object created by {@link Timestamp.toJSON}.\n */\n static fromJSON(json: object): Timestamp {\n if (validateJSON(json, Timestamp._jsonSchema)) {\n return new Timestamp(json.seconds, json.nanoseconds);\n }\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Unexpected error creating Timestamp from JSON.'\n );\n }\n\n /**\n * Converts this object to a primitive string, which allows `Timestamp` objects\n * to be compared using the `>`, `<=`, `>=` and `>` operators.\n */\n valueOf(): string {\n // This method returns a string of the form . where\n // is translated to have a non-negative value and both \n // and are left-padded with zeroes to be a consistent length.\n // Strings with this format then have a lexicographical ordering that matches\n // the expected ordering. The translation is done to avoid having\n // a leading negative sign (i.e. a leading '-' character) in its string\n // representation, which would affect its lexicographical ordering.\n const adjustedSeconds = this.seconds - MIN_SECONDS;\n // Note: Up to 12 decimal digits are required to represent all valid\n // 'seconds' values.\n const formattedSeconds = String(adjustedSeconds).padStart(12, '0');\n const formattedNanoseconds = String(this.nanoseconds).padStart(9, '0');\n return formattedSeconds + '.' + formattedNanoseconds;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Timestamp } from '../lite-api/timestamp';\nimport {\n Value as ProtoValue,\n MapValue as ProtoMapValue\n} from '../protos/firestore_proto_api';\n\nimport { normalizeTimestamp } from './normalize';\n\n/**\n * Represents a locally-applied ServerTimestamp.\n *\n * Server Timestamps are backed by MapValues that contain an internal field\n * `__type__` with a value of `server_timestamp`. The previous value and local\n * write time are stored in its `__previous_value__` and `__local_write_time__`\n * fields respectively.\n *\n * Notes:\n * - ServerTimestampValue instances are created as the result of applying a\n * transform. They can only exist in the local view of a document. Therefore\n * they do not need to be parsed or serialized.\n * - When evaluated locally (e.g. for snapshot.data()), they by default\n * evaluate to `null`. This behavior can be configured by passing custom\n * FieldValueOptions to value().\n * - With respect to other ServerTimestampValues, they sort by their\n * localWriteTime.\n */\n\nconst SERVER_TIMESTAMP_SENTINEL = 'server_timestamp';\nconst TYPE_KEY = '__type__';\nconst PREVIOUS_VALUE_KEY = '__previous_value__';\nconst LOCAL_WRITE_TIME_KEY = '__local_write_time__';\n\nexport function isServerTimestamp(value: ProtoValue | null): boolean {\n const type = (value?.mapValue?.fields || {})[TYPE_KEY]?.stringValue;\n return type === SERVER_TIMESTAMP_SENTINEL;\n}\n\n/**\n * Creates a new ServerTimestamp proto value (using the internal format).\n */\nexport function serverTimestamp(\n localWriteTime: Timestamp,\n previousValue: ProtoValue | null\n): ProtoValue {\n const mapValue: ProtoMapValue = {\n fields: {\n [TYPE_KEY]: {\n stringValue: SERVER_TIMESTAMP_SENTINEL\n },\n [LOCAL_WRITE_TIME_KEY]: {\n timestampValue: {\n seconds: localWriteTime.seconds,\n nanos: localWriteTime.nanoseconds\n }\n }\n }\n };\n\n // We should avoid storing deeply nested server timestamp map values\n // because we never use the intermediate \"previous values\".\n // For example:\n // previous: 42L, add: t1, result: t1 -> 42L\n // previous: t1, add: t2, result: t2 -> 42L (NOT t2 -> t1 -> 42L)\n // previous: t2, add: t3, result: t3 -> 42L (NOT t3 -> t2 -> t1 -> 42L)\n // `getPreviousValue` recursively traverses server timestamps to find the\n // least recent Value.\n if (previousValue && isServerTimestamp(previousValue)) {\n previousValue = getPreviousValue(previousValue);\n }\n if (previousValue) {\n mapValue.fields![PREVIOUS_VALUE_KEY] = previousValue;\n }\n\n return { mapValue };\n}\n\n/**\n * Returns the value of the field before this ServerTimestamp was set.\n *\n * Preserving the previous values allows the user to display the last resoled\n * value until the backend responds with the timestamp.\n */\nexport function getPreviousValue(value: ProtoValue): ProtoValue | null {\n const previousValue = value.mapValue!.fields![PREVIOUS_VALUE_KEY];\n\n if (isServerTimestamp(previousValue)) {\n return getPreviousValue(previousValue);\n }\n return previousValue;\n}\n\n/**\n * Returns the local time at which this timestamp was first set.\n */\nexport function getLocalWriteTime(value: ProtoValue): Timestamp {\n const localWriteTime = normalizeTimestamp(\n value.mapValue!.fields![LOCAL_WRITE_TIME_KEY].timestampValue!\n );\n return new Timestamp(localWriteTime.seconds, localWriteTime.nanos);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DatabaseId } from '../core/database_info';\nimport {\n ArrayValue,\n LatLng,\n MapValue,\n Timestamp,\n Value as ProtoValue,\n Value\n} from '../protos/firestore_proto_api';\nimport { fail } from '../util/assert';\nimport {\n arrayEquals,\n compareUtf8Strings,\n primitiveComparator\n} from '../util/misc';\nimport { forEach, objectSize } from '../util/obj';\nimport { isNegativeZero } from '../util/types';\n\nimport { DocumentKey } from './document_key';\nimport {\n normalizeByteString,\n normalizeNumber,\n normalizeTimestamp\n} from './normalize';\nimport {\n getLocalWriteTime,\n getPreviousValue,\n isServerTimestamp\n} from './server_timestamps';\nimport { TypeOrder } from './type_order';\n\nexport const TYPE_KEY = '__type__';\nconst MAX_VALUE_TYPE = '__max__';\nexport const MAX_VALUE: Value = {\n mapValue: {\n fields: {\n '__type__': { stringValue: MAX_VALUE_TYPE }\n }\n }\n};\n\nexport const VECTOR_VALUE_SENTINEL = '__vector__';\nexport const VECTOR_MAP_VECTORS_KEY = 'value';\n\nexport const MIN_VALUE: Value = {\n nullValue: 'NULL_VALUE'\n};\n\n/** Extracts the backend's type order for the provided value. */\nexport function typeOrder(value: Value): TypeOrder {\n if ('nullValue' in value) {\n return TypeOrder.NullValue;\n } else if ('booleanValue' in value) {\n return TypeOrder.BooleanValue;\n } else if ('integerValue' in value || 'doubleValue' in value) {\n return TypeOrder.NumberValue;\n } else if ('timestampValue' in value) {\n return TypeOrder.TimestampValue;\n } else if ('stringValue' in value) {\n return TypeOrder.StringValue;\n } else if ('bytesValue' in value) {\n return TypeOrder.BlobValue;\n } else if ('referenceValue' in value) {\n return TypeOrder.RefValue;\n } else if ('geoPointValue' in value) {\n return TypeOrder.GeoPointValue;\n } else if ('arrayValue' in value) {\n return TypeOrder.ArrayValue;\n } else if ('mapValue' in value) {\n if (isServerTimestamp(value)) {\n return TypeOrder.ServerTimestampValue;\n } else if (isMaxValue(value)) {\n return TypeOrder.MaxValue;\n } else if (isVectorValue(value)) {\n return TypeOrder.VectorValue;\n }\n return TypeOrder.ObjectValue;\n } else {\n return fail(0x6e87, 'Invalid value type', { value });\n }\n}\n\n/** Tests `left` and `right` for equality based on the backend semantics. */\nexport function valueEquals(left: Value, right: Value): boolean {\n if (left === right) {\n return true;\n }\n\n const leftType = typeOrder(left);\n const rightType = typeOrder(right);\n if (leftType !== rightType) {\n return false;\n }\n\n switch (leftType) {\n case TypeOrder.NullValue:\n return true;\n case TypeOrder.BooleanValue:\n return left.booleanValue === right.booleanValue;\n case TypeOrder.ServerTimestampValue:\n return getLocalWriteTime(left).isEqual(getLocalWriteTime(right));\n case TypeOrder.TimestampValue:\n return timestampEquals(left, right);\n case TypeOrder.StringValue:\n return left.stringValue === right.stringValue;\n case TypeOrder.BlobValue:\n return blobEquals(left, right);\n case TypeOrder.RefValue:\n return left.referenceValue === right.referenceValue;\n case TypeOrder.GeoPointValue:\n return geoPointEquals(left, right);\n case TypeOrder.NumberValue:\n return numberEquals(left, right);\n case TypeOrder.ArrayValue:\n return arrayEquals(\n left.arrayValue!.values || [],\n right.arrayValue!.values || [],\n valueEquals\n );\n case TypeOrder.VectorValue:\n case TypeOrder.ObjectValue:\n return objectEquals(left, right);\n case TypeOrder.MaxValue:\n return true;\n default:\n return fail(0xcbf8, 'Unexpected value type', { left });\n }\n}\n\nfunction timestampEquals(left: Value, right: Value): boolean {\n if (\n typeof left.timestampValue === 'string' &&\n typeof right.timestampValue === 'string' &&\n left.timestampValue.length === right.timestampValue.length\n ) {\n // Use string equality for ISO 8601 timestamps\n return left.timestampValue === right.timestampValue;\n }\n\n const leftTimestamp = normalizeTimestamp(left.timestampValue!);\n const rightTimestamp = normalizeTimestamp(right.timestampValue!);\n return (\n leftTimestamp.seconds === rightTimestamp.seconds &&\n leftTimestamp.nanos === rightTimestamp.nanos\n );\n}\n\nfunction geoPointEquals(left: Value, right: Value): boolean {\n return (\n normalizeNumber(left.geoPointValue!.latitude) ===\n normalizeNumber(right.geoPointValue!.latitude) &&\n normalizeNumber(left.geoPointValue!.longitude) ===\n normalizeNumber(right.geoPointValue!.longitude)\n );\n}\n\nfunction blobEquals(left: Value, right: Value): boolean {\n return normalizeByteString(left.bytesValue!).isEqual(\n normalizeByteString(right.bytesValue!)\n );\n}\n\nexport function numberEquals(left: Value, right: Value): boolean {\n if ('integerValue' in left && 'integerValue' in right) {\n return (\n normalizeNumber(left.integerValue) === normalizeNumber(right.integerValue)\n );\n } else if ('doubleValue' in left && 'doubleValue' in right) {\n const n1 = normalizeNumber(left.doubleValue!);\n const n2 = normalizeNumber(right.doubleValue!);\n\n if (n1 === n2) {\n return isNegativeZero(n1) === isNegativeZero(n2);\n } else {\n return isNaN(n1) && isNaN(n2);\n }\n }\n\n return false;\n}\n\nfunction objectEquals(left: Value, right: Value): boolean {\n const leftMap = left.mapValue!.fields || {};\n const rightMap = right.mapValue!.fields || {};\n\n if (objectSize(leftMap) !== objectSize(rightMap)) {\n return false;\n }\n\n for (const key in leftMap) {\n if (leftMap.hasOwnProperty(key)) {\n if (\n rightMap[key] === undefined ||\n !valueEquals(leftMap[key], rightMap[key])\n ) {\n return false;\n }\n }\n }\n return true;\n}\n\n/** Returns true if the ArrayValue contains the specified element. */\nexport function arrayValueContains(\n haystack: ArrayValue,\n needle: Value\n): boolean {\n return (\n (haystack.values || []).find(v => valueEquals(v, needle)) !== undefined\n );\n}\n\nexport function valueCompare(left: Value, right: Value): number {\n if (left === right) {\n return 0;\n }\n\n const leftType = typeOrder(left);\n const rightType = typeOrder(right);\n\n if (leftType !== rightType) {\n return primitiveComparator(leftType, rightType);\n }\n\n switch (leftType) {\n case TypeOrder.NullValue:\n case TypeOrder.MaxValue:\n return 0;\n case TypeOrder.BooleanValue:\n return primitiveComparator(left.booleanValue!, right.booleanValue!);\n case TypeOrder.NumberValue:\n return compareNumbers(left, right);\n case TypeOrder.TimestampValue:\n return compareTimestamps(left.timestampValue!, right.timestampValue!);\n case TypeOrder.ServerTimestampValue:\n return compareTimestamps(\n getLocalWriteTime(left),\n getLocalWriteTime(right)\n );\n case TypeOrder.StringValue:\n return compareUtf8Strings(left.stringValue!, right.stringValue!);\n case TypeOrder.BlobValue:\n return compareBlobs(left.bytesValue!, right.bytesValue!);\n case TypeOrder.RefValue:\n return compareReferences(left.referenceValue!, right.referenceValue!);\n case TypeOrder.GeoPointValue:\n return compareGeoPoints(left.geoPointValue!, right.geoPointValue!);\n case TypeOrder.ArrayValue:\n return compareArrays(left.arrayValue!, right.arrayValue!);\n case TypeOrder.VectorValue:\n return compareVectors(left.mapValue!, right.mapValue!);\n case TypeOrder.ObjectValue:\n return compareMaps(left.mapValue!, right.mapValue!);\n default:\n throw fail(0x5ae0, 'Invalid value type', { leftType });\n }\n}\n\nfunction compareNumbers(left: Value, right: Value): number {\n const leftNumber = normalizeNumber(left.integerValue || left.doubleValue);\n const rightNumber = normalizeNumber(right.integerValue || right.doubleValue);\n\n if (leftNumber < rightNumber) {\n return -1;\n } else if (leftNumber > rightNumber) {\n return 1;\n } else if (leftNumber === rightNumber) {\n return 0;\n } else {\n // one or both are NaN.\n if (isNaN(leftNumber)) {\n return isNaN(rightNumber) ? 0 : -1;\n } else {\n return 1;\n }\n }\n}\n\nfunction compareTimestamps(left: Timestamp, right: Timestamp): number {\n if (\n typeof left === 'string' &&\n typeof right === 'string' &&\n left.length === right.length\n ) {\n return primitiveComparator(left, right);\n }\n\n const leftTimestamp = normalizeTimestamp(left);\n const rightTimestamp = normalizeTimestamp(right);\n\n const comparison = primitiveComparator(\n leftTimestamp.seconds,\n rightTimestamp.seconds\n );\n if (comparison !== 0) {\n return comparison;\n }\n return primitiveComparator(leftTimestamp.nanos, rightTimestamp.nanos);\n}\n\nfunction compareReferences(leftPath: string, rightPath: string): number {\n const leftSegments = leftPath.split('/');\n const rightSegments = rightPath.split('/');\n for (let i = 0; i < leftSegments.length && i < rightSegments.length; i++) {\n const comparison = primitiveComparator(leftSegments[i], rightSegments[i]);\n if (comparison !== 0) {\n return comparison;\n }\n }\n return primitiveComparator(leftSegments.length, rightSegments.length);\n}\n\nfunction compareGeoPoints(left: LatLng, right: LatLng): number {\n const comparison = primitiveComparator(\n normalizeNumber(left.latitude),\n normalizeNumber(right.latitude)\n );\n if (comparison !== 0) {\n return comparison;\n }\n return primitiveComparator(\n normalizeNumber(left.longitude),\n normalizeNumber(right.longitude)\n );\n}\n\nfunction compareBlobs(\n left: string | Uint8Array,\n right: string | Uint8Array\n): number {\n const leftBytes = normalizeByteString(left);\n const rightBytes = normalizeByteString(right);\n return leftBytes.compareTo(rightBytes);\n}\n\nfunction compareArrays(left: ArrayValue, right: ArrayValue): number {\n const leftArray = left.values || [];\n const rightArray = right.values || [];\n\n for (let i = 0; i < leftArray.length && i < rightArray.length; ++i) {\n const compare = valueCompare(leftArray[i], rightArray[i]);\n if (compare) {\n return compare;\n }\n }\n return primitiveComparator(leftArray.length, rightArray.length);\n}\n\nfunction compareVectors(left: MapValue, right: MapValue): number {\n const leftMap = left.fields || {};\n const rightMap = right.fields || {};\n\n // The vector is a map, but only vector value is compared.\n const leftArrayValue = leftMap[VECTOR_MAP_VECTORS_KEY]?.arrayValue;\n const rightArrayValue = rightMap[VECTOR_MAP_VECTORS_KEY]?.arrayValue;\n\n const lengthCompare = primitiveComparator(\n leftArrayValue?.values?.length || 0,\n rightArrayValue?.values?.length || 0\n );\n if (lengthCompare !== 0) {\n return lengthCompare;\n }\n\n return compareArrays(leftArrayValue!, rightArrayValue!);\n}\n\nfunction compareMaps(left: MapValue, right: MapValue): number {\n if (left === MAX_VALUE.mapValue && right === MAX_VALUE.mapValue) {\n return 0;\n } else if (left === MAX_VALUE.mapValue) {\n return 1;\n } else if (right === MAX_VALUE.mapValue) {\n return -1;\n }\n\n const leftMap = left.fields || {};\n const leftKeys = Object.keys(leftMap);\n const rightMap = right.fields || {};\n const rightKeys = Object.keys(rightMap);\n\n // Even though MapValues are likely sorted correctly based on their insertion\n // order (e.g. when received from the backend), local modifications can bring\n // elements out of order. We need to re-sort the elements to ensure that\n // canonical IDs are independent of insertion order.\n leftKeys.sort();\n rightKeys.sort();\n\n for (let i = 0; i < leftKeys.length && i < rightKeys.length; ++i) {\n const keyCompare = compareUtf8Strings(leftKeys[i], rightKeys[i]);\n if (keyCompare !== 0) {\n return keyCompare;\n }\n const compare = valueCompare(leftMap[leftKeys[i]], rightMap[rightKeys[i]]);\n if (compare !== 0) {\n return compare;\n }\n }\n\n return primitiveComparator(leftKeys.length, rightKeys.length);\n}\n\n/**\n * Generates the canonical ID for the provided field value (as used in Target\n * serialization).\n */\nexport function canonicalId(value: Value): string {\n return canonifyValue(value);\n}\n\nfunction canonifyValue(value: Value): string {\n if ('nullValue' in value) {\n return 'null';\n } else if ('booleanValue' in value) {\n return '' + value.booleanValue!;\n } else if ('integerValue' in value) {\n return '' + value.integerValue!;\n } else if ('doubleValue' in value) {\n return '' + value.doubleValue!;\n } else if ('timestampValue' in value) {\n return canonifyTimestamp(value.timestampValue!);\n } else if ('stringValue' in value) {\n return value.stringValue!;\n } else if ('bytesValue' in value) {\n return canonifyByteString(value.bytesValue!);\n } else if ('referenceValue' in value) {\n return canonifyReference(value.referenceValue!);\n } else if ('geoPointValue' in value) {\n return canonifyGeoPoint(value.geoPointValue!);\n } else if ('arrayValue' in value) {\n return canonifyArray(value.arrayValue!);\n } else if ('mapValue' in value) {\n return canonifyMap(value.mapValue!);\n } else {\n return fail(0xee4d, 'Invalid value type', { value });\n }\n}\n\nfunction canonifyByteString(byteString: string | Uint8Array): string {\n return normalizeByteString(byteString).toBase64();\n}\n\nfunction canonifyTimestamp(timestamp: Timestamp): string {\n const normalizedTimestamp = normalizeTimestamp(timestamp);\n return `time(${normalizedTimestamp.seconds},${normalizedTimestamp.nanos})`;\n}\n\nfunction canonifyGeoPoint(geoPoint: LatLng): string {\n return `geo(${geoPoint.latitude},${geoPoint.longitude})`;\n}\n\nfunction canonifyReference(referenceValue: string): string {\n return DocumentKey.fromName(referenceValue).toString();\n}\n\nfunction canonifyMap(mapValue: MapValue): string {\n // Iteration order in JavaScript is not guaranteed. To ensure that we generate\n // matching canonical IDs for identical maps, we need to sort the keys.\n const sortedKeys = Object.keys(mapValue.fields || {}).sort();\n\n let result = '{';\n let first = true;\n for (const key of sortedKeys) {\n if (!first) {\n result += ',';\n } else {\n first = false;\n }\n result += `${key}:${canonifyValue(mapValue.fields![key])}`;\n }\n return result + '}';\n}\n\nfunction canonifyArray(arrayValue: ArrayValue): string {\n let result = '[';\n let first = true;\n for (const value of arrayValue.values || []) {\n if (!first) {\n result += ',';\n } else {\n first = false;\n }\n result += canonifyValue(value);\n }\n return result + ']';\n}\n\n/**\n * Returns an approximate (and wildly inaccurate) in-memory size for the field\n * value.\n *\n * The memory size takes into account only the actual user data as it resides\n * in memory and ignores object overhead.\n */\nexport function estimateByteSize(value: Value): number {\n switch (typeOrder(value)) {\n case TypeOrder.NullValue:\n return 4;\n case TypeOrder.BooleanValue:\n return 4;\n case TypeOrder.NumberValue:\n return 8;\n case TypeOrder.TimestampValue:\n // Timestamps are made up of two distinct numbers (seconds + nanoseconds)\n return 16;\n case TypeOrder.ServerTimestampValue:\n const previousValue = getPreviousValue(value);\n return previousValue ? 16 + estimateByteSize(previousValue) : 16;\n case TypeOrder.StringValue:\n // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures:\n // \"JavaScript's String type is [...] a set of elements of 16-bit unsigned\n // integer values\"\n return value.stringValue!.length * 2;\n case TypeOrder.BlobValue:\n return normalizeByteString(value.bytesValue!).approximateByteSize();\n case TypeOrder.RefValue:\n return value.referenceValue!.length;\n case TypeOrder.GeoPointValue:\n // GeoPoints are made up of two distinct numbers (latitude + longitude)\n return 16;\n case TypeOrder.ArrayValue:\n return estimateArrayByteSize(value.arrayValue!);\n case TypeOrder.VectorValue:\n case TypeOrder.ObjectValue:\n return estimateMapByteSize(value.mapValue!);\n default:\n throw fail(0x34ae, 'Invalid value type', { value });\n }\n}\n\nfunction estimateMapByteSize(mapValue: MapValue): number {\n let size = 0;\n forEach(mapValue.fields, (key, val) => {\n size += key.length + estimateByteSize(val);\n });\n return size;\n}\n\nfunction estimateArrayByteSize(arrayValue: ArrayValue): number {\n return (arrayValue.values || []).reduce(\n (previousSize, value) => previousSize + estimateByteSize(value),\n 0\n );\n}\n\n/** Returns a reference value for the provided database and key. */\nexport function refValue(databaseId: DatabaseId, key: DocumentKey): Value {\n return {\n referenceValue: `projects/${databaseId.projectId}/databases/${\n databaseId.database\n }/documents/${key.path.canonicalString()}`\n };\n}\n\n/** Returns true if `value` is an IntegerValue . */\nexport function isInteger(\n value?: Value | null\n): value is { integerValue: string | number } {\n return !!value && 'integerValue' in value;\n}\n\n/** Returns true if `value` is a DoubleValue. */\nexport function isDouble(\n value?: Value | null\n): value is { doubleValue: string | number } {\n return !!value && 'doubleValue' in value;\n}\n\n/** Returns true if `value` is either an IntegerValue or a DoubleValue. */\nexport function isNumber(value?: Value | null): boolean {\n return isInteger(value) || isDouble(value);\n}\n\n/** Returns true if `value` is an ArrayValue. */\nexport function isArray(\n value?: Value | null\n): value is { arrayValue: ArrayValue } {\n return !!value && 'arrayValue' in value;\n}\n\n/** Returns true if `value` is a ReferenceValue. */\nexport function isReferenceValue(\n value?: Value | null\n): value is { referenceValue: string } {\n return !!value && 'referenceValue' in value;\n}\n\n/** Returns true if `value` is a NullValue. */\nexport function isNullValue(\n value?: Value | null\n): value is { nullValue: 'NULL_VALUE' } {\n return !!value && 'nullValue' in value;\n}\n\n/** Returns true if `value` is NaN. */\nexport function isNanValue(\n value?: Value | null\n): value is { doubleValue: 'NaN' | number } {\n return !!value && 'doubleValue' in value && isNaN(Number(value.doubleValue));\n}\n\n/** Returns true if `value` is a MapValue. */\nexport function isMapValue(\n value?: Value | null\n): value is { mapValue: MapValue } {\n return !!value && 'mapValue' in value;\n}\n\n/** Returns true if `value` is a VetorValue. */\nexport function isVectorValue(value: ProtoValue | null): boolean {\n const type = (value?.mapValue?.fields || {})[TYPE_KEY]?.stringValue;\n return type === VECTOR_VALUE_SENTINEL;\n}\n\n/** Creates a deep copy of `source`. */\nexport function deepClone(source: Value): Value {\n if (source.geoPointValue) {\n return { geoPointValue: { ...source.geoPointValue } };\n } else if (\n source.timestampValue &&\n typeof source.timestampValue === 'object'\n ) {\n return { timestampValue: { ...source.timestampValue } };\n } else if (source.mapValue) {\n const target: Value = { mapValue: { fields: {} } };\n forEach(\n source.mapValue.fields,\n (key, val) => (target.mapValue!.fields![key] = deepClone(val))\n );\n return target;\n } else if (source.arrayValue) {\n const target: Value = { arrayValue: { values: [] } };\n for (let i = 0; i < (source.arrayValue.values || []).length; ++i) {\n target.arrayValue!.values![i] = deepClone(source.arrayValue.values![i]);\n }\n return target;\n } else {\n return { ...source };\n }\n}\n\n/** Returns true if the Value represents the canonical {@link #MAX_VALUE} . */\nexport function isMaxValue(value: Value): boolean {\n return (\n (((value.mapValue || {}).fields || {})['__type__'] || {}).stringValue ===\n MAX_VALUE_TYPE\n );\n}\n\nexport const MIN_VECTOR_VALUE = {\n mapValue: {\n fields: {\n [TYPE_KEY]: { stringValue: VECTOR_VALUE_SENTINEL },\n [VECTOR_MAP_VECTORS_KEY]: {\n arrayValue: {}\n }\n }\n }\n};\n\n/** Returns the lowest value for the given value type (inclusive). */\nexport function valuesGetLowerBound(value: Value): Value {\n if ('nullValue' in value) {\n return MIN_VALUE;\n } else if ('booleanValue' in value) {\n return { booleanValue: false };\n } else if ('integerValue' in value || 'doubleValue' in value) {\n return { doubleValue: NaN };\n } else if ('timestampValue' in value) {\n return { timestampValue: { seconds: Number.MIN_SAFE_INTEGER } };\n } else if ('stringValue' in value) {\n return { stringValue: '' };\n } else if ('bytesValue' in value) {\n return { bytesValue: '' };\n } else if ('referenceValue' in value) {\n return refValue(DatabaseId.empty(), DocumentKey.empty());\n } else if ('geoPointValue' in value) {\n return { geoPointValue: { latitude: -90, longitude: -180 } };\n } else if ('arrayValue' in value) {\n return { arrayValue: {} };\n } else if ('mapValue' in value) {\n if (isVectorValue(value)) {\n return MIN_VECTOR_VALUE;\n }\n return { mapValue: {} };\n } else {\n return fail(0x8c66, 'Invalid value type', { value });\n }\n}\n\n/** Returns the largest value for the given value type (exclusive). */\nexport function valuesGetUpperBound(value: Value): Value {\n if ('nullValue' in value) {\n return { booleanValue: false };\n } else if ('booleanValue' in value) {\n return { doubleValue: NaN };\n } else if ('integerValue' in value || 'doubleValue' in value) {\n return { timestampValue: { seconds: Number.MIN_SAFE_INTEGER } };\n } else if ('timestampValue' in value) {\n return { stringValue: '' };\n } else if ('stringValue' in value) {\n return { bytesValue: '' };\n } else if ('bytesValue' in value) {\n return refValue(DatabaseId.empty(), DocumentKey.empty());\n } else if ('referenceValue' in value) {\n return { geoPointValue: { latitude: -90, longitude: -180 } };\n } else if ('geoPointValue' in value) {\n return { arrayValue: {} };\n } else if ('arrayValue' in value) {\n return MIN_VECTOR_VALUE;\n } else if ('mapValue' in value) {\n if (isVectorValue(value)) {\n return { mapValue: {} };\n }\n return MAX_VALUE;\n } else {\n return fail(0xf207, 'Invalid value type', { value });\n }\n}\n\nexport function lowerBoundCompare(\n left: { value: Value; inclusive: boolean },\n right: { value: Value; inclusive: boolean }\n): number {\n const cmp = valueCompare(left.value, right.value);\n if (cmp !== 0) {\n return cmp;\n }\n\n if (left.inclusive && !right.inclusive) {\n return -1;\n } else if (!left.inclusive && right.inclusive) {\n return 1;\n }\n\n return 0;\n}\n\nexport function upperBoundCompare(\n left: { value: Value; inclusive: boolean },\n right: { value: Value; inclusive: boolean }\n): number {\n const cmp = valueCompare(left.value, right.value);\n if (cmp !== 0) {\n return cmp;\n }\n\n if (left.inclusive && !right.inclusive) {\n return 1;\n } else if (!left.inclusive && right.inclusive) {\n return -1;\n }\n\n return 0;\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { isReferenceValue, valueCompare, valueEquals } from '../model/values';\nimport { Value as ProtoValue } from '../protos/firestore_proto_api';\nimport { debugAssert } from '../util/assert';\n\nimport { Direction, OrderBy } from './order_by';\n\n/**\n * Represents a bound of a query.\n *\n * The bound is specified with the given components representing a position and\n * whether it's just before or just after the position (relative to whatever the\n * query order is).\n *\n * The position represents a logical index position for a query. It's a prefix\n * of values for the (potentially implicit) order by clauses of a query.\n *\n * Bound provides a function to determine whether a document comes before or\n * after a bound. This is influenced by whether the position is just before or\n * just after the provided values.\n */\nexport class Bound {\n constructor(readonly position: ProtoValue[], readonly inclusive: boolean) {}\n}\n\nfunction boundCompareToDocument(\n bound: Bound,\n orderBy: OrderBy[],\n doc: Document\n): number {\n debugAssert(\n bound.position.length <= orderBy.length,\n \"Bound has more components than query's orderBy\"\n );\n let comparison = 0;\n for (let i = 0; i < bound.position.length; i++) {\n const orderByComponent = orderBy[i];\n const component = bound.position[i];\n if (orderByComponent.field.isKeyField()) {\n debugAssert(\n isReferenceValue(component),\n 'Bound has a non-key value where the key path is being used.'\n );\n comparison = DocumentKey.comparator(\n DocumentKey.fromName(component.referenceValue),\n doc.key\n );\n } else {\n const docValue = doc.data.field(orderByComponent.field);\n debugAssert(\n docValue !== null,\n 'Field should exist since document matched the orderBy already.'\n );\n comparison = valueCompare(component, docValue);\n }\n if (orderByComponent.dir === Direction.DESCENDING) {\n comparison = comparison * -1;\n }\n if (comparison !== 0) {\n break;\n }\n }\n return comparison;\n}\n\n/**\n * Returns true if a document sorts after a bound using the provided sort\n * order.\n */\nexport function boundSortsAfterDocument(\n bound: Bound,\n orderBy: OrderBy[],\n doc: Document\n): boolean {\n const comparison = boundCompareToDocument(bound, orderBy, doc);\n return bound.inclusive ? comparison >= 0 : comparison > 0;\n}\n\n/**\n * Returns true if a document sorts before a bound using the provided sort\n * order.\n */\nexport function boundSortsBeforeDocument(\n bound: Bound,\n orderBy: OrderBy[],\n doc: Document\n): boolean {\n const comparison = boundCompareToDocument(bound, orderBy, doc);\n return bound.inclusive ? comparison <= 0 : comparison < 0;\n}\n\nexport function boundEquals(left: Bound | null, right: Bound | null): boolean {\n if (left === null) {\n return right === null;\n } else if (right === null) {\n return false;\n }\n\n if (\n left.inclusive !== right.inclusive ||\n left.position.length !== right.position.length\n ) {\n return false;\n }\n for (let i = 0; i < left.position.length; i++) {\n const leftPosition = left.position[i];\n const rightPosition = right.position[i];\n if (!valueEquals(leftPosition, rightPosition)) {\n return false;\n }\n }\n return true;\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { FieldPath } from '../model/path';\nimport {\n arrayValueContains,\n canonicalId,\n isArray,\n isReferenceValue,\n typeOrder,\n valueCompare,\n valueEquals\n} from '../model/values';\nimport { Value as ProtoValue } from '../protos/firestore_proto_api';\nimport { debugAssert, fail } from '../util/assert';\n\n// The operator of a FieldFilter\nexport const enum Operator {\n LESS_THAN = '<',\n LESS_THAN_OR_EQUAL = '<=',\n EQUAL = '==',\n NOT_EQUAL = '!=',\n GREATER_THAN = '>',\n GREATER_THAN_OR_EQUAL = '>=',\n ARRAY_CONTAINS = 'array-contains',\n IN = 'in',\n NOT_IN = 'not-in',\n ARRAY_CONTAINS_ANY = 'array-contains-any'\n}\n\n// The operator of a CompositeFilter\nexport const enum CompositeOperator {\n OR = 'or',\n AND = 'and'\n}\n\nexport abstract class Filter {\n abstract matches(doc: Document): boolean;\n\n abstract getFlattenedFilters(): readonly FieldFilter[];\n\n abstract getFilters(): Filter[];\n}\n\nexport class FieldFilter extends Filter {\n protected constructor(\n public readonly field: FieldPath,\n public readonly op: Operator,\n public readonly value: ProtoValue\n ) {\n super();\n }\n\n /**\n * Creates a filter based on the provided arguments.\n */\n static create(\n field: FieldPath,\n op: Operator,\n value: ProtoValue\n ): FieldFilter {\n if (field.isKeyField()) {\n if (op === Operator.IN || op === Operator.NOT_IN) {\n return this.createKeyFieldInFilter(field, op, value);\n } else {\n debugAssert(\n isReferenceValue(value),\n 'Comparing on key, but filter value not a RefValue'\n );\n debugAssert(\n op !== Operator.ARRAY_CONTAINS && op !== Operator.ARRAY_CONTAINS_ANY,\n `'${op.toString()}' queries don't make sense on document keys.`\n );\n return new KeyFieldFilter(field, op, value);\n }\n } else if (op === Operator.ARRAY_CONTAINS) {\n return new ArrayContainsFilter(field, value);\n } else if (op === Operator.IN) {\n debugAssert(\n isArray(value),\n 'IN filter has invalid value: ' + value.toString()\n );\n return new InFilter(field, value);\n } else if (op === Operator.NOT_IN) {\n debugAssert(\n isArray(value),\n 'NOT_IN filter has invalid value: ' + value.toString()\n );\n return new NotInFilter(field, value);\n } else if (op === Operator.ARRAY_CONTAINS_ANY) {\n debugAssert(\n isArray(value),\n 'ARRAY_CONTAINS_ANY filter has invalid value: ' + value.toString()\n );\n return new ArrayContainsAnyFilter(field, value);\n } else {\n return new FieldFilter(field, op, value);\n }\n }\n\n private static createKeyFieldInFilter(\n field: FieldPath,\n op: Operator.IN | Operator.NOT_IN,\n value: ProtoValue\n ): FieldFilter {\n debugAssert(\n isArray(value),\n `Comparing on key with ${op.toString()}` +\n ', but filter value not an ArrayValue'\n );\n debugAssert(\n (value.arrayValue.values || []).every(elem => isReferenceValue(elem)),\n `Comparing on key with ${op.toString()}` +\n ', but an array value was not a RefValue'\n );\n\n return op === Operator.IN\n ? new KeyFieldInFilter(field, value)\n : new KeyFieldNotInFilter(field, value);\n }\n\n matches(doc: Document): boolean {\n const other = doc.data.field(this.field);\n // Types do not have to match in NOT_EQUAL filters.\n if (this.op === Operator.NOT_EQUAL) {\n return (\n other !== null &&\n other.nullValue === undefined &&\n this.matchesComparison(valueCompare(other!, this.value))\n );\n }\n\n // Only compare types with matching backend order (such as double and int).\n return (\n other !== null &&\n typeOrder(this.value) === typeOrder(other) &&\n this.matchesComparison(valueCompare(other, this.value))\n );\n }\n\n protected matchesComparison(comparison: number): boolean {\n switch (this.op) {\n case Operator.LESS_THAN:\n return comparison < 0;\n case Operator.LESS_THAN_OR_EQUAL:\n return comparison <= 0;\n case Operator.EQUAL:\n return comparison === 0;\n case Operator.NOT_EQUAL:\n return comparison !== 0;\n case Operator.GREATER_THAN:\n return comparison > 0;\n case Operator.GREATER_THAN_OR_EQUAL:\n return comparison >= 0;\n default:\n return fail(0xb8a2, 'Unknown FieldFilter operator', {\n operator: this.op\n });\n }\n }\n\n isInequality(): boolean {\n return (\n [\n Operator.LESS_THAN,\n Operator.LESS_THAN_OR_EQUAL,\n Operator.GREATER_THAN,\n Operator.GREATER_THAN_OR_EQUAL,\n Operator.NOT_EQUAL,\n Operator.NOT_IN\n ].indexOf(this.op) >= 0\n );\n }\n\n getFlattenedFilters(): readonly FieldFilter[] {\n return [this];\n }\n\n getFilters(): Filter[] {\n return [this];\n }\n}\n\nexport class CompositeFilter extends Filter {\n private memoizedFlattenedFilters: FieldFilter[] | null = null;\n\n protected constructor(\n public readonly filters: readonly Filter[],\n public readonly op: CompositeOperator\n ) {\n super();\n }\n\n /**\n * Creates a filter based on the provided arguments.\n */\n static create(filters: Filter[], op: CompositeOperator): CompositeFilter {\n return new CompositeFilter(filters, op);\n }\n\n matches(doc: Document): boolean {\n if (compositeFilterIsConjunction(this)) {\n // For conjunctions, all filters must match, so return false if any filter doesn't match.\n return this.filters.find(filter => !filter.matches(doc)) === undefined;\n } else {\n // For disjunctions, at least one filter should match.\n return this.filters.find(filter => filter.matches(doc)) !== undefined;\n }\n }\n\n getFlattenedFilters(): readonly FieldFilter[] {\n if (this.memoizedFlattenedFilters !== null) {\n return this.memoizedFlattenedFilters;\n }\n\n this.memoizedFlattenedFilters = this.filters.reduce((result, subfilter) => {\n return result.concat(subfilter.getFlattenedFilters());\n }, [] as FieldFilter[]);\n\n return this.memoizedFlattenedFilters;\n }\n\n // Returns a mutable copy of `this.filters`\n getFilters(): Filter[] {\n return Object.assign([], this.filters);\n }\n}\n\nexport function compositeFilterIsConjunction(\n compositeFilter: CompositeFilter\n): boolean {\n return compositeFilter.op === CompositeOperator.AND;\n}\n\nexport function compositeFilterIsDisjunction(\n compositeFilter: CompositeFilter\n): boolean {\n return compositeFilter.op === CompositeOperator.OR;\n}\n\n/**\n * Returns true if this filter is a conjunction of field filters only. Returns false otherwise.\n */\nexport function compositeFilterIsFlatConjunction(\n compositeFilter: CompositeFilter\n): boolean {\n return (\n compositeFilterIsFlat(compositeFilter) &&\n compositeFilterIsConjunction(compositeFilter)\n );\n}\n\n/**\n * Returns true if this filter does not contain any composite filters. Returns false otherwise.\n */\nexport function compositeFilterIsFlat(\n compositeFilter: CompositeFilter\n): boolean {\n for (const filter of compositeFilter.filters) {\n if (filter instanceof CompositeFilter) {\n return false;\n }\n }\n return true;\n}\n\nexport function canonifyFilter(filter: Filter): string {\n debugAssert(\n filter instanceof FieldFilter || filter instanceof CompositeFilter,\n 'canonifyFilter() only supports FieldFilters and CompositeFilters'\n );\n\n if (filter instanceof FieldFilter) {\n // TODO(b/29183165): Technically, this won't be unique if two values have\n // the same description, such as the int 3 and the string \"3\". So we should\n // add the types in here somehow, too.\n return (\n filter.field.canonicalString() +\n filter.op.toString() +\n canonicalId(filter.value)\n );\n } else if (compositeFilterIsFlatConjunction(filter)) {\n // Older SDK versions use an implicit AND operation between their filters.\n // In the new SDK versions, the developer may use an explicit AND filter.\n // To stay consistent with the old usages, we add a special case to ensure\n // the canonical ID for these two are the same. For example:\n // `col.whereEquals(\"a\", 1).whereEquals(\"b\", 2)` should have the same\n // canonical ID as `col.where(and(equals(\"a\",1), equals(\"b\",2)))`.\n return filter.filters.map(filter => canonifyFilter(filter)).join(',');\n } else {\n // filter instanceof CompositeFilter\n const canonicalIdsString = filter.filters\n .map(filter => canonifyFilter(filter))\n .join(',');\n return `${filter.op}(${canonicalIdsString})`;\n }\n}\n\nexport function filterEquals(f1: Filter, f2: Filter): boolean {\n if (f1 instanceof FieldFilter) {\n return fieldFilterEquals(f1, f2);\n } else if (f1 instanceof CompositeFilter) {\n return compositeFilterEquals(f1, f2);\n } else {\n fail(0x4bef, 'Only FieldFilters and CompositeFilters can be compared');\n }\n}\n\nexport function fieldFilterEquals(f1: FieldFilter, f2: Filter): boolean {\n return (\n f2 instanceof FieldFilter &&\n f1.op === f2.op &&\n f1.field.isEqual(f2.field) &&\n valueEquals(f1.value, f2.value)\n );\n}\n\nexport function compositeFilterEquals(\n f1: CompositeFilter,\n f2: Filter\n): boolean {\n if (\n f2 instanceof CompositeFilter &&\n f1.op === f2.op &&\n f1.filters.length === f2.filters.length\n ) {\n const subFiltersMatch: boolean = f1.filters.reduce(\n (result: boolean, f1Filter: Filter, index: number): boolean =>\n result && filterEquals(f1Filter, f2.filters[index]),\n true\n );\n\n return subFiltersMatch;\n }\n\n return false;\n}\n\n/**\n * Returns a new composite filter that contains all filter from\n * `compositeFilter` plus all the given filters in `otherFilters`.\n */\nexport function compositeFilterWithAddedFilters(\n compositeFilter: CompositeFilter,\n otherFilters: Filter[]\n): CompositeFilter {\n const mergedFilters = compositeFilter.filters.concat(otherFilters);\n return CompositeFilter.create(mergedFilters, compositeFilter.op);\n}\n\n/** Returns a debug description for `filter`. */\nexport function stringifyFilter(filter: Filter): string {\n debugAssert(\n filter instanceof FieldFilter || filter instanceof CompositeFilter,\n 'stringifyFilter() only supports FieldFilters and CompositeFilters'\n );\n if (filter instanceof FieldFilter) {\n return stringifyFieldFilter(filter);\n } else if (filter instanceof CompositeFilter) {\n return stringifyCompositeFilter(filter);\n } else {\n return 'Filter';\n }\n}\n\nexport function stringifyCompositeFilter(filter: CompositeFilter): string {\n return (\n filter.op.toString() +\n ` {` +\n filter.getFilters().map(stringifyFilter).join(' ,') +\n '}'\n );\n}\n\nexport function stringifyFieldFilter(filter: FieldFilter): string {\n return `${filter.field.canonicalString()} ${filter.op} ${canonicalId(\n filter.value\n )}`;\n}\n\n/** Filter that matches on key fields (i.e. '__name__'). */\nexport class KeyFieldFilter extends FieldFilter {\n private readonly key: DocumentKey;\n\n constructor(field: FieldPath, op: Operator, value: ProtoValue) {\n super(field, op, value);\n debugAssert(\n isReferenceValue(value),\n 'KeyFieldFilter expects a ReferenceValue'\n );\n this.key = DocumentKey.fromName(value.referenceValue);\n }\n\n matches(doc: Document): boolean {\n const comparison = DocumentKey.comparator(doc.key, this.key);\n return this.matchesComparison(comparison);\n }\n}\n\n/** Filter that matches on key fields within an array. */\nexport class KeyFieldInFilter extends FieldFilter {\n private readonly keys: DocumentKey[];\n\n constructor(field: FieldPath, value: ProtoValue) {\n super(field, Operator.IN, value);\n this.keys = extractDocumentKeysFromArrayValue(Operator.IN, value);\n }\n\n matches(doc: Document): boolean {\n return this.keys.some(key => key.isEqual(doc.key));\n }\n}\n\n/** Filter that matches on key fields not present within an array. */\nexport class KeyFieldNotInFilter extends FieldFilter {\n private readonly keys: DocumentKey[];\n\n constructor(field: FieldPath, value: ProtoValue) {\n super(field, Operator.NOT_IN, value);\n this.keys = extractDocumentKeysFromArrayValue(Operator.NOT_IN, value);\n }\n\n matches(doc: Document): boolean {\n return !this.keys.some(key => key.isEqual(doc.key));\n }\n}\n\nfunction extractDocumentKeysFromArrayValue(\n op: Operator.IN | Operator.NOT_IN,\n value: ProtoValue\n): DocumentKey[] {\n debugAssert(\n isArray(value),\n 'KeyFieldInFilter/KeyFieldNotInFilter expects an ArrayValue'\n );\n return (value.arrayValue?.values || []).map(v => {\n debugAssert(\n isReferenceValue(v),\n `Comparing on key with ${op.toString()}, but an array value was not ` +\n `a ReferenceValue`\n );\n return DocumentKey.fromName(v.referenceValue);\n });\n}\n\n/** A Filter that implements the array-contains operator. */\nexport class ArrayContainsFilter extends FieldFilter {\n constructor(field: FieldPath, value: ProtoValue) {\n super(field, Operator.ARRAY_CONTAINS, value);\n }\n\n matches(doc: Document): boolean {\n const other = doc.data.field(this.field);\n return isArray(other) && arrayValueContains(other.arrayValue, this.value);\n }\n}\n\n/** A Filter that implements the IN operator. */\nexport class InFilter extends FieldFilter {\n constructor(field: FieldPath, value: ProtoValue) {\n super(field, Operator.IN, value);\n debugAssert(isArray(value), 'InFilter expects an ArrayValue');\n }\n\n matches(doc: Document): boolean {\n const other = doc.data.field(this.field);\n return other !== null && arrayValueContains(this.value.arrayValue!, other);\n }\n}\n\n/** A Filter that implements the not-in operator. */\nexport class NotInFilter extends FieldFilter {\n constructor(field: FieldPath, value: ProtoValue) {\n super(field, Operator.NOT_IN, value);\n debugAssert(isArray(value), 'NotInFilter expects an ArrayValue');\n }\n\n matches(doc: Document): boolean {\n if (\n arrayValueContains(this.value.arrayValue!, { nullValue: 'NULL_VALUE' })\n ) {\n return false;\n }\n const other = doc.data.field(this.field);\n return (\n other !== null &&\n other.nullValue === undefined &&\n !arrayValueContains(this.value.arrayValue!, other)\n );\n }\n}\n\n/** A Filter that implements the array-contains-any operator. */\nexport class ArrayContainsAnyFilter extends FieldFilter {\n constructor(field: FieldPath, value: ProtoValue) {\n super(field, Operator.ARRAY_CONTAINS_ANY, value);\n debugAssert(isArray(value), 'ArrayContainsAnyFilter expects an ArrayValue');\n }\n\n matches(doc: Document): boolean {\n const other = doc.data.field(this.field);\n if (!isArray(other) || !other.arrayValue.values) {\n return false;\n }\n return other.arrayValue.values.some(val =>\n arrayValueContains(this.value.arrayValue!, val)\n );\n }\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FieldPath } from '../model/path';\n\n/**\n * The direction of sorting in an order by.\n */\nexport const enum Direction {\n ASCENDING = 'asc',\n DESCENDING = 'desc'\n}\n\n/**\n * An ordering on a field, in some Direction. Direction defaults to ASCENDING.\n */\nexport class OrderBy {\n constructor(\n readonly field: FieldPath,\n readonly dir: Direction = Direction.ASCENDING\n ) {}\n}\n\nexport function canonifyOrderBy(orderBy: OrderBy): string {\n // TODO(b/29183165): Make this collision robust.\n return orderBy.field.canonicalString() + orderBy.dir;\n}\n\nexport function stringifyOrderBy(orderBy: OrderBy): string {\n return `${orderBy.field.canonicalString()} (${orderBy.dir})`;\n}\n\nexport function orderByEquals(left: OrderBy, right: OrderBy): boolean {\n return left.dir === right.dir && left.field.isEqual(right.field);\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Timestamp } from '../lite-api/timestamp';\n\n/**\n * A version of a document in Firestore. This corresponds to the version\n * timestamp, such as update_time or read_time.\n */\nexport class SnapshotVersion {\n static fromTimestamp(value: Timestamp): SnapshotVersion {\n return new SnapshotVersion(value);\n }\n\n static min(): SnapshotVersion {\n return new SnapshotVersion(new Timestamp(0, 0));\n }\n\n static max(): SnapshotVersion {\n return new SnapshotVersion(new Timestamp(253402300799, 1e9 - 1));\n }\n\n private constructor(private timestamp: Timestamp) {}\n\n compareTo(other: SnapshotVersion): number {\n return this.timestamp._compareTo(other.timestamp);\n }\n\n isEqual(other: SnapshotVersion): boolean {\n return this.timestamp.isEqual(other.timestamp);\n }\n\n /** Returns a number representation of the version for use in spec tests. */\n toMicroseconds(): number {\n // Convert to microseconds.\n return this.timestamp.seconds * 1e6 + this.timestamp.nanoseconds / 1000;\n }\n\n toString(): string {\n return 'SnapshotVersion(' + this.timestamp.toString() + ')';\n }\n\n toTimestamp(): Timestamp {\n return this.timestamp;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { debugAssert, fail } from './assert';\n\n/*\n * Implementation of an immutable SortedMap using a Left-leaning\n * Red-Black Tree, adapted from the implementation in Mugs\n * (http://mads379.github.com/mugs/) by Mads Hartmann Jensen\n * (mads379@gmail.com).\n *\n * Original paper on Left-leaning Red-Black Trees:\n * http://www.cs.princeton.edu/~rs/talks/LLRB/LLRB.pdf\n *\n * Invariant 1: No red node has a red child\n * Invariant 2: Every leaf path has the same number of black nodes\n * Invariant 3: Only the left child can be red (left leaning)\n */\n\nexport type Comparator = (key1: K, key2: K) => number;\n\nexport interface Entry {\n key: K;\n value: V;\n}\n\n// An immutable sorted map implementation, based on a Left-leaning Red-Black\n// tree.\nexport class SortedMap {\n // visible for testing\n root: LLRBNode | LLRBEmptyNode;\n\n constructor(\n public comparator: Comparator,\n root?: LLRBNode | LLRBEmptyNode\n ) {\n this.root = root ? root : LLRBNode.EMPTY;\n }\n\n // Returns a copy of the map, with the specified key/value added or replaced.\n insert(key: K, value: V): SortedMap {\n return new SortedMap(\n this.comparator,\n this.root\n .insert(key, value, this.comparator)\n .copy(null, null, LLRBNode.BLACK, null, null)\n );\n }\n\n // Returns a copy of the map, with the specified key removed.\n remove(key: K): SortedMap {\n return new SortedMap(\n this.comparator,\n this.root\n .remove(key, this.comparator)\n .copy(null, null, LLRBNode.BLACK, null, null)\n );\n }\n\n // Returns the value of the node with the given key, or null.\n get(key: K): V | null {\n let node = this.root;\n while (!node.isEmpty()) {\n const cmp = this.comparator(key, node.key);\n if (cmp === 0) {\n return node.value;\n } else if (cmp < 0) {\n node = node.left;\n } else if (cmp > 0) {\n node = node.right;\n }\n }\n return null;\n }\n\n // Returns the index of the element in this sorted map, or -1 if it doesn't\n // exist.\n indexOf(key: K): number {\n // Number of nodes that were pruned when descending right\n let prunedNodes = 0;\n let node = this.root;\n while (!node.isEmpty()) {\n const cmp = this.comparator(key, node.key);\n if (cmp === 0) {\n return prunedNodes + node.left.size;\n } else if (cmp < 0) {\n node = node.left;\n } else {\n // Count all nodes left of the node plus the node itself\n prunedNodes += node.left.size + 1;\n node = node.right;\n }\n }\n // Node not found\n return -1;\n }\n\n isEmpty(): boolean {\n return this.root.isEmpty();\n }\n\n // Returns the total number of nodes in the map.\n get size(): number {\n return this.root.size;\n }\n\n // Returns the minimum key in the map.\n minKey(): K | null {\n return this.root.minKey();\n }\n\n // Returns the maximum key in the map.\n maxKey(): K | null {\n return this.root.maxKey();\n }\n\n // Traverses the map in key order and calls the specified action function\n // for each key/value pair. If action returns true, traversal is aborted.\n // Returns the first truthy value returned by action, or the last falsey\n // value returned by action.\n inorderTraversal(action: (k: K, v: V) => T): T {\n return (this.root as LLRBNode).inorderTraversal(action);\n }\n\n forEach(fn: (k: K, v: V) => void): void {\n this.inorderTraversal((k, v) => {\n fn(k, v);\n return false;\n });\n }\n\n toString(): string {\n const descriptions: string[] = [];\n this.inorderTraversal((k, v) => {\n descriptions.push(`${k}:${v}`);\n return false;\n });\n return `{${descriptions.join(', ')}}`;\n }\n\n // Traverses the map in reverse key order and calls the specified action\n // function for each key/value pair. If action returns true, traversal is\n // aborted.\n // Returns the first truthy value returned by action, or the last falsey\n // value returned by action.\n reverseTraversal(action: (k: K, v: V) => T): T {\n return (this.root as LLRBNode).reverseTraversal(action);\n }\n\n // Returns an iterator over the SortedMap.\n getIterator(): SortedMapIterator {\n return new SortedMapIterator(this.root, null, this.comparator, false);\n }\n\n getIteratorFrom(key: K): SortedMapIterator {\n return new SortedMapIterator(this.root, key, this.comparator, false);\n }\n\n getReverseIterator(): SortedMapIterator {\n return new SortedMapIterator(this.root, null, this.comparator, true);\n }\n\n getReverseIteratorFrom(key: K): SortedMapIterator {\n return new SortedMapIterator(this.root, key, this.comparator, true);\n }\n} // end SortedMap\n\n// An iterator over an LLRBNode.\nexport class SortedMapIterator {\n private isReverse: boolean;\n private nodeStack: Array | LLRBEmptyNode>;\n\n constructor(\n node: LLRBNode | LLRBEmptyNode,\n startKey: K | null,\n comparator: Comparator,\n isReverse: boolean\n ) {\n this.isReverse = isReverse;\n this.nodeStack = [];\n\n let cmp = 1;\n while (!node.isEmpty()) {\n cmp = startKey ? comparator(node.key, startKey) : 1;\n // flip the comparison if we're going in reverse\n if (startKey && isReverse) {\n cmp *= -1;\n }\n\n if (cmp < 0) {\n // This node is less than our start key. ignore it\n if (this.isReverse) {\n node = node.left;\n } else {\n node = node.right;\n }\n } else if (cmp === 0) {\n // This node is exactly equal to our start key. Push it on the stack,\n // but stop iterating;\n this.nodeStack.push(node);\n break;\n } else {\n // This node is greater than our start key, add it to the stack and move\n // to the next one\n this.nodeStack.push(node);\n if (this.isReverse) {\n node = node.right;\n } else {\n node = node.left;\n }\n }\n }\n }\n\n getNext(): Entry {\n debugAssert(\n this.nodeStack.length > 0,\n 'getNext() called on iterator when hasNext() is false.'\n );\n\n let node = this.nodeStack.pop()!;\n const result = { key: node.key, value: node.value };\n\n if (this.isReverse) {\n node = node.left;\n while (!node.isEmpty()) {\n this.nodeStack.push(node);\n node = node.right;\n }\n } else {\n node = node.right;\n while (!node.isEmpty()) {\n this.nodeStack.push(node);\n node = node.left;\n }\n }\n\n return result;\n }\n\n hasNext(): boolean {\n return this.nodeStack.length > 0;\n }\n\n peek(): Entry | null {\n if (this.nodeStack.length === 0) {\n return null;\n }\n\n const node = this.nodeStack[this.nodeStack.length - 1];\n return { key: node.key, value: node.value };\n }\n} // end SortedMapIterator\n\n// Represents a node in a Left-leaning Red-Black tree.\nexport class LLRBNode {\n readonly color: boolean;\n readonly left: LLRBNode | LLRBEmptyNode;\n readonly right: LLRBNode | LLRBEmptyNode;\n readonly size: number;\n\n // Empty node is shared between all LLRB trees.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n static EMPTY: LLRBEmptyNode = null as any;\n\n static RED = true;\n static BLACK = false;\n\n constructor(\n public key: K,\n public value: V,\n color?: boolean,\n left?: LLRBNode | LLRBEmptyNode,\n right?: LLRBNode | LLRBEmptyNode\n ) {\n this.color = color != null ? color : LLRBNode.RED;\n this.left = left != null ? left : LLRBNode.EMPTY;\n this.right = right != null ? right : LLRBNode.EMPTY;\n this.size = this.left.size + 1 + this.right.size;\n }\n\n // Returns a copy of the current node, optionally replacing pieces of it.\n copy(\n key: K | null,\n value: V | null,\n color: boolean | null,\n left: LLRBNode | LLRBEmptyNode | null,\n right: LLRBNode | LLRBEmptyNode | null\n ): LLRBNode {\n return new LLRBNode(\n key != null ? key : this.key,\n value != null ? value : this.value,\n color != null ? color : this.color,\n left != null ? left : this.left,\n right != null ? right : this.right\n );\n }\n\n isEmpty(): boolean {\n return false;\n }\n\n // Traverses the tree in key order and calls the specified action function\n // for each node. If action returns true, traversal is aborted.\n // Returns the first truthy value returned by action, or the last falsey\n // value returned by action.\n inorderTraversal(action: (k: K, v: V) => T): T {\n return (\n (this.left as LLRBNode).inorderTraversal(action) ||\n action(this.key, this.value) ||\n (this.right as LLRBNode).inorderTraversal(action)\n );\n }\n\n // Traverses the tree in reverse key order and calls the specified action\n // function for each node. If action returns true, traversal is aborted.\n // Returns the first truthy value returned by action, or the last falsey\n // value returned by action.\n reverseTraversal(action: (k: K, v: V) => T): T {\n return (\n (this.right as LLRBNode).reverseTraversal(action) ||\n action(this.key, this.value) ||\n (this.left as LLRBNode).reverseTraversal(action)\n );\n }\n\n // Returns the minimum node in the tree.\n private min(): LLRBNode {\n if (this.left.isEmpty()) {\n return this;\n } else {\n return (this.left as LLRBNode).min();\n }\n }\n\n // Returns the maximum key in the tree.\n minKey(): K | null {\n return this.min().key;\n }\n\n // Returns the maximum key in the tree.\n maxKey(): K | null {\n if (this.right.isEmpty()) {\n return this.key;\n } else {\n return this.right.maxKey();\n }\n }\n\n // Returns new tree, with the key/value added.\n insert(key: K, value: V, comparator: Comparator): LLRBNode {\n let n: LLRBNode = this;\n const cmp = comparator(key, n.key);\n if (cmp < 0) {\n n = n.copy(null, null, null, n.left.insert(key, value, comparator), null);\n } else if (cmp === 0) {\n n = n.copy(null, value, null, null, null);\n } else {\n n = n.copy(\n null,\n null,\n null,\n null,\n n.right.insert(key, value, comparator)\n );\n }\n return n.fixUp();\n }\n\n private removeMin(): LLRBNode | LLRBEmptyNode {\n if (this.left.isEmpty()) {\n return LLRBNode.EMPTY;\n }\n let n: LLRBNode = this;\n if (!n.left.isRed() && !n.left.left.isRed()) {\n n = n.moveRedLeft();\n }\n n = n.copy(null, null, null, (n.left as LLRBNode).removeMin(), null);\n return n.fixUp();\n }\n\n // Returns new tree, with the specified item removed.\n remove(\n key: K,\n comparator: Comparator\n ): LLRBNode | LLRBEmptyNode {\n let smallest: LLRBNode;\n let n: LLRBNode = this;\n if (comparator(key, n.key) < 0) {\n if (!n.left.isEmpty() && !n.left.isRed() && !n.left.left.isRed()) {\n n = n.moveRedLeft();\n }\n n = n.copy(null, null, null, n.left.remove(key, comparator), null);\n } else {\n if (n.left.isRed()) {\n n = n.rotateRight();\n }\n if (!n.right.isEmpty() && !n.right.isRed() && !n.right.left.isRed()) {\n n = n.moveRedRight();\n }\n if (comparator(key, n.key) === 0) {\n if (n.right.isEmpty()) {\n return LLRBNode.EMPTY;\n } else {\n smallest = (n.right as LLRBNode).min();\n n = n.copy(\n smallest.key,\n smallest.value,\n null,\n null,\n (n.right as LLRBNode).removeMin()\n );\n }\n }\n n = n.copy(null, null, null, null, n.right.remove(key, comparator));\n }\n return n.fixUp();\n }\n\n isRed(): boolean {\n return this.color;\n }\n\n // Returns new tree after performing any needed rotations.\n private fixUp(): LLRBNode {\n let n: LLRBNode = this;\n if (n.right.isRed() && !n.left.isRed()) {\n n = n.rotateLeft();\n }\n if (n.left.isRed() && n.left.left.isRed()) {\n n = n.rotateRight();\n }\n if (n.left.isRed() && n.right.isRed()) {\n n = n.colorFlip();\n }\n return n;\n }\n\n private moveRedLeft(): LLRBNode {\n let n = this.colorFlip();\n if (n.right.left.isRed()) {\n n = n.copy(\n null,\n null,\n null,\n null,\n (n.right as LLRBNode).rotateRight()\n );\n n = n.rotateLeft();\n n = n.colorFlip();\n }\n return n;\n }\n\n private moveRedRight(): LLRBNode {\n let n = this.colorFlip();\n if (n.left.left.isRed()) {\n n = n.rotateRight();\n n = n.colorFlip();\n }\n return n;\n }\n\n private rotateLeft(): LLRBNode {\n const nl = this.copy(null, null, LLRBNode.RED, null, this.right.left);\n return (this.right as LLRBNode).copy(\n null,\n null,\n this.color,\n nl,\n null\n );\n }\n\n private rotateRight(): LLRBNode {\n const nr = this.copy(null, null, LLRBNode.RED, this.left.right, null);\n return (this.left as LLRBNode).copy(null, null, this.color, null, nr);\n }\n\n private colorFlip(): LLRBNode {\n const left = this.left.copy(null, null, !this.left.color, null, null);\n const right = this.right.copy(null, null, !this.right.color, null, null);\n return this.copy(null, null, !this.color, left, right);\n }\n\n // For testing.\n checkMaxDepth(): boolean {\n const blackDepth = this.check();\n if (Math.pow(2.0, blackDepth) <= this.size + 1) {\n return true;\n } else {\n return false;\n }\n }\n\n // In a balanced RB tree, the black-depth (number of black nodes) from root to\n // leaves is equal on both sides. This function verifies that or asserts.\n protected check(): number {\n if (this.isRed() && this.left.isRed()) {\n throw fail(0xaad2, 'Red node has red child', {\n key: this.key,\n value: this.value\n });\n }\n if (this.right.isRed()) {\n throw fail(0x3721, 'Right child of (`key`, `value`) is red', {\n key: this.key,\n value: this.value\n });\n }\n const blackDepth = (this.left as LLRBNode).check();\n if (blackDepth !== (this.right as LLRBNode).check()) {\n throw fail(0x6d2d, 'Black depths differ');\n } else {\n return blackDepth + (this.isRed() ? 0 : 1);\n }\n }\n} // end LLRBNode\n\n// Represents an empty node (a leaf node in the Red-Black Tree).\nexport class LLRBEmptyNode {\n get key(): never {\n throw fail(0xe1a6, 'LLRBEmptyNode has no key.');\n }\n get value(): never {\n throw fail(0x3f0d, 'LLRBEmptyNode has no value.');\n }\n get color(): never {\n throw fail(0x4157, 'LLRBEmptyNode has no color.');\n }\n get left(): never {\n throw fail(0x741e, 'LLRBEmptyNode has no left child.');\n }\n get right(): never {\n throw fail(0x901e, 'LLRBEmptyNode has no right child.');\n }\n size = 0;\n\n // Returns a copy of the current node.\n copy(\n key: K | null,\n value: V | null,\n color: boolean | null,\n left: LLRBNode | LLRBEmptyNode | null,\n right: LLRBNode | LLRBEmptyNode | null\n ): LLRBEmptyNode {\n return this;\n }\n\n // Returns a copy of the tree, with the specified key/value added.\n insert(key: K, value: V, comparator: Comparator): LLRBNode {\n return new LLRBNode(key, value);\n }\n\n // Returns a copy of the tree, with the specified key removed.\n remove(key: K, comparator: Comparator): LLRBEmptyNode {\n return this;\n }\n\n isEmpty(): boolean {\n return true;\n }\n\n inorderTraversal(action: (k: K, v: V) => boolean): boolean {\n return false;\n }\n\n reverseTraversal(action: (k: K, v: V) => boolean): boolean {\n return false;\n }\n\n minKey(): K | null {\n return null;\n }\n\n maxKey(): K | null {\n return null;\n }\n\n isRed(): boolean {\n return false;\n }\n\n // For testing.\n checkMaxDepth(): boolean {\n return true;\n }\n\n protected check(): 0 {\n return 0;\n }\n} // end LLRBEmptyNode\n\nLLRBNode.EMPTY = new LLRBEmptyNode();\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SortedMap, SortedMapIterator } from './sorted_map';\n\n/**\n * SortedSet is an immutable (copy-on-write) collection that holds elements\n * in order specified by the provided comparator.\n *\n * NOTE: if provided comparator returns 0 for two elements, we consider them to\n * be equal!\n */\nexport class SortedSet {\n private data: SortedMap;\n\n constructor(private comparator: (left: T, right: T) => number) {\n this.data = new SortedMap(this.comparator);\n }\n\n has(elem: T): boolean {\n return this.data.get(elem) !== null;\n }\n\n first(): T | null {\n return this.data.minKey();\n }\n\n last(): T | null {\n return this.data.maxKey();\n }\n\n get size(): number {\n return this.data.size;\n }\n\n indexOf(elem: T): number {\n return this.data.indexOf(elem);\n }\n\n /** Iterates elements in order defined by \"comparator\" */\n forEach(cb: (elem: T) => void): void {\n this.data.inorderTraversal((k: T, v: boolean) => {\n cb(k);\n return false;\n });\n }\n\n /** Iterates over `elem`s such that: range[0] <= elem < range[1]. */\n forEachInRange(range: [T, T], cb: (elem: T) => void): void {\n const iter = this.data.getIteratorFrom(range[0]);\n while (iter.hasNext()) {\n const elem = iter.getNext();\n if (this.comparator(elem.key, range[1]) >= 0) {\n return;\n }\n cb(elem.key);\n }\n }\n\n /**\n * Iterates over `elem`s such that: start <= elem until false is returned.\n */\n forEachWhile(cb: (elem: T) => boolean, start?: T): void {\n let iter: SortedMapIterator;\n if (start !== undefined) {\n iter = this.data.getIteratorFrom(start);\n } else {\n iter = this.data.getIterator();\n }\n while (iter.hasNext()) {\n const elem = iter.getNext();\n const result = cb(elem.key);\n if (!result) {\n return;\n }\n }\n }\n\n /** Finds the least element greater than or equal to `elem`. */\n firstAfterOrEqual(elem: T): T | null {\n const iter = this.data.getIteratorFrom(elem);\n return iter.hasNext() ? iter.getNext().key : null;\n }\n\n getIterator(): SortedSetIterator {\n return new SortedSetIterator(this.data.getIterator());\n }\n\n getIteratorFrom(key: T): SortedSetIterator {\n return new SortedSetIterator(this.data.getIteratorFrom(key));\n }\n\n /** Inserts or updates an element */\n add(elem: T): SortedSet {\n return this.copy(this.data.remove(elem).insert(elem, true));\n }\n\n /** Deletes an element */\n delete(elem: T): SortedSet {\n if (!this.has(elem)) {\n return this;\n }\n return this.copy(this.data.remove(elem));\n }\n\n isEmpty(): boolean {\n return this.data.isEmpty();\n }\n\n unionWith(other: SortedSet): SortedSet {\n let result: SortedSet = this;\n\n // Make sure `result` always refers to the larger one of the two sets.\n if (result.size < other.size) {\n result = other;\n other = this;\n }\n\n other.forEach(elem => {\n result = result.add(elem);\n });\n return result;\n }\n\n isEqual(other: SortedSet): boolean {\n if (!(other instanceof SortedSet)) {\n return false;\n }\n if (this.size !== other.size) {\n return false;\n }\n\n const thisIt = this.data.getIterator();\n const otherIt = other.data.getIterator();\n while (thisIt.hasNext()) {\n const thisElem = thisIt.getNext().key;\n const otherElem = otherIt.getNext().key;\n if (this.comparator(thisElem, otherElem) !== 0) {\n return false;\n }\n }\n return true;\n }\n\n toArray(): T[] {\n const res: T[] = [];\n this.forEach(targetId => {\n res.push(targetId);\n });\n return res;\n }\n\n toString(): string {\n const result: T[] = [];\n this.forEach(elem => result.push(elem));\n return 'SortedSet(' + result.toString() + ')';\n }\n\n private copy(data: SortedMap): SortedSet {\n const result = new SortedSet(this.comparator);\n result.data = data;\n return result;\n }\n}\n\nexport class SortedSetIterator {\n constructor(private iter: SortedMapIterator) {}\n\n getNext(): T {\n return this.iter.getNext().key;\n }\n\n hasNext(): boolean {\n return this.iter.hasNext();\n }\n}\n\n/**\n * Compares two sorted sets for equality using their natural ordering. The\n * method computes the intersection and invokes `onAdd` for every element that\n * is in `after` but not `before`. `onRemove` is invoked for every element in\n * `before` but missing from `after`.\n *\n * The method creates a copy of both `before` and `after` and runs in O(n log\n * n), where n is the size of the two lists.\n *\n * @param before - The elements that exist in the original set.\n * @param after - The elements to diff against the original set.\n * @param comparator - The comparator for the elements in before and after.\n * @param onAdd - A function to invoke for every element that is part of `\n * after` but not `before`.\n * @param onRemove - A function to invoke for every element that is part of\n * `before` but not `after`.\n */\nexport function diffSortedSets(\n before: SortedSet,\n after: SortedSet,\n comparator: (l: T, r: T) => number,\n onAdd: (entry: T) => void,\n onRemove: (entry: T) => void\n): void {\n const beforeIt = before.getIterator();\n const afterIt = after.getIterator();\n\n let beforeValue = advanceIterator(beforeIt);\n let afterValue = advanceIterator(afterIt);\n\n // Walk through the two sets at the same time, using the ordering defined by\n // `comparator`.\n while (beforeValue || afterValue) {\n let added = false;\n let removed = false;\n\n if (beforeValue && afterValue) {\n const cmp = comparator(beforeValue, afterValue);\n if (cmp < 0) {\n // The element was removed if the next element in our ordered\n // walkthrough is only in `before`.\n removed = true;\n } else if (cmp > 0) {\n // The element was added if the next element in our ordered walkthrough\n // is only in `after`.\n added = true;\n }\n } else if (beforeValue != null) {\n removed = true;\n } else {\n added = true;\n }\n\n if (added) {\n onAdd(afterValue!);\n afterValue = advanceIterator(afterIt);\n } else if (removed) {\n onRemove(beforeValue!);\n beforeValue = advanceIterator(beforeIt);\n } else {\n beforeValue = advanceIterator(beforeIt);\n afterValue = advanceIterator(afterIt);\n }\n }\n}\n\n/**\n * Returns the next element from the iterator or `undefined` if none available.\n */\nfunction advanceIterator(it: SortedSetIterator): T | undefined {\n return it.hasNext() ? it.getNext() : undefined;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { debugAssert } from '../util/assert';\nimport { arrayEquals } from '../util/misc';\nimport { SortedSet } from '../util/sorted_set';\n\nimport { FieldPath } from './path';\n\n/**\n * Provides a set of fields that can be used to partially patch a document.\n * FieldMask is used in conjunction with ObjectValue.\n * Examples:\n * foo - Overwrites foo entirely with the provided value. If foo is not\n * present in the companion ObjectValue, the field is deleted.\n * foo.bar - Overwrites only the field bar of the object foo.\n * If foo is not an object, foo is replaced with an object\n * containing foo\n */\nexport class FieldMask {\n constructor(readonly fields: FieldPath[]) {\n // TODO(dimond): validation of FieldMask\n // Sort the field mask to support `FieldMask.isEqual()` and assert below.\n fields.sort(FieldPath.comparator);\n debugAssert(\n !fields.some((v, i) => i !== 0 && v.isEqual(fields[i - 1])),\n 'FieldMask contains field that is not unique: ' +\n fields.find((v, i) => i !== 0 && v.isEqual(fields[i - 1]))!\n );\n }\n\n static empty(): FieldMask {\n return new FieldMask([]);\n }\n\n /**\n * Returns a new FieldMask object that is the result of adding all the given\n * fields paths to this field mask.\n */\n unionWith(extraFields: FieldPath[]): FieldMask {\n let mergedMaskSet = new SortedSet(FieldPath.comparator);\n for (const fieldPath of this.fields) {\n mergedMaskSet = mergedMaskSet.add(fieldPath);\n }\n for (const fieldPath of extraFields) {\n mergedMaskSet = mergedMaskSet.add(fieldPath);\n }\n return new FieldMask(mergedMaskSet.toArray());\n }\n\n /**\n * Verifies that `fieldPath` is included by at least one field in this field\n * mask.\n *\n * This is an O(n) operation, where `n` is the size of the field mask.\n */\n covers(fieldPath: FieldPath): boolean {\n for (const fieldMaskPath of this.fields) {\n if (fieldMaskPath.isPrefixOf(fieldPath)) {\n return true;\n }\n }\n return false;\n }\n\n isEqual(other: FieldMask): boolean {\n return arrayEquals(this.fields, other.fields, (l, r) => l.isEqual(r));\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n MapValue as ProtoMapValue,\n Value as ProtoValue\n} from '../protos/firestore_proto_api';\nimport { debugAssert } from '../util/assert';\nimport { forEach } from '../util/obj';\n\nimport { FieldMask } from './field_mask';\nimport { FieldPath } from './path';\nimport { isServerTimestamp } from './server_timestamps';\nimport { deepClone, isMapValue, valueEquals } from './values';\n\nexport interface JsonObject {\n [name: string]: T;\n}\n/**\n * An ObjectValue represents a MapValue in the Firestore Proto and offers the\n * ability to add and remove fields (via the ObjectValueBuilder).\n */\nexport class ObjectValue {\n constructor(readonly value: { mapValue: ProtoMapValue }) {\n debugAssert(\n !isServerTimestamp(value),\n 'ServerTimestamps should be converted to ServerTimestampValue'\n );\n }\n\n static empty(): ObjectValue {\n return new ObjectValue({ mapValue: {} });\n }\n\n /**\n * Returns the value at the given path or null.\n *\n * @param path - the path to search\n * @returns The value at the path or null if the path is not set.\n */\n field(path: FieldPath): ProtoValue | null {\n if (path.isEmpty()) {\n return this.value;\n } else {\n let currentLevel: ProtoValue = this.value;\n for (let i = 0; i < path.length - 1; ++i) {\n currentLevel = (currentLevel.mapValue!.fields || {})[path.get(i)];\n if (!isMapValue(currentLevel)) {\n return null;\n }\n }\n currentLevel = (currentLevel.mapValue!.fields! || {})[path.lastSegment()];\n return currentLevel || null;\n }\n }\n\n /**\n * Sets the field to the provided value.\n *\n * @param path - The field path to set.\n * @param value - The value to set.\n */\n set(path: FieldPath, value: ProtoValue): void {\n debugAssert(\n !path.isEmpty(),\n 'Cannot set field for empty path on ObjectValue'\n );\n const fieldsMap = this.getFieldsMap(path.popLast());\n fieldsMap[path.lastSegment()] = deepClone(value);\n }\n\n /**\n * Sets the provided fields to the provided values.\n *\n * @param data - A map of fields to values (or null for deletes).\n */\n setAll(data: Map): void {\n let parent = FieldPath.emptyPath();\n\n let upserts: { [key: string]: ProtoValue } = {};\n let deletes: string[] = [];\n\n data.forEach((value, path) => {\n if (!parent.isImmediateParentOf(path)) {\n // Insert the accumulated changes at this parent location\n const fieldsMap = this.getFieldsMap(parent);\n this.applyChanges(fieldsMap, upserts, deletes);\n upserts = {};\n deletes = [];\n parent = path.popLast();\n }\n\n if (value) {\n upserts[path.lastSegment()] = deepClone(value);\n } else {\n deletes.push(path.lastSegment());\n }\n });\n\n const fieldsMap = this.getFieldsMap(parent);\n this.applyChanges(fieldsMap, upserts, deletes);\n }\n\n /**\n * Removes the field at the specified path. If there is no field at the\n * specified path, nothing is changed.\n *\n * @param path - The field path to remove.\n */\n delete(path: FieldPath): void {\n debugAssert(\n !path.isEmpty(),\n 'Cannot delete field for empty path on ObjectValue'\n );\n const nestedValue = this.field(path.popLast());\n if (isMapValue(nestedValue) && nestedValue.mapValue.fields) {\n delete nestedValue.mapValue.fields[path.lastSegment()];\n }\n }\n\n isEqual(other: ObjectValue): boolean {\n return valueEquals(this.value, other.value);\n }\n\n /**\n * Returns the map that contains the leaf element of `path`. If the parent\n * entry does not yet exist, or if it is not a map, a new map will be created.\n */\n private getFieldsMap(path: FieldPath): Record {\n let current = this.value;\n\n if (!current.mapValue!.fields) {\n current.mapValue = { fields: {} };\n }\n\n for (let i = 0; i < path.length; ++i) {\n let next = current.mapValue!.fields![path.get(i)];\n if (!isMapValue(next) || !next.mapValue.fields) {\n next = { mapValue: { fields: {} } };\n current.mapValue!.fields![path.get(i)] = next;\n }\n current = next as { mapValue: ProtoMapValue };\n }\n\n return current.mapValue!.fields!;\n }\n\n /**\n * Modifies `fieldsMap` by adding, replacing or deleting the specified\n * entries.\n */\n private applyChanges(\n fieldsMap: Record,\n inserts: { [key: string]: ProtoValue },\n deletes: string[]\n ): void {\n forEach(inserts, (key, val) => (fieldsMap[key] = val));\n for (const field of deletes) {\n delete fieldsMap[field];\n }\n }\n\n clone(): ObjectValue {\n return new ObjectValue(\n deepClone(this.value) as { mapValue: ProtoMapValue }\n );\n }\n}\n\n/**\n * Returns a FieldMask built from all fields in a MapValue.\n */\nexport function extractFieldMask(value: ProtoMapValue): FieldMask {\n const fields: FieldPath[] = [];\n forEach(value!.fields, (key, value) => {\n const currentPath = new FieldPath([key]);\n if (isMapValue(value)) {\n const nestedMask = extractFieldMask(value.mapValue!);\n const nestedFields = nestedMask.fields;\n if (nestedFields.length === 0) {\n // Preserve the empty map by adding it to the FieldMask.\n fields.push(currentPath);\n } else {\n // For nested and non-empty ObjectValues, add the FieldPath of the\n // leaf nodes.\n for (const nestedPath of nestedFields) {\n fields.push(currentPath.child(nestedPath));\n }\n }\n } else {\n // For nested and non-empty ObjectValues, add the FieldPath of the leaf\n // nodes.\n fields.push(currentPath);\n }\n });\n return new FieldMask(fields);\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { debugAssert, fail } from '../util/assert';\n\nimport { DocumentKey } from './document_key';\nimport { ObjectValue } from './object_value';\nimport { FieldPath } from './path';\nimport { valueCompare } from './values';\n\n/**\n * Whether the document represents an existing document, a document that is\n * known to exist or a document whose state or existence is unknown.\n */\nconst enum DocumentType {\n /**\n * Represents the initial state of a MutableDocument when only the document\n * key is known. Invalid documents transition to other states as mutations are\n * applied. If a document remains invalid after applying mutations, it should\n * be discarded.\n *\n * Invalid documents can have neither local nor committed mutations.\n */\n INVALID,\n /**\n * Represents a document in Firestore with a key, version, data and whether\n * the data has local mutations applied to it.\n *\n * Found documents can be synced or have or committed mutations applied.\n */\n FOUND_DOCUMENT,\n /**\n * Represents that no documents exists for the key at the given version.\n *\n * Documents that are deleted based on a local mutation do not raise snapshots\n * with `hasPendingWrites`. As such, deleted documents never have\n * `HAS_LOCAL_MUTATIONS` set. Once a delete is committed, we store them with\n * `HAS_COMMITTED_MUTATIONS` until we received the delete from the Watch\n * stream.\n */\n NO_DOCUMENT,\n /**\n * Represents an existing document whose data is unknown (e.g. a document that\n * was updated without a known base document).\n *\n * An unknown document always has `HAS_COMMITTED_MUTATIONS` set, since unknown\n * documents can only be generated by applying a patch mutation from a write\n * acknowledgement.\n */\n UNKNOWN_DOCUMENT\n}\n\n/** Describes whether a document has latency-compensated edits applied. */\nconst enum DocumentState {\n /** No mutations applied. Document was sent to us by Watch. */\n SYNCED,\n /**\n * Local mutations applied via the mutation queue. Document is potentially\n * inconsistent.\n */\n HAS_LOCAL_MUTATIONS,\n /**\n * Mutations applied based on a write acknowledgment. Document is potentially\n * inconsistent.\n */\n HAS_COMMITTED_MUTATIONS\n}\n\n/**\n * Represents a document in Firestore with a key, version, data and whether the\n * data has local mutations applied to it.\n */\nexport interface Document {\n /** The key for this document */\n readonly key: DocumentKey;\n\n /**\n * The version of this document if it exists or a version at which this\n * document was guaranteed to not exist.\n */\n readonly version: SnapshotVersion;\n\n /**\n * The timestamp at which this document was read from the remote server. Uses\n * `SnapshotVersion.min()` for documents created by the user.\n */\n readonly readTime: SnapshotVersion;\n\n /**\n * The timestamp at which the document was created. This value increases\n * monotonically when a document is deleted then recreated. It can also be\n * compared to `createTime` of other documents and the `readTime` of a query.\n */\n readonly createTime: SnapshotVersion;\n\n /** The underlying data of this document or an empty value if no data exists. */\n readonly data: ObjectValue;\n\n /** Returns whether local mutations were applied via the mutation queue. */\n readonly hasLocalMutations: boolean;\n\n /** Returns whether mutations were applied based on a write acknowledgment. */\n readonly hasCommittedMutations: boolean;\n\n /**\n * Whether this document had a local mutation applied that has not yet been\n * acknowledged by Watch.\n */\n readonly hasPendingWrites: boolean;\n\n /**\n * Returns whether this document is valid (i.e. it is an entry in the\n * RemoteDocumentCache, was created by a mutation or read from the backend).\n */\n isValidDocument(): boolean;\n\n /**\n * Returns whether the document exists and its data is known at the current\n * version.\n */\n isFoundDocument(): boolean;\n\n /**\n * Returns whether the document is known to not exist at the current version.\n */\n isNoDocument(): boolean;\n\n /**\n * Returns whether the document exists and its data is unknown at the current\n * version.\n */\n isUnknownDocument(): boolean;\n\n isEqual(other: Document | null | undefined): boolean;\n\n /** Creates a mutable copy of this document. */\n mutableCopy(): MutableDocument;\n\n toString(): string;\n}\n\n/**\n * Represents a document in Firestore with a key, version, data and whether it\n * has local mutations applied to it.\n *\n * Documents can transition between states via `convertToFoundDocument()`,\n * `convertToNoDocument()` and `convertToUnknownDocument()`. If a document does\n * not transition to one of these states even after all mutations have been\n * applied, `isValidDocument()` returns false and the document should be removed\n * from all views.\n */\nexport class MutableDocument implements Document {\n private constructor(\n readonly key: DocumentKey,\n private documentType: DocumentType,\n public version: SnapshotVersion,\n public readTime: SnapshotVersion,\n public createTime: SnapshotVersion,\n public data: ObjectValue,\n private documentState: DocumentState\n ) {}\n\n /**\n * Creates a document with no known version or data, but which can serve as\n * base document for mutations.\n */\n static newInvalidDocument(documentKey: DocumentKey): MutableDocument {\n return new MutableDocument(\n documentKey,\n DocumentType.INVALID,\n /* version */ SnapshotVersion.min(),\n /* readTime */ SnapshotVersion.min(),\n /* createTime */ SnapshotVersion.min(),\n ObjectValue.empty(),\n DocumentState.SYNCED\n );\n }\n\n /**\n * Creates a new document that is known to exist with the given data at the\n * given version.\n */\n static newFoundDocument(\n documentKey: DocumentKey,\n version: SnapshotVersion,\n createTime: SnapshotVersion,\n value: ObjectValue\n ): MutableDocument {\n return new MutableDocument(\n documentKey,\n DocumentType.FOUND_DOCUMENT,\n /* version */ version,\n /* readTime */ SnapshotVersion.min(),\n /* createTime */ createTime,\n value,\n DocumentState.SYNCED\n );\n }\n\n /** Creates a new document that is known to not exist at the given version. */\n static newNoDocument(\n documentKey: DocumentKey,\n version: SnapshotVersion\n ): MutableDocument {\n return new MutableDocument(\n documentKey,\n DocumentType.NO_DOCUMENT,\n /* version */ version,\n /* readTime */ SnapshotVersion.min(),\n /* createTime */ SnapshotVersion.min(),\n ObjectValue.empty(),\n DocumentState.SYNCED\n );\n }\n\n /**\n * Creates a new document that is known to exist at the given version but\n * whose data is not known (e.g. a document that was updated without a known\n * base document).\n */\n static newUnknownDocument(\n documentKey: DocumentKey,\n version: SnapshotVersion\n ): MutableDocument {\n return new MutableDocument(\n documentKey,\n DocumentType.UNKNOWN_DOCUMENT,\n /* version */ version,\n /* readTime */ SnapshotVersion.min(),\n /* createTime */ SnapshotVersion.min(),\n ObjectValue.empty(),\n DocumentState.HAS_COMMITTED_MUTATIONS\n );\n }\n\n /**\n * Changes the document type to indicate that it exists and that its version\n * and data are known.\n */\n convertToFoundDocument(\n version: SnapshotVersion,\n value: ObjectValue\n ): MutableDocument {\n // If a document is switching state from being an invalid or deleted\n // document to a valid (FOUND_DOCUMENT) document, either due to receiving an\n // update from Watch or due to applying a local set mutation on top\n // of a deleted document, our best guess about its createTime would be the\n // version at which the document transitioned to a FOUND_DOCUMENT.\n if (\n this.createTime.isEqual(SnapshotVersion.min()) &&\n (this.documentType === DocumentType.NO_DOCUMENT ||\n this.documentType === DocumentType.INVALID)\n ) {\n this.createTime = version;\n }\n this.version = version;\n this.documentType = DocumentType.FOUND_DOCUMENT;\n this.data = value;\n this.documentState = DocumentState.SYNCED;\n return this;\n }\n\n /**\n * Changes the document type to indicate that it doesn't exist at the given\n * version.\n */\n convertToNoDocument(version: SnapshotVersion): MutableDocument {\n this.version = version;\n this.documentType = DocumentType.NO_DOCUMENT;\n this.data = ObjectValue.empty();\n this.documentState = DocumentState.SYNCED;\n return this;\n }\n\n /**\n * Changes the document type to indicate that it exists at a given version but\n * that its data is not known (e.g. a document that was updated without a known\n * base document).\n */\n convertToUnknownDocument(version: SnapshotVersion): MutableDocument {\n this.version = version;\n this.documentType = DocumentType.UNKNOWN_DOCUMENT;\n this.data = ObjectValue.empty();\n this.documentState = DocumentState.HAS_COMMITTED_MUTATIONS;\n return this;\n }\n\n setHasCommittedMutations(): MutableDocument {\n debugAssert(\n this.isValidDocument(),\n 'Invalid documents cannot have committed mutations'\n );\n this.documentState = DocumentState.HAS_COMMITTED_MUTATIONS;\n return this;\n }\n\n setHasLocalMutations(): MutableDocument {\n this.documentState = DocumentState.HAS_LOCAL_MUTATIONS;\n this.version = SnapshotVersion.min();\n return this;\n }\n\n setReadTime(readTime: SnapshotVersion): MutableDocument {\n this.readTime = readTime;\n return this;\n }\n\n get hasLocalMutations(): boolean {\n return this.documentState === DocumentState.HAS_LOCAL_MUTATIONS;\n }\n\n get hasCommittedMutations(): boolean {\n return this.documentState === DocumentState.HAS_COMMITTED_MUTATIONS;\n }\n\n get hasPendingWrites(): boolean {\n return this.hasLocalMutations || this.hasCommittedMutations;\n }\n\n isValidDocument(): boolean {\n return this.documentType !== DocumentType.INVALID;\n }\n\n isFoundDocument(): boolean {\n return this.documentType === DocumentType.FOUND_DOCUMENT;\n }\n\n isNoDocument(): boolean {\n return this.documentType === DocumentType.NO_DOCUMENT;\n }\n\n isUnknownDocument(): boolean {\n return this.documentType === DocumentType.UNKNOWN_DOCUMENT;\n }\n\n isEqual(other: Document | null | undefined): boolean {\n return (\n other instanceof MutableDocument &&\n this.key.isEqual(other.key) &&\n this.version.isEqual(other.version) &&\n this.documentType === other.documentType &&\n this.documentState === other.documentState &&\n this.data.isEqual(other.data)\n );\n }\n\n mutableCopy(): MutableDocument {\n return new MutableDocument(\n this.key,\n this.documentType,\n this.version,\n this.readTime,\n this.createTime,\n this.data.clone(),\n this.documentState\n );\n }\n\n toString(): string {\n return (\n `Document(${this.key}, ${this.version}, ${JSON.stringify(\n this.data.value\n )}, ` +\n `{createTime: ${this.createTime}}), ` +\n `{documentType: ${this.documentType}}), ` +\n `{documentState: ${this.documentState}})`\n );\n }\n}\n\n/**\n * Compares the value for field `field` in the provided documents. Throws if\n * the field does not exist in both documents.\n */\nexport function compareDocumentsByField(\n field: FieldPath,\n d1: Document,\n d2: Document\n): number {\n const v1 = d1.data.field(field);\n const v2 = d2.data.field(field);\n if (v1 !== null && v2 !== null) {\n return valueCompare(v1, v2);\n } else {\n return fail(\n 0xa786,\n \"Trying to compare documents on fields that don't exist\"\n );\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DocumentKey } from '../model/document_key';\nimport {\n FieldIndex,\n fieldIndexGetArraySegment,\n fieldIndexGetDirectionalSegments,\n IndexKind\n} from '../model/field_index';\nimport { FieldPath, ResourcePath } from '../model/path';\nimport {\n canonicalId,\n MAX_VALUE,\n MIN_VALUE,\n lowerBoundCompare,\n upperBoundCompare,\n valuesGetLowerBound,\n valuesGetUpperBound\n} from '../model/values';\nimport { Value as ProtoValue } from '../protos/firestore_proto_api';\nimport { debugCast } from '../util/assert';\nimport { SortedSet } from '../util/sorted_set';\nimport { isNullOrUndefined } from '../util/types';\n\nimport { Bound, boundEquals } from './bound';\nimport {\n Filter,\n FieldFilter,\n canonifyFilter,\n stringifyFilter,\n filterEquals,\n Operator\n} from './filter';\nimport {\n canonifyOrderBy,\n OrderBy,\n orderByEquals,\n stringifyOrderBy\n} from './order_by';\n\n/**\n * A Target represents the WatchTarget representation of a Query, which is used\n * by the LocalStore and the RemoteStore to keep track of and to execute\n * backend queries. While a Query can represent multiple Targets, each Targets\n * maps to a single WatchTarget in RemoteStore and a single TargetData entry\n * in persistence.\n */\nexport interface Target {\n readonly path: ResourcePath;\n readonly collectionGroup: string | null;\n readonly orderBy: OrderBy[];\n readonly filters: Filter[];\n readonly limit: number | null;\n readonly startAt: Bound | null;\n readonly endAt: Bound | null;\n}\n\n// Visible for testing\nexport class TargetImpl implements Target {\n memoizedCanonicalId: string | null = null;\n constructor(\n readonly path: ResourcePath,\n readonly collectionGroup: string | null = null,\n readonly orderBy: OrderBy[] = [],\n readonly filters: Filter[] = [],\n readonly limit: number | null = null,\n readonly startAt: Bound | null = null,\n readonly endAt: Bound | null = null\n ) {}\n}\n\n/**\n * Initializes a Target with a path and optional additional query constraints.\n * Path must currently be empty if this is a collection group query.\n *\n * NOTE: you should always construct `Target` from `Query.toTarget` instead of\n * using this factory method, because `Query` provides an implicit `orderBy`\n * property.\n */\nexport function newTarget(\n path: ResourcePath,\n collectionGroup: string | null = null,\n orderBy: OrderBy[] = [],\n filters: Filter[] = [],\n limit: number | null = null,\n startAt: Bound | null = null,\n endAt: Bound | null = null\n): Target {\n return new TargetImpl(\n path,\n collectionGroup,\n orderBy,\n filters,\n limit,\n startAt,\n endAt\n );\n}\n\nexport function canonifyTarget(target: Target): string {\n const targetImpl = debugCast(target, TargetImpl);\n\n if (targetImpl.memoizedCanonicalId === null) {\n let str = targetImpl.path.canonicalString();\n if (targetImpl.collectionGroup !== null) {\n str += '|cg:' + targetImpl.collectionGroup;\n }\n str += '|f:';\n str += targetImpl.filters.map(f => canonifyFilter(f)).join(',');\n str += '|ob:';\n str += targetImpl.orderBy.map(o => canonifyOrderBy(o)).join(',');\n\n if (!isNullOrUndefined(targetImpl.limit)) {\n str += '|l:';\n str += targetImpl.limit!;\n }\n if (targetImpl.startAt) {\n str += '|lb:';\n str += targetImpl.startAt.inclusive ? 'b:' : 'a:';\n str += targetImpl.startAt.position.map(p => canonicalId(p)).join(',');\n }\n if (targetImpl.endAt) {\n str += '|ub:';\n str += targetImpl.endAt.inclusive ? 'a:' : 'b:';\n str += targetImpl.endAt.position.map(p => canonicalId(p)).join(',');\n }\n targetImpl.memoizedCanonicalId = str;\n }\n return targetImpl.memoizedCanonicalId;\n}\n\nexport function stringifyTarget(target: Target): string {\n let str = target.path.canonicalString();\n if (target.collectionGroup !== null) {\n str += ' collectionGroup=' + target.collectionGroup;\n }\n if (target.filters.length > 0) {\n str += `, filters: [${target.filters\n .map(f => stringifyFilter(f))\n .join(', ')}]`;\n }\n if (!isNullOrUndefined(target.limit)) {\n str += ', limit: ' + target.limit;\n }\n if (target.orderBy.length > 0) {\n str += `, orderBy: [${target.orderBy\n .map(o => stringifyOrderBy(o))\n .join(', ')}]`;\n }\n if (target.startAt) {\n str += ', startAt: ';\n str += target.startAt.inclusive ? 'b:' : 'a:';\n str += target.startAt.position.map(p => canonicalId(p)).join(',');\n }\n if (target.endAt) {\n str += ', endAt: ';\n str += target.endAt.inclusive ? 'a:' : 'b:';\n str += target.endAt.position.map(p => canonicalId(p)).join(',');\n }\n return `Target(${str})`;\n}\n\nexport function targetEquals(left: Target, right: Target): boolean {\n if (left.limit !== right.limit) {\n return false;\n }\n\n if (left.orderBy.length !== right.orderBy.length) {\n return false;\n }\n\n for (let i = 0; i < left.orderBy.length; i++) {\n if (!orderByEquals(left.orderBy[i], right.orderBy[i])) {\n return false;\n }\n }\n\n if (left.filters.length !== right.filters.length) {\n return false;\n }\n\n for (let i = 0; i < left.filters.length; i++) {\n if (!filterEquals(left.filters[i], right.filters[i])) {\n return false;\n }\n }\n\n if (left.collectionGroup !== right.collectionGroup) {\n return false;\n }\n\n if (!left.path.isEqual(right.path)) {\n return false;\n }\n\n if (!boundEquals(left.startAt, right.startAt)) {\n return false;\n }\n\n return boundEquals(left.endAt, right.endAt);\n}\n\nexport function targetIsDocumentTarget(target: Target): boolean {\n return (\n DocumentKey.isDocumentKey(target.path) &&\n target.collectionGroup === null &&\n target.filters.length === 0\n );\n}\n\n/** Returns the field filters that target the given field path. */\nexport function targetGetFieldFiltersForPath(\n target: Target,\n path: FieldPath\n): FieldFilter[] {\n return target.filters.filter(\n f => f instanceof FieldFilter && f.field.isEqual(path)\n ) as FieldFilter[];\n}\n\n/**\n * Returns the values that are used in ARRAY_CONTAINS or ARRAY_CONTAINS_ANY\n * filters. Returns `null` if there are no such filters.\n */\nexport function targetGetArrayValues(\n target: Target,\n fieldIndex: FieldIndex\n): ProtoValue[] | null {\n const segment = fieldIndexGetArraySegment(fieldIndex);\n if (segment === undefined) {\n return null;\n }\n\n for (const fieldFilter of targetGetFieldFiltersForPath(\n target,\n segment.fieldPath\n )) {\n switch (fieldFilter.op) {\n case Operator.ARRAY_CONTAINS_ANY:\n return fieldFilter.value.arrayValue!.values || [];\n case Operator.ARRAY_CONTAINS:\n return [fieldFilter.value];\n default:\n // Remaining filters are not array filters.\n }\n }\n return null;\n}\n\n/**\n * Returns the list of values that are used in != or NOT_IN filters. Returns\n * `null` if there are no such filters.\n */\nexport function targetGetNotInValues(\n target: Target,\n fieldIndex: FieldIndex\n): ProtoValue[] | null {\n const values = new Map();\n\n for (const segment of fieldIndexGetDirectionalSegments(fieldIndex)) {\n for (const fieldFilter of targetGetFieldFiltersForPath(\n target,\n segment.fieldPath\n )) {\n switch (fieldFilter.op) {\n case Operator.EQUAL:\n case Operator.IN:\n // Encode equality prefix, which is encoded in the index value before\n // the inequality (e.g. `a == 'a' && b != 'b'` is encoded to\n // `value != 'ab'`).\n values.set(segment.fieldPath.canonicalString(), fieldFilter.value);\n break;\n case Operator.NOT_IN:\n case Operator.NOT_EQUAL:\n // NotIn/NotEqual is always a suffix. There cannot be any remaining\n // segments and hence we can return early here.\n values.set(segment.fieldPath.canonicalString(), fieldFilter.value);\n return Array.from(values.values());\n default:\n // Remaining filters cannot be used as notIn bounds.\n }\n }\n }\n\n return null;\n}\n\n/**\n * Returns a lower bound of field values that can be used as a starting point to\n * scan the index defined by `fieldIndex`. Returns `MIN_VALUE` if no lower bound\n * exists.\n */\nexport function targetGetLowerBound(\n target: Target,\n fieldIndex: FieldIndex\n): Bound {\n const values: ProtoValue[] = [];\n let inclusive = true;\n\n // For each segment, retrieve a lower bound if there is a suitable filter or\n // startAt.\n for (const segment of fieldIndexGetDirectionalSegments(fieldIndex)) {\n const segmentBound =\n segment.kind === IndexKind.ASCENDING\n ? targetGetAscendingBound(target, segment.fieldPath, target.startAt)\n : targetGetDescendingBound(target, segment.fieldPath, target.startAt);\n\n values.push(segmentBound.value);\n inclusive &&= segmentBound.inclusive;\n }\n return new Bound(values, inclusive);\n}\n\n/**\n * Returns an upper bound of field values that can be used as an ending point\n * when scanning the index defined by `fieldIndex`. Returns `MAX_VALUE` if no\n * upper bound exists.\n */\nexport function targetGetUpperBound(\n target: Target,\n fieldIndex: FieldIndex\n): Bound {\n const values: ProtoValue[] = [];\n let inclusive = true;\n\n // For each segment, retrieve an upper bound if there is a suitable filter or\n // endAt.\n for (const segment of fieldIndexGetDirectionalSegments(fieldIndex)) {\n const segmentBound =\n segment.kind === IndexKind.ASCENDING\n ? targetGetDescendingBound(target, segment.fieldPath, target.endAt)\n : targetGetAscendingBound(target, segment.fieldPath, target.endAt);\n\n values.push(segmentBound.value);\n inclusive &&= segmentBound.inclusive;\n }\n\n return new Bound(values, inclusive);\n}\n\n/**\n * Returns the value to use as the lower bound for ascending index segment at\n * the provided `fieldPath` (or the upper bound for an descending segment).\n */\nfunction targetGetAscendingBound(\n target: Target,\n fieldPath: FieldPath,\n bound: Bound | null\n): { value: ProtoValue; inclusive: boolean } {\n let value: ProtoValue = MIN_VALUE;\n\n let inclusive = true;\n\n // Process all filters to find a value for the current field segment\n for (const fieldFilter of targetGetFieldFiltersForPath(target, fieldPath)) {\n let filterValue: ProtoValue = MIN_VALUE;\n let filterInclusive = true;\n\n switch (fieldFilter.op) {\n case Operator.LESS_THAN:\n case Operator.LESS_THAN_OR_EQUAL:\n filterValue = valuesGetLowerBound(fieldFilter.value);\n break;\n case Operator.EQUAL:\n case Operator.IN:\n case Operator.GREATER_THAN_OR_EQUAL:\n filterValue = fieldFilter.value;\n break;\n case Operator.GREATER_THAN:\n filterValue = fieldFilter.value;\n filterInclusive = false;\n break;\n case Operator.NOT_EQUAL:\n case Operator.NOT_IN:\n filterValue = MIN_VALUE;\n break;\n default:\n // Remaining filters cannot be used as lower bounds.\n }\n\n if (\n lowerBoundCompare(\n { value, inclusive },\n { value: filterValue, inclusive: filterInclusive }\n ) < 0\n ) {\n value = filterValue;\n inclusive = filterInclusive;\n }\n }\n\n // If there is an additional bound, compare the values against the existing\n // range to see if we can narrow the scope.\n if (bound !== null) {\n for (let i = 0; i < target.orderBy.length; ++i) {\n const orderBy = target.orderBy[i];\n if (orderBy.field.isEqual(fieldPath)) {\n const cursorValue = bound.position[i];\n if (\n lowerBoundCompare(\n { value, inclusive },\n { value: cursorValue, inclusive: bound.inclusive }\n ) < 0\n ) {\n value = cursorValue;\n inclusive = bound.inclusive;\n }\n break;\n }\n }\n }\n\n return { value, inclusive };\n}\n\n/**\n * Returns the value to use as the upper bound for ascending index segment at\n * the provided `fieldPath` (or the lower bound for a descending segment).\n */\nfunction targetGetDescendingBound(\n target: Target,\n fieldPath: FieldPath,\n bound: Bound | null\n): { value: ProtoValue; inclusive: boolean } {\n let value: ProtoValue = MAX_VALUE;\n let inclusive = true;\n\n // Process all filters to find a value for the current field segment\n for (const fieldFilter of targetGetFieldFiltersForPath(target, fieldPath)) {\n let filterValue: ProtoValue = MAX_VALUE;\n let filterInclusive = true;\n\n switch (fieldFilter.op) {\n case Operator.GREATER_THAN_OR_EQUAL:\n case Operator.GREATER_THAN:\n filterValue = valuesGetUpperBound(fieldFilter.value);\n filterInclusive = false;\n break;\n case Operator.EQUAL:\n case Operator.IN:\n case Operator.LESS_THAN_OR_EQUAL:\n filterValue = fieldFilter.value;\n break;\n case Operator.LESS_THAN:\n filterValue = fieldFilter.value;\n filterInclusive = false;\n break;\n case Operator.NOT_EQUAL:\n case Operator.NOT_IN:\n filterValue = MAX_VALUE;\n break;\n default:\n // Remaining filters cannot be used as upper bounds.\n }\n\n if (\n upperBoundCompare(\n { value, inclusive },\n { value: filterValue, inclusive: filterInclusive }\n ) > 0\n ) {\n value = filterValue;\n inclusive = filterInclusive;\n }\n }\n\n // If there is an additional bound, compare the values against the existing\n // range to see if we can narrow the scope.\n if (bound !== null) {\n for (let i = 0; i < target.orderBy.length; ++i) {\n const orderBy = target.orderBy[i];\n if (orderBy.field.isEqual(fieldPath)) {\n const cursorValue = bound.position[i];\n if (\n upperBoundCompare(\n { value, inclusive },\n { value: cursorValue, inclusive: bound.inclusive }\n ) > 0\n ) {\n value = cursorValue;\n inclusive = bound.inclusive;\n }\n break;\n }\n }\n }\n\n return { value, inclusive };\n}\n\n/** Returns the number of segments of a perfect index for this target. */\nexport function targetGetSegmentCount(target: Target): number {\n let fields = new SortedSet(FieldPath.comparator);\n let hasArraySegment = false;\n\n for (const filter of target.filters) {\n for (const subFilter of filter.getFlattenedFilters()) {\n // __name__ is not an explicit segment of any index, so we don't need to\n // count it.\n if (subFilter.field.isKeyField()) {\n continue;\n }\n\n // ARRAY_CONTAINS or ARRAY_CONTAINS_ANY filters must be counted separately.\n // For instance, it is possible to have an index for \"a ARRAY a ASC\". Even\n // though these are on the same field, they should be counted as two\n // separate segments in an index.\n if (\n subFilter.op === Operator.ARRAY_CONTAINS ||\n subFilter.op === Operator.ARRAY_CONTAINS_ANY\n ) {\n hasArraySegment = true;\n } else {\n fields = fields.add(subFilter.field);\n }\n }\n }\n\n for (const orderBy of target.orderBy) {\n // __name__ is not an explicit segment of any index, so we don't need to\n // count it.\n if (!orderBy.field.isKeyField()) {\n fields = fields.add(orderBy.field);\n }\n }\n\n return fields.size + (hasArraySegment ? 1 : 0);\n}\n\nexport function targetHasLimit(target: Target): boolean {\n return target.limit !== null;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { compareDocumentsByField, Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { FieldPath, ResourcePath } from '../model/path';\nimport { debugAssert, debugCast, fail } from '../util/assert';\nimport { SortedSet } from '../util/sorted_set';\n\nimport {\n Bound,\n boundSortsAfterDocument,\n boundSortsBeforeDocument\n} from './bound';\nimport { FieldFilter, Filter } from './filter';\nimport { Direction, OrderBy } from './order_by';\nimport {\n canonifyTarget,\n newTarget,\n stringifyTarget,\n Target,\n targetEquals\n} from './target';\n\nexport const enum LimitType {\n First = 'F',\n Last = 'L'\n}\n\n/**\n * The Query interface defines all external properties of a query.\n *\n * QueryImpl implements this interface to provide memoization for `queryNormalizedOrderBy`\n * and `queryToTarget`.\n */\nexport interface Query {\n readonly path: ResourcePath;\n readonly collectionGroup: string | null;\n readonly explicitOrderBy: OrderBy[];\n readonly filters: Filter[];\n readonly limit: number | null;\n readonly limitType: LimitType;\n readonly startAt: Bound | null;\n readonly endAt: Bound | null;\n}\n\n/**\n * Query encapsulates all the query attributes we support in the SDK. It can\n * be run against the LocalStore, as well as be converted to a `Target` to\n * query the RemoteStore results.\n *\n * Visible for testing.\n */\nexport class QueryImpl implements Query {\n memoizedNormalizedOrderBy: OrderBy[] | null = null;\n\n // The corresponding `Target` of this `Query` instance, for use with\n // non-aggregate queries.\n memoizedTarget: Target | null = null;\n\n // The corresponding `Target` of this `Query` instance, for use with\n // aggregate queries. Unlike targets for non-aggregate queries,\n // aggregate query targets do not contain normalized order-bys, they only\n // contain explicit order-bys.\n memoizedAggregateTarget: Target | null = null;\n\n /**\n * Initializes a Query with a path and optional additional query constraints.\n * Path must currently be empty if this is a collection group query.\n */\n constructor(\n readonly path: ResourcePath,\n readonly collectionGroup: string | null = null,\n readonly explicitOrderBy: OrderBy[] = [],\n readonly filters: Filter[] = [],\n readonly limit: number | null = null,\n readonly limitType: LimitType = LimitType.First,\n readonly startAt: Bound | null = null,\n readonly endAt: Bound | null = null\n ) {\n if (this.startAt) {\n debugAssert(\n this.startAt.position.length <= queryNormalizedOrderBy(this).length,\n 'Bound is longer than orderBy'\n );\n }\n if (this.endAt) {\n debugAssert(\n this.endAt.position.length <= queryNormalizedOrderBy(this).length,\n 'Bound is longer than orderBy'\n );\n }\n }\n}\n\n/** Creates a new Query instance with the options provided. */\nexport function newQuery(\n path: ResourcePath,\n collectionGroup: string | null,\n explicitOrderBy: OrderBy[],\n filters: Filter[],\n limit: number | null,\n limitType: LimitType,\n startAt: Bound | null,\n endAt: Bound | null\n): Query {\n return new QueryImpl(\n path,\n collectionGroup,\n explicitOrderBy,\n filters,\n limit,\n limitType,\n startAt,\n endAt\n );\n}\n\n/** Creates a new Query for a query that matches all documents at `path` */\nexport function newQueryForPath(path: ResourcePath): Query {\n return new QueryImpl(path);\n}\n\n/**\n * Helper to convert a collection group query into a collection query at a\n * specific path. This is used when executing collection group queries, since\n * we have to split the query into a set of collection queries at multiple\n * paths.\n */\nexport function asCollectionQueryAtPath(\n query: Query,\n path: ResourcePath\n): Query {\n return new QueryImpl(\n path,\n /*collectionGroup=*/ null,\n query.explicitOrderBy.slice(),\n query.filters.slice(),\n query.limit,\n query.limitType,\n query.startAt,\n query.endAt\n );\n}\n\n/**\n * Returns true if this query does not specify any query constraints that\n * could remove results.\n */\nexport function queryMatchesAllDocuments(query: Query): boolean {\n return (\n query.filters.length === 0 &&\n query.limit === null &&\n query.startAt == null &&\n query.endAt == null &&\n (query.explicitOrderBy.length === 0 ||\n (query.explicitOrderBy.length === 1 &&\n query.explicitOrderBy[0].field.isKeyField()))\n );\n}\n\n// Returns the sorted set of inequality filter fields used in this query.\nexport function getInequalityFilterFields(query: Query): SortedSet {\n let result = new SortedSet(FieldPath.comparator);\n query.filters.forEach((filter: Filter) => {\n const subFilters = filter.getFlattenedFilters();\n subFilters.forEach((filter: FieldFilter) => {\n if (filter.isInequality()) {\n result = result.add(filter.field);\n }\n });\n });\n return result;\n}\n\n/**\n * Creates a new Query for a collection group query that matches all documents\n * within the provided collection group.\n */\nexport function newQueryForCollectionGroup(collectionId: string): Query {\n return new QueryImpl(ResourcePath.emptyPath(), collectionId);\n}\n\n/**\n * Returns whether the query matches a single document by path (rather than a\n * collection).\n */\nexport function isDocumentQuery(query: Query): boolean {\n return (\n DocumentKey.isDocumentKey(query.path) &&\n query.collectionGroup === null &&\n query.filters.length === 0\n );\n}\n\n/**\n * Returns whether the query matches a collection group rather than a specific\n * collection.\n */\nexport function isCollectionGroupQuery(query: Query): boolean {\n return query.collectionGroup !== null;\n}\n\n/**\n * Returns the normalized order-by constraint that is used to execute the Query,\n * which can be different from the order-by constraints the user provided (e.g.\n * the SDK and backend always orders by `__name__`). The normalized order-by\n * includes implicit order-bys in addition to the explicit user provided\n * order-bys.\n */\nexport function queryNormalizedOrderBy(query: Query): OrderBy[] {\n const queryImpl = debugCast(query, QueryImpl);\n if (queryImpl.memoizedNormalizedOrderBy === null) {\n queryImpl.memoizedNormalizedOrderBy = [];\n const fieldsNormalized = new Set();\n\n // Any explicit order by fields should be added as is.\n for (const orderBy of queryImpl.explicitOrderBy) {\n queryImpl.memoizedNormalizedOrderBy.push(orderBy);\n fieldsNormalized.add(orderBy.field.canonicalString());\n }\n\n // The order of the implicit ordering always matches the last explicit order by.\n const lastDirection =\n queryImpl.explicitOrderBy.length > 0\n ? queryImpl.explicitOrderBy[queryImpl.explicitOrderBy.length - 1].dir\n : Direction.ASCENDING;\n\n // Any inequality fields not explicitly ordered should be implicitly ordered in a lexicographical\n // order. When there are multiple inequality filters on the same field, the field should be added\n // only once.\n // Note: `SortedSet` sorts the key field before other fields. However, we want the key\n // field to be sorted last.\n const inequalityFields: SortedSet =\n getInequalityFilterFields(queryImpl);\n inequalityFields.forEach(field => {\n if (\n !fieldsNormalized.has(field.canonicalString()) &&\n !field.isKeyField()\n ) {\n queryImpl.memoizedNormalizedOrderBy!.push(\n new OrderBy(field, lastDirection)\n );\n }\n });\n\n // Add the document key field to the last if it is not explicitly ordered.\n if (!fieldsNormalized.has(FieldPath.keyField().canonicalString())) {\n queryImpl.memoizedNormalizedOrderBy.push(\n new OrderBy(FieldPath.keyField(), lastDirection)\n );\n }\n }\n return queryImpl.memoizedNormalizedOrderBy;\n}\n\n/**\n * Converts this `Query` instance to its corresponding `Target` representation.\n */\nexport function queryToTarget(query: Query): Target {\n const queryImpl = debugCast(query, QueryImpl);\n if (!queryImpl.memoizedTarget) {\n queryImpl.memoizedTarget = _queryToTarget(\n queryImpl,\n queryNormalizedOrderBy(query)\n );\n }\n\n return queryImpl.memoizedTarget;\n}\n\n/**\n * Converts this `Query` instance to its corresponding `Target` representation,\n * for use within an aggregate query. Unlike targets for non-aggregate queries,\n * aggregate query targets do not contain normalized order-bys, they only\n * contain explicit order-bys.\n */\nexport function queryToAggregateTarget(query: Query): Target {\n const queryImpl = debugCast(query, QueryImpl);\n\n if (!queryImpl.memoizedAggregateTarget) {\n // Do not include implicit order-bys for aggregate queries.\n queryImpl.memoizedAggregateTarget = _queryToTarget(\n queryImpl,\n query.explicitOrderBy\n );\n }\n\n return queryImpl.memoizedAggregateTarget;\n}\n\nfunction _queryToTarget(queryImpl: QueryImpl, orderBys: OrderBy[]): Target {\n if (queryImpl.limitType === LimitType.First) {\n return newTarget(\n queryImpl.path,\n queryImpl.collectionGroup,\n orderBys,\n queryImpl.filters,\n queryImpl.limit,\n queryImpl.startAt,\n queryImpl.endAt\n );\n } else {\n // Flip the orderBy directions since we want the last results\n orderBys = orderBys.map(orderBy => {\n const dir =\n orderBy.dir === Direction.DESCENDING\n ? Direction.ASCENDING\n : Direction.DESCENDING;\n return new OrderBy(orderBy.field, dir);\n });\n\n // We need to swap the cursors to match the now-flipped query ordering.\n const startAt = queryImpl.endAt\n ? new Bound(queryImpl.endAt.position, queryImpl.endAt.inclusive)\n : null;\n const endAt = queryImpl.startAt\n ? new Bound(queryImpl.startAt.position, queryImpl.startAt.inclusive)\n : null;\n\n // Now return as a LimitType.First query.\n return newTarget(\n queryImpl.path,\n queryImpl.collectionGroup,\n orderBys,\n queryImpl.filters,\n queryImpl.limit,\n startAt,\n endAt\n );\n }\n}\n\nexport function queryWithAddedFilter(query: Query, filter: Filter): Query {\n debugAssert(\n !isDocumentQuery(query),\n 'No filtering allowed for document query'\n );\n\n const newFilters = query.filters.concat([filter]);\n return new QueryImpl(\n query.path,\n query.collectionGroup,\n query.explicitOrderBy.slice(),\n newFilters,\n query.limit,\n query.limitType,\n query.startAt,\n query.endAt\n );\n}\n\nexport function queryWithAddedOrderBy(query: Query, orderBy: OrderBy): Query {\n debugAssert(\n !query.startAt && !query.endAt,\n 'Bounds must be set after orderBy'\n );\n // TODO(dimond): validate that orderBy does not list the same key twice.\n const newOrderBy = query.explicitOrderBy.concat([orderBy]);\n return new QueryImpl(\n query.path,\n query.collectionGroup,\n newOrderBy,\n query.filters.slice(),\n query.limit,\n query.limitType,\n query.startAt,\n query.endAt\n );\n}\n\nexport function queryWithLimit(\n query: Query,\n limit: number | null,\n limitType: LimitType\n): Query {\n return new QueryImpl(\n query.path,\n query.collectionGroup,\n query.explicitOrderBy.slice(),\n query.filters.slice(),\n limit,\n limitType,\n query.startAt,\n query.endAt\n );\n}\n\nexport function queryWithStartAt(query: Query, bound: Bound): Query {\n return new QueryImpl(\n query.path,\n query.collectionGroup,\n query.explicitOrderBy.slice(),\n query.filters.slice(),\n query.limit,\n query.limitType,\n bound,\n query.endAt\n );\n}\n\nexport function queryWithEndAt(query: Query, bound: Bound): Query {\n return new QueryImpl(\n query.path,\n query.collectionGroup,\n query.explicitOrderBy.slice(),\n query.filters.slice(),\n query.limit,\n query.limitType,\n query.startAt,\n bound\n );\n}\n\nexport function queryEquals(left: Query, right: Query): boolean {\n return (\n targetEquals(queryToTarget(left), queryToTarget(right)) &&\n left.limitType === right.limitType\n );\n}\n\n// TODO(b/29183165): This is used to get a unique string from a query to, for\n// example, use as a dictionary key, but the implementation is subject to\n// collisions. Make it collision-free.\nexport function canonifyQuery(query: Query): string {\n return `${canonifyTarget(queryToTarget(query))}|lt:${query.limitType}`;\n}\n\nexport function stringifyQuery(query: Query): string {\n return `Query(target=${stringifyTarget(queryToTarget(query))}; limitType=${\n query.limitType\n })`;\n}\n\n/** Returns whether `doc` matches the constraints of `query`. */\nexport function queryMatches(query: Query, doc: Document): boolean {\n return (\n doc.isFoundDocument() &&\n queryMatchesPathAndCollectionGroup(query, doc) &&\n queryMatchesOrderBy(query, doc) &&\n queryMatchesFilters(query, doc) &&\n queryMatchesBounds(query, doc)\n );\n}\n\nfunction queryMatchesPathAndCollectionGroup(\n query: Query,\n doc: Document\n): boolean {\n const docPath = doc.key.path;\n if (query.collectionGroup !== null) {\n // NOTE: this.path is currently always empty since we don't expose Collection\n // Group queries rooted at a document path yet.\n return (\n doc.key.hasCollectionId(query.collectionGroup) &&\n query.path.isPrefixOf(docPath)\n );\n } else if (DocumentKey.isDocumentKey(query.path)) {\n // exact match for document queries\n return query.path.isEqual(docPath);\n } else {\n // shallow ancestor queries by default\n return query.path.isImmediateParentOf(docPath);\n }\n}\n\n/**\n * A document must have a value for every ordering clause in order to show up\n * in the results.\n */\nfunction queryMatchesOrderBy(query: Query, doc: Document): boolean {\n // We must use `queryNormalizedOrderBy()` to get the list of all orderBys (both implicit and explicit).\n // Note that for OR queries, orderBy applies to all disjunction terms and implicit orderBys must\n // be taken into account. For example, the query \"a > 1 || b==1\" has an implicit \"orderBy a\" due\n // to the inequality, and is evaluated as \"a > 1 orderBy a || b==1 orderBy a\".\n // A document with content of {b:1} matches the filters, but does not match the orderBy because\n // it's missing the field 'a'.\n for (const orderBy of queryNormalizedOrderBy(query)) {\n // order-by key always matches\n if (!orderBy.field.isKeyField() && doc.data.field(orderBy.field) === null) {\n return false;\n }\n }\n return true;\n}\n\nfunction queryMatchesFilters(query: Query, doc: Document): boolean {\n for (const filter of query.filters) {\n if (!filter.matches(doc)) {\n return false;\n }\n }\n return true;\n}\n\n/** Makes sure a document is within the bounds, if provided. */\nfunction queryMatchesBounds(query: Query, doc: Document): boolean {\n if (\n query.startAt &&\n !boundSortsBeforeDocument(query.startAt, queryNormalizedOrderBy(query), doc)\n ) {\n return false;\n }\n if (\n query.endAt &&\n !boundSortsAfterDocument(query.endAt, queryNormalizedOrderBy(query), doc)\n ) {\n return false;\n }\n return true;\n}\n\n/**\n * Returns the collection group that this query targets.\n *\n * PORTING NOTE: This is only used in the Web SDK to facilitate multi-tab\n * synchronization for query results.\n */\nexport function queryCollectionGroup(query: Query): string {\n return (\n query.collectionGroup ||\n (query.path.length % 2 === 1\n ? query.path.lastSegment()\n : query.path.get(query.path.length - 2))\n );\n}\n\n/**\n * Returns a new comparator function that can be used to compare two documents\n * based on the Query's ordering constraint.\n */\nexport function newQueryComparator(\n query: Query\n): (d1: Document, d2: Document) => number {\n return (d1: Document, d2: Document): number => {\n let comparedOnKeyField = false;\n for (const orderBy of queryNormalizedOrderBy(query)) {\n const comp = compareDocs(orderBy, d1, d2);\n if (comp !== 0) {\n return comp;\n }\n comparedOnKeyField = comparedOnKeyField || orderBy.field.isKeyField();\n }\n // Assert that we actually compared by key\n debugAssert(\n comparedOnKeyField,\n \"orderBy used that doesn't compare on key field\"\n );\n return 0;\n };\n}\n\nexport function compareDocs(\n orderBy: OrderBy,\n d1: Document,\n d2: Document\n): number {\n const comparison = orderBy.field.isKeyField()\n ? DocumentKey.comparator(d1.key, d2.key)\n : compareDocumentsByField(orderBy.field, d1, d2);\n switch (orderBy.dir) {\n case Direction.ASCENDING:\n return comparison;\n case Direction.DESCENDING:\n return -1 * comparison;\n default:\n return fail(0x4d4e, 'Unknown direction', { direction: orderBy.dir });\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Value as ProtoValue } from '../protos/firestore_proto_api';\nimport { isNegativeZero, isSafeInteger } from '../util/types';\n\n/** Base interface for the Serializer implementation. */\nexport interface Serializer {\n readonly useProto3Json: boolean;\n}\n\n/**\n * Returns an DoubleValue for `value` that is encoded based the serializer's\n * `useProto3Json` setting.\n */\nexport function toDouble(serializer: Serializer, value: number): ProtoValue {\n if (serializer.useProto3Json) {\n if (isNaN(value)) {\n return { doubleValue: 'NaN' };\n } else if (value === Infinity) {\n return { doubleValue: 'Infinity' };\n } else if (value === -Infinity) {\n return { doubleValue: '-Infinity' };\n }\n }\n return { doubleValue: isNegativeZero(value) ? '-0' : value };\n}\n\n/**\n * Returns an IntegerValue for `value`.\n */\nexport function toInteger(value: number): ProtoValue {\n return { integerValue: '' + value };\n}\n\n/**\n * Returns a value for a number that's appropriate to put into a proto.\n * The return value is an IntegerValue if it can safely represent the value,\n * otherwise a DoubleValue is returned.\n */\nexport function toNumber(serializer: Serializer, value: number): ProtoValue {\n return isSafeInteger(value) ? toInteger(value) : toDouble(serializer, value);\n}\n","/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Timestamp } from '../lite-api/timestamp';\nimport { Value as ProtoValue } from '../protos/firestore_proto_api';\nimport { Serializer, toDouble, toInteger } from '../remote/number_serializer';\nimport { debugAssert } from '../util/assert';\nimport { arrayEquals } from '../util/misc';\n\nimport { normalizeNumber } from './normalize';\nimport { serverTimestamp } from './server_timestamps';\nimport { isArray, isInteger, isNumber, valueEquals } from './values';\n\n/** Used to represent a field transform on a mutation. */\nexport class TransformOperation {\n // Make sure that the structural type of `TransformOperation` is unique.\n // See https://github.com/microsoft/TypeScript/issues/5451\n private _ = undefined;\n}\n\n/**\n * Computes the local transform result against the provided `previousValue`,\n * optionally using the provided localWriteTime.\n */\nexport function applyTransformOperationToLocalView(\n transform: TransformOperation,\n previousValue: ProtoValue | null,\n localWriteTime: Timestamp\n): ProtoValue {\n if (transform instanceof ServerTimestampTransform) {\n return serverTimestamp(localWriteTime, previousValue);\n } else if (transform instanceof ArrayUnionTransformOperation) {\n return applyArrayUnionTransformOperation(transform, previousValue);\n } else if (transform instanceof ArrayRemoveTransformOperation) {\n return applyArrayRemoveTransformOperation(transform, previousValue);\n } else {\n debugAssert(\n transform instanceof NumericIncrementTransformOperation,\n 'Expected NumericIncrementTransformOperation but was: ' + transform\n );\n return applyNumericIncrementTransformOperationToLocalView(\n transform,\n previousValue\n );\n }\n}\n\n/**\n * Computes a final transform result after the transform has been acknowledged\n * by the server, potentially using the server-provided transformResult.\n */\nexport function applyTransformOperationToRemoteDocument(\n transform: TransformOperation,\n previousValue: ProtoValue | null,\n transformResult: ProtoValue | null\n): ProtoValue {\n // The server just sends null as the transform result for array operations,\n // so we have to calculate a result the same as we do for local\n // applications.\n if (transform instanceof ArrayUnionTransformOperation) {\n return applyArrayUnionTransformOperation(transform, previousValue);\n } else if (transform instanceof ArrayRemoveTransformOperation) {\n return applyArrayRemoveTransformOperation(transform, previousValue);\n }\n\n debugAssert(\n transformResult !== null,\n \"Didn't receive transformResult for non-array transform\"\n );\n return transformResult;\n}\n\n/**\n * If this transform operation is not idempotent, returns the base value to\n * persist for this transform. If a base value is returned, the transform\n * operation is always applied to this base value, even if document has\n * already been updated.\n *\n * Base values provide consistent behavior for non-idempotent transforms and\n * allow us to return the same latency-compensated value even if the backend\n * has already applied the transform operation. The base value is null for\n * idempotent transforms, as they can be re-played even if the backend has\n * already applied them.\n *\n * @returns a base value to store along with the mutation, or null for\n * idempotent transforms.\n */\nexport function computeTransformOperationBaseValue(\n transform: TransformOperation,\n previousValue: ProtoValue | null\n): ProtoValue | null {\n if (transform instanceof NumericIncrementTransformOperation) {\n return isNumber(previousValue) ? previousValue! : { integerValue: 0 };\n }\n return null;\n}\n\nexport function transformOperationEquals(\n left: TransformOperation,\n right: TransformOperation\n): boolean {\n if (\n left instanceof ArrayUnionTransformOperation &&\n right instanceof ArrayUnionTransformOperation\n ) {\n return arrayEquals(left.elements, right.elements, valueEquals);\n } else if (\n left instanceof ArrayRemoveTransformOperation &&\n right instanceof ArrayRemoveTransformOperation\n ) {\n return arrayEquals(left.elements, right.elements, valueEquals);\n } else if (\n left instanceof NumericIncrementTransformOperation &&\n right instanceof NumericIncrementTransformOperation\n ) {\n return valueEquals(left.operand, right.operand);\n }\n\n return (\n left instanceof ServerTimestampTransform &&\n right instanceof ServerTimestampTransform\n );\n}\n\n/** Transforms a value into a server-generated timestamp. */\nexport class ServerTimestampTransform extends TransformOperation {}\n\n/** Transforms an array value via a union operation. */\nexport class ArrayUnionTransformOperation extends TransformOperation {\n constructor(readonly elements: ProtoValue[]) {\n super();\n }\n}\n\nfunction applyArrayUnionTransformOperation(\n transform: ArrayUnionTransformOperation,\n previousValue: ProtoValue | null\n): ProtoValue {\n const values = coercedFieldValuesArray(previousValue);\n for (const toUnion of transform.elements) {\n if (!values.some(element => valueEquals(element, toUnion))) {\n values.push(toUnion);\n }\n }\n return { arrayValue: { values } };\n}\n\n/** Transforms an array value via a remove operation. */\nexport class ArrayRemoveTransformOperation extends TransformOperation {\n constructor(readonly elements: ProtoValue[]) {\n super();\n }\n}\n\nfunction applyArrayRemoveTransformOperation(\n transform: ArrayRemoveTransformOperation,\n previousValue: ProtoValue | null\n): ProtoValue {\n let values = coercedFieldValuesArray(previousValue);\n for (const toRemove of transform.elements) {\n values = values.filter(element => !valueEquals(element, toRemove));\n }\n return { arrayValue: { values } };\n}\n\n/**\n * Implements the backend semantics for locally computed NUMERIC_ADD (increment)\n * transforms. Converts all field values to integers or doubles, but unlike the\n * backend does not cap integer values at 2^63. Instead, JavaScript number\n * arithmetic is used and precision loss can occur for values greater than 2^53.\n */\nexport class NumericIncrementTransformOperation extends TransformOperation {\n constructor(readonly serializer: Serializer, readonly operand: ProtoValue) {\n super();\n debugAssert(\n isNumber(operand),\n 'NumericIncrementTransform transform requires a NumberValue'\n );\n }\n}\n\nexport function applyNumericIncrementTransformOperationToLocalView(\n transform: NumericIncrementTransformOperation,\n previousValue: ProtoValue | null\n): ProtoValue {\n // PORTING NOTE: Since JavaScript's integer arithmetic is limited to 53 bit\n // precision and resolves overflows by reducing precision, we do not\n // manually cap overflows at 2^63.\n const baseValue = computeTransformOperationBaseValue(\n transform,\n previousValue\n )!;\n const sum = asNumber(baseValue) + asNumber(transform.operand);\n if (isInteger(baseValue) && isInteger(transform.operand)) {\n return toInteger(sum);\n } else {\n return toDouble(transform.serializer, sum);\n }\n}\n\nfunction asNumber(value: ProtoValue): number {\n return normalizeNumber(value.integerValue || value.doubleValue);\n}\n\nfunction coercedFieldValuesArray(value: ProtoValue | null): ProtoValue[] {\n return isArray(value) && value.arrayValue.values\n ? value.arrayValue.values.slice()\n : [];\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { Timestamp } from '../lite-api/timestamp';\nimport { Value as ProtoValue } from '../protos/firestore_proto_api';\nimport { debugAssert, hardAssert } from '../util/assert';\nimport { arrayEquals } from '../util/misc';\nimport { SortedSet } from '../util/sorted_set';\n\nimport { Document, MutableDocument } from './document';\nimport { DocumentKey } from './document_key';\nimport { FieldMask } from './field_mask';\nimport { ObjectValue } from './object_value';\nimport { FieldPath } from './path';\nimport {\n applyTransformOperationToLocalView,\n applyTransformOperationToRemoteDocument,\n computeTransformOperationBaseValue,\n TransformOperation,\n transformOperationEquals\n} from './transform_operation';\n\n/** A field path and the TransformOperation to perform upon it. */\nexport class FieldTransform {\n constructor(\n readonly field: FieldPath,\n readonly transform: TransformOperation\n ) {}\n}\n\nexport function fieldTransformEquals(\n left: FieldTransform,\n right: FieldTransform\n): boolean {\n return (\n left.field.isEqual(right.field) &&\n transformOperationEquals(left.transform, right.transform)\n );\n}\n\nexport function fieldTransformsAreEqual(\n left?: FieldTransform[],\n right?: FieldTransform[]\n): boolean {\n if (left === undefined && right === undefined) {\n return true;\n }\n\n if (left && right) {\n return arrayEquals(left, right, (l, r) => fieldTransformEquals(l, r));\n }\n\n return false;\n}\n\n/** The result of successfully applying a mutation to the backend. */\nexport class MutationResult {\n constructor(\n /**\n * The version at which the mutation was committed:\n *\n * - For most operations, this is the updateTime in the WriteResult.\n * - For deletes, the commitTime of the WriteResponse (because deletes are\n * not stored and have no updateTime).\n *\n * Note that these versions can be different: No-op writes will not change\n * the updateTime even though the commitTime advances.\n */\n readonly version: SnapshotVersion,\n /**\n * The resulting fields returned from the backend after a mutation\n * containing field transforms has been committed. Contains one FieldValue\n * for each FieldTransform that was in the mutation.\n *\n * Will be empty if the mutation did not contain any field transforms.\n */\n readonly transformResults: Array\n ) {}\n}\n\nexport const enum MutationType {\n Set,\n Patch,\n Delete,\n Verify\n}\n\n/**\n * Encodes a precondition for a mutation. This follows the model that the\n * backend accepts with the special case of an explicit \"empty\" precondition\n * (meaning no precondition).\n */\nexport class Precondition {\n private constructor(\n readonly updateTime?: SnapshotVersion,\n readonly exists?: boolean\n ) {\n debugAssert(\n updateTime === undefined || exists === undefined,\n 'Precondition can specify \"exists\" or \"updateTime\" but not both'\n );\n }\n\n /** Creates a new empty Precondition. */\n static none(): Precondition {\n return new Precondition();\n }\n\n /** Creates a new Precondition with an exists flag. */\n static exists(exists: boolean): Precondition {\n return new Precondition(undefined, exists);\n }\n\n /** Creates a new Precondition based on a version a document exists at. */\n static updateTime(version: SnapshotVersion): Precondition {\n return new Precondition(version);\n }\n\n /** Returns whether this Precondition is empty. */\n get isNone(): boolean {\n return this.updateTime === undefined && this.exists === undefined;\n }\n\n isEqual(other: Precondition): boolean {\n return (\n this.exists === other.exists &&\n (this.updateTime\n ? !!other.updateTime && this.updateTime.isEqual(other.updateTime)\n : !other.updateTime)\n );\n }\n}\n\n/** Returns true if the preconditions is valid for the given document. */\nexport function preconditionIsValidForDocument(\n precondition: Precondition,\n document: MutableDocument\n): boolean {\n if (precondition.updateTime !== undefined) {\n return (\n document.isFoundDocument() &&\n document.version.isEqual(precondition.updateTime)\n );\n } else if (precondition.exists !== undefined) {\n return precondition.exists === document.isFoundDocument();\n } else {\n debugAssert(precondition.isNone, 'Precondition should be empty');\n return true;\n }\n}\n\n/**\n * A mutation describes a self-contained change to a document. Mutations can\n * create, replace, delete, and update subsets of documents.\n *\n * Mutations not only act on the value of the document but also its version.\n *\n * For local mutations (mutations that haven't been committed yet), we preserve\n * the existing version for Set and Patch mutations. For Delete mutations, we\n * reset the version to 0.\n *\n * Here's the expected transition table.\n *\n * MUTATION APPLIED TO RESULTS IN\n *\n * SetMutation Document(v3) Document(v3)\n * SetMutation NoDocument(v3) Document(v0)\n * SetMutation InvalidDocument(v0) Document(v0)\n * PatchMutation Document(v3) Document(v3)\n * PatchMutation NoDocument(v3) NoDocument(v3)\n * PatchMutation InvalidDocument(v0) UnknownDocument(v3)\n * DeleteMutation Document(v3) NoDocument(v0)\n * DeleteMutation NoDocument(v3) NoDocument(v0)\n * DeleteMutation InvalidDocument(v0) NoDocument(v0)\n *\n * For acknowledged mutations, we use the updateTime of the WriteResponse as\n * the resulting version for Set and Patch mutations. As deletes have no\n * explicit update time, we use the commitTime of the WriteResponse for\n * Delete mutations.\n *\n * If a mutation is acknowledged by the backend but fails the precondition check\n * locally, we transition to an `UnknownDocument` and rely on Watch to send us\n * the updated version.\n *\n * Field transforms are used only with Patch and Set Mutations. We use the\n * `updateTransforms` message to store transforms, rather than the `transforms`s\n * messages.\n *\n * ## Subclassing Notes\n *\n * Every type of mutation needs to implement its own applyToRemoteDocument() and\n * applyToLocalView() to implement the actual behavior of applying the mutation\n * to some source document (see `setMutationApplyToRemoteDocument()` for an\n * example).\n */\nexport abstract class Mutation {\n abstract readonly type: MutationType;\n abstract readonly key: DocumentKey;\n abstract readonly precondition: Precondition;\n abstract readonly fieldTransforms: FieldTransform[];\n /**\n * Returns a `FieldMask` representing the fields that will be changed by\n * applying this mutation. Returns `null` if the mutation will overwrite the\n * entire document.\n */\n abstract getFieldMask(): FieldMask | null;\n}\n\n/**\n * A utility method to calculate a `Mutation` representing the overlay from the\n * final state of the document, and a `FieldMask` representing the fields that\n * are mutated by the local mutations.\n */\nexport function calculateOverlayMutation(\n doc: MutableDocument,\n mask: FieldMask | null\n): Mutation | null {\n if (!doc.hasLocalMutations || (mask && mask!.fields.length === 0)) {\n return null;\n }\n\n // mask is null when sets or deletes are applied to the current document.\n if (mask === null) {\n if (doc.isNoDocument()) {\n return new DeleteMutation(doc.key, Precondition.none());\n } else {\n return new SetMutation(doc.key, doc.data, Precondition.none());\n }\n } else {\n const docValue = doc.data;\n const patchValue = ObjectValue.empty();\n let maskSet = new SortedSet(FieldPath.comparator);\n for (let path of mask.fields) {\n if (!maskSet.has(path)) {\n let value = docValue.field(path);\n // If we are deleting a nested field, we take the immediate parent as\n // the mask used to construct the resulting mutation.\n // Justification: Nested fields can create parent fields implicitly. If\n // only a leaf entry is deleted in later mutations, the parent field\n // should still remain, but we may have lost this information.\n // Consider mutation (foo.bar 1), then mutation (foo.bar delete()).\n // This leaves the final result (foo, {}). Despite the fact that `doc`\n // has the correct result, `foo` is not in `mask`, and the resulting\n // mutation would miss `foo`.\n if (value === null && path.length > 1) {\n path = path.popLast();\n value = docValue.field(path);\n }\n if (value === null) {\n patchValue.delete(path);\n } else {\n patchValue.set(path, value);\n }\n maskSet = maskSet.add(path);\n }\n }\n return new PatchMutation(\n doc.key,\n patchValue,\n new FieldMask(maskSet.toArray()),\n Precondition.none()\n );\n }\n}\n\n/**\n * Applies this mutation to the given document for the purposes of computing a\n * new remote document. If the input document doesn't match the expected state\n * (e.g. it is invalid or outdated), the document type may transition to\n * unknown.\n *\n * @param mutation - The mutation to apply.\n * @param document - The document to mutate. The input document can be an\n * invalid document if the client has no knowledge of the pre-mutation state\n * of the document.\n * @param mutationResult - The result of applying the mutation from the backend.\n */\nexport function mutationApplyToRemoteDocument(\n mutation: Mutation,\n document: MutableDocument,\n mutationResult: MutationResult\n): void {\n mutationVerifyKeyMatches(mutation, document);\n if (mutation instanceof SetMutation) {\n setMutationApplyToRemoteDocument(mutation, document, mutationResult);\n } else if (mutation instanceof PatchMutation) {\n patchMutationApplyToRemoteDocument(mutation, document, mutationResult);\n } else {\n debugAssert(\n mutation instanceof DeleteMutation,\n 'Unexpected mutation type: ' + mutation\n );\n deleteMutationApplyToRemoteDocument(mutation, document, mutationResult);\n }\n}\n\n/**\n * Applies this mutation to the given document for the purposes of computing\n * the new local view of a document. If the input document doesn't match the\n * expected state, the document is not modified.\n *\n * @param mutation - The mutation to apply.\n * @param document - The document to mutate. The input document can be an\n * invalid document if the client has no knowledge of the pre-mutation state\n * of the document.\n * @param previousMask - The fields that have been updated before applying this mutation.\n * @param localWriteTime - A timestamp indicating the local write time of the\n * batch this mutation is a part of.\n * @returns A `FieldMask` representing the fields that are changed by applying this mutation.\n */\nexport function mutationApplyToLocalView(\n mutation: Mutation,\n document: MutableDocument,\n previousMask: FieldMask | null,\n localWriteTime: Timestamp\n): FieldMask | null {\n mutationVerifyKeyMatches(mutation, document);\n\n if (mutation instanceof SetMutation) {\n return setMutationApplyToLocalView(\n mutation,\n document,\n previousMask,\n localWriteTime\n );\n } else if (mutation instanceof PatchMutation) {\n return patchMutationApplyToLocalView(\n mutation,\n document,\n previousMask,\n localWriteTime\n );\n } else {\n debugAssert(\n mutation instanceof DeleteMutation,\n 'Unexpected mutation type: ' + mutation\n );\n return deleteMutationApplyToLocalView(mutation, document, previousMask);\n }\n}\n\n/**\n * If this mutation is not idempotent, returns the base value to persist with\n * this mutation. If a base value is returned, the mutation is always applied\n * to this base value, even if document has already been updated.\n *\n * The base value is a sparse object that consists of only the document\n * fields for which this mutation contains a non-idempotent transformation\n * (e.g. a numeric increment). The provided value guarantees consistent\n * behavior for non-idempotent transforms and allow us to return the same\n * latency-compensated value even if the backend has already applied the\n * mutation. The base value is null for idempotent mutations, as they can be\n * re-played even if the backend has already applied them.\n *\n * @returns a base value to store along with the mutation, or null for\n * idempotent mutations.\n */\nexport function mutationExtractBaseValue(\n mutation: Mutation,\n document: Document\n): ObjectValue | null {\n let baseObject: ObjectValue | null = null;\n for (const fieldTransform of mutation.fieldTransforms) {\n const existingValue = document.data.field(fieldTransform.field);\n const coercedValue = computeTransformOperationBaseValue(\n fieldTransform.transform,\n existingValue || null\n );\n\n if (coercedValue != null) {\n if (baseObject === null) {\n baseObject = ObjectValue.empty();\n }\n baseObject.set(fieldTransform.field, coercedValue);\n }\n }\n return baseObject ? baseObject : null;\n}\n\nexport function mutationEquals(left: Mutation, right: Mutation): boolean {\n if (left.type !== right.type) {\n return false;\n }\n\n if (!left.key.isEqual(right.key)) {\n return false;\n }\n\n if (!left.precondition.isEqual(right.precondition)) {\n return false;\n }\n\n if (!fieldTransformsAreEqual(left.fieldTransforms, right.fieldTransforms)) {\n return false;\n }\n\n if (left.type === MutationType.Set) {\n return (left as SetMutation).value.isEqual((right as SetMutation).value);\n }\n\n if (left.type === MutationType.Patch) {\n return (\n (left as PatchMutation).data.isEqual((right as PatchMutation).data) &&\n (left as PatchMutation).fieldMask.isEqual(\n (right as PatchMutation).fieldMask\n )\n );\n }\n\n return true;\n}\n\nfunction mutationVerifyKeyMatches(\n mutation: Mutation,\n document: MutableDocument\n): void {\n debugAssert(\n document.key.isEqual(mutation.key),\n 'Can only apply a mutation to a document with the same key'\n );\n}\n\n/**\n * A mutation that creates or replaces the document at the given key with the\n * object value contents.\n */\nexport class SetMutation extends Mutation {\n constructor(\n readonly key: DocumentKey,\n readonly value: ObjectValue,\n readonly precondition: Precondition,\n readonly fieldTransforms: FieldTransform[] = []\n ) {\n super();\n }\n\n readonly type: MutationType = MutationType.Set;\n\n getFieldMask(): FieldMask | null {\n return null;\n }\n}\n\nfunction setMutationApplyToRemoteDocument(\n mutation: SetMutation,\n document: MutableDocument,\n mutationResult: MutationResult\n): void {\n // Unlike setMutationApplyToLocalView, if we're applying a mutation to a\n // remote document the server has accepted the mutation so the precondition\n // must have held.\n const newData = mutation.value.clone();\n const transformResults = serverTransformResults(\n mutation.fieldTransforms,\n document,\n mutationResult.transformResults\n );\n newData.setAll(transformResults);\n document\n .convertToFoundDocument(mutationResult.version, newData)\n .setHasCommittedMutations();\n}\n\nfunction setMutationApplyToLocalView(\n mutation: SetMutation,\n document: MutableDocument,\n previousMask: FieldMask | null,\n localWriteTime: Timestamp\n): FieldMask | null {\n if (!preconditionIsValidForDocument(mutation.precondition, document)) {\n // The mutation failed to apply (e.g. a document ID created with add()\n // caused a name collision).\n return previousMask;\n }\n\n const newData = mutation.value.clone();\n const transformResults = localTransformResults(\n mutation.fieldTransforms,\n localWriteTime,\n document\n );\n newData.setAll(transformResults);\n document\n .convertToFoundDocument(document.version, newData)\n .setHasLocalMutations();\n return null; // SetMutation overwrites all fields.\n}\n\n/**\n * A mutation that modifies fields of the document at the given key with the\n * given values. The values are applied through a field mask:\n *\n * * When a field is in both the mask and the values, the corresponding field\n * is updated.\n * * When a field is in neither the mask nor the values, the corresponding\n * field is unmodified.\n * * When a field is in the mask but not in the values, the corresponding field\n * is deleted.\n * * When a field is not in the mask but is in the values, the values map is\n * ignored.\n */\nexport class PatchMutation extends Mutation {\n constructor(\n readonly key: DocumentKey,\n readonly data: ObjectValue,\n readonly fieldMask: FieldMask,\n readonly precondition: Precondition,\n readonly fieldTransforms: FieldTransform[] = []\n ) {\n super();\n }\n\n readonly type: MutationType = MutationType.Patch;\n\n getFieldMask(): FieldMask | null {\n return this.fieldMask;\n }\n}\n\nfunction patchMutationApplyToRemoteDocument(\n mutation: PatchMutation,\n document: MutableDocument,\n mutationResult: MutationResult\n): void {\n if (!preconditionIsValidForDocument(mutation.precondition, document)) {\n // Since the mutation was not rejected, we know that the precondition\n // matched on the backend. We therefore must not have the expected version\n // of the document in our cache and convert to an UnknownDocument with a\n // known updateTime.\n document.convertToUnknownDocument(mutationResult.version);\n return;\n }\n\n const transformResults = serverTransformResults(\n mutation.fieldTransforms,\n document,\n mutationResult.transformResults\n );\n const newData = document.data;\n newData.setAll(getPatch(mutation));\n newData.setAll(transformResults);\n document\n .convertToFoundDocument(mutationResult.version, newData)\n .setHasCommittedMutations();\n}\n\nfunction patchMutationApplyToLocalView(\n mutation: PatchMutation,\n document: MutableDocument,\n previousMask: FieldMask | null,\n localWriteTime: Timestamp\n): FieldMask | null {\n if (!preconditionIsValidForDocument(mutation.precondition, document)) {\n return previousMask;\n }\n\n const transformResults = localTransformResults(\n mutation.fieldTransforms,\n localWriteTime,\n document\n );\n const newData = document.data;\n newData.setAll(getPatch(mutation));\n newData.setAll(transformResults);\n document\n .convertToFoundDocument(document.version, newData)\n .setHasLocalMutations();\n\n if (previousMask === null) {\n return null;\n }\n\n return previousMask\n .unionWith(mutation.fieldMask.fields)\n .unionWith(mutation.fieldTransforms.map(transform => transform.field));\n}\n\n/**\n * Returns a FieldPath/Value map with the content of the PatchMutation.\n */\nfunction getPatch(mutation: PatchMutation): Map {\n const result = new Map();\n mutation.fieldMask.fields.forEach(fieldPath => {\n if (!fieldPath.isEmpty()) {\n const newValue = mutation.data.field(fieldPath);\n result.set(fieldPath, newValue);\n }\n });\n return result;\n}\n\n/**\n * Creates a list of \"transform results\" (a transform result is a field value\n * representing the result of applying a transform) for use after a mutation\n * containing transforms has been acknowledged by the server.\n *\n * @param fieldTransforms - The field transforms to apply the result to.\n * @param mutableDocument - The current state of the document after applying all\n * previous mutations.\n * @param serverTransformResults - The transform results received by the server.\n * @returns The transform results list.\n */\nfunction serverTransformResults(\n fieldTransforms: FieldTransform[],\n mutableDocument: MutableDocument,\n serverTransformResults: Array\n): Map {\n const transformResults = new Map();\n hardAssert(\n fieldTransforms.length === serverTransformResults.length,\n 0x7f90,\n 'server transform result count should match field transform count',\n {\n serverTransformResultCount: serverTransformResults.length,\n fieldTransformCount: fieldTransforms.length\n }\n );\n\n for (let i = 0; i < serverTransformResults.length; i++) {\n const fieldTransform = fieldTransforms[i];\n const transform = fieldTransform.transform;\n const previousValue = mutableDocument.data.field(fieldTransform.field);\n transformResults.set(\n fieldTransform.field,\n applyTransformOperationToRemoteDocument(\n transform,\n previousValue,\n serverTransformResults[i]\n )\n );\n }\n return transformResults;\n}\n\n/**\n * Creates a list of \"transform results\" (a transform result is a field value\n * representing the result of applying a transform) for use when applying a\n * transform locally.\n *\n * @param fieldTransforms - The field transforms to apply the result to.\n * @param localWriteTime - The local time of the mutation (used to\n * generate ServerTimestampValues).\n * @param mutableDocument - The document to apply transforms on.\n * @returns The transform results list.\n */\nfunction localTransformResults(\n fieldTransforms: FieldTransform[],\n localWriteTime: Timestamp,\n mutableDocument: MutableDocument\n): Map {\n const transformResults = new Map();\n for (const fieldTransform of fieldTransforms) {\n const transform = fieldTransform.transform;\n\n const previousValue = mutableDocument.data.field(fieldTransform.field);\n transformResults.set(\n fieldTransform.field,\n applyTransformOperationToLocalView(\n transform,\n previousValue,\n localWriteTime\n )\n );\n }\n return transformResults;\n}\n\n/** A mutation that deletes the document at the given key. */\nexport class DeleteMutation extends Mutation {\n constructor(readonly key: DocumentKey, readonly precondition: Precondition) {\n super();\n }\n\n readonly type: MutationType = MutationType.Delete;\n readonly fieldTransforms: FieldTransform[] = [];\n\n getFieldMask(): FieldMask | null {\n return null;\n }\n}\n\nfunction deleteMutationApplyToRemoteDocument(\n mutation: DeleteMutation,\n document: MutableDocument,\n mutationResult: MutationResult\n): void {\n debugAssert(\n mutationResult.transformResults.length === 0,\n 'Transform results received by DeleteMutation.'\n );\n\n // Unlike applyToLocalView, if we're applying a mutation to a remote\n // document the server has accepted the mutation so the precondition must\n // have held.\n document\n .convertToNoDocument(mutationResult.version)\n .setHasCommittedMutations();\n}\n\nfunction deleteMutationApplyToLocalView(\n mutation: DeleteMutation,\n document: MutableDocument,\n previousMask: FieldMask | null\n): FieldMask | null {\n debugAssert(\n document.key.isEqual(mutation.key),\n 'Can only apply mutation to document with same key'\n );\n if (preconditionIsValidForDocument(mutation.precondition, document)) {\n document.convertToNoDocument(document.version).setHasLocalMutations();\n return null;\n }\n return previousMask;\n}\n\n/**\n * A mutation that verifies the existence of the document at the given key with\n * the provided precondition.\n *\n * The `verify` operation is only used in Transactions, and this class serves\n * primarily to facilitate serialization into protos.\n */\nexport class VerifyMutation extends Mutation {\n constructor(readonly key: DocumentKey, readonly precondition: Precondition) {\n super();\n }\n\n readonly type: MutationType = MutationType.Verify;\n readonly fieldTransforms: FieldTransform[] = [];\n\n getFieldMask(): FieldMask | null {\n return null;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Aggregate } from '../core/aggregate';\nimport { Bound } from '../core/bound';\nimport { DatabaseId } from '../core/database_info';\nimport {\n CompositeFilter,\n compositeFilterIsFlatConjunction,\n CompositeOperator,\n FieldFilter,\n Filter,\n Operator\n} from '../core/filter';\nimport { Direction, OrderBy } from '../core/order_by';\nimport {\n LimitType,\n newQuery,\n newQueryForPath,\n Query,\n queryToTarget\n} from '../core/query';\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { targetIsDocumentTarget, Target } from '../core/target';\nimport { TargetId } from '../core/types';\nimport { Timestamp } from '../lite-api/timestamp';\nimport { TargetData, TargetPurpose } from '../local/target_data';\nimport { MutableDocument } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { FieldMask } from '../model/field_mask';\nimport {\n DeleteMutation,\n FieldTransform,\n Mutation,\n MutationResult,\n PatchMutation,\n Precondition,\n SetMutation,\n VerifyMutation\n} from '../model/mutation';\nimport { normalizeTimestamp } from '../model/normalize';\nimport { ObjectValue } from '../model/object_value';\nimport { FieldPath, ResourcePath } from '../model/path';\nimport {\n ArrayRemoveTransformOperation,\n ArrayUnionTransformOperation,\n NumericIncrementTransformOperation,\n ServerTimestampTransform,\n TransformOperation\n} from '../model/transform_operation';\nimport { isNanValue, isNullValue } from '../model/values';\nimport {\n ApiClientObjectMap as ProtoApiClientObjectMap,\n BatchGetDocumentsResponse as ProtoBatchGetDocumentsResponse,\n CompositeFilterOp as ProtoCompositeFilterOp,\n Cursor as ProtoCursor,\n Document as ProtoDocument,\n DocumentMask as ProtoDocumentMask,\n DocumentsTarget as ProtoDocumentsTarget,\n FieldFilterOp as ProtoFieldFilterOp,\n FieldReference as ProtoFieldReference,\n FieldTransform as ProtoFieldTransform,\n Filter as ProtoFilter,\n ListenResponse as ProtoListenResponse,\n Order as ProtoOrder,\n OrderDirection as ProtoOrderDirection,\n Precondition as ProtoPrecondition,\n QueryTarget as ProtoQueryTarget,\n RunAggregationQueryRequest as ProtoRunAggregationQueryRequest,\n Aggregation as ProtoAggregation,\n Status as ProtoStatus,\n Target as ProtoTarget,\n TargetChangeTargetChangeType as ProtoTargetChangeTargetChangeType,\n Timestamp as ProtoTimestamp,\n Write as ProtoWrite,\n WriteResult as ProtoWriteResult\n} from '../protos/firestore_proto_api';\nimport { debugAssert, fail, hardAssert } from '../util/assert';\nimport { ByteString } from '../util/byte_string';\nimport { Code, FirestoreError } from '../util/error';\nimport { isNullOrUndefined } from '../util/types';\n\nimport { ExistenceFilter } from './existence_filter';\nimport { Serializer } from './number_serializer';\nimport { mapCodeFromRpcCode } from './rpc_error';\nimport {\n DocumentWatchChange,\n ExistenceFilterChange,\n WatchChange,\n WatchTargetChange,\n WatchTargetChangeState\n} from './watch_change';\n\nconst DIRECTIONS = (() => {\n const dirs: { [dir: string]: ProtoOrderDirection } = {};\n dirs[Direction.ASCENDING] = 'ASCENDING';\n dirs[Direction.DESCENDING] = 'DESCENDING';\n return dirs;\n})();\n\nconst OPERATORS = (() => {\n const ops: { [op: string]: ProtoFieldFilterOp } = {};\n ops[Operator.LESS_THAN] = 'LESS_THAN';\n ops[Operator.LESS_THAN_OR_EQUAL] = 'LESS_THAN_OR_EQUAL';\n ops[Operator.GREATER_THAN] = 'GREATER_THAN';\n ops[Operator.GREATER_THAN_OR_EQUAL] = 'GREATER_THAN_OR_EQUAL';\n ops[Operator.EQUAL] = 'EQUAL';\n ops[Operator.NOT_EQUAL] = 'NOT_EQUAL';\n ops[Operator.ARRAY_CONTAINS] = 'ARRAY_CONTAINS';\n ops[Operator.IN] = 'IN';\n ops[Operator.NOT_IN] = 'NOT_IN';\n ops[Operator.ARRAY_CONTAINS_ANY] = 'ARRAY_CONTAINS_ANY';\n return ops;\n})();\n\nconst COMPOSITE_OPERATORS = (() => {\n const ops: { [op: string]: ProtoCompositeFilterOp } = {};\n ops[CompositeOperator.AND] = 'AND';\n ops[CompositeOperator.OR] = 'OR';\n return ops;\n})();\n\nfunction assertPresent(value: unknown, description: string): asserts value {\n debugAssert(!isNullOrUndefined(value), description + ' is missing');\n}\n\n/**\n * This class generates JsonObject values for the Datastore API suitable for\n * sending to either GRPC stub methods or via the JSON/HTTP REST API.\n *\n * The serializer supports both Protobuf.js and Proto3 JSON formats. By\n * setting `useProto3Json` to true, the serializer will use the Proto3 JSON\n * format.\n *\n * For a description of the Proto3 JSON format check\n * https://developers.google.com/protocol-buffers/docs/proto3#json\n *\n * TODO(klimt): We can remove the databaseId argument if we keep the full\n * resource name in documents.\n */\nexport class JsonProtoSerializer implements Serializer {\n constructor(\n readonly databaseId: DatabaseId,\n readonly useProto3Json: boolean\n ) {}\n}\n\nfunction fromRpcStatus(status: ProtoStatus): FirestoreError {\n const code =\n status.code === undefined ? Code.UNKNOWN : mapCodeFromRpcCode(status.code);\n return new FirestoreError(code, status.message || '');\n}\n\n/**\n * Returns a value for a number (or null) that's appropriate to put into\n * a google.protobuf.Int32Value proto.\n * DO NOT USE THIS FOR ANYTHING ELSE.\n * This method cheats. It's typed as returning \"number\" because that's what\n * our generated proto interfaces say Int32Value must be. But GRPC actually\n * expects a { value: } struct.\n */\nfunction toInt32Proto(\n serializer: JsonProtoSerializer,\n val: number | null\n): number | { value: number } | null {\n if (serializer.useProto3Json || isNullOrUndefined(val)) {\n return val;\n } else {\n return { value: val };\n }\n}\n\n/**\n * Returns a number (or null) from a google.protobuf.Int32Value proto.\n */\nfunction fromInt32Proto(\n val: number | { value: number } | undefined\n): number | null {\n let result;\n if (typeof val === 'object') {\n result = val.value;\n } else {\n result = val;\n }\n return isNullOrUndefined(result) ? null : result;\n}\n\n/**\n * Returns a value for a Date that's appropriate to put into a proto.\n */\nexport function toTimestamp(\n serializer: JsonProtoSerializer,\n timestamp: Timestamp\n): ProtoTimestamp {\n if (serializer.useProto3Json) {\n // Serialize to ISO-8601 date format, but with full nano resolution.\n // Since JS Date has only millis, let's only use it for the seconds and\n // then manually add the fractions to the end.\n const jsDateStr = new Date(timestamp.seconds * 1000).toISOString();\n // Remove .xxx frac part and Z in the end.\n const strUntilSeconds = jsDateStr.replace(/\\.\\d*/, '').replace('Z', '');\n // Pad the fraction out to 9 digits (nanos).\n const nanoStr = ('000000000' + timestamp.nanoseconds).slice(-9);\n\n return `${strUntilSeconds}.${nanoStr}Z`;\n } else {\n return {\n seconds: '' + timestamp.seconds,\n nanos: timestamp.nanoseconds\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } as any;\n }\n}\n\n/**\n * Returns a Timestamp typed object given protobuf timestamp value.\n */\nexport function fromTimestamp(date: ProtoTimestamp): Timestamp {\n const timestamp = normalizeTimestamp(date);\n return new Timestamp(timestamp.seconds, timestamp.nanos);\n}\n\n/**\n * Returns a value for bytes that's appropriate to put in a proto.\n *\n * Visible for testing.\n */\nexport function toBytes(\n serializer: JsonProtoSerializer,\n bytes: ByteString\n): string | Uint8Array {\n if (serializer.useProto3Json) {\n return bytes.toBase64();\n } else {\n return bytes.toUint8Array();\n }\n}\n\n/**\n * Returns a ByteString based on the proto string value.\n */\nexport function fromBytes(\n serializer: JsonProtoSerializer,\n value: string | Uint8Array | undefined\n): ByteString {\n if (serializer.useProto3Json) {\n hardAssert(\n value === undefined || typeof value === 'string',\n 0xe30b,\n 'value must be undefined or a string when using proto3 Json'\n );\n return ByteString.fromBase64String(value ? value : '');\n } else {\n hardAssert(\n value === undefined ||\n // Check if the value is an instance of both Buffer and Uint8Array,\n // despite the fact that Buffer extends Uint8Array. In some\n // environments, such as jsdom, the prototype chain of Buffer\n // does not indicate that it extends Uint8Array.\n value instanceof Buffer ||\n value instanceof Uint8Array,\n 0x3f41,\n 'value must be undefined, Buffer, or Uint8Array'\n );\n return ByteString.fromUint8Array(value ? value : new Uint8Array());\n }\n}\n\nexport function toVersion(\n serializer: JsonProtoSerializer,\n version: SnapshotVersion\n): ProtoTimestamp {\n return toTimestamp(serializer, version.toTimestamp());\n}\n\nexport function fromVersion(version: ProtoTimestamp): SnapshotVersion {\n hardAssert(!!version, 0xc050, \"Trying to deserialize version that isn't set\");\n return SnapshotVersion.fromTimestamp(fromTimestamp(version));\n}\n\nexport function toResourceName(\n databaseId: DatabaseId,\n path: ResourcePath\n): string {\n return toResourcePath(databaseId, path).canonicalString();\n}\n\nexport function toResourcePath(\n databaseId: DatabaseId,\n path?: ResourcePath\n): ResourcePath {\n const resourcePath = fullyQualifiedPrefixPath(databaseId).child('documents');\n return path === undefined ? resourcePath : resourcePath.child(path);\n}\n\nfunction fromResourceName(name: string): ResourcePath {\n const resource = ResourcePath.fromString(name);\n hardAssert(\n isValidResourceName(resource),\n 0x27ce,\n 'Tried to deserialize invalid key',\n { key: resource.toString() }\n );\n return resource;\n}\n\nexport function toName(\n serializer: JsonProtoSerializer,\n key: DocumentKey\n): string {\n return toResourceName(serializer.databaseId, key.path);\n}\n\nexport function fromName(\n serializer: JsonProtoSerializer,\n name: string\n): DocumentKey {\n const resource = fromResourceName(name);\n\n if (resource.get(1) !== serializer.databaseId.projectId) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Tried to deserialize key from different project: ' +\n resource.get(1) +\n ' vs ' +\n serializer.databaseId.projectId\n );\n }\n\n if (resource.get(3) !== serializer.databaseId.database) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Tried to deserialize key from different database: ' +\n resource.get(3) +\n ' vs ' +\n serializer.databaseId.database\n );\n }\n return new DocumentKey(extractLocalPathFromResourceName(resource));\n}\n\nfunction toQueryPath(\n serializer: JsonProtoSerializer,\n path: ResourcePath\n): string {\n return toResourceName(serializer.databaseId, path);\n}\n\nfunction fromQueryPath(name: string): ResourcePath {\n const resourceName = fromResourceName(name);\n // In v1beta1 queries for collections at the root did not have a trailing\n // \"/documents\". In v1 all resource paths contain \"/documents\". Preserve the\n // ability to read the v1beta1 form for compatibility with queries persisted\n // in the local target cache.\n if (resourceName.length === 4) {\n return ResourcePath.emptyPath();\n }\n return extractLocalPathFromResourceName(resourceName);\n}\n\nexport function getEncodedDatabaseId(serializer: JsonProtoSerializer): string {\n const path = new ResourcePath([\n 'projects',\n serializer.databaseId.projectId,\n 'databases',\n serializer.databaseId.database\n ]);\n return path.canonicalString();\n}\n\nfunction fullyQualifiedPrefixPath(databaseId: DatabaseId): ResourcePath {\n return new ResourcePath([\n 'projects',\n databaseId.projectId,\n 'databases',\n databaseId.database\n ]);\n}\n\nfunction extractLocalPathFromResourceName(\n resourceName: ResourcePath\n): ResourcePath {\n hardAssert(\n resourceName.length > 4 && resourceName.get(4) === 'documents',\n 0x71a3,\n 'tried to deserialize invalid key',\n { key: resourceName.toString() }\n );\n return resourceName.popFirst(5);\n}\n\n/** Creates a Document proto from key and fields (but no create/update time) */\nexport function toMutationDocument(\n serializer: JsonProtoSerializer,\n key: DocumentKey,\n fields: ObjectValue\n): ProtoDocument {\n return {\n name: toName(serializer, key),\n fields: fields.value.mapValue.fields\n };\n}\n\nexport function toDocument(\n serializer: JsonProtoSerializer,\n document: MutableDocument\n): ProtoDocument {\n debugAssert(\n !document.hasLocalMutations,\n \"Can't serialize documents with mutations.\"\n );\n return {\n name: toName(serializer, document.key),\n fields: document.data.value.mapValue.fields,\n updateTime: toTimestamp(serializer, document.version.toTimestamp()),\n createTime: toTimestamp(serializer, document.createTime.toTimestamp())\n };\n}\n\nexport function fromDocument(\n serializer: JsonProtoSerializer,\n document: ProtoDocument,\n hasCommittedMutations?: boolean\n): MutableDocument {\n const key = fromName(serializer, document.name!);\n const version = fromVersion(document.updateTime!);\n // If we read a document from persistence that is missing createTime, it's due\n // to older SDK versions not storing this information. In such cases, we'll\n // set the createTime to zero. This can be removed in the long term.\n const createTime = document.createTime\n ? fromVersion(document.createTime)\n : SnapshotVersion.min();\n const data = new ObjectValue({ mapValue: { fields: document.fields } });\n const result = MutableDocument.newFoundDocument(\n key,\n version,\n createTime,\n data\n );\n if (hasCommittedMutations) {\n result.setHasCommittedMutations();\n }\n return hasCommittedMutations ? result.setHasCommittedMutations() : result;\n}\n\nfunction fromFound(\n serializer: JsonProtoSerializer,\n doc: ProtoBatchGetDocumentsResponse\n): MutableDocument {\n hardAssert(\n !!doc.found,\n 0xaa33,\n 'Tried to deserialize a found document from a missing document.'\n );\n assertPresent(doc.found.name, 'doc.found.name');\n assertPresent(doc.found.updateTime, 'doc.found.updateTime');\n const key = fromName(serializer, doc.found.name);\n const version = fromVersion(doc.found.updateTime);\n const createTime = doc.found.createTime\n ? fromVersion(doc.found.createTime)\n : SnapshotVersion.min();\n const data = new ObjectValue({ mapValue: { fields: doc.found.fields } });\n return MutableDocument.newFoundDocument(key, version, createTime, data);\n}\n\nfunction fromMissing(\n serializer: JsonProtoSerializer,\n result: ProtoBatchGetDocumentsResponse\n): MutableDocument {\n hardAssert(\n !!result.missing,\n 0x0f36,\n 'Tried to deserialize a missing document from a found document.'\n );\n hardAssert(\n !!result.readTime,\n 0x5995,\n 'Tried to deserialize a missing document without a read time.'\n );\n const key = fromName(serializer, result.missing);\n const version = fromVersion(result.readTime);\n return MutableDocument.newNoDocument(key, version);\n}\n\nexport function fromBatchGetDocumentsResponse(\n serializer: JsonProtoSerializer,\n result: ProtoBatchGetDocumentsResponse\n): MutableDocument {\n if ('found' in result) {\n return fromFound(serializer, result);\n } else if ('missing' in result) {\n return fromMissing(serializer, result);\n }\n return fail(0x1c42, 'invalid batch get response', { result });\n}\n\nexport function fromWatchChange(\n serializer: JsonProtoSerializer,\n change: ProtoListenResponse\n): WatchChange {\n let watchChange: WatchChange;\n if ('targetChange' in change) {\n assertPresent(change.targetChange, 'targetChange');\n // proto3 default value is unset in JSON (undefined), so use 'NO_CHANGE'\n // if unset\n const state = fromWatchTargetChangeState(\n change.targetChange.targetChangeType || 'NO_CHANGE'\n );\n const targetIds: TargetId[] = change.targetChange.targetIds || [];\n\n const resumeToken = fromBytes(serializer, change.targetChange.resumeToken);\n const causeProto = change.targetChange!.cause;\n const cause = causeProto && fromRpcStatus(causeProto);\n watchChange = new WatchTargetChange(\n state,\n targetIds,\n resumeToken,\n cause || null\n );\n } else if ('documentChange' in change) {\n assertPresent(change.documentChange, 'documentChange');\n const entityChange = change.documentChange;\n assertPresent(entityChange.document, 'documentChange.name');\n assertPresent(entityChange.document.name, 'documentChange.document.name');\n assertPresent(\n entityChange.document.updateTime,\n 'documentChange.document.updateTime'\n );\n const key = fromName(serializer, entityChange.document.name);\n const version = fromVersion(entityChange.document.updateTime);\n const createTime = entityChange.document.createTime\n ? fromVersion(entityChange.document.createTime)\n : SnapshotVersion.min();\n const data = new ObjectValue({\n mapValue: { fields: entityChange.document.fields }\n });\n const doc = MutableDocument.newFoundDocument(\n key,\n version,\n createTime,\n data\n );\n const updatedTargetIds = entityChange.targetIds || [];\n const removedTargetIds = entityChange.removedTargetIds || [];\n watchChange = new DocumentWatchChange(\n updatedTargetIds,\n removedTargetIds,\n doc.key,\n doc\n );\n } else if ('documentDelete' in change) {\n assertPresent(change.documentDelete, 'documentDelete');\n const docDelete = change.documentDelete;\n assertPresent(docDelete.document, 'documentDelete.document');\n const key = fromName(serializer, docDelete.document);\n const version = docDelete.readTime\n ? fromVersion(docDelete.readTime)\n : SnapshotVersion.min();\n const doc = MutableDocument.newNoDocument(key, version);\n const removedTargetIds = docDelete.removedTargetIds || [];\n watchChange = new DocumentWatchChange([], removedTargetIds, doc.key, doc);\n } else if ('documentRemove' in change) {\n assertPresent(change.documentRemove, 'documentRemove');\n const docRemove = change.documentRemove;\n assertPresent(docRemove.document, 'documentRemove');\n const key = fromName(serializer, docRemove.document);\n const removedTargetIds = docRemove.removedTargetIds || [];\n watchChange = new DocumentWatchChange([], removedTargetIds, key, null);\n } else if ('filter' in change) {\n // TODO(dimond): implement existence filter parsing with strategy.\n assertPresent(change.filter, 'filter');\n const filter = change.filter;\n assertPresent(filter.targetId, 'filter.targetId');\n const { count = 0, unchangedNames } = filter;\n const existenceFilter = new ExistenceFilter(count, unchangedNames);\n const targetId = filter.targetId;\n watchChange = new ExistenceFilterChange(targetId, existenceFilter);\n } else {\n return fail(0x2d51, 'Unknown change type', { change });\n }\n return watchChange;\n}\n\nfunction fromWatchTargetChangeState(\n state: ProtoTargetChangeTargetChangeType\n): WatchTargetChangeState {\n if (state === 'NO_CHANGE') {\n return WatchTargetChangeState.NoChange;\n } else if (state === 'ADD') {\n return WatchTargetChangeState.Added;\n } else if (state === 'REMOVE') {\n return WatchTargetChangeState.Removed;\n } else if (state === 'CURRENT') {\n return WatchTargetChangeState.Current;\n } else if (state === 'RESET') {\n return WatchTargetChangeState.Reset;\n } else {\n return fail(0x9991, 'Got unexpected TargetChange.state', { state });\n }\n}\n\nexport function versionFromListenResponse(\n change: ProtoListenResponse\n): SnapshotVersion {\n // We have only reached a consistent snapshot for the entire stream if there\n // is a read_time set and it applies to all targets (i.e. the list of\n // targets is empty). The backend is guaranteed to send such responses.\n if (!('targetChange' in change)) {\n return SnapshotVersion.min();\n }\n const targetChange = change.targetChange!;\n if (targetChange.targetIds && targetChange.targetIds.length) {\n return SnapshotVersion.min();\n }\n if (!targetChange.readTime) {\n return SnapshotVersion.min();\n }\n return fromVersion(targetChange.readTime);\n}\n\nexport function toMutation(\n serializer: JsonProtoSerializer,\n mutation: Mutation\n): ProtoWrite {\n let result: ProtoWrite;\n if (mutation instanceof SetMutation) {\n result = {\n update: toMutationDocument(serializer, mutation.key, mutation.value)\n };\n } else if (mutation instanceof DeleteMutation) {\n result = { delete: toName(serializer, mutation.key) };\n } else if (mutation instanceof PatchMutation) {\n result = {\n update: toMutationDocument(serializer, mutation.key, mutation.data),\n updateMask: toDocumentMask(mutation.fieldMask)\n };\n } else if (mutation instanceof VerifyMutation) {\n result = {\n verify: toName(serializer, mutation.key)\n };\n } else {\n return fail(0x40d7, 'Unknown mutation type', {\n mutationType: mutation.type\n });\n }\n\n if (mutation.fieldTransforms.length > 0) {\n result.updateTransforms = mutation.fieldTransforms.map(transform =>\n toFieldTransform(serializer, transform)\n );\n }\n\n if (!mutation.precondition.isNone) {\n result.currentDocument = toPrecondition(serializer, mutation.precondition);\n }\n\n return result;\n}\n\nexport function fromMutation(\n serializer: JsonProtoSerializer,\n proto: ProtoWrite\n): Mutation {\n const precondition = proto.currentDocument\n ? fromPrecondition(proto.currentDocument)\n : Precondition.none();\n\n const fieldTransforms = proto.updateTransforms\n ? proto.updateTransforms.map(transform =>\n fromFieldTransform(serializer, transform)\n )\n : [];\n\n if (proto.update) {\n assertPresent(proto.update.name, 'name');\n const key = fromName(serializer, proto.update.name);\n const value = new ObjectValue({\n mapValue: { fields: proto.update.fields }\n });\n\n if (proto.updateMask) {\n const fieldMask = fromDocumentMask(proto.updateMask);\n return new PatchMutation(\n key,\n value,\n fieldMask,\n precondition,\n fieldTransforms\n );\n } else {\n return new SetMutation(key, value, precondition, fieldTransforms);\n }\n } else if (proto.delete) {\n const key = fromName(serializer, proto.delete);\n return new DeleteMutation(key, precondition);\n } else if (proto.verify) {\n const key = fromName(serializer, proto.verify);\n return new VerifyMutation(key, precondition);\n } else {\n return fail(0x05b7, 'unknown mutation proto', { proto });\n }\n}\n\nfunction toPrecondition(\n serializer: JsonProtoSerializer,\n precondition: Precondition\n): ProtoPrecondition {\n debugAssert(!precondition.isNone, \"Can't serialize an empty precondition\");\n if (precondition.updateTime !== undefined) {\n return {\n updateTime: toVersion(serializer, precondition.updateTime)\n };\n } else if (precondition.exists !== undefined) {\n return { exists: precondition.exists };\n } else {\n return fail(0x6b69, 'Unknown precondition');\n }\n}\n\nfunction fromPrecondition(precondition: ProtoPrecondition): Precondition {\n if (precondition.updateTime !== undefined) {\n return Precondition.updateTime(fromVersion(precondition.updateTime));\n } else if (precondition.exists !== undefined) {\n return Precondition.exists(precondition.exists);\n } else {\n return Precondition.none();\n }\n}\n\nfunction fromWriteResult(\n proto: ProtoWriteResult,\n commitTime: ProtoTimestamp\n): MutationResult {\n // NOTE: Deletes don't have an updateTime.\n let version = proto.updateTime\n ? fromVersion(proto.updateTime)\n : fromVersion(commitTime);\n\n if (version.isEqual(SnapshotVersion.min())) {\n // The Firestore Emulator currently returns an update time of 0 for\n // deletes of non-existing documents (rather than null). This breaks the\n // test \"get deleted doc while offline with source=cache\" as NoDocuments\n // with version 0 are filtered by IndexedDb's RemoteDocumentCache.\n // TODO(#2149): Remove this when Emulator is fixed\n version = fromVersion(commitTime);\n }\n\n return new MutationResult(version, proto.transformResults || []);\n}\n\nexport function fromWriteResults(\n protos: ProtoWriteResult[] | undefined,\n commitTime?: ProtoTimestamp\n): MutationResult[] {\n if (protos && protos.length > 0) {\n hardAssert(\n commitTime !== undefined,\n 0x3811,\n 'Received a write result without a commit time'\n );\n return protos.map(proto => fromWriteResult(proto, commitTime));\n } else {\n return [];\n }\n}\n\nfunction toFieldTransform(\n serializer: JsonProtoSerializer,\n fieldTransform: FieldTransform\n): ProtoFieldTransform {\n const transform = fieldTransform.transform;\n if (transform instanceof ServerTimestampTransform) {\n return {\n fieldPath: fieldTransform.field.canonicalString(),\n setToServerValue: 'REQUEST_TIME'\n };\n } else if (transform instanceof ArrayUnionTransformOperation) {\n return {\n fieldPath: fieldTransform.field.canonicalString(),\n appendMissingElements: {\n values: transform.elements\n }\n };\n } else if (transform instanceof ArrayRemoveTransformOperation) {\n return {\n fieldPath: fieldTransform.field.canonicalString(),\n removeAllFromArray: {\n values: transform.elements\n }\n };\n } else if (transform instanceof NumericIncrementTransformOperation) {\n return {\n fieldPath: fieldTransform.field.canonicalString(),\n increment: transform.operand\n };\n } else {\n throw fail(0x51c2, 'Unknown transform', {\n transform: fieldTransform.transform\n });\n }\n}\n\nfunction fromFieldTransform(\n serializer: JsonProtoSerializer,\n proto: ProtoFieldTransform\n): FieldTransform {\n let transform: TransformOperation | null = null;\n if ('setToServerValue' in proto) {\n hardAssert(\n proto.setToServerValue === 'REQUEST_TIME',\n 0x40f6,\n 'Unknown server value transform proto',\n { proto }\n );\n transform = new ServerTimestampTransform();\n } else if ('appendMissingElements' in proto) {\n const values = proto.appendMissingElements!.values || [];\n transform = new ArrayUnionTransformOperation(values);\n } else if ('removeAllFromArray' in proto) {\n const values = proto.removeAllFromArray!.values || [];\n transform = new ArrayRemoveTransformOperation(values);\n } else if ('increment' in proto) {\n transform = new NumericIncrementTransformOperation(\n serializer,\n proto.increment!\n );\n } else {\n fail(0x40c8, 'Unknown transform proto', { proto });\n }\n const fieldPath = FieldPath.fromServerFormat(proto.fieldPath!);\n return new FieldTransform(fieldPath, transform!);\n}\n\nexport function toDocumentsTarget(\n serializer: JsonProtoSerializer,\n target: Target\n): ProtoDocumentsTarget {\n return { documents: [toQueryPath(serializer, target.path)] };\n}\n\nexport function fromDocumentsTarget(\n documentsTarget: ProtoDocumentsTarget\n): Target {\n const count = documentsTarget.documents!.length;\n hardAssert(\n count === 1,\n 0x07ae,\n 'DocumentsTarget contained other than 1 document',\n {\n count\n }\n );\n const name = documentsTarget.documents![0];\n return queryToTarget(newQueryForPath(fromQueryPath(name)));\n}\n\nexport function toQueryTarget(\n serializer: JsonProtoSerializer,\n target: Target\n): { queryTarget: ProtoQueryTarget; parent: ResourcePath } {\n // Dissect the path into parent, collectionId, and optional key filter.\n const queryTarget: ProtoQueryTarget = { structuredQuery: {} };\n const path = target.path;\n let parent: ResourcePath;\n if (target.collectionGroup !== null) {\n debugAssert(\n path.length % 2 === 0,\n 'Collection Group queries should be within a document path or root.'\n );\n parent = path;\n queryTarget.structuredQuery!.from = [\n {\n collectionId: target.collectionGroup,\n allDescendants: true\n }\n ];\n } else {\n debugAssert(\n path.length % 2 !== 0,\n 'Document queries with filters are not supported.'\n );\n parent = path.popLast();\n queryTarget.structuredQuery!.from = [{ collectionId: path.lastSegment() }];\n }\n queryTarget.parent = toQueryPath(serializer, parent);\n\n const where = toFilters(target.filters);\n if (where) {\n queryTarget.structuredQuery!.where = where;\n }\n\n const orderBy = toOrder(target.orderBy);\n if (orderBy) {\n queryTarget.structuredQuery!.orderBy = orderBy;\n }\n\n const limit = toInt32Proto(serializer, target.limit);\n if (limit !== null) {\n queryTarget.structuredQuery!.limit = limit;\n }\n\n if (target.startAt) {\n queryTarget.structuredQuery!.startAt = toStartAtCursor(target.startAt);\n }\n if (target.endAt) {\n queryTarget.structuredQuery!.endAt = toEndAtCursor(target.endAt);\n }\n\n return { queryTarget, parent };\n}\n\nexport function toRunAggregationQueryRequest(\n serializer: JsonProtoSerializer,\n target: Target,\n aggregates: Aggregate[],\n skipAliasing?: boolean\n): {\n request: ProtoRunAggregationQueryRequest;\n aliasMap: Record;\n parent: ResourcePath;\n} {\n const { queryTarget, parent } = toQueryTarget(serializer, target);\n const aliasMap: Record = {};\n\n const aggregations: ProtoAggregation[] = [];\n let aggregationNum = 0;\n\n aggregates.forEach(aggregate => {\n // Map all client-side aliases to a unique short-form\n // alias. This avoids issues with client-side aliases that\n // exceed the 1500-byte string size limit.\n const serverAlias = skipAliasing\n ? aggregate.alias\n : `aggregate_${aggregationNum++}`;\n aliasMap[serverAlias] = aggregate.alias;\n\n if (aggregate.aggregateType === 'count') {\n aggregations.push({\n alias: serverAlias,\n count: {}\n });\n } else if (aggregate.aggregateType === 'avg') {\n aggregations.push({\n alias: serverAlias,\n avg: {\n field: toFieldPathReference(aggregate.fieldPath!)\n }\n });\n } else if (aggregate.aggregateType === 'sum') {\n aggregations.push({\n alias: serverAlias,\n sum: {\n field: toFieldPathReference(aggregate.fieldPath!)\n }\n });\n }\n });\n\n return {\n request: {\n structuredAggregationQuery: {\n aggregations,\n structuredQuery: queryTarget.structuredQuery\n },\n parent: queryTarget.parent\n },\n aliasMap,\n parent\n };\n}\n\nexport function convertQueryTargetToQuery(target: ProtoQueryTarget): Query {\n let path = fromQueryPath(target.parent!);\n\n const query = target.structuredQuery!;\n const fromCount = query.from ? query.from.length : 0;\n let collectionGroup: string | null = null;\n if (fromCount > 0) {\n hardAssert(\n fromCount === 1,\n 0xfe26,\n 'StructuredQuery.from with more than one collection is not supported.'\n );\n const from = query.from![0];\n if (from.allDescendants) {\n collectionGroup = from.collectionId!;\n } else {\n path = path.child(from.collectionId!);\n }\n }\n\n let filterBy: Filter[] = [];\n if (query.where) {\n filterBy = fromFilters(query.where);\n }\n\n let orderBy: OrderBy[] = [];\n if (query.orderBy) {\n orderBy = fromOrder(query.orderBy);\n }\n\n let limit: number | null = null;\n if (query.limit) {\n limit = fromInt32Proto(query.limit);\n }\n\n let startAt: Bound | null = null;\n if (query.startAt) {\n startAt = fromStartAtCursor(query.startAt);\n }\n\n let endAt: Bound | null = null;\n if (query.endAt) {\n endAt = fromEndAtCursor(query.endAt);\n }\n\n return newQuery(\n path,\n collectionGroup,\n orderBy,\n filterBy,\n limit,\n LimitType.First,\n startAt,\n endAt\n );\n}\n\nexport function fromQueryTarget(target: ProtoQueryTarget): Target {\n return queryToTarget(convertQueryTargetToQuery(target));\n}\n\nexport function toListenRequestLabels(\n serializer: JsonProtoSerializer,\n targetData: TargetData\n): ProtoApiClientObjectMap | null {\n const value = toLabel(targetData.purpose);\n if (value == null) {\n return null;\n } else {\n return {\n 'goog-listen-tags': value\n };\n }\n}\n\nexport function toLabel(purpose: TargetPurpose): string | null {\n switch (purpose) {\n case TargetPurpose.Listen:\n return null;\n case TargetPurpose.ExistenceFilterMismatch:\n return 'existence-filter-mismatch';\n case TargetPurpose.ExistenceFilterMismatchBloom:\n return 'existence-filter-mismatch-bloom';\n case TargetPurpose.LimboResolution:\n return 'limbo-document';\n default:\n return fail(0x713b, 'Unrecognized query purpose', { purpose });\n }\n}\n\nexport function toTarget(\n serializer: JsonProtoSerializer,\n targetData: TargetData\n): ProtoTarget {\n let result: ProtoTarget;\n const target = targetData.target;\n\n if (targetIsDocumentTarget(target)) {\n result = { documents: toDocumentsTarget(serializer, target) };\n } else {\n result = { query: toQueryTarget(serializer, target).queryTarget };\n }\n\n result.targetId = targetData.targetId;\n\n if (targetData.resumeToken.approximateByteSize() > 0) {\n result.resumeToken = toBytes(serializer, targetData.resumeToken);\n const expectedCount = toInt32Proto(serializer, targetData.expectedCount);\n if (expectedCount !== null) {\n result.expectedCount = expectedCount;\n }\n } else if (targetData.snapshotVersion.compareTo(SnapshotVersion.min()) > 0) {\n // TODO(wuandy): Consider removing above check because it is most likely true.\n // Right now, many tests depend on this behaviour though (leaving min() out\n // of serialization).\n result.readTime = toTimestamp(\n serializer,\n targetData.snapshotVersion.toTimestamp()\n );\n const expectedCount = toInt32Proto(serializer, targetData.expectedCount);\n if (expectedCount !== null) {\n result.expectedCount = expectedCount;\n }\n }\n\n return result;\n}\n\nfunction toFilters(filters: Filter[]): ProtoFilter | undefined {\n if (filters.length === 0) {\n return;\n }\n\n return toFilter(CompositeFilter.create(filters, CompositeOperator.AND));\n}\n\nfunction fromFilters(filter: ProtoFilter): Filter[] {\n const result = fromFilter(filter);\n\n if (\n result instanceof CompositeFilter &&\n compositeFilterIsFlatConjunction(result)\n ) {\n return result.getFilters();\n }\n\n return [result];\n}\n\nfunction fromFilter(filter: ProtoFilter): Filter {\n if (filter.unaryFilter !== undefined) {\n return fromUnaryFilter(filter);\n } else if (filter.fieldFilter !== undefined) {\n return fromFieldFilter(filter);\n } else if (filter.compositeFilter !== undefined) {\n return fromCompositeFilter(filter);\n } else {\n return fail(0x7591, 'Unknown filter', { filter });\n }\n}\n\nfunction toOrder(orderBys: OrderBy[]): ProtoOrder[] | undefined {\n if (orderBys.length === 0) {\n return;\n }\n return orderBys.map(order => toPropertyOrder(order));\n}\n\nfunction fromOrder(orderBys: ProtoOrder[]): OrderBy[] {\n return orderBys.map(order => fromPropertyOrder(order));\n}\n\nfunction toStartAtCursor(cursor: Bound): ProtoCursor {\n return {\n before: cursor.inclusive,\n values: cursor.position\n };\n}\n\nfunction toEndAtCursor(cursor: Bound): ProtoCursor {\n return {\n before: !cursor.inclusive,\n values: cursor.position\n };\n}\n\nfunction fromStartAtCursor(cursor: ProtoCursor): Bound {\n const inclusive = !!cursor.before;\n const position = cursor.values || [];\n return new Bound(position, inclusive);\n}\n\nfunction fromEndAtCursor(cursor: ProtoCursor): Bound {\n const inclusive = !cursor.before;\n const position = cursor.values || [];\n return new Bound(position, inclusive);\n}\n\n// visible for testing\nexport function toDirection(dir: Direction): ProtoOrderDirection {\n return DIRECTIONS[dir];\n}\n\n// visible for testing\nexport function fromDirection(\n dir: ProtoOrderDirection | undefined\n): Direction | undefined {\n switch (dir) {\n case 'ASCENDING':\n return Direction.ASCENDING;\n case 'DESCENDING':\n return Direction.DESCENDING;\n default:\n return undefined;\n }\n}\n\n// visible for testing\nexport function toOperatorName(op: Operator): ProtoFieldFilterOp {\n return OPERATORS[op];\n}\n\nexport function toCompositeOperatorName(\n op: CompositeOperator\n): ProtoCompositeFilterOp {\n return COMPOSITE_OPERATORS[op];\n}\n\nexport function fromOperatorName(op: ProtoFieldFilterOp): Operator {\n switch (op) {\n case 'EQUAL':\n return Operator.EQUAL;\n case 'NOT_EQUAL':\n return Operator.NOT_EQUAL;\n case 'GREATER_THAN':\n return Operator.GREATER_THAN;\n case 'GREATER_THAN_OR_EQUAL':\n return Operator.GREATER_THAN_OR_EQUAL;\n case 'LESS_THAN':\n return Operator.LESS_THAN;\n case 'LESS_THAN_OR_EQUAL':\n return Operator.LESS_THAN_OR_EQUAL;\n case 'ARRAY_CONTAINS':\n return Operator.ARRAY_CONTAINS;\n case 'IN':\n return Operator.IN;\n case 'NOT_IN':\n return Operator.NOT_IN;\n case 'ARRAY_CONTAINS_ANY':\n return Operator.ARRAY_CONTAINS_ANY;\n case 'OPERATOR_UNSPECIFIED':\n return fail(0xe2fe, 'Unspecified operator');\n default:\n return fail(0xc54a, 'Unknown operator');\n }\n}\n\nexport function fromCompositeOperatorName(\n op: ProtoCompositeFilterOp\n): CompositeOperator {\n switch (op) {\n case 'AND':\n return CompositeOperator.AND;\n case 'OR':\n return CompositeOperator.OR;\n default:\n return fail(0x0402, 'Unknown operator');\n }\n}\n\nexport function toFieldPathReference(path: FieldPath): ProtoFieldReference {\n return { fieldPath: path.canonicalString() };\n}\n\nexport function fromFieldPathReference(\n fieldReference: ProtoFieldReference\n): FieldPath {\n return FieldPath.fromServerFormat(fieldReference.fieldPath!);\n}\n\n// visible for testing\nexport function toPropertyOrder(orderBy: OrderBy): ProtoOrder {\n return {\n field: toFieldPathReference(orderBy.field),\n direction: toDirection(orderBy.dir)\n };\n}\n\nexport function fromPropertyOrder(orderBy: ProtoOrder): OrderBy {\n return new OrderBy(\n fromFieldPathReference(orderBy.field!),\n fromDirection(orderBy.direction)\n );\n}\n\n// visible for testing\nexport function toFilter(filter: Filter): ProtoFilter {\n if (filter instanceof FieldFilter) {\n return toUnaryOrFieldFilter(filter);\n } else if (filter instanceof CompositeFilter) {\n return toCompositeFilter(filter);\n } else {\n return fail(0xd65d, 'Unrecognized filter type', { filter });\n }\n}\n\nexport function toCompositeFilter(filter: CompositeFilter): ProtoFilter {\n const protos = filter.getFilters().map(filter => toFilter(filter));\n\n if (protos.length === 1) {\n return protos[0];\n }\n\n return {\n compositeFilter: {\n op: toCompositeOperatorName(filter.op),\n filters: protos\n }\n };\n}\n\nexport function toUnaryOrFieldFilter(filter: FieldFilter): ProtoFilter {\n if (filter.op === Operator.EQUAL) {\n if (isNanValue(filter.value)) {\n return {\n unaryFilter: {\n field: toFieldPathReference(filter.field),\n op: 'IS_NAN'\n }\n };\n } else if (isNullValue(filter.value)) {\n return {\n unaryFilter: {\n field: toFieldPathReference(filter.field),\n op: 'IS_NULL'\n }\n };\n }\n } else if (filter.op === Operator.NOT_EQUAL) {\n if (isNanValue(filter.value)) {\n return {\n unaryFilter: {\n field: toFieldPathReference(filter.field),\n op: 'IS_NOT_NAN'\n }\n };\n } else if (isNullValue(filter.value)) {\n return {\n unaryFilter: {\n field: toFieldPathReference(filter.field),\n op: 'IS_NOT_NULL'\n }\n };\n }\n }\n return {\n fieldFilter: {\n field: toFieldPathReference(filter.field),\n op: toOperatorName(filter.op),\n value: filter.value\n }\n };\n}\n\nexport function fromUnaryFilter(filter: ProtoFilter): Filter {\n switch (filter.unaryFilter!.op!) {\n case 'IS_NAN':\n const nanField = fromFieldPathReference(filter.unaryFilter!.field!);\n return FieldFilter.create(nanField, Operator.EQUAL, {\n doubleValue: NaN\n });\n case 'IS_NULL':\n const nullField = fromFieldPathReference(filter.unaryFilter!.field!);\n return FieldFilter.create(nullField, Operator.EQUAL, {\n nullValue: 'NULL_VALUE'\n });\n case 'IS_NOT_NAN':\n const notNanField = fromFieldPathReference(filter.unaryFilter!.field!);\n return FieldFilter.create(notNanField, Operator.NOT_EQUAL, {\n doubleValue: NaN\n });\n case 'IS_NOT_NULL':\n const notNullField = fromFieldPathReference(filter.unaryFilter!.field!);\n return FieldFilter.create(notNullField, Operator.NOT_EQUAL, {\n nullValue: 'NULL_VALUE'\n });\n case 'OPERATOR_UNSPECIFIED':\n return fail(0xef81, 'Unspecified filter');\n default:\n return fail(0xed36, 'Unknown filter');\n }\n}\n\nexport function fromFieldFilter(filter: ProtoFilter): FieldFilter {\n return FieldFilter.create(\n fromFieldPathReference(filter.fieldFilter!.field!),\n fromOperatorName(filter.fieldFilter!.op!),\n filter.fieldFilter!.value!\n );\n}\n\nexport function fromCompositeFilter(filter: ProtoFilter): CompositeFilter {\n return CompositeFilter.create(\n filter.compositeFilter!.filters!.map(filter => fromFilter(filter)),\n fromCompositeOperatorName(filter.compositeFilter!.op!)\n );\n}\n\nexport function toDocumentMask(fieldMask: FieldMask): ProtoDocumentMask {\n const canonicalFields: string[] = [];\n fieldMask.fields.forEach(field =>\n canonicalFields.push(field.canonicalString())\n );\n return {\n fieldPaths: canonicalFields\n };\n}\n\nexport function fromDocumentMask(proto: ProtoDocumentMask): FieldMask {\n const paths = proto.fieldPaths || [];\n return new FieldMask(paths.map(path => FieldPath.fromServerFormat(path)));\n}\n\nexport function isValidResourceName(path: ResourcePath): boolean {\n // Resource names have at least 4 components (project ID, database ID)\n return (\n path.length >= 4 &&\n path.get(0) === 'projects' &&\n path.get(2) === 'databases'\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** Return the Platform-specific serializer monitor. */\nimport { DatabaseId } from '../../core/database_info';\nimport { JsonProtoSerializer } from '../../remote/serializer';\n\nexport function newSerializer(databaseId: DatabaseId): JsonProtoSerializer {\n return new JsonProtoSerializer(databaseId, /* useProto3Json= */ true);\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { AsyncQueue, DelayedOperation, TimerId } from '../util/async_queue';\nimport { logDebug } from '../util/log';\n\nconst LOG_TAG = 'ExponentialBackoff';\n\n/**\n * Initial backoff time in milliseconds after an error.\n * Set to 1s according to https://cloud.google.com/apis/design/errors.\n */\nconst DEFAULT_BACKOFF_INITIAL_DELAY_MS = 1000;\n\nconst DEFAULT_BACKOFF_FACTOR = 1.5;\n\n/** Maximum backoff time in milliseconds */\nconst DEFAULT_BACKOFF_MAX_DELAY_MS = 60 * 1000;\n\n/**\n * A helper for running delayed tasks following an exponential backoff curve\n * between attempts.\n *\n * Each delay is made up of a \"base\" delay which follows the exponential\n * backoff curve, and a +/- 50% \"jitter\" that is calculated and added to the\n * base delay. This prevents clients from accidentally synchronizing their\n * delays causing spikes of load to the backend.\n */\nexport class ExponentialBackoff {\n private currentBaseMs: number = 0;\n private timerPromise: DelayedOperation | null = null;\n /** The last backoff attempt, as epoch milliseconds. */\n private lastAttemptTime = Date.now();\n\n constructor(\n /**\n * The AsyncQueue to run backoff operations on.\n */\n private readonly queue: AsyncQueue,\n /**\n * The ID to use when scheduling backoff operations on the AsyncQueue.\n */\n private readonly timerId: TimerId,\n /**\n * The initial delay (used as the base delay on the first retry attempt).\n * Note that jitter will still be applied, so the actual delay could be as\n * little as 0.5*initialDelayMs.\n */\n private readonly initialDelayMs: number = DEFAULT_BACKOFF_INITIAL_DELAY_MS,\n /**\n * The multiplier to use to determine the extended base delay after each\n * attempt.\n */\n private readonly backoffFactor: number = DEFAULT_BACKOFF_FACTOR,\n /**\n * The maximum base delay after which no further backoff is performed.\n * Note that jitter will still be applied, so the actual delay could be as\n * much as 1.5*maxDelayMs.\n */\n private readonly maxDelayMs: number = DEFAULT_BACKOFF_MAX_DELAY_MS\n ) {\n this.reset();\n }\n\n /**\n * Resets the backoff delay.\n *\n * The very next backoffAndWait() will have no delay. If it is called again\n * (i.e. due to an error), initialDelayMs (plus jitter) will be used, and\n * subsequent ones will increase according to the backoffFactor.\n */\n reset(): void {\n this.currentBaseMs = 0;\n }\n\n /**\n * Resets the backoff delay to the maximum delay (e.g. for use after a\n * RESOURCE_EXHAUSTED error).\n */\n resetToMax(): void {\n this.currentBaseMs = this.maxDelayMs;\n }\n\n /**\n * Returns a promise that resolves after currentDelayMs, and increases the\n * delay for any subsequent attempts. If there was a pending backoff operation\n * already, it will be canceled.\n */\n backoffAndRun(op: () => Promise): void {\n // Cancel any pending backoff operation.\n this.cancel();\n\n // First schedule using the current base (which may be 0 and should be\n // honored as such).\n const desiredDelayWithJitterMs = Math.floor(\n this.currentBaseMs + this.jitterDelayMs()\n );\n\n // Guard against lastAttemptTime being in the future due to a clock change.\n const delaySoFarMs = Math.max(0, Date.now() - this.lastAttemptTime);\n\n // Guard against the backoff delay already being past.\n const remainingDelayMs = Math.max(\n 0,\n desiredDelayWithJitterMs - delaySoFarMs\n );\n\n if (remainingDelayMs > 0) {\n logDebug(\n LOG_TAG,\n `Backing off for ${remainingDelayMs} ms ` +\n `(base delay: ${this.currentBaseMs} ms, ` +\n `delay with jitter: ${desiredDelayWithJitterMs} ms, ` +\n `last attempt: ${delaySoFarMs} ms ago)`\n );\n }\n\n this.timerPromise = this.queue.enqueueAfterDelay(\n this.timerId,\n remainingDelayMs,\n () => {\n this.lastAttemptTime = Date.now();\n return op();\n }\n );\n\n // Apply backoff factor to determine next delay and ensure it is within\n // bounds.\n this.currentBaseMs *= this.backoffFactor;\n if (this.currentBaseMs < this.initialDelayMs) {\n this.currentBaseMs = this.initialDelayMs;\n }\n if (this.currentBaseMs > this.maxDelayMs) {\n this.currentBaseMs = this.maxDelayMs;\n }\n }\n\n skipBackoff(): void {\n if (this.timerPromise !== null) {\n this.timerPromise.skipDelay();\n this.timerPromise = null;\n }\n }\n\n cancel(): void {\n if (this.timerPromise !== null) {\n this.timerPromise.cancel();\n this.timerPromise = null;\n }\n }\n\n /** Returns a random value in the range [-currentBaseMs/2, currentBaseMs/2] */\n private jitterDelayMs(): number {\n return (Math.random() - 0.5) * this.currentBaseMs;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { CredentialsProvider } from '../api/credentials';\nimport { User } from '../auth/user';\nimport { Aggregate } from '../core/aggregate';\nimport { DatabaseId } from '../core/database_info';\nimport { queryToAggregateTarget, Query, queryToTarget } from '../core/query';\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { Mutation } from '../model/mutation';\nimport { ResourcePath } from '../model/path';\nimport {\n ApiClientObjectMap,\n BatchGetDocumentsRequest as ProtoBatchGetDocumentsRequest,\n BatchGetDocumentsResponse as ProtoBatchGetDocumentsResponse,\n RunAggregationQueryRequest as ProtoRunAggregationQueryRequest,\n RunAggregationQueryResponse as ProtoRunAggregationQueryResponse,\n RunQueryRequest as ProtoRunQueryRequest,\n RunQueryResponse as ProtoRunQueryResponse,\n Value\n} from '../protos/firestore_proto_api';\nimport { debugAssert, debugCast, hardAssert } from '../util/assert';\nimport { AsyncQueue } from '../util/async_queue';\nimport { Code, FirestoreError } from '../util/error';\nimport { isNullOrUndefined } from '../util/types';\n\nimport { Connection } from './connection';\nimport {\n PersistentListenStream,\n PersistentWriteStream,\n WatchStreamListener,\n WriteStreamListener\n} from './persistent_stream';\nimport {\n fromDocument,\n fromBatchGetDocumentsResponse,\n JsonProtoSerializer,\n toMutation,\n toName,\n toQueryTarget,\n toResourcePath,\n toRunAggregationQueryRequest\n} from './serializer';\n\n/**\n * Datastore and its related methods are a wrapper around the external Google\n * Cloud Datastore grpc API, which provides an interface that is more convenient\n * for the rest of the client SDK architecture to consume.\n */\nexport abstract class Datastore {\n abstract terminate(): void;\n abstract serializer: JsonProtoSerializer;\n}\n\n/**\n * An implementation of Datastore that exposes additional state for internal\n * consumption.\n */\nclass DatastoreImpl extends Datastore {\n terminated = false;\n\n constructor(\n readonly authCredentials: CredentialsProvider,\n readonly appCheckCredentials: CredentialsProvider,\n readonly connection: Connection,\n readonly serializer: JsonProtoSerializer\n ) {\n super();\n }\n\n verifyInitialized(): void {\n debugAssert(!!this.connection, 'Datastore.start() not called');\n if (this.terminated) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'The client has already been terminated.'\n );\n }\n }\n\n /** Invokes the provided RPC with auth and AppCheck tokens. */\n invokeRPC(\n rpcName: string,\n databaseId: DatabaseId,\n resourcePath: ResourcePath,\n request: Req\n ): Promise {\n this.verifyInitialized();\n return Promise.all([\n this.authCredentials.getToken(),\n this.appCheckCredentials.getToken()\n ])\n .then(([authToken, appCheckToken]) => {\n return this.connection.invokeRPC(\n rpcName,\n toResourcePath(databaseId, resourcePath),\n request,\n authToken,\n appCheckToken\n );\n })\n .catch((error: FirestoreError) => {\n if (error.name === 'FirebaseError') {\n if (error.code === Code.UNAUTHENTICATED) {\n this.authCredentials.invalidateToken();\n this.appCheckCredentials.invalidateToken();\n }\n throw error;\n } else {\n throw new FirestoreError(Code.UNKNOWN, error.toString());\n }\n });\n }\n\n /** Invokes the provided RPC with streamed results with auth and AppCheck tokens. */\n invokeStreamingRPC(\n rpcName: string,\n databaseId: DatabaseId,\n resourcePath: ResourcePath,\n request: Req,\n expectedResponseCount?: number\n ): Promise {\n this.verifyInitialized();\n return Promise.all([\n this.authCredentials.getToken(),\n this.appCheckCredentials.getToken()\n ])\n .then(([authToken, appCheckToken]) => {\n return this.connection.invokeStreamingRPC(\n rpcName,\n toResourcePath(databaseId, resourcePath),\n request,\n authToken,\n appCheckToken,\n expectedResponseCount\n );\n })\n .catch((error: FirestoreError) => {\n if (error.name === 'FirebaseError') {\n if (error.code === Code.UNAUTHENTICATED) {\n this.authCredentials.invalidateToken();\n this.appCheckCredentials.invalidateToken();\n }\n throw error;\n } else {\n throw new FirestoreError(Code.UNKNOWN, error.toString());\n }\n });\n }\n\n terminate(): void {\n this.terminated = true;\n this.connection.terminate();\n }\n}\n\n// TODO(firestorexp): Make sure there is only one Datastore instance per\n// firestore-exp client.\nexport function newDatastore(\n authCredentials: CredentialsProvider,\n appCheckCredentials: CredentialsProvider,\n connection: Connection,\n serializer: JsonProtoSerializer\n): Datastore {\n return new DatastoreImpl(\n authCredentials,\n appCheckCredentials,\n connection,\n serializer\n );\n}\n\nexport async function invokeCommitRpc(\n datastore: Datastore,\n mutations: Mutation[]\n): Promise {\n const datastoreImpl = debugCast(datastore, DatastoreImpl);\n const request = {\n writes: mutations.map(m => toMutation(datastoreImpl.serializer, m))\n };\n await datastoreImpl.invokeRPC(\n 'Commit',\n datastoreImpl.serializer.databaseId,\n ResourcePath.emptyPath(),\n request\n );\n}\n\nexport async function invokeBatchGetDocumentsRpc(\n datastore: Datastore,\n keys: DocumentKey[]\n): Promise {\n const datastoreImpl = debugCast(datastore, DatastoreImpl);\n const request = {\n documents: keys.map(k => toName(datastoreImpl.serializer, k))\n };\n const response = await datastoreImpl.invokeStreamingRPC<\n ProtoBatchGetDocumentsRequest,\n ProtoBatchGetDocumentsResponse\n >(\n 'BatchGetDocuments',\n datastoreImpl.serializer.databaseId,\n ResourcePath.emptyPath(),\n request,\n keys.length\n );\n\n const docs = new Map();\n response.forEach(proto => {\n const doc = fromBatchGetDocumentsResponse(datastoreImpl.serializer, proto);\n docs.set(doc.key.toString(), doc);\n });\n const result: Document[] = [];\n keys.forEach(key => {\n const doc = docs.get(key.toString());\n hardAssert(!!doc, 0xd7c2, 'Missing entity in write response for `key`', {\n key\n });\n result.push(doc);\n });\n return result;\n}\n\nexport async function invokeRunQueryRpc(\n datastore: Datastore,\n query: Query\n): Promise {\n const datastoreImpl = debugCast(datastore, DatastoreImpl);\n const { queryTarget, parent } = toQueryTarget(\n datastoreImpl.serializer,\n queryToTarget(query)\n );\n const response = await datastoreImpl.invokeStreamingRPC<\n ProtoRunQueryRequest,\n ProtoRunQueryResponse\n >('RunQuery', datastoreImpl.serializer.databaseId, parent, {\n structuredQuery: queryTarget.structuredQuery\n });\n return (\n response\n // Omit RunQueryResponses that only contain readTimes.\n .filter(proto => !!proto.document)\n .map(proto =>\n fromDocument(datastoreImpl.serializer, proto.document!, undefined)\n )\n );\n}\n\nexport async function invokeRunAggregationQueryRpc(\n datastore: Datastore,\n query: Query,\n aggregates: Aggregate[]\n): Promise> {\n const datastoreImpl = debugCast(datastore, DatastoreImpl);\n const { request, aliasMap, parent } = toRunAggregationQueryRequest(\n datastoreImpl.serializer,\n queryToAggregateTarget(query),\n aggregates\n );\n\n if (!datastoreImpl.connection.shouldResourcePathBeIncludedInRequest) {\n delete request.parent;\n }\n const response = await datastoreImpl.invokeStreamingRPC<\n ProtoRunAggregationQueryRequest,\n ProtoRunAggregationQueryResponse\n >(\n 'RunAggregationQuery',\n datastoreImpl.serializer.databaseId,\n parent,\n request,\n /*expectedResponseCount=*/ 1\n );\n\n // Omit RunAggregationQueryResponse that only contain readTimes.\n const filteredResult = response.filter(proto => !!proto.result);\n\n hardAssert(\n filteredResult.length === 1,\n 0xfcd7,\n 'Aggregation fields are missing from result.'\n );\n debugAssert(\n !isNullOrUndefined(filteredResult[0].result),\n 'aggregationQueryResponse.result'\n );\n debugAssert(\n !isNullOrUndefined(filteredResult[0].result.aggregateFields),\n 'aggregationQueryResponse.result.aggregateFields'\n );\n\n // Remap the short-form aliases that were sent to the server\n // to the client-side aliases. Users will access the results\n // using the client-side alias.\n const unmappedAggregateFields = filteredResult[0].result?.aggregateFields;\n const remappedFields = Object.keys(unmappedAggregateFields).reduce<\n ApiClientObjectMap\n >((accumulator, key) => {\n debugAssert(\n !isNullOrUndefined(aliasMap[key]),\n `'${key}' not present in aliasMap result`\n );\n accumulator[aliasMap[key]] = unmappedAggregateFields[key]!;\n return accumulator;\n }, {});\n\n return remappedFields;\n}\n\nexport function newPersistentWriteStream(\n datastore: Datastore,\n queue: AsyncQueue,\n listener: WriteStreamListener\n): PersistentWriteStream {\n const datastoreImpl = debugCast(datastore, DatastoreImpl);\n datastoreImpl.verifyInitialized();\n return new PersistentWriteStream(\n queue,\n datastoreImpl.connection,\n datastoreImpl.authCredentials,\n datastoreImpl.appCheckCredentials,\n datastoreImpl.serializer,\n listener\n );\n}\n\nexport function newPersistentWatchStream(\n datastore: Datastore,\n queue: AsyncQueue,\n listener: WatchStreamListener\n): PersistentListenStream {\n const datastoreImpl = debugCast(datastore, DatastoreImpl);\n datastoreImpl.verifyInitialized();\n return new PersistentListenStream(\n queue,\n datastoreImpl.connection,\n datastoreImpl.authCredentials,\n datastoreImpl.appCheckCredentials,\n datastoreImpl.serializer,\n listener\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport { _FirebaseService } from '@firebase/app';\n\nimport { CredentialsProvider } from '../api/credentials';\nimport { cloneLongPollingOptions } from '../api/long_polling_options';\nimport { User } from '../auth/user';\nimport { DatabaseId, DatabaseInfo } from '../core/database_info';\nimport { newConnection } from '../platform/connection';\nimport { newSerializer } from '../platform/serializer';\nimport { Datastore, newDatastore } from '../remote/datastore';\nimport { Code, FirestoreError } from '../util/error';\nimport { logDebug } from '../util/log';\n\nimport { FirestoreSettingsImpl } from './settings';\n\nexport const LOG_TAG = 'ComponentProvider';\n\n// The components module manages the lifetime of dependencies of the Firestore\n// client. Dependencies can be lazily constructed and only one exists per\n// Firestore instance.\n\n/**\n * An interface implemented by FirebaseFirestore that provides compatibility\n * with the usage in this file.\n *\n * This interface mainly exists to remove a cyclic dependency.\n */\nexport interface FirestoreService extends _FirebaseService {\n _authCredentials: CredentialsProvider;\n _appCheckCredentials: CredentialsProvider;\n _persistenceKey: string;\n _databaseId: DatabaseId;\n _terminated: boolean;\n\n _freezeSettings(): FirestoreSettingsImpl;\n}\n/**\n * An instance map that ensures only one Datastore exists per Firestore\n * instance.\n */\nconst datastoreInstances = new Map();\n\n/**\n * Returns an initialized and started Datastore for the given Firestore\n * instance. Callers must invoke removeComponents() when the Firestore\n * instance is terminated.\n */\nexport function getDatastore(firestore: FirestoreService): Datastore {\n if (firestore._terminated) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'The client has already been terminated.'\n );\n }\n if (!datastoreInstances.has(firestore)) {\n logDebug(LOG_TAG, 'Initializing Datastore');\n const databaseInfo = makeDatabaseInfo(\n firestore._databaseId,\n firestore.app.options.appId || '',\n firestore._persistenceKey,\n firestore._freezeSettings()\n );\n const connection = newConnection(databaseInfo);\n const serializer = newSerializer(firestore._databaseId);\n const datastore = newDatastore(\n firestore._authCredentials,\n firestore._appCheckCredentials,\n connection,\n serializer\n );\n\n datastoreInstances.set(firestore, datastore);\n }\n return datastoreInstances.get(firestore)!;\n}\n\n/**\n * Removes all components associated with the provided instance. Must be called\n * when the `Firestore` instance is terminated.\n */\nexport function removeComponents(firestore: FirestoreService): void {\n const datastore = datastoreInstances.get(firestore);\n if (datastore) {\n logDebug(LOG_TAG, 'Removing Datastore');\n datastoreInstances.delete(firestore);\n datastore.terminate();\n }\n}\n\nexport function makeDatabaseInfo(\n databaseId: DatabaseId,\n appId: string,\n persistenceKey: string,\n settings: FirestoreSettingsImpl\n): DatabaseInfo {\n return new DatabaseInfo(\n databaseId,\n appId,\n persistenceKey,\n settings.host,\n settings.ssl,\n settings.experimentalForceLongPolling,\n settings.experimentalAutoDetectLongPolling,\n cloneLongPollingOptions(settings.experimentalLongPollingOptions),\n settings.useFetchStreams,\n settings.isUsingEmulator\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DatabaseInfo } from '../../core/database_info';\nimport { Connection } from '../../remote/connection';\n\nimport { FetchConnection } from './fetch_connection';\n\nexport { newConnectivityMonitor } from '../browser/connection';\n\n/** Initializes the HTTP connection for the REST API. */\nexport function newConnection(databaseInfo: DatabaseInfo): Connection {\n return new FetchConnection(databaseInfo);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirestoreError } from '../api';\nimport { ListenSequence } from '../core/listen_sequence';\nimport { ListenSequenceNumber } from '../core/types';\nimport { debugAssert } from '../util/assert';\nimport { AsyncQueue, DelayedOperation, TimerId } from '../util/async_queue';\nimport { getLogLevel, logDebug, LogLevel } from '../util/log';\nimport { primitiveComparator } from '../util/misc';\nimport { SortedSet } from '../util/sorted_set';\n\nimport { ignoreIfPrimaryLeaseLoss, LocalStore } from './local_store';\nimport {\n ActiveTargets,\n GC_DID_NOT_RUN,\n LRU_COLLECTION_DISABLED,\n LruDelegate,\n LruGarbageCollector,\n LruParams,\n LruResults\n} from './lru_garbage_collector';\nimport { Scheduler } from './persistence';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { isIndexedDbTransactionError } from './simple_db';\n\nconst LOG_TAG = 'LruGarbageCollector';\n\nexport const LRU_MINIMUM_CACHE_SIZE_BYTES = 1 * 1024 * 1024;\n\n/** How long we wait to try running LRU GC after SDK initialization. */\nconst INITIAL_GC_DELAY_MS = 1 * 60 * 1000;\n/** Minimum amount of time between GC checks, after the first one. */\nconst REGULAR_GC_DELAY_MS = 5 * 60 * 1000;\n\n// The type and comparator for the items contained in the SortedSet used in\n// place of a priority queue for the RollingSequenceNumberBuffer.\ntype BufferEntry = [ListenSequenceNumber, number];\n\nfunction bufferEntryComparator(\n [aSequence, aIndex]: BufferEntry,\n [bSequence, bIndex]: BufferEntry\n): number {\n const seqCmp = primitiveComparator(aSequence, bSequence);\n if (seqCmp === 0) {\n // This order doesn't matter, but we can bias against churn by sorting\n // entries created earlier as less than newer entries.\n return primitiveComparator(aIndex, bIndex);\n } else {\n return seqCmp;\n }\n}\n\n/**\n * Used to calculate the nth sequence number. Keeps a rolling buffer of the\n * lowest n values passed to `addElement`, and finally reports the largest of\n * them in `maxValue`.\n */\nclass RollingSequenceNumberBuffer {\n private buffer: SortedSet = new SortedSet(\n bufferEntryComparator\n );\n\n private previousIndex = 0;\n\n constructor(private readonly maxElements: number) {}\n\n private nextIndex(): number {\n return ++this.previousIndex;\n }\n\n addElement(sequenceNumber: ListenSequenceNumber): void {\n const entry: BufferEntry = [sequenceNumber, this.nextIndex()];\n if (this.buffer.size < this.maxElements) {\n this.buffer = this.buffer.add(entry);\n } else {\n const highestValue = this.buffer.last()!;\n if (bufferEntryComparator(entry, highestValue) < 0) {\n this.buffer = this.buffer.delete(highestValue).add(entry);\n }\n }\n }\n\n get maxValue(): ListenSequenceNumber {\n // Guaranteed to be non-empty. If we decide we are not collecting any\n // sequence numbers, nthSequenceNumber below short-circuits. If we have\n // decided that we are collecting n sequence numbers, it's because n is some\n // percentage of the existing sequence numbers. That means we should never\n // be in a situation where we are collecting sequence numbers but don't\n // actually have any.\n return this.buffer.last()![0];\n }\n}\n\n/**\n * This class is responsible for the scheduling of LRU garbage collection. It handles checking\n * whether or not GC is enabled, as well as which delay to use before the next run.\n */\nexport class LruScheduler implements Scheduler {\n private gcTask: DelayedOperation | null;\n\n constructor(\n private readonly garbageCollector: LruGarbageCollector,\n private readonly asyncQueue: AsyncQueue,\n private readonly localStore: LocalStore\n ) {\n this.gcTask = null;\n }\n\n start(): void {\n debugAssert(\n this.gcTask === null,\n 'Cannot start an already started LruScheduler'\n );\n if (\n this.garbageCollector.params.cacheSizeCollectionThreshold !==\n LRU_COLLECTION_DISABLED\n ) {\n this.scheduleGC(INITIAL_GC_DELAY_MS);\n }\n }\n\n stop(): void {\n if (this.gcTask) {\n this.gcTask.cancel();\n this.gcTask = null;\n }\n }\n\n get started(): boolean {\n return this.gcTask !== null;\n }\n\n private scheduleGC(delay: number): void {\n debugAssert(\n this.gcTask === null,\n 'Cannot schedule GC while a task is pending'\n );\n logDebug(LOG_TAG, `Garbage collection scheduled in ${delay}ms`);\n this.gcTask = this.asyncQueue.enqueueAfterDelay(\n TimerId.LruGarbageCollection,\n delay,\n async () => {\n this.gcTask = null;\n try {\n await this.localStore.collectGarbage(this.garbageCollector);\n } catch (e) {\n if (isIndexedDbTransactionError(e as Error)) {\n logDebug(\n LOG_TAG,\n 'Ignoring IndexedDB error during garbage collection: ',\n e\n );\n } else {\n await ignoreIfPrimaryLeaseLoss(e as FirestoreError);\n }\n }\n await this.scheduleGC(REGULAR_GC_DELAY_MS);\n }\n );\n }\n}\n\n/**\n * Implements the steps for LRU garbage collection.\n */\nclass LruGarbageCollectorImpl implements LruGarbageCollector {\n constructor(\n private readonly delegate: LruDelegate,\n readonly params: LruParams\n ) {}\n\n calculateTargetCount(\n txn: PersistenceTransaction,\n percentile: number\n ): PersistencePromise {\n return this.delegate.getSequenceNumberCount(txn).next(targetCount => {\n return Math.floor((percentile / 100.0) * targetCount);\n });\n }\n\n nthSequenceNumber(\n txn: PersistenceTransaction,\n n: number\n ): PersistencePromise {\n if (n === 0) {\n return PersistencePromise.resolve(ListenSequence.INVALID);\n }\n\n const buffer = new RollingSequenceNumberBuffer(n);\n return this.delegate\n .forEachTarget(txn, target => buffer.addElement(target.sequenceNumber))\n .next(() => {\n return this.delegate.forEachOrphanedDocumentSequenceNumber(\n txn,\n sequenceNumber => buffer.addElement(sequenceNumber)\n );\n })\n .next(() => buffer.maxValue);\n }\n\n removeTargets(\n txn: PersistenceTransaction,\n upperBound: ListenSequenceNumber,\n activeTargetIds: ActiveTargets\n ): PersistencePromise {\n return this.delegate.removeTargets(txn, upperBound, activeTargetIds);\n }\n\n removeOrphanedDocuments(\n txn: PersistenceTransaction,\n upperBound: ListenSequenceNumber\n ): PersistencePromise {\n return this.delegate.removeOrphanedDocuments(txn, upperBound);\n }\n\n collect(\n txn: PersistenceTransaction,\n activeTargetIds: ActiveTargets\n ): PersistencePromise {\n if (this.params.cacheSizeCollectionThreshold === LRU_COLLECTION_DISABLED) {\n logDebug('LruGarbageCollector', 'Garbage collection skipped; disabled');\n return PersistencePromise.resolve(GC_DID_NOT_RUN);\n }\n\n return this.getCacheSize(txn).next(cacheSize => {\n if (cacheSize < this.params.cacheSizeCollectionThreshold) {\n logDebug(\n 'LruGarbageCollector',\n `Garbage collection skipped; Cache size ${cacheSize} ` +\n `is lower than threshold ${this.params.cacheSizeCollectionThreshold}`\n );\n return GC_DID_NOT_RUN;\n } else {\n return this.runGarbageCollection(txn, activeTargetIds);\n }\n });\n }\n\n getCacheSize(txn: PersistenceTransaction): PersistencePromise {\n return this.delegate.getCacheSize(txn);\n }\n\n private runGarbageCollection(\n txn: PersistenceTransaction,\n activeTargetIds: ActiveTargets\n ): PersistencePromise {\n let upperBoundSequenceNumber: number;\n let sequenceNumbersToCollect: number, targetsRemoved: number;\n // Timestamps for various pieces of the process\n let countedTargetsTs: number,\n foundUpperBoundTs: number,\n removedTargetsTs: number,\n removedDocumentsTs: number;\n const startTs = Date.now();\n return this.calculateTargetCount(txn, this.params.percentileToCollect)\n .next(sequenceNumbers => {\n // Cap at the configured max\n if (sequenceNumbers > this.params.maximumSequenceNumbersToCollect) {\n logDebug(\n 'LruGarbageCollector',\n 'Capping sequence numbers to collect down ' +\n `to the maximum of ${this.params.maximumSequenceNumbersToCollect} ` +\n `from ${sequenceNumbers}`\n );\n sequenceNumbersToCollect =\n this.params.maximumSequenceNumbersToCollect;\n } else {\n sequenceNumbersToCollect = sequenceNumbers;\n }\n countedTargetsTs = Date.now();\n\n return this.nthSequenceNumber(txn, sequenceNumbersToCollect);\n })\n .next(upperBound => {\n upperBoundSequenceNumber = upperBound;\n foundUpperBoundTs = Date.now();\n\n return this.removeTargets(\n txn,\n upperBoundSequenceNumber,\n activeTargetIds\n );\n })\n .next(numTargetsRemoved => {\n targetsRemoved = numTargetsRemoved;\n removedTargetsTs = Date.now();\n\n return this.removeOrphanedDocuments(txn, upperBoundSequenceNumber);\n })\n .next(documentsRemoved => {\n removedDocumentsTs = Date.now();\n\n if (getLogLevel() <= LogLevel.DEBUG) {\n const desc =\n 'LRU Garbage Collection\\n' +\n `\\tCounted targets in ${countedTargetsTs - startTs}ms\\n` +\n `\\tDetermined least recently used ${sequenceNumbersToCollect} in ` +\n `${foundUpperBoundTs - countedTargetsTs}ms\\n` +\n `\\tRemoved ${targetsRemoved} targets in ` +\n `${removedTargetsTs - foundUpperBoundTs}ms\\n` +\n `\\tRemoved ${documentsRemoved} documents in ` +\n `${removedDocumentsTs - removedTargetsTs}ms\\n` +\n `Total Duration: ${removedDocumentsTs - startTs}ms`;\n logDebug('LruGarbageCollector', desc);\n }\n\n return PersistencePromise.resolve({\n didRun: true,\n sequenceNumbersCollected: sequenceNumbersToCollect,\n targetsRemoved,\n documentsRemoved\n });\n });\n }\n}\n\nexport function newLruGarbageCollector(\n delegate: LruDelegate,\n params: LruParams\n): LruGarbageCollector {\n return new LruGarbageCollectorImpl(delegate, params);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { EmulatorMockTokenOptions } from '@firebase/util';\n\nimport { FirestoreLocalCache } from '../api/cache_config';\nimport { CredentialsSettings } from '../api/credentials';\nimport {\n ExperimentalLongPollingOptions,\n cloneLongPollingOptions,\n longPollingOptionsEqual\n} from '../api/long_polling_options';\nimport {\n LRU_COLLECTION_DISABLED,\n LRU_DEFAULT_CACHE_SIZE_BYTES\n} from '../local/lru_garbage_collector';\nimport { LRU_MINIMUM_CACHE_SIZE_BYTES } from '../local/lru_garbage_collector_impl';\nimport { Code, FirestoreError } from '../util/error';\nimport { validateIsNotUsedTogether } from '../util/input_validation';\n\n// settings() defaults:\nexport const DEFAULT_HOST = 'firestore.googleapis.com';\nexport const DEFAULT_SSL = true;\n\n// The minimum long-polling timeout is hardcoded on the server. The value here\n// should be kept in sync with the value used by the server, as the server will\n// silently ignore a value below the minimum and fall back to the default.\n// Googlers see b/266868871 for relevant discussion.\nconst MIN_LONG_POLLING_TIMEOUT_SECONDS = 5;\n\n// No maximum long-polling timeout is configured in the server, and defaults to\n// 30 seconds, which is what Watch appears to use.\n// Googlers see b/266868871 for relevant discussion.\nconst MAX_LONG_POLLING_TIMEOUT_SECONDS = 30;\n\n// Whether long-polling auto-detected is enabled by default.\nconst DEFAULT_AUTO_DETECT_LONG_POLLING = true;\n\n/**\n * Specifies custom configurations for your Cloud Firestore instance.\n * You must set these before invoking any other methods.\n */\nexport interface FirestoreSettings {\n /** The hostname to connect to. */\n host?: string;\n\n /** Whether to use SSL when connecting. */\n ssl?: boolean;\n\n /**\n * Whether to skip nested properties that are set to `undefined` during\n * object serialization. If set to `true`, these properties are skipped\n * and not written to Firestore. If set to `false` or omitted, the SDK\n * throws an exception when it encounters properties of type `undefined`.\n */\n ignoreUndefinedProperties?: boolean;\n}\n\n/**\n * @internal\n * Undocumented, private additional settings not exposed in our public API.\n */\nexport interface PrivateSettings extends FirestoreSettings {\n // Can be a google-auth-library or gapi client.\n credentials?: CredentialsSettings;\n cacheSizeBytes?: number;\n experimentalForceLongPolling?: boolean;\n experimentalAutoDetectLongPolling?: boolean;\n experimentalLongPollingOptions?: ExperimentalLongPollingOptions;\n useFetchStreams?: boolean;\n emulatorOptions?: { mockUserToken?: EmulatorMockTokenOptions | string };\n\n localCache?: FirestoreLocalCache;\n}\n\n/**\n * A concrete type describing all the values that can be applied via a\n * user-supplied `FirestoreSettings` object. This is a separate type so that\n * defaults can be supplied and the value can be checked for equality.\n */\nexport class FirestoreSettingsImpl {\n /** The hostname to connect to. */\n readonly host: string;\n\n /** Whether to use SSL when connecting. */\n readonly ssl: boolean;\n\n readonly cacheSizeBytes: number;\n\n readonly experimentalForceLongPolling: boolean;\n\n readonly experimentalAutoDetectLongPolling: boolean;\n\n readonly experimentalLongPollingOptions: ExperimentalLongPollingOptions;\n\n readonly ignoreUndefinedProperties: boolean;\n\n readonly useFetchStreams: boolean;\n readonly localCache?: FirestoreLocalCache;\n\n readonly isUsingEmulator: boolean;\n\n // Can be a google-auth-library or gapi client.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n credentials?: any;\n\n constructor(settings: PrivateSettings) {\n if (settings.host === undefined) {\n if (settings.ssl !== undefined) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n \"Can't provide ssl option if host option is not set\"\n );\n }\n this.host = DEFAULT_HOST;\n this.ssl = DEFAULT_SSL;\n } else {\n this.host = settings.host;\n this.ssl = settings.ssl ?? DEFAULT_SSL;\n }\n this.isUsingEmulator = settings.emulatorOptions !== undefined;\n\n this.credentials = settings.credentials;\n this.ignoreUndefinedProperties = !!settings.ignoreUndefinedProperties;\n this.localCache = settings.localCache;\n\n if (settings.cacheSizeBytes === undefined) {\n this.cacheSizeBytes = LRU_DEFAULT_CACHE_SIZE_BYTES;\n } else {\n if (\n settings.cacheSizeBytes !== LRU_COLLECTION_DISABLED &&\n settings.cacheSizeBytes < LRU_MINIMUM_CACHE_SIZE_BYTES\n ) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `cacheSizeBytes must be at least ${LRU_MINIMUM_CACHE_SIZE_BYTES}`\n );\n } else {\n this.cacheSizeBytes = settings.cacheSizeBytes;\n }\n }\n\n validateIsNotUsedTogether(\n 'experimentalForceLongPolling',\n settings.experimentalForceLongPolling,\n 'experimentalAutoDetectLongPolling',\n settings.experimentalAutoDetectLongPolling\n );\n\n this.experimentalForceLongPolling = !!settings.experimentalForceLongPolling;\n\n if (this.experimentalForceLongPolling) {\n this.experimentalAutoDetectLongPolling = false;\n } else if (settings.experimentalAutoDetectLongPolling === undefined) {\n this.experimentalAutoDetectLongPolling = DEFAULT_AUTO_DETECT_LONG_POLLING;\n } else {\n // For backwards compatibility, coerce the value to boolean even though\n // the TypeScript compiler has narrowed the type to boolean already.\n // noinspection PointlessBooleanExpressionJS\n this.experimentalAutoDetectLongPolling =\n !!settings.experimentalAutoDetectLongPolling;\n }\n\n this.experimentalLongPollingOptions = cloneLongPollingOptions(\n settings.experimentalLongPollingOptions ?? {}\n );\n validateLongPollingOptions(this.experimentalLongPollingOptions);\n\n this.useFetchStreams = !!settings.useFetchStreams;\n }\n\n isEqual(other: FirestoreSettingsImpl): boolean {\n return (\n this.host === other.host &&\n this.ssl === other.ssl &&\n this.credentials === other.credentials &&\n this.cacheSizeBytes === other.cacheSizeBytes &&\n this.experimentalForceLongPolling ===\n other.experimentalForceLongPolling &&\n this.experimentalAutoDetectLongPolling ===\n other.experimentalAutoDetectLongPolling &&\n longPollingOptionsEqual(\n this.experimentalLongPollingOptions,\n other.experimentalLongPollingOptions\n ) &&\n this.ignoreUndefinedProperties === other.ignoreUndefinedProperties &&\n this.useFetchStreams === other.useFetchStreams\n );\n }\n}\n\nfunction validateLongPollingOptions(\n options: ExperimentalLongPollingOptions\n): void {\n if (options.timeoutSeconds !== undefined) {\n if (isNaN(options.timeoutSeconds)) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `invalid long polling timeout: ` +\n `${options.timeoutSeconds} (must not be NaN)`\n );\n }\n if (options.timeoutSeconds < MIN_LONG_POLLING_TIMEOUT_SECONDS) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `invalid long polling timeout: ${options.timeoutSeconds} ` +\n `(minimum allowed value is ${MIN_LONG_POLLING_TIMEOUT_SECONDS})`\n );\n }\n if (options.timeoutSeconds > MAX_LONG_POLLING_TIMEOUT_SECONDS) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `invalid long polling timeout: ${options.timeoutSeconds} ` +\n `(maximum allowed value is ${MAX_LONG_POLLING_TIMEOUT_SECONDS})`\n );\n }\n }\n}\n","/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ListenSequenceNumber, TargetId } from '../core/types';\nimport { SortedMap } from '../util/sorted_map';\n\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { TargetData } from './target_data';\n\n/**\n * Describes a map whose keys are active target ids. We do not care about the type of the\n * values.\n */\nexport type ActiveTargets = SortedMap;\n\nexport const GC_DID_NOT_RUN: LruResults = {\n didRun: false,\n sequenceNumbersCollected: 0,\n targetsRemoved: 0,\n documentsRemoved: 0\n};\n\nexport const LRU_COLLECTION_DISABLED = -1;\nexport const LRU_DEFAULT_CACHE_SIZE_BYTES = 40 * 1024 * 1024;\n\nexport class LruParams {\n private static readonly DEFAULT_COLLECTION_PERCENTILE = 10;\n private static readonly DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT = 1000;\n\n static withCacheSize(cacheSize: number): LruParams {\n return new LruParams(\n cacheSize,\n LruParams.DEFAULT_COLLECTION_PERCENTILE,\n LruParams.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT\n );\n }\n\n static readonly DEFAULT: LruParams = new LruParams(\n LRU_DEFAULT_CACHE_SIZE_BYTES,\n LruParams.DEFAULT_COLLECTION_PERCENTILE,\n LruParams.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT\n );\n\n static readonly DISABLED: LruParams = new LruParams(\n LRU_COLLECTION_DISABLED,\n 0,\n 0\n );\n\n constructor(\n // When we attempt to collect, we will only do so if the cache size is greater than this\n // threshold. Passing `COLLECTION_DISABLED` here will cause collection to always be skipped.\n readonly cacheSizeCollectionThreshold: number,\n // The percentage of sequence numbers that we will attempt to collect\n readonly percentileToCollect: number,\n // A cap on the total number of sequence numbers that will be collected. This prevents\n // us from collecting a huge number of sequence numbers if the cache has grown very large.\n readonly maximumSequenceNumbersToCollect: number\n ) {}\n}\n\nexport interface LruGarbageCollector {\n readonly params: LruParams;\n\n collect(\n txn: PersistenceTransaction,\n activeTargetIds: ActiveTargets\n ): PersistencePromise;\n\n /** Given a percentile of target to collect, returns the number of targets to collect. */\n calculateTargetCount(\n txn: PersistenceTransaction,\n percentile: number\n ): PersistencePromise;\n\n /** Returns the nth sequence number, counting in order from the smallest. */\n nthSequenceNumber(\n txn: PersistenceTransaction,\n n: number\n ): PersistencePromise;\n\n /**\n * Removes documents that have a sequence number equal to or less than the\n * upper bound and are not otherwise pinned.\n */\n removeOrphanedDocuments(\n txn: PersistenceTransaction,\n upperBound: ListenSequenceNumber\n ): PersistencePromise;\n\n getCacheSize(txn: PersistenceTransaction): PersistencePromise;\n\n /**\n * Removes targets with a sequence number equal to or less than the given\n * upper bound, and removes document associations with those targets.\n */\n removeTargets(\n txn: PersistenceTransaction,\n upperBound: ListenSequenceNumber,\n activeTargetIds: ActiveTargets\n ): PersistencePromise;\n}\n\n/**\n * Describes the results of a garbage collection run. `didRun` will be set to\n * `false` if collection was skipped (either it is disabled or the cache size\n * has not hit the threshold). If collection ran, the other fields will be\n * filled in with the details of the results.\n */\nexport interface LruResults {\n readonly didRun: boolean;\n readonly sequenceNumbersCollected: number;\n readonly targetsRemoved: number;\n readonly documentsRemoved: number;\n}\n\n/**\n * Persistence layers intending to use LRU Garbage collection should have\n * reference delegates that implement this interface. This interface defines the\n * operations that the LRU garbage collector needs from the persistence layer.\n */\nexport interface LruDelegate {\n readonly garbageCollector: LruGarbageCollector;\n\n /** Enumerates all the targets in the TargetCache. */\n forEachTarget(\n txn: PersistenceTransaction,\n f: (target: TargetData) => void\n ): PersistencePromise;\n\n getSequenceNumberCount(\n txn: PersistenceTransaction\n ): PersistencePromise;\n\n /**\n * Enumerates sequence numbers for documents not associated with a target.\n * Note that this may include duplicate sequence numbers.\n */\n forEachOrphanedDocumentSequenceNumber(\n txn: PersistenceTransaction,\n f: (sequenceNumber: ListenSequenceNumber) => void\n ): PersistencePromise;\n\n /**\n * Removes all targets that have a sequence number less than or equal to\n * `upperBound`, and are not present in the `activeTargetIds` set.\n *\n * @returns the number of targets removed.\n */\n removeTargets(\n txn: PersistenceTransaction,\n upperBound: ListenSequenceNumber,\n activeTargetIds: ActiveTargets\n ): PersistencePromise;\n\n /**\n * Removes all unreferenced documents from the cache that have a sequence\n * number less than or equal to the given `upperBound`.\n *\n * @returns the number of documents removed.\n */\n removeOrphanedDocuments(\n txn: PersistenceTransaction,\n upperBound: ListenSequenceNumber\n ): PersistencePromise;\n\n getCacheSize(txn: PersistenceTransaction): PersistencePromise;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport {\n _getProvider,\n _removeServiceInstance,\n FirebaseApp,\n getApp\n} from '@firebase/app';\nimport {\n createMockUserToken,\n deepEqual,\n EmulatorMockTokenOptions,\n getDefaultEmulatorHostnameAndPort,\n isCloudWorkstation,\n pingServer,\n updateEmulatorBanner\n} from '@firebase/util';\n\nimport {\n CredentialsProvider,\n EmulatorAuthCredentialsProvider,\n makeAuthCredentialsProvider,\n OAuthToken\n} from '../api/credentials';\nimport { User } from '../auth/user';\nimport { DatabaseId, DEFAULT_DATABASE_NAME } from '../core/database_info';\nimport { Code, FirestoreError } from '../util/error';\nimport { cast } from '../util/input_validation';\nimport { logWarn } from '../util/log';\n\nimport { FirestoreService, removeComponents } from './components';\nimport {\n DEFAULT_HOST,\n FirestoreSettingsImpl,\n PrivateSettings,\n FirestoreSettings\n} from './settings';\n\nexport { EmulatorMockTokenOptions } from '@firebase/util';\n\ndeclare module '@firebase/component' {\n interface NameServiceMapping {\n 'firestore/lite': Firestore;\n }\n}\n\n/**\n * The Cloud Firestore service interface.\n *\n * Do not call this constructor directly. Instead, use {@link (getFirestore:1)}.\n */\nexport class Firestore implements FirestoreService {\n /**\n * Whether it's a Firestore or Firestore Lite instance.\n */\n type: 'firestore-lite' | 'firestore' = 'firestore-lite';\n\n readonly _persistenceKey: string = '(lite)';\n\n private _settings = new FirestoreSettingsImpl({});\n private _settingsFrozen = false;\n private _emulatorOptions: {\n mockUserToken?: EmulatorMockTokenOptions | string;\n } = {};\n\n // A task that is assigned when the terminate() is invoked and resolved when\n // all components have shut down. Otherwise, Firestore is not terminated,\n // which can mean either the FirestoreClient is in the process of starting,\n // or restarting.\n private _terminateTask: Promise | 'notTerminated' = 'notTerminated';\n\n /** @hideconstructor */\n constructor(\n public _authCredentials: CredentialsProvider,\n public _appCheckCredentials: CredentialsProvider,\n readonly _databaseId: DatabaseId,\n readonly _app?: FirebaseApp\n ) {}\n\n /**\n * The {@link @firebase/app#FirebaseApp} associated with this `Firestore` service\n * instance.\n */\n get app(): FirebaseApp {\n if (!this._app) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n \"Firestore was not initialized using the Firebase SDK. 'app' is \" +\n 'not available'\n );\n }\n return this._app;\n }\n\n get _initialized(): boolean {\n return this._settingsFrozen;\n }\n\n get _terminated(): boolean {\n return this._terminateTask !== 'notTerminated';\n }\n\n _setSettings(settings: PrivateSettings): void {\n if (this._settingsFrozen) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'Firestore has already been started and its settings can no longer ' +\n 'be changed. You can only modify settings before calling any other ' +\n 'methods on a Firestore object.'\n );\n }\n this._settings = new FirestoreSettingsImpl(settings);\n this._emulatorOptions = settings.emulatorOptions || {};\n\n if (settings.credentials !== undefined) {\n this._authCredentials = makeAuthCredentialsProvider(settings.credentials);\n }\n }\n\n _getSettings(): FirestoreSettingsImpl {\n return this._settings;\n }\n\n _getEmulatorOptions(): { mockUserToken?: EmulatorMockTokenOptions | string } {\n return this._emulatorOptions;\n }\n\n _freezeSettings(): FirestoreSettingsImpl {\n this._settingsFrozen = true;\n return this._settings;\n }\n\n _delete(): Promise {\n // The `_terminateTask` must be assigned future that completes when\n // terminate is complete. The existence of this future puts SDK in state\n // that will not accept further API interaction.\n if (this._terminateTask === 'notTerminated') {\n this._terminateTask = this._terminate();\n }\n return this._terminateTask;\n }\n\n async _restart(): Promise {\n // The `_terminateTask` must equal 'notTerminated' after restart to\n // signal that client is in a state that accepts API calls.\n if (this._terminateTask === 'notTerminated') {\n await this._terminate();\n } else {\n this._terminateTask = 'notTerminated';\n }\n }\n\n /** Returns a JSON-serializable representation of this `Firestore` instance. */\n toJSON(): object {\n return {\n app: this._app,\n databaseId: this._databaseId,\n settings: this._settings\n };\n }\n\n /**\n * Terminates all components used by this client. Subclasses can override\n * this method to clean up their own dependencies, but must also call this\n * method.\n *\n * Only ever called once.\n */\n protected _terminate(): Promise {\n removeComponents(this);\n return Promise.resolve();\n }\n}\n\n/**\n * Initializes a new instance of Cloud Firestore with the provided settings.\n * Can only be called before any other functions, including\n * {@link (getFirestore:1)}. If the custom settings are empty, this function is\n * equivalent to calling {@link (getFirestore:1)}.\n *\n * @param app - The {@link @firebase/app#FirebaseApp} with which the `Firestore` instance will\n * be associated.\n * @param settings - A settings object to configure the `Firestore` instance.\n * @returns A newly initialized `Firestore` instance.\n */\nexport function initializeFirestore(\n app: FirebaseApp,\n settings: FirestoreSettings\n): Firestore;\n/**\n * Initializes a new instance of Cloud Firestore with the provided settings.\n * Can only be called before any other functions, including\n * {@link (getFirestore:1)}. If the custom settings are empty, this function is\n * equivalent to calling {@link (getFirestore:1)}.\n *\n * @param app - The {@link @firebase/app#FirebaseApp} with which the `Firestore` instance will\n * be associated.\n * @param settings - A settings object to configure the `Firestore` instance.\n * @param databaseId - The name of the database.\n * @returns A newly initialized `Firestore` instance.\n * @beta\n */\nexport function initializeFirestore(\n app: FirebaseApp,\n settings: FirestoreSettings,\n databaseId?: string\n): Firestore;\nexport function initializeFirestore(\n app: FirebaseApp,\n settings: FirestoreSettings,\n databaseId?: string\n): Firestore {\n if (!databaseId) {\n databaseId = DEFAULT_DATABASE_NAME;\n }\n const provider = _getProvider(app, 'firestore/lite');\n\n if (provider.isInitialized(databaseId)) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'Firestore can only be initialized once per app.'\n );\n }\n\n return provider.initialize({\n options: settings,\n instanceIdentifier: databaseId\n });\n}\n\n/**\n * Returns the existing default {@link Firestore} instance that is associated with the\n * default {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new\n * instance with default settings.\n *\n * @returns The {@link Firestore} instance of the provided app.\n */\nexport function getFirestore(): Firestore;\n/**\n * Returns the existing default {@link Firestore} instance that is associated with the\n * provided {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new\n * instance with default settings.\n *\n * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned {@link Firestore}\n * instance is associated with.\n * @returns The {@link Firestore} instance of the provided app.\n */\nexport function getFirestore(app: FirebaseApp): Firestore;\n/**\n * Returns the existing {@link Firestore} instance that is associated with the\n * default {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new\n * instance with default settings.\n *\n * @param databaseId - The name of the database.\n * @returns The {@link Firestore} instance of the provided app.\n * @beta\n */\nexport function getFirestore(databaseId: string): Firestore;\n/**\n * Returns the existing {@link Firestore} instance that is associated with the\n * provided {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new\n * instance with default settings.\n *\n * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned {@link Firestore}\n * instance is associated with.\n * @param databaseId - The name of the database.\n * @returns The {@link Firestore} instance of the provided app.\n * @beta\n */\nexport function getFirestore(app: FirebaseApp, databaseId: string): Firestore;\nexport function getFirestore(\n appOrDatabaseId?: FirebaseApp | string,\n optionalDatabaseId?: string\n): Firestore {\n const app: FirebaseApp =\n typeof appOrDatabaseId === 'object' ? appOrDatabaseId : getApp();\n const databaseId =\n typeof appOrDatabaseId === 'string'\n ? appOrDatabaseId\n : optionalDatabaseId || '(default)';\n const db = _getProvider(app, 'firestore/lite').getImmediate({\n identifier: databaseId\n }) as Firestore;\n if (!db._initialized) {\n const emulator = getDefaultEmulatorHostnameAndPort('firestore');\n if (emulator) {\n connectFirestoreEmulator(db, ...emulator);\n }\n }\n return db;\n}\n\n/**\n * Modify this instance to communicate with the Cloud Firestore emulator.\n *\n * Note: This must be called before this instance has been used to do any\n * operations.\n *\n * @param firestore - The `Firestore` instance to configure to connect to the\n * emulator.\n * @param host - the emulator host (ex: localhost).\n * @param port - the emulator port (ex: 9000).\n * @param options.mockUserToken - the mock auth token to use for unit testing\n * Security Rules.\n */\nexport function connectFirestoreEmulator(\n firestore: Firestore,\n host: string,\n port: number,\n options: {\n mockUserToken?: EmulatorMockTokenOptions | string;\n } = {}\n): void {\n firestore = cast(firestore, Firestore);\n const useSsl = isCloudWorkstation(host);\n const settings = firestore._getSettings();\n const existingConfig = {\n ...settings,\n emulatorOptions: firestore._getEmulatorOptions()\n };\n const newHostSetting = `${host}:${port}`;\n if (useSsl) {\n void pingServer(`https://${newHostSetting}`);\n updateEmulatorBanner('Firestore', true);\n }\n if (settings.host !== DEFAULT_HOST && settings.host !== newHostSetting) {\n logWarn(\n 'Host has been set in both settings() and connectFirestoreEmulator(), emulator host ' +\n 'will be used.'\n );\n }\n const newConfig = {\n ...settings,\n host: newHostSetting,\n ssl: useSsl,\n emulatorOptions: options\n };\n // No-op if the new configuration matches the current configuration. This supports SSR\n // enviornments which might call `connectFirestoreEmulator` multiple times as a standard practice.\n if (deepEqual(newConfig, existingConfig)) {\n return;\n }\n\n firestore._setSettings(newConfig);\n\n if (options.mockUserToken) {\n let token: string;\n let user: User;\n if (typeof options.mockUserToken === 'string') {\n token = options.mockUserToken;\n user = User.MOCK_USER;\n } else {\n // Let createMockUserToken validate first (catches common mistakes like\n // invalid field \"uid\" and missing field \"sub\" / \"user_id\".)\n token = createMockUserToken(\n options.mockUserToken,\n firestore._app?.options.projectId\n );\n const uid = options.mockUserToken.sub || options.mockUserToken.user_id;\n if (!uid) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n \"mockUserToken must contain 'sub' or 'user_id' field!\"\n );\n }\n user = new User(uid);\n }\n\n firestore._authCredentials = new EmulatorAuthCredentialsProvider(\n new OAuthToken(token, user)\n );\n }\n}\n\n/**\n * Terminates the provided `Firestore` instance.\n *\n * After calling `terminate()` only the `clearIndexedDbPersistence()` functions\n * may be used. Any other function will throw a `FirestoreError`. Termination\n * does not cancel any pending writes, and any promises that are awaiting a\n * response from the server will not be resolved.\n *\n * To restart after termination, create a new instance of `Firestore` with\n * {@link (getFirestore:1)}.\n *\n * Note: Under normal circumstances, calling `terminate()` is not required. This\n * function is useful only when you want to force this instance to release all of\n * its resources or in combination with {@link clearIndexedDbPersistence} to\n * ensure that all local state is destroyed between test runs.\n *\n * @param firestore - The `Firestore` instance to terminate.\n * @returns A `Promise` that is resolved when the instance has been successfully\n * terminated.\n */\nexport function terminate(firestore: Firestore): Promise {\n firestore = cast(firestore, Firestore);\n _removeServiceInstance(firestore.app, 'firestore/lite');\n return firestore._delete();\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { AggregateType } from '../core/aggregate';\nimport { FieldPath as InternalFieldPath } from '../model/path';\nimport { ApiClientObjectMap, Value } from '../protos/firestore_proto_api';\n\nimport { average, count, sum } from './aggregate';\nimport { DocumentData, Query } from './reference';\nimport { AbstractUserDataWriter } from './user_data_writer';\n\nexport { AggregateType };\n\n/**\n * Represents an aggregation that can be performed by Firestore.\n */\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport class AggregateField {\n /** A type string to uniquely identify instances of this class. */\n readonly type = 'AggregateField';\n\n /** Indicates the aggregation operation of this AggregateField. */\n readonly aggregateType: AggregateType;\n\n /**\n * Create a new AggregateField\n * @param aggregateType Specifies the type of aggregation operation to perform.\n * @param _internalFieldPath Optionally specifies the field that is aggregated.\n * @internal\n */\n constructor(\n aggregateType: AggregateType = 'count',\n readonly _internalFieldPath?: InternalFieldPath\n ) {\n this.aggregateType = aggregateType;\n }\n}\n\n/**\n * The union of all `AggregateField` types that are supported by Firestore.\n */\nexport type AggregateFieldType =\n | ReturnType\n | ReturnType\n | ReturnType;\n\n/**\n * Specifies a set of aggregations and their aliases.\n */\nexport interface AggregateSpec {\n [field: string]: AggregateFieldType;\n}\n\n/**\n * A type whose keys are taken from an `AggregateSpec`, and whose values are the\n * result of the aggregation performed by the corresponding `AggregateField`\n * from the input `AggregateSpec`.\n */\nexport type AggregateSpecData = {\n [P in keyof T]: T[P] extends AggregateField ? U : never;\n};\n\n/**\n * The results of executing an aggregation query.\n */\nexport class AggregateQuerySnapshot<\n AggregateSpecType extends AggregateSpec,\n AppModelType = DocumentData,\n DbModelType extends DocumentData = DocumentData\n> {\n /** A type string to uniquely identify instances of this class. */\n readonly type = 'AggregateQuerySnapshot';\n\n /**\n * The underlying query over which the aggregations recorded in this\n * `AggregateQuerySnapshot` were performed.\n */\n readonly query: Query;\n\n /** @hideconstructor */\n constructor(\n query: Query,\n private readonly _userDataWriter: AbstractUserDataWriter,\n private readonly _data: ApiClientObjectMap\n ) {\n this.query = query;\n }\n\n /**\n * Returns the results of the aggregations performed over the underlying\n * query.\n *\n * The keys of the returned object will be the same as those of the\n * `AggregateSpec` object specified to the aggregation method, and the values\n * will be the corresponding aggregation result.\n *\n * @returns The results of the aggregations performed over the underlying\n * query.\n */\n data(): AggregateSpecData {\n return this._userDataWriter.convertObjectMap(\n this._data\n ) as AggregateSpecData;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getModularInstance } from '@firebase/util';\n\nimport {\n newQueryForCollectionGroup,\n newQueryForPath,\n Query as InternalQuery,\n queryEquals\n} from '../core/query';\nimport { DocumentKey } from '../model/document_key';\nimport { ResourcePath } from '../model/path';\nimport { Code, FirestoreError } from '../util/error';\nimport {\n cast,\n validateCollectionPath,\n validateDocumentPath,\n validateNonEmptyArgument\n} from '../util/input_validation';\n// API extractor fails importing property unless we also explicitly import Property.\n// eslint-disable-next-line @typescript-eslint/no-unused-vars, unused-imports/no-unused-imports-ts\nimport { Property, property, validateJSON } from '../util/json_validation';\nimport { AutoId } from '../util/misc';\n\nimport { Firestore } from './database';\nimport { FieldPath } from './field_path';\nimport { FieldValue } from './field_value';\nimport { FirestoreDataConverter } from './snapshot';\nimport { NestedUpdateFields, Primitive } from './types';\n\n/**\n * Document data (for use with {@link @firebase/firestore/lite#(setDoc:1)}) consists of fields mapped to\n * values.\n */\nexport interface DocumentData {\n /** A mapping between a field and its value. */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [field: string]: any;\n}\n\n/**\n * Similar to TypeScript's `Partial`, but allows nested fields to be\n * omitted and FieldValues to be passed in as property values.\n */\nexport type PartialWithFieldValue =\n | Partial\n | (T extends Primitive\n ? T\n : T extends {}\n ? { [K in keyof T]?: PartialWithFieldValue | FieldValue }\n : never);\n\n/**\n * Allows FieldValues to be passed in as a property value while maintaining\n * type safety.\n */\nexport type WithFieldValue =\n | T\n | (T extends Primitive\n ? T\n : T extends {}\n ? { [K in keyof T]: WithFieldValue | FieldValue }\n : never);\n\n/**\n * Update data (for use with {@link (updateDoc:1)}) that consists of field paths\n * (e.g. 'foo' or 'foo.baz') mapped to values. Fields that contain dots\n * reference nested fields within the document. FieldValues can be passed in\n * as property values.\n */\nexport type UpdateData = T extends Primitive\n ? T\n : T extends {}\n ? { [K in keyof T]?: UpdateData | FieldValue } & NestedUpdateFields\n : Partial;\n/**\n * An options object that configures the behavior of {@link @firebase/firestore/lite#(setDoc:1)}, {@link\n * @firebase/firestore/lite#(WriteBatch.set:1)} and {@link @firebase/firestore/lite#(Transaction.set:1)} calls. These calls can be\n * configured to perform granular merges instead of overwriting the target\n * documents in their entirety by providing a `SetOptions` with `merge: true`.\n *\n * @param merge - Changes the behavior of a `setDoc()` call to only replace the\n * values specified in its data argument. Fields omitted from the `setDoc()`\n * call remain untouched. If your input sets any field to an empty map, all\n * nested fields are overwritten.\n * @param mergeFields - Changes the behavior of `setDoc()` calls to only replace\n * the specified field paths. Any field path that is not specified is ignored\n * and remains untouched. If your input sets any field to an empty map, all\n * nested fields are overwritten.\n */\nexport type SetOptions =\n | {\n readonly merge?: boolean;\n }\n | {\n readonly mergeFields?: Array;\n };\n\n/**\n * A `Query` refers to a query which you can read or listen to. You can also\n * construct refined `Query` objects by adding filters and ordering.\n */\nexport class Query<\n AppModelType = DocumentData,\n DbModelType extends DocumentData = DocumentData\n> {\n /** The type of this Firestore reference. */\n readonly type: 'query' | 'collection' = 'query';\n\n /**\n * The `Firestore` instance for the Firestore database (useful for performing\n * transactions, etc.).\n */\n readonly firestore: Firestore;\n\n // This is the lite version of the Query class in the main SDK.\n\n /** @hideconstructor protected */\n constructor(\n firestore: Firestore,\n /**\n * If provided, the `FirestoreDataConverter` associated with this instance.\n */\n readonly converter: FirestoreDataConverter<\n AppModelType,\n DbModelType\n > | null,\n readonly _query: InternalQuery\n ) {\n this.firestore = firestore;\n }\n\n /**\n * Removes the current converter.\n *\n * @param converter - `null` removes the current converter.\n * @returns A `Query` that does not use a\n * converter.\n */\n withConverter(converter: null): Query;\n /**\n * Applies a custom data converter to this query, allowing you to use your own\n * custom model objects with Firestore. When you call {@link getDocs} with\n * the returned query, the provided converter will convert between Firestore\n * data of type `NewDbModelType` and your custom type `NewAppModelType`.\n *\n * @param converter - Converts objects to and from Firestore.\n * @returns A `Query` that uses the provided converter.\n */\n withConverter<\n NewAppModelType,\n NewDbModelType extends DocumentData = DocumentData\n >(\n converter: FirestoreDataConverter\n ): Query;\n withConverter<\n NewAppModelType,\n NewDbModelType extends DocumentData = DocumentData\n >(\n converter: FirestoreDataConverter | null\n ): Query {\n return new Query(\n this.firestore,\n converter,\n this._query\n );\n }\n}\n\n/**\n * A `DocumentReference` refers to a document location in a Firestore database\n * and can be used to write, read, or listen to the location. The document at\n * the referenced location may or may not exist.\n */\nexport class DocumentReference<\n AppModelType = DocumentData,\n DbModelType extends DocumentData = DocumentData\n> {\n /** The type of this Firestore reference. */\n readonly type = 'document';\n\n /**\n * The {@link Firestore} instance the document is in.\n * This is useful for performing transactions, for example.\n */\n readonly firestore: Firestore;\n\n /** @hideconstructor */\n constructor(\n firestore: Firestore,\n /**\n * If provided, the `FirestoreDataConverter` associated with this instance.\n */\n readonly converter: FirestoreDataConverter<\n AppModelType,\n DbModelType\n > | null,\n readonly _key: DocumentKey\n ) {\n this.firestore = firestore;\n }\n\n get _path(): ResourcePath {\n return this._key.path;\n }\n\n /**\n * The document's identifier within its collection.\n */\n get id(): string {\n return this._key.path.lastSegment();\n }\n\n /**\n * A string representing the path of the referenced document (relative\n * to the root of the database).\n */\n get path(): string {\n return this._key.path.canonicalString();\n }\n\n /**\n * The collection this `DocumentReference` belongs to.\n */\n get parent(): CollectionReference {\n return new CollectionReference(\n this.firestore,\n this.converter,\n this._key.path.popLast()\n );\n }\n\n /**\n * Applies a custom data converter to this `DocumentReference`, allowing you\n * to use your own custom model objects with Firestore. When you call {@link\n * @firebase/firestore/lite#(setDoc:1)}, {@link @firebase/firestore/lite#getDoc}, etc. with the returned `DocumentReference`\n * instance, the provided converter will convert between Firestore data of\n * type `NewDbModelType` and your custom type `NewAppModelType`.\n *\n * @param converter - Converts objects to and from Firestore.\n * @returns A `DocumentReference` that uses the provided converter.\n */\n withConverter<\n NewAppModelType,\n NewDbModelType extends DocumentData = DocumentData\n >(\n converter: FirestoreDataConverter\n ): DocumentReference;\n /**\n * Removes the current converter.\n *\n * @param converter - `null` removes the current converter.\n * @returns A `DocumentReference` that does not\n * use a converter.\n */\n withConverter(converter: null): DocumentReference;\n withConverter<\n NewAppModelType,\n NewDbModelType extends DocumentData = DocumentData\n >(\n converter: FirestoreDataConverter | null\n ): DocumentReference {\n return new DocumentReference(\n this.firestore,\n converter,\n this._key\n );\n }\n\n static _jsonSchemaVersion: string = 'firestore/documentReference/1.0';\n static _jsonSchema = {\n type: property('string', DocumentReference._jsonSchemaVersion),\n referencePath: property('string')\n };\n\n /**\n * Returns a JSON-serializable representation of this `DocumentReference` instance.\n *\n * @returns a JSON representation of this object.\n */\n toJSON(): object {\n return {\n type: DocumentReference._jsonSchemaVersion,\n referencePath: this._key.toString()\n };\n }\n\n /**\n * Builds a `DocumentReference` instance from a JSON object created by\n * {@link DocumentReference.toJSON}.\n *\n * @param firestore - The {@link Firestore} instance the snapshot should be loaded for.\n * @param json a JSON object represention of a `DocumentReference` instance\n * @returns an instance of {@link DocumentReference} if the JSON object could be parsed. Throws a\n * {@link FirestoreError} if an error occurs.\n */\n static fromJSON(firestore: Firestore, json: object): DocumentReference;\n /**\n * Builds a `DocumentReference` instance from a JSON object created by\n * {@link DocumentReference.toJSON}.\n *\n * @param firestore - The {@link Firestore} instance the snapshot should be loaded for.\n * @param json a JSON object represention of a `DocumentReference` instance\n * @param converter - Converts objects to and from Firestore.\n * @returns an instance of {@link DocumentReference} if the JSON object could be parsed. Throws a\n * {@link FirestoreError} if an error occurs.\n */\n static fromJSON<\n NewAppModelType = DocumentData,\n NewDbModelType extends DocumentData = DocumentData\n >(\n firestore: Firestore,\n json: object,\n converter: FirestoreDataConverter\n ): DocumentReference;\n static fromJSON<\n NewAppModelType = DocumentData,\n NewDbModelType extends DocumentData = DocumentData\n >(\n firestore: Firestore,\n json: object,\n converter?: FirestoreDataConverter\n ): DocumentReference {\n if (validateJSON(json, DocumentReference._jsonSchema)) {\n return new DocumentReference(\n firestore,\n converter ? converter : null,\n new DocumentKey(ResourcePath.fromString(json.referencePath))\n );\n }\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Unexpected error creating Bytes from JSON.'\n );\n }\n}\n\n/**\n * A `CollectionReference` object can be used for adding documents, getting\n * document references, and querying for documents (using {@link (query:1)}).\n */\nexport class CollectionReference<\n AppModelType = DocumentData,\n DbModelType extends DocumentData = DocumentData\n> extends Query {\n /** The type of this Firestore reference. */\n readonly type = 'collection';\n\n /** @hideconstructor */\n constructor(\n firestore: Firestore,\n converter: FirestoreDataConverter | null,\n readonly _path: ResourcePath\n ) {\n super(firestore, converter, newQueryForPath(_path));\n }\n\n /** The collection's identifier. */\n get id(): string {\n return this._query.path.lastSegment();\n }\n\n /**\n * A string representing the path of the referenced collection (relative\n * to the root of the database).\n */\n get path(): string {\n return this._query.path.canonicalString();\n }\n\n /**\n * A reference to the containing `DocumentReference` if this is a\n * subcollection. If this isn't a subcollection, the reference is null.\n */\n get parent(): DocumentReference | null {\n const parentPath = this._path.popLast();\n if (parentPath.isEmpty()) {\n return null;\n } else {\n return new DocumentReference(\n this.firestore,\n /* converter= */ null,\n new DocumentKey(parentPath)\n );\n }\n }\n\n /**\n * Applies a custom data converter to this `CollectionReference`, allowing you\n * to use your own custom model objects with Firestore. When you call {@link\n * addDoc} with the returned `CollectionReference` instance, the provided\n * converter will convert between Firestore data of type `NewDbModelType` and\n * your custom type `NewAppModelType`.\n *\n * @param converter - Converts objects to and from Firestore.\n * @returns A `CollectionReference` that uses the provided converter.\n */\n withConverter<\n NewAppModelType,\n NewDbModelType extends DocumentData = DocumentData\n >(\n converter: FirestoreDataConverter\n ): CollectionReference;\n /**\n * Removes the current converter.\n *\n * @param converter - `null` removes the current converter.\n * @returns A `CollectionReference` that does not\n * use a converter.\n */\n withConverter(\n converter: null\n ): CollectionReference;\n withConverter<\n NewAppModelType,\n NewDbModelType extends DocumentData = DocumentData\n >(\n converter: FirestoreDataConverter | null\n ): CollectionReference {\n return new CollectionReference(\n this.firestore,\n converter,\n this._path\n );\n }\n}\n\n/**\n * Gets a `CollectionReference` instance that refers to the collection at\n * the specified absolute path.\n *\n * @param firestore - A reference to the root `Firestore` instance.\n * @param path - A slash-separated path to a collection.\n * @param pathSegments - Additional path segments to apply relative to the first\n * argument.\n * @throws If the final path has an even number of segments and does not point\n * to a collection.\n * @returns The `CollectionReference` instance.\n */\nexport function collection(\n firestore: Firestore,\n path: string,\n ...pathSegments: string[]\n): CollectionReference;\n/**\n * Gets a `CollectionReference` instance that refers to a subcollection of\n * `reference` at the specified relative path.\n *\n * @param reference - A reference to a collection.\n * @param path - A slash-separated path to a collection.\n * @param pathSegments - Additional path segments to apply relative to the first\n * argument.\n * @throws If the final path has an even number of segments and does not point\n * to a collection.\n * @returns The `CollectionReference` instance.\n */\nexport function collection(\n reference: CollectionReference,\n path: string,\n ...pathSegments: string[]\n): CollectionReference;\n/**\n * Gets a `CollectionReference` instance that refers to a subcollection of\n * `reference` at the specified relative path.\n *\n * @param reference - A reference to a Firestore document.\n * @param path - A slash-separated path to a collection.\n * @param pathSegments - Additional path segments that will be applied relative\n * to the first argument.\n * @throws If the final path has an even number of segments and does not point\n * to a collection.\n * @returns The `CollectionReference` instance.\n */\nexport function collection(\n reference: DocumentReference,\n path: string,\n ...pathSegments: string[]\n): CollectionReference;\nexport function collection(\n parent:\n | Firestore\n | DocumentReference\n | CollectionReference,\n path: string,\n ...pathSegments: string[]\n): CollectionReference {\n parent = getModularInstance(parent);\n\n validateNonEmptyArgument('collection', 'path', path);\n if (parent instanceof Firestore) {\n const absolutePath = ResourcePath.fromString(path, ...pathSegments);\n validateCollectionPath(absolutePath);\n return new CollectionReference(parent, /* converter= */ null, absolutePath);\n } else {\n if (\n !(parent instanceof DocumentReference) &&\n !(parent instanceof CollectionReference)\n ) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Expected first argument to collection() to be a CollectionReference, ' +\n 'a DocumentReference or FirebaseFirestore'\n );\n }\n const absolutePath = parent._path.child(\n ResourcePath.fromString(path, ...pathSegments)\n );\n validateCollectionPath(absolutePath);\n return new CollectionReference(\n parent.firestore,\n /* converter= */ null,\n absolutePath\n );\n }\n}\n\n// TODO(firestorelite): Consider using ErrorFactory -\n// https://github.com/firebase/firebase-js-sdk/blob/0131e1f/packages/util/src/errors.ts#L106\n\n/**\n * Creates and returns a new `Query` instance that includes all documents in the\n * database that are contained in a collection or subcollection with the\n * given `collectionId`.\n *\n * @param firestore - A reference to the root `Firestore` instance.\n * @param collectionId - Identifies the collections to query over. Every\n * collection or subcollection with this ID as the last segment of its path\n * will be included. Cannot contain a slash.\n * @returns The created `Query`.\n */\nexport function collectionGroup(\n firestore: Firestore,\n collectionId: string\n): Query {\n firestore = cast(firestore, Firestore);\n\n validateNonEmptyArgument('collectionGroup', 'collection id', collectionId);\n if (collectionId.indexOf('/') >= 0) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid collection ID '${collectionId}' passed to function ` +\n `collectionGroup(). Collection IDs must not contain '/'.`\n );\n }\n\n return new Query(\n firestore,\n /* converter= */ null,\n newQueryForCollectionGroup(collectionId)\n );\n}\n\n/**\n * Gets a `DocumentReference` instance that refers to the document at the\n * specified absolute path.\n *\n * @param firestore - A reference to the root `Firestore` instance.\n * @param path - A slash-separated path to a document.\n * @param pathSegments - Additional path segments that will be applied relative\n * to the first argument.\n * @throws If the final path has an odd number of segments and does not point to\n * a document.\n * @returns The `DocumentReference` instance.\n */\nexport function doc(\n firestore: Firestore,\n path: string,\n ...pathSegments: string[]\n): DocumentReference;\n/**\n * Gets a `DocumentReference` instance that refers to a document within\n * `reference` at the specified relative path. If no path is specified, an\n * automatically-generated unique ID will be used for the returned\n * `DocumentReference`.\n *\n * @param reference - A reference to a collection.\n * @param path - A slash-separated path to a document. Has to be omitted to use\n * auto-generated IDs.\n * @param pathSegments - Additional path segments that will be applied relative\n * to the first argument.\n * @throws If the final path has an odd number of segments and does not point to\n * a document.\n * @returns The `DocumentReference` instance.\n */\nexport function doc(\n reference: CollectionReference,\n path?: string,\n ...pathSegments: string[]\n): DocumentReference;\n/**\n * Gets a `DocumentReference` instance that refers to a document within\n * `reference` at the specified relative path.\n *\n * @param reference - A reference to a Firestore document.\n * @param path - A slash-separated path to a document.\n * @param pathSegments - Additional path segments that will be applied relative\n * to the first argument.\n * @throws If the final path has an odd number of segments and does not point to\n * a document.\n * @returns The `DocumentReference` instance.\n */\nexport function doc(\n reference: DocumentReference,\n path: string,\n ...pathSegments: string[]\n): DocumentReference;\nexport function doc(\n parent:\n | Firestore\n | CollectionReference\n | DocumentReference,\n path?: string,\n ...pathSegments: string[]\n): DocumentReference {\n parent = getModularInstance(parent);\n\n // We allow omission of 'pathString' but explicitly prohibit passing in both\n // 'undefined' and 'null'.\n if (arguments.length === 1) {\n path = AutoId.newId();\n }\n validateNonEmptyArgument('doc', 'path', path);\n\n if (parent instanceof Firestore) {\n const absolutePath = ResourcePath.fromString(path, ...pathSegments);\n validateDocumentPath(absolutePath);\n return new DocumentReference(\n parent,\n /* converter= */ null,\n new DocumentKey(absolutePath)\n );\n } else {\n if (\n !(parent instanceof DocumentReference) &&\n !(parent instanceof CollectionReference)\n ) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Expected first argument to collection() to be a CollectionReference, ' +\n 'a DocumentReference or FirebaseFirestore'\n );\n }\n const absolutePath = parent._path.child(\n ResourcePath.fromString(path, ...pathSegments)\n );\n validateDocumentPath(absolutePath);\n return new DocumentReference(\n parent.firestore,\n parent instanceof CollectionReference ? parent.converter : null,\n new DocumentKey(absolutePath)\n );\n }\n}\n\n/**\n * Returns true if the provided references are equal.\n *\n * @param left - A reference to compare.\n * @param right - A reference to compare.\n * @returns true if the references point to the same location in the same\n * Firestore database.\n */\nexport function refEqual(\n left:\n | DocumentReference\n | CollectionReference,\n right:\n | DocumentReference\n | CollectionReference\n): boolean {\n left = getModularInstance(left);\n right = getModularInstance(right);\n\n if (\n (left instanceof DocumentReference ||\n left instanceof CollectionReference) &&\n (right instanceof DocumentReference || right instanceof CollectionReference)\n ) {\n return (\n left.firestore === right.firestore &&\n left.path === right.path &&\n left.converter === right.converter\n );\n }\n return false;\n}\n\n/**\n * Returns true if the provided queries point to the same collection and apply\n * the same constraints.\n *\n * @param left - A `Query` to compare.\n * @param right - A `Query` to compare.\n * @returns true if the references point to the same location in the same\n * Firestore database.\n */\nexport function queryEqual(\n left: Query,\n right: Query\n): boolean {\n left = getModularInstance(left);\n right = getModularInstance(right);\n\n if (left instanceof Query && right instanceof Query) {\n return (\n left.firestore === right.firestore &&\n queryEquals(left._query, right._query) &&\n left.converter === right.converter\n );\n }\n return false;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ByteString } from '../util/byte_string';\nimport { Code, FirestoreError } from '../util/error';\n// API extractor fails importing property unless we also explicitly import Property.\n// eslint-disable-next-line @typescript-eslint/no-unused-vars, unused-imports/no-unused-imports-ts\nimport { Property, property, validateJSON } from '../util/json_validation';\n\n/**\n * An immutable object representing an array of bytes.\n */\nexport class Bytes {\n _byteString: ByteString;\n\n /** @hideconstructor */\n constructor(byteString: ByteString) {\n this._byteString = byteString;\n }\n\n /**\n * Creates a new `Bytes` object from the given Base64 string, converting it to\n * bytes.\n *\n * @param base64 - The Base64 string used to create the `Bytes` object.\n */\n static fromBase64String(base64: string): Bytes {\n try {\n return new Bytes(ByteString.fromBase64String(base64));\n } catch (e) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Failed to construct data from Base64 string: ' + e\n );\n }\n }\n\n /**\n * Creates a new `Bytes` object from the given Uint8Array.\n *\n * @param array - The Uint8Array used to create the `Bytes` object.\n */\n static fromUint8Array(array: Uint8Array): Bytes {\n return new Bytes(ByteString.fromUint8Array(array));\n }\n\n /**\n * Returns the underlying bytes as a Base64-encoded string.\n *\n * @returns The Base64-encoded string created from the `Bytes` object.\n */\n toBase64(): string {\n return this._byteString.toBase64();\n }\n\n /**\n * Returns the underlying bytes in a new `Uint8Array`.\n *\n * @returns The Uint8Array created from the `Bytes` object.\n */\n toUint8Array(): Uint8Array {\n return this._byteString.toUint8Array();\n }\n\n /**\n * Returns a string representation of the `Bytes` object.\n *\n * @returns A string representation of the `Bytes` object.\n */\n toString(): string {\n return 'Bytes(base64: ' + this.toBase64() + ')';\n }\n\n /**\n * Returns true if this `Bytes` object is equal to the provided one.\n *\n * @param other - The `Bytes` object to compare against.\n * @returns true if this `Bytes` object is equal to the provided one.\n */\n isEqual(other: Bytes): boolean {\n return this._byteString.isEqual(other._byteString);\n }\n\n static _jsonSchemaVersion: string = 'firestore/bytes/1.0';\n static _jsonSchema = {\n type: property('string', Bytes._jsonSchemaVersion),\n bytes: property('string')\n };\n\n /**\n * Returns a JSON-serializable representation of this `Bytes` instance.\n *\n * @returns a JSON representation of this object.\n */\n toJSON(): object {\n return {\n type: Bytes._jsonSchemaVersion,\n bytes: this.toBase64()\n };\n }\n\n /**\n * Builds a `Bytes` instance from a JSON object created by {@link Bytes.toJSON}.\n *\n * @param json a JSON object represention of a `Bytes` instance\n * @returns an instance of {@link Bytes} if the JSON object could be parsed. Throws a\n * {@link FirestoreError} if an error occurs.\n */\n static fromJSON(json: object): Bytes {\n if (validateJSON(json, Bytes._jsonSchema)) {\n return Bytes.fromBase64String(json.bytes);\n }\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Unexpected error creating Bytes from JSON.'\n );\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n DOCUMENT_KEY_NAME,\n FieldPath as InternalFieldPath\n} from '../model/path';\nimport { Code, FirestoreError } from '../util/error';\n\n/**\n * A `FieldPath` refers to a field in a document. The path may consist of a\n * single field name (referring to a top-level field in the document), or a\n * list of field names (referring to a nested field in the document).\n *\n * Create a `FieldPath` by providing field names. If more than one field\n * name is provided, the path will point to a nested field in a document.\n */\nexport class FieldPath {\n /** Internal representation of a Firestore field path. */\n readonly _internalPath: InternalFieldPath;\n\n /**\n * Creates a `FieldPath` from the provided field names. If more than one field\n * name is provided, the path will point to a nested field in a document.\n *\n * @param fieldNames - A list of field names.\n */\n constructor(...fieldNames: string[]) {\n for (let i = 0; i < fieldNames.length; ++i) {\n if (fieldNames[i].length === 0) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid field name at argument $(i + 1). ` +\n 'Field names must not be empty.'\n );\n }\n }\n\n this._internalPath = new InternalFieldPath(fieldNames);\n }\n\n /**\n * Returns true if this `FieldPath` is equal to the provided one.\n *\n * @param other - The `FieldPath` to compare against.\n * @returns true if this `FieldPath` is equal to the provided one.\n */\n isEqual(other: FieldPath): boolean {\n return this._internalPath.isEqual(other._internalPath);\n }\n}\n\n/**\n * Returns a special sentinel `FieldPath` to refer to the ID of a document.\n * It can be used in queries to sort or filter by the document ID.\n */\nexport function documentId(): FieldPath {\n return new FieldPath(DOCUMENT_KEY_NAME);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ParseContext } from '../api/parse_context';\nimport { FieldTransform } from '../model/mutation';\n\n/**\n * Sentinel values that can be used when writing document fields with `set()`\n * or `update()`.\n */\nexport abstract class FieldValue {\n /**\n * @param _methodName - The public API endpoint that returns this class.\n * @hideconstructor\n */\n constructor(public _methodName: string) {}\n\n /** Compares `FieldValue`s for equality. */\n abstract isEqual(other: FieldValue): boolean;\n abstract _toFieldTransform(context: ParseContext): FieldTransform | null;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Code, FirestoreError } from '../util/error';\n// API extractor fails importing 'property' unless we also explicitly import 'Property'.\n// eslint-disable-next-line @typescript-eslint/no-unused-vars, unused-imports/no-unused-imports-ts\nimport { Property, property, validateJSON } from '../util/json_validation';\nimport { primitiveComparator } from '../util/misc';\n\n/**\n * An immutable object representing a geographic location in Firestore. The\n * location is represented as latitude/longitude pair.\n *\n * Latitude values are in the range of [-90, 90].\n * Longitude values are in the range of [-180, 180].\n */\nexport class GeoPoint {\n // Prefix with underscore to signal this is a private variable in JS and\n // prevent it showing up for autocompletion when typing latitude or longitude.\n private _lat: number;\n private _long: number;\n\n /**\n * Creates a new immutable `GeoPoint` object with the provided latitude and\n * longitude values.\n * @param latitude - The latitude as number between -90 and 90.\n * @param longitude - The longitude as number between -180 and 180.\n */\n constructor(latitude: number, longitude: number) {\n if (!isFinite(latitude) || latitude < -90 || latitude > 90) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Latitude must be a number between -90 and 90, but was: ' + latitude\n );\n }\n if (!isFinite(longitude) || longitude < -180 || longitude > 180) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Longitude must be a number between -180 and 180, but was: ' + longitude\n );\n }\n\n this._lat = latitude;\n this._long = longitude;\n }\n\n /**\n * The latitude of this `GeoPoint` instance.\n */\n get latitude(): number {\n return this._lat;\n }\n\n /**\n * The longitude of this `GeoPoint` instance.\n */\n get longitude(): number {\n return this._long;\n }\n\n /**\n * Returns true if this `GeoPoint` is equal to the provided one.\n *\n * @param other - The `GeoPoint` to compare against.\n * @returns true if this `GeoPoint` is equal to the provided one.\n */\n isEqual(other: GeoPoint): boolean {\n return this._lat === other._lat && this._long === other._long;\n }\n\n /**\n * Actually private to JS consumers of our API, so this function is prefixed\n * with an underscore.\n */\n _compareTo(other: GeoPoint): number {\n return (\n primitiveComparator(this._lat, other._lat) ||\n primitiveComparator(this._long, other._long)\n );\n }\n\n static _jsonSchemaVersion: string = 'firestore/geoPoint/1.0';\n static _jsonSchema = {\n type: property('string', GeoPoint._jsonSchemaVersion),\n latitude: property('number'),\n longitude: property('number')\n };\n\n /**\n * Returns a JSON-serializable representation of this `GeoPoint` instance.\n *\n * @returns a JSON representation of this object.\n */\n toJSON(): { latitude: number; longitude: number; type: string } {\n return {\n latitude: this._lat,\n longitude: this._long,\n type: GeoPoint._jsonSchemaVersion\n };\n }\n\n /**\n * Builds a `GeoPoint` instance from a JSON object created by {@link GeoPoint.toJSON}.\n *\n * @param json a JSON object represention of a `GeoPoint` instance\n * @returns an instance of {@link GeoPoint} if the JSON object could be parsed. Throws a\n * {@link FirestoreError} if an error occurs.\n */\n static fromJSON(json: object): GeoPoint {\n if (validateJSON(json, GeoPoint._jsonSchema)) {\n return new GeoPoint(json.latitude, json.longitude);\n }\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Unexpected error creating GeoPoint from JSON.'\n );\n }\n}\n","/**\n * @license\n * Copyright 2024 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isPrimitiveArrayEqual } from '../util/array';\nimport { Code, FirestoreError } from '../util/error';\n// API extractor fails importing 'property' unless we also explicitly import 'Property'.\n// eslint-disable-next-line @typescript-eslint/no-unused-vars, unused-imports/no-unused-imports-ts\nimport { Property, property, validateJSON } from '../util/json_validation';\n\n/**\n * Represents a vector type in Firestore documents.\n * Create an instance with {@link vector}.\n *\n * @class VectorValue\n */\nexport class VectorValue {\n private readonly _values: number[];\n\n /**\n * @private\n * @internal\n */\n constructor(values: number[] | undefined) {\n // Making a copy of the parameter.\n this._values = (values || []).map(n => n);\n }\n\n /**\n * Returns a copy of the raw number array form of the vector.\n */\n toArray(): number[] {\n return this._values.map(n => n);\n }\n\n /**\n * Returns `true` if the two `VectorValue` values have the same raw number arrays, returns `false` otherwise.\n */\n isEqual(other: VectorValue): boolean {\n return isPrimitiveArrayEqual(this._values, other._values);\n }\n\n static _jsonSchemaVersion: string = 'firestore/vectorValue/1.0';\n static _jsonSchema = {\n type: property('string', VectorValue._jsonSchemaVersion),\n vectorValues: property('object')\n };\n\n /**\n * Returns a JSON-serializable representation of this `VectorValue` instance.\n *\n * @returns a JSON representation of this object.\n */\n toJSON(): object {\n return {\n type: VectorValue._jsonSchemaVersion,\n vectorValues: this._values\n };\n }\n\n /**\n * Builds a `VectorValue` instance from a JSON object created by {@link VectorValue.toJSON}.\n *\n * @param json a JSON object represention of a `VectorValue` instance.\n * @returns an instance of {@link VectorValue} if the JSON object could be parsed. Throws a\n * {@link FirestoreError} if an error occurs.\n */\n static fromJSON(json: object): VectorValue {\n if (validateJSON(json, VectorValue._jsonSchema)) {\n if (\n Array.isArray(json.vectorValues) &&\n json.vectorValues.every(element => typeof element === 'number')\n ) {\n return new VectorValue(json.vectorValues);\n }\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n \"Expected 'vectorValues' field to be a number array\"\n );\n }\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Unexpected error creating Timestamp from JSON.'\n );\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Returns true iff the array contains the value using strong equality.\n */\nexport function includes(array: T[], value: T): boolean {\n for (let i = 0; i < array.length; i++) {\n if (array[i] === value) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * Returns true iff the array contains any value matching the predicate\n */\nexport function some(array: T[], predicate: (t: T) => boolean): boolean {\n for (let i = 0; i < array.length; i++) {\n if (predicate(array[i])) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * Calls predicate function for each item in the array until the predicate\n * returns true, at which point the index of that item is returned. If the\n * predicate does not return true for any item, null is returned.\n */\nexport function findIndex
(\n array: A[],\n predicate: (value: A) => boolean\n): number | null {\n for (let i = 0; i < array.length; i++) {\n if (predicate(array[i])) {\n return i;\n }\n }\n return null;\n}\n\n/**\n * Compares two array for equality using comparator. The method computes the\n * intersection and invokes `onAdd` for every element that is in `after` but not\n * `before`. `onRemove` is invoked for every element in `before` but missing\n * from `after`.\n *\n * The method creates a copy of both `before` and `after` and runs in O(n log\n * n), where n is the size of the two lists.\n *\n * @param before - The elements that exist in the original array.\n * @param after - The elements to diff against the original array.\n * @param comparator - The comparator for the elements in before and after.\n * @param onAdd - A function to invoke for every element that is part of `\n * after` but not `before`.\n * @param onRemove - A function to invoke for every element that is part of\n * `before` but not `after`.\n */\nexport function diffArrays(\n before: T[],\n after: T[],\n comparator: (l: T, r: T) => number,\n onAdd: (entry: T) => void,\n onRemove: (entry: T) => void\n): void {\n before = [...before];\n after = [...after];\n before.sort(comparator);\n after.sort(comparator);\n\n const bLen = before.length;\n const aLen = after.length;\n let a = 0;\n let b = 0;\n while (a < aLen && b < bLen) {\n const cmp = comparator(before[b], after[a]);\n if (cmp < 0) {\n // The element was removed if the next element in our ordered\n // walkthrough is only in `before`.\n onRemove(before[b++]);\n } else if (cmp > 0) {\n // The element was added if the next element in our ordered walkthrough\n // is only in `after`.\n onAdd(after[a++]);\n } else {\n a++;\n b++;\n }\n }\n while (a < aLen) {\n onAdd(after[a++]);\n }\n while (b < bLen) {\n onRemove(before[b++]);\n }\n}\n\n/**\n * Verifies equality for an array of objects using the `isEqual` interface.\n *\n * @private\n * @internal\n * @param left Array of objects supporting `isEqual`.\n * @param right Array of objects supporting `isEqual`.\n * @return True if arrays are equal.\n */\nexport function isArrayEqual boolean }>(\n left: T[],\n right: T[]\n): boolean {\n if (left.length !== right.length) {\n return false;\n }\n\n for (let i = 0; i < left.length; ++i) {\n if (!left[i].isEqual(right[i])) {\n return false;\n }\n }\n\n return true;\n}\n\n/**\n * Verifies equality for an array of primitives.\n *\n * @private\n * @internal\n * @param left Array of primitives.\n * @param right Array of primitives.\n * @return True if arrays are equal.\n */\nexport function isPrimitiveArrayEqual(\n left: T[],\n right: T[]\n): boolean {\n if (left.length !== right.length) {\n return false;\n }\n\n for (let i = 0; i < left.length; ++i) {\n if (left[i] !== right[i]) {\n return false;\n }\n }\n\n return true;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n DocumentData,\n FieldPath as PublicFieldPath,\n SetOptions\n} from '@firebase/firestore-types';\nimport { Compat, deepEqual, getModularInstance } from '@firebase/util';\n\nimport { ParseContext } from '../api/parse_context';\nimport { DatabaseId } from '../core/database_info';\nimport { DocumentKey } from '../model/document_key';\nimport { FieldMask } from '../model/field_mask';\nimport {\n FieldTransform,\n Mutation,\n PatchMutation,\n Precondition,\n SetMutation\n} from '../model/mutation';\nimport { ObjectValue } from '../model/object_value';\nimport { FieldPath as InternalFieldPath } from '../model/path';\nimport {\n ArrayRemoveTransformOperation,\n ArrayUnionTransformOperation,\n NumericIncrementTransformOperation,\n ServerTimestampTransform\n} from '../model/transform_operation';\nimport {\n TYPE_KEY,\n VECTOR_MAP_VECTORS_KEY,\n VECTOR_VALUE_SENTINEL\n} from '../model/values';\nimport { newSerializer } from '../platform/serializer';\nimport {\n MapValue as ProtoMapValue,\n Value as ProtoValue\n} from '../protos/firestore_proto_api';\nimport { toDouble, toNumber } from '../remote/number_serializer';\nimport {\n JsonProtoSerializer,\n toBytes,\n toResourceName,\n toTimestamp\n} from '../remote/serializer';\nimport { debugAssert, fail } from '../util/assert';\nimport { Code, FirestoreError } from '../util/error';\nimport { isPlainObject, valueDescription } from '../util/input_validation';\nimport { Dict, forEach, isEmpty } from '../util/obj';\n\nimport { Bytes } from './bytes';\nimport { Firestore } from './database';\nimport { FieldPath } from './field_path';\nimport { FieldValue } from './field_value';\nimport { GeoPoint } from './geo_point';\nimport {\n DocumentReference,\n PartialWithFieldValue,\n WithFieldValue\n} from './reference';\nimport { Timestamp } from './timestamp';\nimport { VectorValue } from './vector_value';\n\nconst RESERVED_FIELD_REGEX = /^__.*__$/;\n\n/**\n * An untyped Firestore Data Converter interface that is shared between the\n * lite, firestore-exp and classic SDK.\n */\nexport interface UntypedFirestoreDataConverter<\n AppModelType,\n DbModelType extends DocumentData = DocumentData\n> {\n toFirestore(\n modelObject: WithFieldValue\n ): WithFieldValue;\n toFirestore(\n modelObject: PartialWithFieldValue,\n options: SetOptions\n ): PartialWithFieldValue;\n fromFirestore(snapshot: unknown, options?: unknown): AppModelType;\n}\n\n/** The result of parsing document data (e.g. for a setData call). */\nexport class ParsedSetData {\n constructor(\n readonly data: ObjectValue,\n readonly fieldMask: FieldMask | null,\n readonly fieldTransforms: FieldTransform[]\n ) {}\n\n toMutation(key: DocumentKey, precondition: Precondition): Mutation {\n if (this.fieldMask !== null) {\n return new PatchMutation(\n key,\n this.data,\n this.fieldMask,\n precondition,\n this.fieldTransforms\n );\n } else {\n return new SetMutation(\n key,\n this.data,\n precondition,\n this.fieldTransforms\n );\n }\n }\n}\n\n/** The result of parsing \"update\" data (i.e. for an updateData call). */\nexport class ParsedUpdateData {\n constructor(\n readonly data: ObjectValue,\n // The fieldMask does not include document transforms.\n readonly fieldMask: FieldMask,\n readonly fieldTransforms: FieldTransform[]\n ) {}\n\n toMutation(key: DocumentKey, precondition: Precondition): Mutation {\n return new PatchMutation(\n key,\n this.data,\n this.fieldMask,\n precondition,\n this.fieldTransforms\n );\n }\n}\n\n/*\n * Represents what type of API method provided the data being parsed; useful\n * for determining which error conditions apply during parsing and providing\n * better error messages.\n */\nexport const enum UserDataSource {\n Set,\n Update,\n MergeSet,\n /**\n * Indicates the source is a where clause, cursor bound, arrayUnion()\n * element, etc. Of note, isWrite(source) will return false.\n */\n Argument,\n /**\n * Indicates that the source is an Argument that may directly contain nested\n * arrays (e.g. the operand of an `in` query).\n */\n ArrayArgument\n}\n\nfunction isWrite(dataSource: UserDataSource): boolean {\n switch (dataSource) {\n case UserDataSource.Set: // fall through\n case UserDataSource.MergeSet: // fall through\n case UserDataSource.Update:\n return true;\n case UserDataSource.Argument:\n case UserDataSource.ArrayArgument:\n return false;\n default:\n throw fail(0x9c4b, 'Unexpected case for UserDataSource', {\n dataSource\n });\n }\n}\n\n/** Contains the settings that are mutated as we parse user data. */\ninterface ContextSettings {\n /** Indicates what kind of API method this data came from. */\n readonly dataSource: UserDataSource;\n /** The name of the method the user called to create the ParseContext. */\n readonly methodName: string;\n /** The document the user is attempting to modify, if that applies. */\n readonly targetDoc?: DocumentKey;\n /**\n * A path within the object being parsed. This could be an empty path (in\n * which case the context represents the root of the data being parsed), or a\n * nonempty path (indicating the context represents a nested location within\n * the data).\n */\n readonly path?: InternalFieldPath;\n /**\n * Whether or not this context corresponds to an element of an array.\n * If not set, elements are treated as if they were outside of arrays.\n */\n readonly arrayElement?: boolean;\n /**\n * Whether or not a converter was specified in this context. If true, error\n * messages will reference the converter when invalid data is provided.\n */\n readonly hasConverter?: boolean;\n}\n\n/** A \"context\" object passed around while parsing user data. */\nclass ParseContextImpl implements ParseContext {\n readonly fieldTransforms: FieldTransform[];\n readonly fieldMask: InternalFieldPath[];\n /**\n * Initializes a ParseContext with the given source and path.\n *\n * @param settings - The settings for the parser.\n * @param databaseId - The database ID of the Firestore instance.\n * @param serializer - The serializer to use to generate the Value proto.\n * @param ignoreUndefinedProperties - Whether to ignore undefined properties\n * rather than throw.\n * @param fieldTransforms - A mutable list of field transforms encountered\n * while parsing the data.\n * @param fieldMask - A mutable list of field paths encountered while parsing\n * the data.\n *\n * TODO(b/34871131): We don't support array paths right now, so path can be\n * null to indicate the context represents any location within an array (in\n * which case certain features will not work and errors will be somewhat\n * compromised).\n */\n constructor(\n readonly settings: ContextSettings,\n readonly databaseId: DatabaseId,\n readonly serializer: JsonProtoSerializer,\n readonly ignoreUndefinedProperties: boolean,\n fieldTransforms?: FieldTransform[],\n fieldMask?: InternalFieldPath[]\n ) {\n // Minor hack: If fieldTransforms is undefined, we assume this is an\n // external call and we need to validate the entire path.\n if (fieldTransforms === undefined) {\n this.validatePath();\n }\n this.fieldTransforms = fieldTransforms || [];\n this.fieldMask = fieldMask || [];\n }\n\n get path(): InternalFieldPath | undefined {\n return this.settings.path;\n }\n\n get dataSource(): UserDataSource {\n return this.settings.dataSource;\n }\n\n /** Returns a new context with the specified settings overwritten. */\n contextWith(configuration: Partial): ParseContextImpl {\n return new ParseContextImpl(\n { ...this.settings, ...configuration },\n this.databaseId,\n this.serializer,\n this.ignoreUndefinedProperties,\n this.fieldTransforms,\n this.fieldMask\n );\n }\n\n childContextForField(field: string): ParseContextImpl {\n const childPath = this.path?.child(field);\n const context = this.contextWith({ path: childPath, arrayElement: false });\n context.validatePathSegment(field);\n return context;\n }\n\n childContextForFieldPath(field: InternalFieldPath): ParseContextImpl {\n const childPath = this.path?.child(field);\n const context = this.contextWith({ path: childPath, arrayElement: false });\n context.validatePath();\n return context;\n }\n\n childContextForArray(index: number): ParseContextImpl {\n // TODO(b/34871131): We don't support array paths right now; so make path\n // undefined.\n return this.contextWith({ path: undefined, arrayElement: true });\n }\n\n createError(reason: string): FirestoreError {\n return createError(\n reason,\n this.settings.methodName,\n this.settings.hasConverter || false,\n this.path,\n this.settings.targetDoc\n );\n }\n\n /** Returns 'true' if 'fieldPath' was traversed when creating this context. */\n contains(fieldPath: InternalFieldPath): boolean {\n return (\n this.fieldMask.find(field => fieldPath.isPrefixOf(field)) !== undefined ||\n this.fieldTransforms.find(transform =>\n fieldPath.isPrefixOf(transform.field)\n ) !== undefined\n );\n }\n\n private validatePath(): void {\n // TODO(b/34871131): Remove null check once we have proper paths for fields\n // within arrays.\n if (!this.path) {\n return;\n }\n for (let i = 0; i < this.path.length; i++) {\n this.validatePathSegment(this.path.get(i));\n }\n }\n\n private validatePathSegment(segment: string): void {\n if (segment.length === 0) {\n throw this.createError('Document fields must not be empty');\n }\n if (isWrite(this.dataSource) && RESERVED_FIELD_REGEX.test(segment)) {\n throw this.createError('Document fields cannot begin and end with \"__\"');\n }\n }\n}\n\n/**\n * Helper for parsing raw user input (provided via the API) into internal model\n * classes.\n */\nexport class UserDataReader {\n private readonly serializer: JsonProtoSerializer;\n\n constructor(\n private readonly databaseId: DatabaseId,\n private readonly ignoreUndefinedProperties: boolean,\n serializer?: JsonProtoSerializer\n ) {\n this.serializer = serializer || newSerializer(databaseId);\n }\n\n /** Creates a new top-level parse context. */\n createContext(\n dataSource: UserDataSource,\n methodName: string,\n targetDoc?: DocumentKey,\n hasConverter = false\n ): ParseContextImpl {\n return new ParseContextImpl(\n {\n dataSource,\n methodName,\n targetDoc,\n path: InternalFieldPath.emptyPath(),\n arrayElement: false,\n hasConverter\n },\n this.databaseId,\n this.serializer,\n this.ignoreUndefinedProperties\n );\n }\n}\n\nexport function newUserDataReader(firestore: Firestore): UserDataReader {\n const settings = firestore._freezeSettings();\n const serializer = newSerializer(firestore._databaseId);\n return new UserDataReader(\n firestore._databaseId,\n !!settings.ignoreUndefinedProperties,\n serializer\n );\n}\n\n/** Parse document data from a set() call. */\nexport function parseSetData(\n userDataReader: UserDataReader,\n methodName: string,\n targetDoc: DocumentKey,\n input: unknown,\n hasConverter: boolean,\n options: SetOptions = {}\n): ParsedSetData {\n const context = userDataReader.createContext(\n options.merge || options.mergeFields\n ? UserDataSource.MergeSet\n : UserDataSource.Set,\n methodName,\n targetDoc,\n hasConverter\n );\n validatePlainObject('Data must be an object, but it was:', context, input);\n const updateData = parseObject(input, context)!;\n\n let fieldMask: FieldMask | null;\n let fieldTransforms: FieldTransform[];\n\n if (options.merge) {\n fieldMask = new FieldMask(context.fieldMask);\n fieldTransforms = context.fieldTransforms;\n } else if (options.mergeFields) {\n const validatedFieldPaths: InternalFieldPath[] = [];\n\n for (const stringOrFieldPath of options.mergeFields) {\n const fieldPath = fieldPathFromArgument(\n methodName,\n stringOrFieldPath,\n targetDoc\n );\n if (!context.contains(fieldPath)) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Field '${fieldPath}' is specified in your field mask but missing from your input data.`\n );\n }\n\n if (!fieldMaskContains(validatedFieldPaths, fieldPath)) {\n validatedFieldPaths.push(fieldPath);\n }\n }\n\n fieldMask = new FieldMask(validatedFieldPaths);\n fieldTransforms = context.fieldTransforms.filter(transform =>\n fieldMask!.covers(transform.field)\n );\n } else {\n fieldMask = null;\n fieldTransforms = context.fieldTransforms;\n }\n\n return new ParsedSetData(\n new ObjectValue(updateData),\n fieldMask,\n fieldTransforms\n );\n}\n\nexport class DeleteFieldValueImpl extends FieldValue {\n _toFieldTransform(context: ParseContextImpl): null {\n if (context.dataSource === UserDataSource.MergeSet) {\n // No transform to add for a delete, but we need to add it to our\n // fieldMask so it gets deleted.\n context.fieldMask.push(context.path!);\n } else if (context.dataSource === UserDataSource.Update) {\n debugAssert(\n context.path!.length > 0,\n `${this._methodName}() at the top level should have already ` +\n 'been handled.'\n );\n throw context.createError(\n `${this._methodName}() can only appear at the top level ` +\n 'of your update data'\n );\n } else {\n // We shouldn't encounter delete sentinels for queries or non-merge set() calls.\n throw context.createError(\n `${this._methodName}() cannot be used with set() unless you pass ` +\n '{merge:true}'\n );\n }\n return null;\n }\n\n isEqual(other: FieldValue): boolean {\n return other instanceof DeleteFieldValueImpl;\n }\n}\n\n/**\n * Creates a child context for parsing SerializableFieldValues.\n *\n * This is different than calling `ParseContext.contextWith` because it keeps\n * the fieldTransforms and fieldMask separate.\n *\n * The created context has its `dataSource` set to `UserDataSource.Argument`.\n * Although these values are used with writes, any elements in these FieldValues\n * are not considered writes since they cannot contain any FieldValue sentinels,\n * etc.\n *\n * @param fieldValue - The sentinel FieldValue for which to create a child\n * context.\n * @param context - The parent context.\n * @param arrayElement - Whether or not the FieldValue has an array.\n */\nfunction createSentinelChildContext(\n fieldValue: FieldValue,\n context: ParseContextImpl,\n arrayElement: boolean\n): ParseContextImpl {\n return new ParseContextImpl(\n {\n dataSource: UserDataSource.Argument,\n targetDoc: context.settings.targetDoc,\n methodName: fieldValue._methodName,\n arrayElement\n },\n context.databaseId,\n context.serializer,\n context.ignoreUndefinedProperties\n );\n}\n\nexport class ServerTimestampFieldValueImpl extends FieldValue {\n _toFieldTransform(context: ParseContextImpl): FieldTransform {\n return new FieldTransform(context.path!, new ServerTimestampTransform());\n }\n\n isEqual(other: FieldValue): boolean {\n return other instanceof ServerTimestampFieldValueImpl;\n }\n}\n\nexport class ArrayUnionFieldValueImpl extends FieldValue {\n constructor(methodName: string, private readonly _elements: unknown[]) {\n super(methodName);\n }\n\n _toFieldTransform(context: ParseContextImpl): FieldTransform {\n const parseContext = createSentinelChildContext(\n this,\n context,\n /*array=*/ true\n );\n const parsedElements = this._elements.map(\n element => parseData(element, parseContext)!\n );\n const arrayUnion = new ArrayUnionTransformOperation(parsedElements);\n return new FieldTransform(context.path!, arrayUnion);\n }\n\n isEqual(other: FieldValue): boolean {\n return (\n other instanceof ArrayUnionFieldValueImpl &&\n deepEqual(this._elements, other._elements)\n );\n }\n}\n\nexport class ArrayRemoveFieldValueImpl extends FieldValue {\n constructor(methodName: string, private readonly _elements: unknown[]) {\n super(methodName);\n }\n\n _toFieldTransform(context: ParseContextImpl): FieldTransform {\n const parseContext = createSentinelChildContext(\n this,\n context,\n /*array=*/ true\n );\n const parsedElements = this._elements.map(\n element => parseData(element, parseContext)!\n );\n const arrayUnion = new ArrayRemoveTransformOperation(parsedElements);\n return new FieldTransform(context.path!, arrayUnion);\n }\n\n isEqual(other: FieldValue): boolean {\n return (\n other instanceof ArrayRemoveFieldValueImpl &&\n deepEqual(this._elements, other._elements)\n );\n }\n}\n\nexport class NumericIncrementFieldValueImpl extends FieldValue {\n constructor(methodName: string, private readonly _operand: number) {\n super(methodName);\n }\n\n _toFieldTransform(context: ParseContextImpl): FieldTransform {\n const numericIncrement = new NumericIncrementTransformOperation(\n context.serializer,\n toNumber(context.serializer, this._operand)\n );\n return new FieldTransform(context.path!, numericIncrement);\n }\n\n isEqual(other: FieldValue): boolean {\n return (\n other instanceof NumericIncrementFieldValueImpl &&\n this._operand === other._operand\n );\n }\n}\n\n/** Parse update data from an update() call. */\nexport function parseUpdateData(\n userDataReader: UserDataReader,\n methodName: string,\n targetDoc: DocumentKey,\n input: unknown\n): ParsedUpdateData {\n const context = userDataReader.createContext(\n UserDataSource.Update,\n methodName,\n targetDoc\n );\n validatePlainObject('Data must be an object, but it was:', context, input);\n\n const fieldMaskPaths: InternalFieldPath[] = [];\n const updateData = ObjectValue.empty();\n forEach(input as Dict, (key, value) => {\n const path = fieldPathFromDotSeparatedString(methodName, key, targetDoc);\n\n // For Compat types, we have to \"extract\" the underlying types before\n // performing validation.\n value = getModularInstance(value);\n\n const childContext = context.childContextForFieldPath(path);\n if (value instanceof DeleteFieldValueImpl) {\n // Add it to the field mask, but don't add anything to updateData.\n fieldMaskPaths.push(path);\n } else {\n const parsedValue = parseData(value, childContext);\n if (parsedValue != null) {\n fieldMaskPaths.push(path);\n updateData.set(path, parsedValue);\n }\n }\n });\n\n const mask = new FieldMask(fieldMaskPaths);\n return new ParsedUpdateData(updateData, mask, context.fieldTransforms);\n}\n\n/** Parse update data from a list of field/value arguments. */\nexport function parseUpdateVarargs(\n userDataReader: UserDataReader,\n methodName: string,\n targetDoc: DocumentKey,\n field: string | PublicFieldPath | Compat,\n value: unknown,\n moreFieldsAndValues: unknown[]\n): ParsedUpdateData {\n const context = userDataReader.createContext(\n UserDataSource.Update,\n methodName,\n targetDoc\n );\n const keys = [fieldPathFromArgument(methodName, field, targetDoc)];\n const values = [value];\n\n if (moreFieldsAndValues.length % 2 !== 0) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Function ${methodName}() needs to be called with an even number ` +\n 'of arguments that alternate between field names and values.'\n );\n }\n\n for (let i = 0; i < moreFieldsAndValues.length; i += 2) {\n keys.push(\n fieldPathFromArgument(\n methodName,\n moreFieldsAndValues[i] as string | PublicFieldPath\n )\n );\n values.push(moreFieldsAndValues[i + 1]);\n }\n\n const fieldMaskPaths: InternalFieldPath[] = [];\n const updateData = ObjectValue.empty();\n\n // We iterate in reverse order to pick the last value for a field if the\n // user specified the field multiple times.\n for (let i = keys.length - 1; i >= 0; --i) {\n if (!fieldMaskContains(fieldMaskPaths, keys[i])) {\n const path = keys[i];\n let value = values[i];\n\n // For Compat types, we have to \"extract\" the underlying types before\n // performing validation.\n value = getModularInstance(value);\n\n const childContext = context.childContextForFieldPath(path);\n if (value instanceof DeleteFieldValueImpl) {\n // Add it to the field mask, but don't add anything to updateData.\n fieldMaskPaths.push(path);\n } else {\n const parsedValue = parseData(value, childContext);\n if (parsedValue != null) {\n fieldMaskPaths.push(path);\n updateData.set(path, parsedValue);\n }\n }\n }\n }\n\n const mask = new FieldMask(fieldMaskPaths);\n return new ParsedUpdateData(updateData, mask, context.fieldTransforms);\n}\n\n/**\n * Parse a \"query value\" (e.g. value in a where filter or a value in a cursor\n * bound).\n *\n * @param allowArrays - Whether the query value is an array that may directly\n * contain additional arrays (e.g. the operand of an `in` query).\n */\nexport function parseQueryValue(\n userDataReader: UserDataReader,\n methodName: string,\n input: unknown,\n allowArrays = false\n): ProtoValue {\n const context = userDataReader.createContext(\n allowArrays ? UserDataSource.ArrayArgument : UserDataSource.Argument,\n methodName\n );\n const parsed = parseData(input, context);\n debugAssert(parsed != null, 'Parsed data should not be null.');\n debugAssert(\n context.fieldTransforms.length === 0,\n 'Field transforms should have been disallowed.'\n );\n return parsed;\n}\n\n/**\n * Parses user data to Protobuf Values.\n *\n * @param input - Data to be parsed.\n * @param context - A context object representing the current path being parsed,\n * the source of the data being parsed, etc.\n * @returns The parsed value, or null if the value was a FieldValue sentinel\n * that should not be included in the resulting parsed data.\n */\nexport function parseData(\n input: unknown,\n context: ParseContextImpl\n): ProtoValue | null {\n // Unwrap the API type from the Compat SDK. This will return the API type\n // from firestore-exp.\n input = getModularInstance(input);\n\n if (looksLikeJsonObject(input)) {\n validatePlainObject('Unsupported field value:', context, input);\n return parseObject(input, context);\n } else if (input instanceof FieldValue) {\n // FieldValues usually parse into transforms (except deleteField())\n // in which case we do not want to include this field in our parsed data\n // (as doing so will overwrite the field directly prior to the transform\n // trying to transform it). So we don't add this location to\n // context.fieldMask and we return null as our parsing result.\n parseSentinelFieldValue(input, context);\n return null;\n } else if (input === undefined && context.ignoreUndefinedProperties) {\n // If the input is undefined it can never participate in the fieldMask, so\n // don't handle this below. If `ignoreUndefinedProperties` is false,\n // `parseScalarValue` will reject an undefined value.\n return null;\n } else {\n // If context.path is null we are inside an array and we don't support\n // field mask paths more granular than the top-level array.\n if (context.path) {\n context.fieldMask.push(context.path);\n }\n\n if (input instanceof Array) {\n // TODO(b/34871131): Include the path containing the array in the error\n // message.\n // In the case of IN queries, the parsed data is an array (representing\n // the set of values to be included for the IN query) that may directly\n // contain additional arrays (each representing an individual field\n // value), so we disable this validation.\n if (\n context.settings.arrayElement &&\n context.dataSource !== UserDataSource.ArrayArgument\n ) {\n throw context.createError('Nested arrays are not supported');\n }\n return parseArray(input as unknown[], context);\n } else {\n return parseScalarValue(input, context);\n }\n }\n}\n\nexport function parseObject(\n obj: Dict,\n context: ParseContextImpl\n): { mapValue: ProtoMapValue } {\n const fields: Dict = {};\n\n if (isEmpty(obj)) {\n // If we encounter an empty object, we explicitly add it to the update\n // mask to ensure that the server creates a map entry.\n if (context.path && context.path.length > 0) {\n context.fieldMask.push(context.path);\n }\n } else {\n forEach(obj, (key: string, val: unknown) => {\n const parsedValue = parseData(val, context.childContextForField(key));\n if (parsedValue != null) {\n fields[key] = parsedValue;\n }\n });\n }\n\n return { mapValue: { fields } };\n}\n\nfunction parseArray(array: unknown[], context: ParseContextImpl): ProtoValue {\n const values: ProtoValue[] = [];\n let entryIndex = 0;\n for (const entry of array) {\n let parsedEntry = parseData(\n entry,\n context.childContextForArray(entryIndex)\n );\n if (parsedEntry == null) {\n // Just include nulls in the array for fields being replaced with a\n // sentinel.\n parsedEntry = { nullValue: 'NULL_VALUE' };\n }\n values.push(parsedEntry);\n entryIndex++;\n }\n return { arrayValue: { values } };\n}\n\n/**\n * \"Parses\" the provided FieldValueImpl, adding any necessary transforms to\n * context.fieldTransforms.\n */\nfunction parseSentinelFieldValue(\n value: FieldValue,\n context: ParseContextImpl\n): void {\n // Sentinels are only supported with writes, and not within arrays.\n if (!isWrite(context.dataSource)) {\n throw context.createError(\n `${value._methodName}() can only be used with update() and set()`\n );\n }\n if (!context.path) {\n throw context.createError(\n `${value._methodName}() is not currently supported inside arrays`\n );\n }\n\n const fieldTransform = value._toFieldTransform(context);\n if (fieldTransform) {\n context.fieldTransforms.push(fieldTransform);\n }\n}\n\n/**\n * Helper to parse a scalar value (i.e. not an Object, Array, or FieldValue)\n *\n * @returns The parsed value\n */\nfunction parseScalarValue(\n value: unknown,\n context: ParseContextImpl\n): ProtoValue | null {\n value = getModularInstance(value);\n\n if (value === null) {\n return { nullValue: 'NULL_VALUE' };\n } else if (typeof value === 'number') {\n return toNumber(context.serializer, value);\n } else if (typeof value === 'boolean') {\n return { booleanValue: value };\n } else if (typeof value === 'string') {\n return { stringValue: value };\n } else if (value instanceof Date) {\n const timestamp = Timestamp.fromDate(value);\n return {\n timestampValue: toTimestamp(context.serializer, timestamp)\n };\n } else if (value instanceof Timestamp) {\n // Firestore backend truncates precision down to microseconds. To ensure\n // offline mode works the same with regards to truncation, perform the\n // truncation immediately without waiting for the backend to do that.\n const timestamp = new Timestamp(\n value.seconds,\n Math.floor(value.nanoseconds / 1000) * 1000\n );\n return {\n timestampValue: toTimestamp(context.serializer, timestamp)\n };\n } else if (value instanceof GeoPoint) {\n return {\n geoPointValue: {\n latitude: value.latitude,\n longitude: value.longitude\n }\n };\n } else if (value instanceof Bytes) {\n return { bytesValue: toBytes(context.serializer, value._byteString) };\n } else if (value instanceof DocumentReference) {\n const thisDb = context.databaseId;\n const otherDb = value.firestore._databaseId;\n if (!otherDb.isEqual(thisDb)) {\n throw context.createError(\n 'Document reference is for database ' +\n `${otherDb.projectId}/${otherDb.database} but should be ` +\n `for database ${thisDb.projectId}/${thisDb.database}`\n );\n }\n return {\n referenceValue: toResourceName(\n value.firestore._databaseId || context.databaseId,\n value._key.path\n )\n };\n } else if (value instanceof VectorValue) {\n return parseVectorValue(value, context);\n } else {\n throw context.createError(\n `Unsupported field value: ${valueDescription(value)}`\n );\n }\n}\n\n/**\n * Creates a new VectorValue proto value (using the internal format).\n */\nexport function parseVectorValue(\n value: VectorValue,\n context: ParseContextImpl\n): ProtoValue {\n const mapValue: ProtoMapValue = {\n fields: {\n [TYPE_KEY]: {\n stringValue: VECTOR_VALUE_SENTINEL\n },\n [VECTOR_MAP_VECTORS_KEY]: {\n arrayValue: {\n values: value.toArray().map(value => {\n if (typeof value !== 'number') {\n throw context.createError(\n 'VectorValues must only contain numeric values.'\n );\n }\n\n return toDouble(context.serializer, value);\n })\n }\n }\n }\n };\n\n return { mapValue };\n}\n\n/**\n * Checks whether an object looks like a JSON object that should be converted\n * into a struct. Normal class/prototype instances are considered to look like\n * JSON objects since they should be converted to a struct value. Arrays, Dates,\n * GeoPoints, etc. are not considered to look like JSON objects since they map\n * to specific FieldValue types other than ObjectValue.\n */\nfunction looksLikeJsonObject(input: unknown): boolean {\n return (\n typeof input === 'object' &&\n input !== null &&\n !(input instanceof Array) &&\n !(input instanceof Date) &&\n !(input instanceof Timestamp) &&\n !(input instanceof GeoPoint) &&\n !(input instanceof Bytes) &&\n !(input instanceof DocumentReference) &&\n !(input instanceof FieldValue) &&\n !(input instanceof VectorValue)\n );\n}\n\nfunction validatePlainObject(\n message: string,\n context: ParseContextImpl,\n input: unknown\n): asserts input is Dict {\n if (!looksLikeJsonObject(input) || !isPlainObject(input)) {\n const description = valueDescription(input);\n if (description === 'an object') {\n // Massage the error if it was an object.\n throw context.createError(message + ' a custom object');\n } else {\n throw context.createError(message + ' ' + description);\n }\n }\n}\n\n/**\n * Helper that calls fromDotSeparatedString() but wraps any error thrown.\n */\nexport function fieldPathFromArgument(\n methodName: string,\n path: string | PublicFieldPath | Compat,\n targetDoc?: DocumentKey\n): InternalFieldPath {\n // If required, replace the FieldPath Compat class with the firestore-exp\n // FieldPath.\n path = getModularInstance(path);\n\n if (path instanceof FieldPath) {\n return path._internalPath;\n } else if (typeof path === 'string') {\n return fieldPathFromDotSeparatedString(methodName, path);\n } else {\n const message = 'Field path arguments must be of type string or ';\n throw createError(\n message,\n methodName,\n /* hasConverter= */ false,\n /* path= */ undefined,\n targetDoc\n );\n }\n}\n\n/**\n * Matches any characters in a field path string that are reserved.\n */\nconst FIELD_PATH_RESERVED = new RegExp('[~\\\\*/\\\\[\\\\]]');\n\n/**\n * Wraps fromDotSeparatedString with an error message about the method that\n * was thrown.\n * @param methodName - The publicly visible method name\n * @param path - The dot-separated string form of a field path which will be\n * split on dots.\n * @param targetDoc - The document against which the field path will be\n * evaluated.\n */\nexport function fieldPathFromDotSeparatedString(\n methodName: string,\n path: string,\n targetDoc?: DocumentKey\n): InternalFieldPath {\n const found = path.search(FIELD_PATH_RESERVED);\n if (found >= 0) {\n throw createError(\n `Invalid field path (${path}). Paths must not contain ` +\n `'~', '*', '/', '[', or ']'`,\n methodName,\n /* hasConverter= */ false,\n /* path= */ undefined,\n targetDoc\n );\n }\n\n try {\n return new FieldPath(...path.split('.'))._internalPath;\n } catch (e) {\n throw createError(\n `Invalid field path (${path}). Paths must not be empty, ` +\n `begin with '.', end with '.', or contain '..'`,\n methodName,\n /* hasConverter= */ false,\n /* path= */ undefined,\n targetDoc\n );\n }\n}\n\nfunction createError(\n reason: string,\n methodName: string,\n hasConverter: boolean,\n path?: InternalFieldPath,\n targetDoc?: DocumentKey\n): FirestoreError {\n const hasPath = path && !path.isEmpty();\n const hasDocument = targetDoc !== undefined;\n let message = `Function ${methodName}() called with invalid data`;\n if (hasConverter) {\n message += ' (via `toFirestore()`)';\n }\n message += '. ';\n\n let description = '';\n if (hasPath || hasDocument) {\n description += ' (found';\n\n if (hasPath) {\n description += ` in field ${path}`;\n }\n if (hasDocument) {\n description += ` in document ${targetDoc}`;\n }\n description += ')';\n }\n\n return new FirestoreError(\n Code.INVALID_ARGUMENT,\n message + reason + description\n );\n}\n\n/** Checks `haystack` if FieldPath `needle` is present. Runs in O(n). */\nfunction fieldMaskContains(\n haystack: InternalFieldPath[],\n needle: InternalFieldPath\n): boolean {\n return haystack.some(v => v.isEqual(needle));\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Compat, getModularInstance } from '@firebase/util';\n\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { FieldPath as InternalFieldPath } from '../model/path';\nimport { arrayEquals } from '../util/misc';\n\nimport { Firestore } from './database';\nimport { FieldPath } from './field_path';\nimport {\n DocumentData,\n DocumentReference,\n PartialWithFieldValue,\n Query,\n queryEqual,\n SetOptions,\n WithFieldValue\n} from './reference';\nimport {\n fieldPathFromDotSeparatedString,\n UntypedFirestoreDataConverter\n} from './user_data_reader';\nimport { AbstractUserDataWriter } from './user_data_writer';\n\n/**\n * Converter used by `withConverter()` to transform user objects of type\n * `AppModelType` into Firestore data of type `DbModelType`.\n *\n * Using the converter allows you to specify generic type arguments when\n * storing and retrieving objects from Firestore.\n *\n * In this context, an \"AppModel\" is a class that is used in an application to\n * package together related information and functionality. Such a class could,\n * for example, have properties with complex, nested data types, properties used\n * for memoization, properties of types not supported by Firestore (such as\n * `symbol` and `bigint`), and helper functions that perform compound\n * operations. Such classes are not suitable and/or possible to store into a\n * Firestore database. Instead, instances of such classes need to be converted\n * to \"plain old JavaScript objects\" (POJOs) with exclusively primitive\n * properties, potentially nested inside other POJOs or arrays of POJOs. In this\n * context, this type is referred to as the \"DbModel\" and would be an object\n * suitable for persisting into Firestore. For convenience, applications can\n * implement `FirestoreDataConverter` and register the converter with Firestore\n * objects, such as `DocumentReference` or `Query`, to automatically convert\n * `AppModel` to `DbModel` when storing into Firestore, and convert `DbModel`\n * to `AppModel` when retrieving from Firestore.\n *\n * @example\n *\n * Simple Example\n *\n * ```typescript\n * const numberConverter = {\n * toFirestore(value: WithFieldValue) {\n * return { value };\n * },\n * fromFirestore(snapshot: QueryDocumentSnapshot, options: SnapshotOptions) {\n * return snapshot.data(options).value as number;\n * }\n * };\n *\n * async function simpleDemo(db: Firestore): Promise {\n * const documentRef = doc(db, 'values/value123').withConverter(numberConverter);\n *\n * // converters are used with `setDoc`, `addDoc`, and `getDoc`\n * await setDoc(documentRef, 42);\n * const snapshot1 = await getDoc(documentRef);\n * assertEqual(snapshot1.data(), 42);\n *\n * // converters are not used when writing data with `updateDoc`\n * await updateDoc(documentRef, { value: 999 });\n * const snapshot2 = await getDoc(documentRef);\n * assertEqual(snapshot2.data(), 999);\n * }\n * ```\n *\n * Advanced Example\n *\n * ```typescript\n * // The Post class is a model that is used by our application.\n * // This class may have properties and methods that are specific\n * // to our application execution, which do not need to be persisted\n * // to Firestore.\n * class Post {\n * constructor(\n * readonly title: string,\n * readonly author: string,\n * readonly lastUpdatedMillis: number\n * ) {}\n * toString(): string {\n * return `${this.title} by ${this.author}`;\n * }\n * }\n *\n * // The PostDbModel represents how we want our posts to be stored\n * // in Firestore. This DbModel has different properties (`ttl`,\n * // `aut`, and `lut`) from the Post class we use in our application.\n * interface PostDbModel {\n * ttl: string;\n * aut: { firstName: string; lastName: string };\n * lut: Timestamp;\n * }\n *\n * // The `PostConverter` implements `FirestoreDataConverter` and specifies\n * // how the Firestore SDK can convert `Post` objects to `PostDbModel`\n * // objects and vice versa.\n * class PostConverter implements FirestoreDataConverter {\n * toFirestore(post: WithFieldValue): WithFieldValue {\n * return {\n * ttl: post.title,\n * aut: this._autFromAuthor(post.author),\n * lut: this._lutFromLastUpdatedMillis(post.lastUpdatedMillis)\n * };\n * }\n *\n * fromFirestore(snapshot: QueryDocumentSnapshot, options: SnapshotOptions): Post {\n * const data = snapshot.data(options) as PostDbModel;\n * const author = `${data.aut.firstName} ${data.aut.lastName}`;\n * return new Post(data.ttl, author, data.lut.toMillis());\n * }\n *\n * _autFromAuthor(\n * author: string | FieldValue\n * ): { firstName: string; lastName: string } | FieldValue {\n * if (typeof author !== 'string') {\n * // `author` is a FieldValue, so just return it.\n * return author;\n * }\n * const [firstName, lastName] = author.split(' ');\n * return {firstName, lastName};\n * }\n *\n * _lutFromLastUpdatedMillis(\n * lastUpdatedMillis: number | FieldValue\n * ): Timestamp | FieldValue {\n * if (typeof lastUpdatedMillis !== 'number') {\n * // `lastUpdatedMillis` must be a FieldValue, so just return it.\n * return lastUpdatedMillis;\n * }\n * return Timestamp.fromMillis(lastUpdatedMillis);\n * }\n * }\n *\n * async function advancedDemo(db: Firestore): Promise {\n * // Create a `DocumentReference` with a `FirestoreDataConverter`.\n * const documentRef = doc(db, 'posts/post123').withConverter(new PostConverter());\n *\n * // The `data` argument specified to `setDoc()` is type checked by the\n * // TypeScript compiler to be compatible with `Post`. Since the `data`\n * // argument is typed as `WithFieldValue` rather than just `Post`,\n * // this allows properties of the `data` argument to also be special\n * // Firestore values that perform server-side mutations, such as\n * // `arrayRemove()`, `deleteField()`, and `serverTimestamp()`.\n * await setDoc(documentRef, {\n * title: 'My Life',\n * author: 'Foo Bar',\n * lastUpdatedMillis: serverTimestamp()\n * });\n *\n * // The TypeScript compiler will fail to compile if the `data` argument to\n * // `setDoc()` is _not_ compatible with `WithFieldValue`. This\n * // type checking prevents the caller from specifying objects with incorrect\n * // properties or property values.\n * // @ts-expect-error \"Argument of type { ttl: string; } is not assignable\n * // to parameter of type WithFieldValue\"\n * await setDoc(documentRef, { ttl: 'The Title' });\n *\n * // When retrieving a document with `getDoc()` the `DocumentSnapshot`\n * // object's `data()` method returns a `Post`, rather than a generic object,\n * // which would have been returned if the `DocumentReference` did _not_ have a\n * // `FirestoreDataConverter` attached to it.\n * const snapshot1: DocumentSnapshot = await getDoc(documentRef);\n * const post1: Post = snapshot1.data()!;\n * if (post1) {\n * assertEqual(post1.title, 'My Life');\n * assertEqual(post1.author, 'Foo Bar');\n * }\n *\n * // The `data` argument specified to `updateDoc()` is type checked by the\n * // TypeScript compiler to be compatible with `PostDbModel`. Note that\n * // unlike `setDoc()`, whose `data` argument must be compatible with `Post`,\n * // the `data` argument to `updateDoc()` must be compatible with\n * // `PostDbModel`. Similar to `setDoc()`, since the `data` argument is typed\n * // as `WithFieldValue` rather than just `PostDbModel`, this\n * // allows properties of the `data` argument to also be those special\n * // Firestore values, like `arrayRemove()`, `deleteField()`, and\n * // `serverTimestamp()`.\n * await updateDoc(documentRef, {\n * 'aut.firstName': 'NewFirstName',\n * lut: serverTimestamp()\n * });\n *\n * // The TypeScript compiler will fail to compile if the `data` argument to\n * // `updateDoc()` is _not_ compatible with `WithFieldValue`.\n * // This type checking prevents the caller from specifying objects with\n * // incorrect properties or property values.\n * // @ts-expect-error \"Argument of type { title: string; } is not assignable\n * // to parameter of type WithFieldValue\"\n * await updateDoc(documentRef, { title: 'New Title' });\n * const snapshot2: DocumentSnapshot = await getDoc(documentRef);\n * const post2: Post = snapshot2.data()!;\n * if (post2) {\n * assertEqual(post2.title, 'My Life');\n * assertEqual(post2.author, 'NewFirstName Bar');\n * }\n * }\n * ```\n */\nexport interface FirestoreDataConverter<\n AppModelType,\n DbModelType extends DocumentData = DocumentData\n> {\n /**\n * Called by the Firestore SDK to convert a custom model object of type\n * `AppModelType` into a plain JavaScript object (suitable for writing\n * directly to the Firestore database) of type `DbModelType`. Used with\n * {@link @firebase/firestore/lite#(setDoc:1)},\n * {@link @firebase/firestore/lite#(WriteBatch.set:1)} and\n * {@link @firebase/firestore/lite#(Transaction.set:1)}.\n *\n * The `WithFieldValue` type extends `T` to also allow FieldValues such as\n * {@link (deleteField:1)} to be used as property values.\n */\n toFirestore(\n modelObject: WithFieldValue\n ): WithFieldValue;\n\n /**\n * Called by the Firestore SDK to convert a custom model object of type\n * `AppModelType` into a plain JavaScript object (suitable for writing\n * directly to the Firestore database) of type `DbModelType`. Used with\n * {@link @firebase/firestore/lite#(setDoc:1)},\n * {@link @firebase/firestore/lite#(WriteBatch.set:1)} and\n * {@link @firebase/firestore/lite#(Transaction.set:1)} with `merge:true`\n * or `mergeFields`.\n *\n * The `PartialWithFieldValue` type extends `Partial` to allow\n * FieldValues such as {@link (arrayUnion:1)} to be used as property values.\n * It also supports nested `Partial` by allowing nested fields to be\n * omitted.\n */\n toFirestore(\n modelObject: PartialWithFieldValue,\n options: SetOptions\n ): PartialWithFieldValue;\n\n /**\n * Called by the Firestore SDK to convert Firestore data into an object of\n * type `AppModelType`. You can access your data by calling:\n * `snapshot.data()`.\n *\n *\n * Generally, the data returned from `snapshot.data()` can be cast to\n * `DbModelType`; however, this is not guaranteed because Firestore does not\n * enforce a schema on the database. For example, writes from a previous\n * version of the application or writes from another client that did not use a\n * type converter could have written data with different properties and/or\n * property types. The implementation will need to choose whether to\n * gracefully recover from non-conforming data or throw an error.\n *\n * @param snapshot - A `QueryDocumentSnapshot` containing your data and\n * metadata.\n */\n fromFirestore(\n snapshot: QueryDocumentSnapshot\n ): AppModelType;\n}\n\n/**\n * A `DocumentSnapshot` contains data read from a document in your Firestore\n * database. The data can be extracted with `.data()` or `.get()` to\n * get a specific field.\n *\n * For a `DocumentSnapshot` that points to a non-existing document, any data\n * access will return 'undefined'. You can use the `exists()` method to\n * explicitly verify a document's existence.\n */\nexport class DocumentSnapshot<\n AppModelType = DocumentData,\n DbModelType extends DocumentData = DocumentData\n> {\n // Note: This class is stripped down version of the DocumentSnapshot in\n // the legacy SDK. The changes are:\n // - No support for SnapshotMetadata.\n // - No support for SnapshotOptions.\n\n /** @hideconstructor protected */\n constructor(\n public _firestore: Firestore,\n public _userDataWriter: AbstractUserDataWriter,\n public _key: DocumentKey,\n public _document: Document | null,\n public _converter: UntypedFirestoreDataConverter<\n AppModelType,\n DbModelType\n > | null\n ) {}\n\n /** Property of the `DocumentSnapshot` that provides the document's ID. */\n get id(): string {\n return this._key.path.lastSegment();\n }\n\n /**\n * The `DocumentReference` for the document included in the `DocumentSnapshot`.\n */\n get ref(): DocumentReference {\n return new DocumentReference(\n this._firestore,\n this._converter,\n this._key\n );\n }\n\n /**\n * Signals whether or not the document at the snapshot's location exists.\n *\n * @returns true if the document exists.\n */\n exists(): this is QueryDocumentSnapshot {\n return this._document !== null;\n }\n\n /**\n * Retrieves all fields in the document as an `Object`. Returns `undefined` if\n * the document doesn't exist.\n *\n * @returns An `Object` containing all fields in the document or `undefined`\n * if the document doesn't exist.\n */\n data(): AppModelType | undefined {\n if (!this._document) {\n return undefined;\n } else if (this._converter) {\n // We only want to use the converter and create a new DocumentSnapshot\n // if a converter has been provided.\n const snapshot = new QueryDocumentSnapshot(\n this._firestore,\n this._userDataWriter,\n this._key,\n this._document,\n /* converter= */ null\n );\n return this._converter.fromFirestore(snapshot);\n } else {\n return this._userDataWriter.convertValue(\n this._document.data.value\n ) as AppModelType;\n }\n }\n\n /**\n * Retrieves the field specified by `fieldPath`. Returns `undefined` if the\n * document or field doesn't exist.\n *\n * @param fieldPath - The path (for example 'foo' or 'foo.bar') to a specific\n * field.\n * @returns The data at the specified field location or undefined if no such\n * field exists in the document.\n */\n // We are using `any` here to avoid an explicit cast by our users.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n get(fieldPath: string | FieldPath): any {\n if (this._document) {\n const value = this._document.data.field(\n fieldPathFromArgument('DocumentSnapshot.get', fieldPath)\n );\n if (value !== null) {\n return this._userDataWriter.convertValue(value);\n }\n }\n return undefined;\n }\n}\n\n/**\n * A `QueryDocumentSnapshot` contains data read from a document in your\n * Firestore database as part of a query. The document is guaranteed to exist\n * and its data can be extracted with `.data()` or `.get()` to get a\n * specific field.\n *\n * A `QueryDocumentSnapshot` offers the same API surface as a\n * `DocumentSnapshot`. Since query results contain only existing documents, the\n * `exists` property will always be true and `data()` will never return\n * 'undefined'.\n */\nexport class QueryDocumentSnapshot<\n AppModelType = DocumentData,\n DbModelType extends DocumentData = DocumentData\n> extends DocumentSnapshot {\n /**\n * Retrieves all fields in the document as an `Object`.\n *\n * @override\n * @returns An `Object` containing all fields in the document.\n */\n data(): AppModelType {\n return super.data() as AppModelType;\n }\n}\n\n/**\n * A `QuerySnapshot` contains zero or more `DocumentSnapshot` objects\n * representing the results of a query. The documents can be accessed as an\n * array via the `docs` property or enumerated using the `forEach` method. The\n * number of documents can be determined via the `empty` and `size`\n * properties.\n */\nexport class QuerySnapshot<\n AppModelType = DocumentData,\n DbModelType extends DocumentData = DocumentData\n> {\n /**\n * The query on which you called {@link getDocs} in order to get this\n * `QuerySnapshot`.\n */\n readonly query: Query;\n\n /** @hideconstructor */\n constructor(\n _query: Query,\n readonly _docs: Array>\n ) {\n this.query = _query;\n }\n\n /** An array of all the documents in the `QuerySnapshot`. */\n get docs(): Array> {\n return [...this._docs];\n }\n\n /** The number of documents in the `QuerySnapshot`. */\n get size(): number {\n return this.docs.length;\n }\n\n /** True if there are no documents in the `QuerySnapshot`. */\n get empty(): boolean {\n return this.docs.length === 0;\n }\n\n /**\n * Enumerates all of the documents in the `QuerySnapshot`.\n *\n * @param callback - A callback to be called with a `QueryDocumentSnapshot` for\n * each document in the snapshot.\n * @param thisArg - The `this` binding for the callback.\n */\n forEach(\n callback: (\n result: QueryDocumentSnapshot\n ) => void,\n thisArg?: unknown\n ): void {\n this._docs.forEach(callback, thisArg);\n }\n}\n\n/**\n * Returns true if the provided snapshots are equal.\n *\n * @param left - A snapshot to compare.\n * @param right - A snapshot to compare.\n * @returns true if the snapshots are equal.\n */\nexport function snapshotEqual(\n left:\n | DocumentSnapshot\n | QuerySnapshot,\n right:\n | DocumentSnapshot\n | QuerySnapshot\n): boolean {\n left = getModularInstance(left);\n right = getModularInstance(right);\n\n if (left instanceof DocumentSnapshot && right instanceof DocumentSnapshot) {\n return (\n left._firestore === right._firestore &&\n left._key.isEqual(right._key) &&\n (left._document === null\n ? right._document === null\n : left._document.isEqual(right._document)) &&\n left._converter === right._converter\n );\n } else if (left instanceof QuerySnapshot && right instanceof QuerySnapshot) {\n return (\n queryEqual(left.query, right.query) &&\n arrayEquals(left.docs, right.docs, snapshotEqual)\n );\n }\n\n return false;\n}\n\n/**\n * Helper that calls `fromDotSeparatedString()` but wraps any error thrown.\n */\nexport function fieldPathFromArgument(\n methodName: string,\n arg: string | FieldPath | Compat\n): InternalFieldPath {\n if (typeof arg === 'string') {\n return fieldPathFromDotSeparatedString(methodName, arg);\n } else if (arg instanceof FieldPath) {\n return arg._internalPath;\n } else {\n return arg._delegate._internalPath;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getModularInstance } from '@firebase/util';\n\nimport { Bound } from '../core/bound';\nimport { DatabaseId } from '../core/database_info';\nimport {\n CompositeFilter,\n CompositeOperator,\n FieldFilter,\n Filter,\n Operator\n} from '../core/filter';\nimport { Direction, OrderBy } from '../core/order_by';\nimport {\n isCollectionGroupQuery,\n LimitType,\n Query as InternalQuery,\n queryNormalizedOrderBy,\n queryWithAddedFilter,\n queryWithAddedOrderBy,\n queryWithEndAt,\n queryWithLimit,\n queryWithStartAt\n} from '../core/query';\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { FieldPath as InternalFieldPath, ResourcePath } from '../model/path';\nimport { isServerTimestamp } from '../model/server_timestamps';\nimport { refValue } from '../model/values';\nimport { Value as ProtoValue } from '../protos/firestore_proto_api';\nimport { Code, FirestoreError } from '../util/error';\nimport {\n validatePositiveNumber,\n valueDescription\n} from '../util/input_validation';\n\nimport { FieldPath } from './field_path';\nimport { DocumentData, DocumentReference, Query } from './reference';\nimport { DocumentSnapshot, fieldPathFromArgument } from './snapshot';\nimport {\n newUserDataReader,\n parseQueryValue,\n UserDataReader\n} from './user_data_reader';\n\nexport function validateHasExplicitOrderByForLimitToLast(\n query: InternalQuery\n): void {\n if (\n query.limitType === LimitType.Last &&\n query.explicitOrderBy.length === 0\n ) {\n throw new FirestoreError(\n Code.UNIMPLEMENTED,\n 'limitToLast() queries require specifying at least one orderBy() clause'\n );\n }\n}\n\n/** Describes the different query constraints available in this SDK. */\nexport type QueryConstraintType =\n | 'where'\n | 'orderBy'\n | 'limit'\n | 'limitToLast'\n | 'startAt'\n | 'startAfter'\n | 'endAt'\n | 'endBefore';\n\n/**\n * An `AppliableConstraint` is an abstraction of a constraint that can be applied\n * to a Firestore query.\n */\nexport abstract class AppliableConstraint {\n /**\n * Takes the provided {@link Query} and returns a copy of the {@link Query} with this\n * {@link AppliableConstraint} applied.\n */\n abstract _apply(\n query: Query\n ): Query;\n}\n\n/**\n * A `QueryConstraint` is used to narrow the set of documents returned by a\n * Firestore query. `QueryConstraint`s are created by invoking {@link where},\n * {@link orderBy}, {@link (startAt:1)}, {@link (startAfter:1)}, {@link\n * (endBefore:1)}, {@link (endAt:1)}, {@link limit}, {@link limitToLast} and\n * can then be passed to {@link (query:1)} to create a new query instance that\n * also contains this `QueryConstraint`.\n */\nexport abstract class QueryConstraint extends AppliableConstraint {\n /** The type of this query constraint */\n abstract readonly type: QueryConstraintType;\n\n /**\n * Takes the provided {@link Query} and returns a copy of the {@link Query} with this\n * {@link AppliableConstraint} applied.\n */\n abstract _apply(\n query: Query\n ): Query;\n}\n\n/**\n * Creates a new immutable instance of {@link Query} that is extended to also\n * include additional query constraints.\n *\n * @param query - The {@link Query} instance to use as a base for the new\n * constraints.\n * @param compositeFilter - The {@link QueryCompositeFilterConstraint} to\n * apply. Create {@link QueryCompositeFilterConstraint} using {@link and} or\n * {@link or}.\n * @param queryConstraints - Additional {@link QueryNonFilterConstraint}s to\n * apply (e.g. {@link orderBy}, {@link limit}).\n * @throws if any of the provided query constraints cannot be combined with the\n * existing or new constraints.\n */\nexport function query(\n query: Query,\n compositeFilter: QueryCompositeFilterConstraint,\n ...queryConstraints: QueryNonFilterConstraint[]\n): Query;\n\n/**\n * Creates a new immutable instance of {@link Query} that is extended to also\n * include additional query constraints.\n *\n * @param query - The {@link Query} instance to use as a base for the new\n * constraints.\n * @param queryConstraints - The list of {@link QueryConstraint}s to apply.\n * @throws if any of the provided query constraints cannot be combined with the\n * existing or new constraints.\n */\nexport function query(\n query: Query,\n ...queryConstraints: QueryConstraint[]\n): Query;\n\nexport function query(\n query: Query,\n queryConstraint: QueryCompositeFilterConstraint | QueryConstraint | undefined,\n ...additionalQueryConstraints: Array<\n QueryConstraint | QueryNonFilterConstraint\n >\n): Query {\n let queryConstraints: AppliableConstraint[] = [];\n\n if (queryConstraint instanceof AppliableConstraint) {\n queryConstraints.push(queryConstraint);\n }\n\n queryConstraints = queryConstraints.concat(additionalQueryConstraints);\n\n validateQueryConstraintArray(queryConstraints);\n\n for (const constraint of queryConstraints) {\n query = constraint._apply(query);\n }\n return query;\n}\n\n/**\n * A `QueryFieldFilterConstraint` is used to narrow the set of documents returned by\n * a Firestore query by filtering on one or more document fields.\n * `QueryFieldFilterConstraint`s are created by invoking {@link where} and can then\n * be passed to {@link (query:1)} to create a new query instance that also contains\n * this `QueryFieldFilterConstraint`.\n */\nexport class QueryFieldFilterConstraint extends QueryConstraint {\n /** The type of this query constraint */\n readonly type = 'where';\n\n /**\n * @internal\n */\n protected constructor(\n private readonly _field: InternalFieldPath,\n private _op: Operator,\n private _value: unknown\n ) {\n super();\n }\n\n static _create(\n _field: InternalFieldPath,\n _op: Operator,\n _value: unknown\n ): QueryFieldFilterConstraint {\n return new QueryFieldFilterConstraint(_field, _op, _value);\n }\n\n _apply(\n query: Query\n ): Query {\n const filter = this._parse(query);\n validateNewFieldFilter(query._query, filter);\n return new Query(\n query.firestore,\n query.converter,\n queryWithAddedFilter(query._query, filter)\n );\n }\n\n _parse(\n query: Query\n ): FieldFilter {\n const reader = newUserDataReader(query.firestore);\n const filter = newQueryFilter(\n query._query,\n 'where',\n reader,\n query.firestore._databaseId,\n this._field,\n this._op,\n this._value\n );\n return filter;\n }\n}\n\n/**\n * Filter conditions in a {@link where} clause are specified using the\n * strings '<', '<=', '==', '!=', '>=', '>', 'array-contains', 'in',\n * 'array-contains-any', and 'not-in'.\n */\nexport type WhereFilterOp =\n | '<'\n | '<='\n | '=='\n | '!='\n | '>='\n | '>'\n | 'array-contains'\n | 'in'\n | 'array-contains-any'\n | 'not-in';\n\n/**\n * Creates a {@link QueryFieldFilterConstraint} that enforces that documents\n * must contain the specified field and that the value should satisfy the\n * relation constraint provided.\n *\n * @param fieldPath - The path to compare\n * @param opStr - The operation string (e.g \"<\", \"<=\", \"==\", \"<\",\n * \"<=\", \"!=\").\n * @param value - The value for comparison\n * @returns The created {@link QueryFieldFilterConstraint}.\n */\nexport function where(\n fieldPath: string | FieldPath,\n opStr: WhereFilterOp,\n value: unknown\n): QueryFieldFilterConstraint {\n const op = opStr as Operator;\n const field = fieldPathFromArgument('where', fieldPath);\n return QueryFieldFilterConstraint._create(field, op, value);\n}\n\n/**\n * A `QueryCompositeFilterConstraint` is used to narrow the set of documents\n * returned by a Firestore query by performing the logical OR or AND of multiple\n * {@link QueryFieldFilterConstraint}s or {@link QueryCompositeFilterConstraint}s.\n * `QueryCompositeFilterConstraint`s are created by invoking {@link or} or\n * {@link and} and can then be passed to {@link (query:1)} to create a new query\n * instance that also contains the `QueryCompositeFilterConstraint`.\n */\nexport class QueryCompositeFilterConstraint extends AppliableConstraint {\n /**\n * @internal\n */\n protected constructor(\n /** The type of this query constraint */\n readonly type: 'or' | 'and',\n private readonly _queryConstraints: QueryFilterConstraint[]\n ) {\n super();\n }\n\n static _create(\n type: 'or' | 'and',\n _queryConstraints: QueryFilterConstraint[]\n ): QueryCompositeFilterConstraint {\n return new QueryCompositeFilterConstraint(type, _queryConstraints);\n }\n\n _parse(\n query: Query\n ): Filter {\n const parsedFilters = this._queryConstraints\n .map(queryConstraint => {\n return queryConstraint._parse(query);\n })\n .filter(parsedFilter => parsedFilter.getFilters().length > 0);\n\n if (parsedFilters.length === 1) {\n return parsedFilters[0];\n }\n\n return CompositeFilter.create(parsedFilters, this._getOperator());\n }\n\n _apply(\n query: Query\n ): Query {\n const parsedFilter = this._parse(query);\n if (parsedFilter.getFilters().length === 0) {\n // Return the existing query if not adding any more filters (e.g. an empty\n // composite filter).\n return query;\n }\n validateNewFilter(query._query, parsedFilter);\n\n return new Query(\n query.firestore,\n query.converter,\n queryWithAddedFilter(query._query, parsedFilter)\n );\n }\n\n _getQueryConstraints(): readonly AppliableConstraint[] {\n return this._queryConstraints;\n }\n\n _getOperator(): CompositeOperator {\n return this.type === 'and' ? CompositeOperator.AND : CompositeOperator.OR;\n }\n}\n\n/**\n * `QueryNonFilterConstraint` is a helper union type that represents\n * QueryConstraints which are used to narrow or order the set of documents,\n * but that do not explicitly filter on a document field.\n * `QueryNonFilterConstraint`s are created by invoking {@link orderBy},\n * {@link (startAt:1)}, {@link (startAfter:1)}, {@link (endBefore:1)}, {@link (endAt:1)},\n * {@link limit} or {@link limitToLast} and can then be passed to {@link (query:1)}\n * to create a new query instance that also contains the `QueryConstraint`.\n */\nexport type QueryNonFilterConstraint =\n | QueryOrderByConstraint\n | QueryLimitConstraint\n | QueryStartAtConstraint\n | QueryEndAtConstraint;\n\n/**\n * `QueryFilterConstraint` is a helper union type that represents\n * {@link QueryFieldFilterConstraint} and {@link QueryCompositeFilterConstraint}.\n */\nexport type QueryFilterConstraint =\n | QueryFieldFilterConstraint\n | QueryCompositeFilterConstraint;\n\n/**\n * Creates a new {@link QueryCompositeFilterConstraint} that is a disjunction of\n * the given filter constraints. A disjunction filter includes a document if it\n * satisfies any of the given filters.\n *\n * @param queryConstraints - Optional. The list of\n * {@link QueryFilterConstraint}s to perform a disjunction for. These must be\n * created with calls to {@link where}, {@link or}, or {@link and}.\n * @returns The newly created {@link QueryCompositeFilterConstraint}.\n */\nexport function or(\n ...queryConstraints: QueryFilterConstraint[]\n): QueryCompositeFilterConstraint {\n // Only support QueryFilterConstraints\n queryConstraints.forEach(queryConstraint =>\n validateQueryFilterConstraint('or', queryConstraint)\n );\n\n return QueryCompositeFilterConstraint._create(\n CompositeOperator.OR,\n queryConstraints as QueryFilterConstraint[]\n );\n}\n\n/**\n * Creates a new {@link QueryCompositeFilterConstraint} that is a conjunction of\n * the given filter constraints. A conjunction filter includes a document if it\n * satisfies all of the given filters.\n *\n * @param queryConstraints - Optional. The list of\n * {@link QueryFilterConstraint}s to perform a conjunction for. These must be\n * created with calls to {@link where}, {@link or}, or {@link and}.\n * @returns The newly created {@link QueryCompositeFilterConstraint}.\n */\nexport function and(\n ...queryConstraints: QueryFilterConstraint[]\n): QueryCompositeFilterConstraint {\n // Only support QueryFilterConstraints\n queryConstraints.forEach(queryConstraint =>\n validateQueryFilterConstraint('and', queryConstraint)\n );\n\n return QueryCompositeFilterConstraint._create(\n CompositeOperator.AND,\n queryConstraints as QueryFilterConstraint[]\n );\n}\n\n/**\n * A `QueryOrderByConstraint` is used to sort the set of documents returned by a\n * Firestore query. `QueryOrderByConstraint`s are created by invoking\n * {@link orderBy} and can then be passed to {@link (query:1)} to create a new query\n * instance that also contains this `QueryOrderByConstraint`.\n *\n * Note: Documents that do not contain the orderBy field will not be present in\n * the query result.\n */\nexport class QueryOrderByConstraint extends QueryConstraint {\n /** The type of this query constraint */\n readonly type = 'orderBy';\n\n /**\n * @internal\n */\n protected constructor(\n private readonly _field: InternalFieldPath,\n private _direction: Direction\n ) {\n super();\n }\n\n static _create(\n _field: InternalFieldPath,\n _direction: Direction\n ): QueryOrderByConstraint {\n return new QueryOrderByConstraint(_field, _direction);\n }\n\n _apply(\n query: Query\n ): Query {\n const orderBy = newQueryOrderBy(query._query, this._field, this._direction);\n return new Query(\n query.firestore,\n query.converter,\n queryWithAddedOrderBy(query._query, orderBy)\n );\n }\n}\n\n/**\n * The direction of a {@link orderBy} clause is specified as 'desc' or 'asc'\n * (descending or ascending).\n */\nexport type OrderByDirection = 'desc' | 'asc';\n\n/**\n * Creates a {@link QueryOrderByConstraint} that sorts the query result by the\n * specified field, optionally in descending order instead of ascending.\n *\n * Note: Documents that do not contain the specified field will not be present\n * in the query result.\n *\n * @param fieldPath - The field to sort by.\n * @param directionStr - Optional direction to sort by ('asc' or 'desc'). If\n * not specified, order will be ascending.\n * @returns The created {@link QueryOrderByConstraint}.\n */\nexport function orderBy(\n fieldPath: string | FieldPath,\n directionStr: OrderByDirection = 'asc'\n): QueryOrderByConstraint {\n const direction = directionStr as Direction;\n const path = fieldPathFromArgument('orderBy', fieldPath);\n return QueryOrderByConstraint._create(path, direction);\n}\n\n/**\n * A `QueryLimitConstraint` is used to limit the number of documents returned by\n * a Firestore query.\n * `QueryLimitConstraint`s are created by invoking {@link limit} or\n * {@link limitToLast} and can then be passed to {@link (query:1)} to create a new\n * query instance that also contains this `QueryLimitConstraint`.\n */\nexport class QueryLimitConstraint extends QueryConstraint {\n /**\n * @internal\n */\n protected constructor(\n /** The type of this query constraint */\n readonly type: 'limit' | 'limitToLast',\n private readonly _limit: number,\n private readonly _limitType: LimitType\n ) {\n super();\n }\n\n static _create(\n type: 'limit' | 'limitToLast',\n _limit: number,\n _limitType: LimitType\n ): QueryLimitConstraint {\n return new QueryLimitConstraint(type, _limit, _limitType);\n }\n\n _apply(\n query: Query\n ): Query {\n return new Query(\n query.firestore,\n query.converter,\n queryWithLimit(query._query, this._limit, this._limitType)\n );\n }\n}\n\n/**\n * Creates a {@link QueryLimitConstraint} that only returns the first matching\n * documents.\n *\n * @param limit - The maximum number of items to return.\n * @returns The created {@link QueryLimitConstraint}.\n */\nexport function limit(limit: number): QueryLimitConstraint {\n validatePositiveNumber('limit', limit);\n return QueryLimitConstraint._create('limit', limit, LimitType.First);\n}\n\n/**\n * Creates a {@link QueryLimitConstraint} that only returns the last matching\n * documents.\n *\n * You must specify at least one `orderBy` clause for `limitToLast` queries,\n * otherwise an exception will be thrown during execution.\n *\n * @param limit - The maximum number of items to return.\n * @returns The created {@link QueryLimitConstraint}.\n */\nexport function limitToLast(limit: number): QueryLimitConstraint {\n validatePositiveNumber('limitToLast', limit);\n return QueryLimitConstraint._create('limitToLast', limit, LimitType.Last);\n}\n\n/**\n * A `QueryStartAtConstraint` is used to exclude documents from the start of a\n * result set returned by a Firestore query.\n * `QueryStartAtConstraint`s are created by invoking {@link (startAt:1)} or\n * {@link (startAfter:1)} and can then be passed to {@link (query:1)} to create a\n * new query instance that also contains this `QueryStartAtConstraint`.\n */\nexport class QueryStartAtConstraint extends QueryConstraint {\n /**\n * @internal\n */\n protected constructor(\n /** The type of this query constraint */\n readonly type: 'startAt' | 'startAfter',\n private readonly _docOrFields: Array>,\n private readonly _inclusive: boolean\n ) {\n super();\n }\n\n static _create(\n type: 'startAt' | 'startAfter',\n _docOrFields: Array>,\n _inclusive: boolean\n ): QueryStartAtConstraint {\n return new QueryStartAtConstraint(type, _docOrFields, _inclusive);\n }\n\n _apply(\n query: Query\n ): Query {\n const bound = newQueryBoundFromDocOrFields(\n query,\n this.type,\n this._docOrFields,\n this._inclusive\n );\n return new Query(\n query.firestore,\n query.converter,\n queryWithStartAt(query._query, bound)\n );\n }\n}\n\n/**\n * Creates a {@link QueryStartAtConstraint} that modifies the result set to\n * start at the provided document (inclusive). The starting position is relative\n * to the order of the query. The document must contain all of the fields\n * provided in the `orderBy` of this query.\n *\n * @param snapshot - The snapshot of the document to start at.\n * @returns A {@link QueryStartAtConstraint} to pass to `query()`.\n */\nexport function startAt(\n snapshot: DocumentSnapshot\n): QueryStartAtConstraint;\n/**\n * Creates a {@link QueryStartAtConstraint} that modifies the result set to\n * start at the provided fields relative to the order of the query. The order of\n * the field values must match the order of the order by clauses of the query.\n *\n * @param fieldValues - The field values to start this query at, in order\n * of the query's order by.\n * @returns A {@link QueryStartAtConstraint} to pass to `query()`.\n */\nexport function startAt(...fieldValues: unknown[]): QueryStartAtConstraint;\nexport function startAt(\n ...docOrFields: Array>\n): QueryStartAtConstraint {\n return QueryStartAtConstraint._create(\n 'startAt',\n docOrFields,\n /*inclusive=*/ true\n );\n}\n\n/**\n * Creates a {@link QueryStartAtConstraint} that modifies the result set to\n * start after the provided document (exclusive). The starting position is\n * relative to the order of the query. The document must contain all of the\n * fields provided in the orderBy of the query.\n *\n * @param snapshot - The snapshot of the document to start after.\n * @returns A {@link QueryStartAtConstraint} to pass to `query()`\n */\nexport function startAfter(\n snapshot: DocumentSnapshot\n): QueryStartAtConstraint;\n/**\n * Creates a {@link QueryStartAtConstraint} that modifies the result set to\n * start after the provided fields relative to the order of the query. The order\n * of the field values must match the order of the order by clauses of the query.\n *\n * @param fieldValues - The field values to start this query after, in order\n * of the query's order by.\n * @returns A {@link QueryStartAtConstraint} to pass to `query()`\n */\nexport function startAfter(...fieldValues: unknown[]): QueryStartAtConstraint;\nexport function startAfter(\n ...docOrFields: Array>\n): QueryStartAtConstraint {\n return QueryStartAtConstraint._create(\n 'startAfter',\n docOrFields,\n /*inclusive=*/ false\n );\n}\n\n/**\n * A `QueryEndAtConstraint` is used to exclude documents from the end of a\n * result set returned by a Firestore query.\n * `QueryEndAtConstraint`s are created by invoking {@link (endAt:1)} or\n * {@link (endBefore:1)} and can then be passed to {@link (query:1)} to create a new\n * query instance that also contains this `QueryEndAtConstraint`.\n */\nexport class QueryEndAtConstraint extends QueryConstraint {\n /**\n * @internal\n */\n protected constructor(\n /** The type of this query constraint */\n readonly type: 'endBefore' | 'endAt',\n private readonly _docOrFields: Array>,\n private readonly _inclusive: boolean\n ) {\n super();\n }\n\n static _create(\n type: 'endBefore' | 'endAt',\n _docOrFields: Array>,\n _inclusive: boolean\n ): QueryEndAtConstraint {\n return new QueryEndAtConstraint(type, _docOrFields, _inclusive);\n }\n\n _apply(\n query: Query\n ): Query {\n const bound = newQueryBoundFromDocOrFields(\n query,\n this.type,\n this._docOrFields,\n this._inclusive\n );\n return new Query(\n query.firestore,\n query.converter,\n queryWithEndAt(query._query, bound)\n );\n }\n}\n\n/**\n * Creates a {@link QueryEndAtConstraint} that modifies the result set to end\n * before the provided document (exclusive). The end position is relative to the\n * order of the query. The document must contain all of the fields provided in\n * the orderBy of the query.\n *\n * @param snapshot - The snapshot of the document to end before.\n * @returns A {@link QueryEndAtConstraint} to pass to `query()`\n */\nexport function endBefore(\n snapshot: DocumentSnapshot\n): QueryEndAtConstraint;\n/**\n * Creates a {@link QueryEndAtConstraint} that modifies the result set to end\n * before the provided fields relative to the order of the query. The order of\n * the field values must match the order of the order by clauses of the query.\n *\n * @param fieldValues - The field values to end this query before, in order\n * of the query's order by.\n * @returns A {@link QueryEndAtConstraint} to pass to `query()`\n */\nexport function endBefore(...fieldValues: unknown[]): QueryEndAtConstraint;\nexport function endBefore(\n ...docOrFields: Array>\n): QueryEndAtConstraint {\n return QueryEndAtConstraint._create(\n 'endBefore',\n docOrFields,\n /*inclusive=*/ false\n );\n}\n\n/**\n * Creates a {@link QueryEndAtConstraint} that modifies the result set to end at\n * the provided document (inclusive). The end position is relative to the order\n * of the query. The document must contain all of the fields provided in the\n * orderBy of the query.\n *\n * @param snapshot - The snapshot of the document to end at.\n * @returns A {@link QueryEndAtConstraint} to pass to `query()`\n */\nexport function endAt(\n snapshot: DocumentSnapshot\n): QueryEndAtConstraint;\n/**\n * Creates a {@link QueryEndAtConstraint} that modifies the result set to end at\n * the provided fields relative to the order of the query. The order of the field\n * values must match the order of the order by clauses of the query.\n *\n * @param fieldValues - The field values to end this query at, in order\n * of the query's order by.\n * @returns A {@link QueryEndAtConstraint} to pass to `query()`\n */\nexport function endAt(...fieldValues: unknown[]): QueryEndAtConstraint;\nexport function endAt(\n ...docOrFields: Array>\n): QueryEndAtConstraint {\n return QueryEndAtConstraint._create(\n 'endAt',\n docOrFields,\n /*inclusive=*/ true\n );\n}\n\n/** Helper function to create a bound from a document or fields */\nfunction newQueryBoundFromDocOrFields<\n AppModelType,\n DbModelType extends DocumentData\n>(\n query: Query,\n methodName: string,\n docOrFields: Array>,\n inclusive: boolean\n): Bound {\n docOrFields[0] = getModularInstance(docOrFields[0]);\n\n if (docOrFields[0] instanceof DocumentSnapshot) {\n return newQueryBoundFromDocument(\n query._query,\n query.firestore._databaseId,\n methodName,\n docOrFields[0]._document,\n inclusive\n );\n } else {\n const reader = newUserDataReader(query.firestore);\n return newQueryBoundFromFields(\n query._query,\n query.firestore._databaseId,\n reader,\n methodName,\n docOrFields,\n inclusive\n );\n }\n}\n\nexport function newQueryFilter(\n query: InternalQuery,\n methodName: string,\n dataReader: UserDataReader,\n databaseId: DatabaseId,\n fieldPath: InternalFieldPath,\n op: Operator,\n value: unknown\n): FieldFilter {\n let fieldValue: ProtoValue;\n if (fieldPath.isKeyField()) {\n if (op === Operator.ARRAY_CONTAINS || op === Operator.ARRAY_CONTAINS_ANY) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid Query. You can't perform '${op}' queries on documentId().`\n );\n } else if (op === Operator.IN || op === Operator.NOT_IN) {\n validateDisjunctiveFilterElements(value, op);\n const referenceList: ProtoValue[] = [];\n for (const arrayValue of value as ProtoValue[]) {\n referenceList.push(parseDocumentIdValue(databaseId, query, arrayValue));\n }\n fieldValue = { arrayValue: { values: referenceList } };\n } else {\n fieldValue = parseDocumentIdValue(databaseId, query, value);\n }\n } else {\n if (\n op === Operator.IN ||\n op === Operator.NOT_IN ||\n op === Operator.ARRAY_CONTAINS_ANY\n ) {\n validateDisjunctiveFilterElements(value, op);\n }\n fieldValue = parseQueryValue(\n dataReader,\n methodName,\n value,\n /* allowArrays= */ op === Operator.IN || op === Operator.NOT_IN\n );\n }\n const filter = FieldFilter.create(fieldPath, op, fieldValue);\n return filter;\n}\n\nexport function newQueryOrderBy(\n query: InternalQuery,\n fieldPath: InternalFieldPath,\n direction: Direction\n): OrderBy {\n if (query.startAt !== null) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Invalid query. You must not call startAt() or startAfter() before ' +\n 'calling orderBy().'\n );\n }\n if (query.endAt !== null) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Invalid query. You must not call endAt() or endBefore() before ' +\n 'calling orderBy().'\n );\n }\n const orderBy = new OrderBy(fieldPath, direction);\n return orderBy;\n}\n\n/**\n * Create a `Bound` from a query and a document.\n *\n * Note that the `Bound` will always include the key of the document\n * and so only the provided document will compare equal to the returned\n * position.\n *\n * Will throw if the document does not contain all fields of the order by\n * of the query or if any of the fields in the order by are an uncommitted\n * server timestamp.\n */\nexport function newQueryBoundFromDocument(\n query: InternalQuery,\n databaseId: DatabaseId,\n methodName: string,\n doc: Document | null,\n inclusive: boolean\n): Bound {\n if (!doc) {\n throw new FirestoreError(\n Code.NOT_FOUND,\n `Can't use a DocumentSnapshot that doesn't exist for ` +\n `${methodName}().`\n );\n }\n\n const components: ProtoValue[] = [];\n\n // Because people expect to continue/end a query at the exact document\n // provided, we need to use the implicit sort order rather than the explicit\n // sort order, because it's guaranteed to contain the document key. That way\n // the position becomes unambiguous and the query continues/ends exactly at\n // the provided document. Without the key (by using the explicit sort\n // orders), multiple documents could match the position, yielding duplicate\n // results.\n for (const orderBy of queryNormalizedOrderBy(query)) {\n if (orderBy.field.isKeyField()) {\n components.push(refValue(databaseId, doc.key));\n } else {\n const value = doc.data.field(orderBy.field);\n if (isServerTimestamp(value)) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Invalid query. You are trying to start or end a query using a ' +\n 'document for which the field \"' +\n orderBy.field +\n '\" is an uncommitted server timestamp. (Since the value of ' +\n 'this field is unknown, you cannot start/end a query with it.)'\n );\n } else if (value !== null) {\n components.push(value);\n } else {\n const field = orderBy.field.canonicalString();\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid query. You are trying to start or end a query using a ` +\n `document for which the field '${field}' (used as the ` +\n `orderBy) does not exist.`\n );\n }\n }\n }\n return new Bound(components, inclusive);\n}\n\n/**\n * Converts a list of field values to a `Bound` for the given query.\n */\nexport function newQueryBoundFromFields(\n query: InternalQuery,\n databaseId: DatabaseId,\n dataReader: UserDataReader,\n methodName: string,\n values: unknown[],\n inclusive: boolean\n): Bound {\n // Use explicit order by's because it has to match the query the user made\n const orderBy = query.explicitOrderBy;\n if (values.length > orderBy.length) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Too many arguments provided to ${methodName}(). ` +\n `The number of arguments must be less than or equal to the ` +\n `number of orderBy() clauses`\n );\n }\n\n const components: ProtoValue[] = [];\n for (let i = 0; i < values.length; i++) {\n const rawValue = values[i];\n const orderByComponent = orderBy[i];\n if (orderByComponent.field.isKeyField()) {\n if (typeof rawValue !== 'string') {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid query. Expected a string for document ID in ` +\n `${methodName}(), but got a ${typeof rawValue}`\n );\n }\n if (!isCollectionGroupQuery(query) && rawValue.indexOf('/') !== -1) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid query. When querying a collection and ordering by documentId(), ` +\n `the value passed to ${methodName}() must be a plain document ID, but ` +\n `'${rawValue}' contains a slash.`\n );\n }\n const path = query.path.child(ResourcePath.fromString(rawValue));\n if (!DocumentKey.isDocumentKey(path)) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid query. When querying a collection group and ordering by ` +\n `documentId(), the value passed to ${methodName}() must result in a ` +\n `valid document path, but '${path}' is not because it contains an odd number ` +\n `of segments.`\n );\n }\n const key = new DocumentKey(path);\n components.push(refValue(databaseId, key));\n } else {\n const wrapped = parseQueryValue(dataReader, methodName, rawValue);\n components.push(wrapped);\n }\n }\n\n return new Bound(components, inclusive);\n}\n\n/**\n * Parses the given `documentIdValue` into a `ReferenceValue`, throwing\n * appropriate errors if the value is anything other than a `DocumentReference`\n * or `string`, or if the string is malformed.\n */\nfunction parseDocumentIdValue(\n databaseId: DatabaseId,\n query: InternalQuery,\n documentIdValue: unknown\n): ProtoValue {\n documentIdValue = getModularInstance(documentIdValue);\n\n if (typeof documentIdValue === 'string') {\n if (documentIdValue === '') {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Invalid query. When querying with documentId(), you ' +\n 'must provide a valid document ID, but it was an empty string.'\n );\n }\n if (!isCollectionGroupQuery(query) && documentIdValue.indexOf('/') !== -1) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid query. When querying a collection by ` +\n `documentId(), you must provide a plain document ID, but ` +\n `'${documentIdValue}' contains a '/' character.`\n );\n }\n const path = query.path.child(ResourcePath.fromString(documentIdValue));\n if (!DocumentKey.isDocumentKey(path)) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid query. When querying a collection group by ` +\n `documentId(), the value provided must result in a valid document path, ` +\n `but '${path}' is not because it has an odd number of segments (${path.length}).`\n );\n }\n return refValue(databaseId, new DocumentKey(path));\n } else if (documentIdValue instanceof DocumentReference) {\n return refValue(databaseId, documentIdValue._key);\n } else {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid query. When querying with documentId(), you must provide a valid ` +\n `string or a DocumentReference, but it was: ` +\n `${valueDescription(documentIdValue)}.`\n );\n }\n}\n\n/**\n * Validates that the value passed into a disjunctive filter satisfies all\n * array requirements.\n */\nfunction validateDisjunctiveFilterElements(\n value: unknown,\n operator: Operator\n): void {\n if (!Array.isArray(value) || value.length === 0) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Invalid Query. A non-empty array is required for ' +\n `'${operator.toString()}' filters.`\n );\n }\n}\n\n/**\n * Given an operator, returns the set of operators that cannot be used with it.\n *\n * This is not a comprehensive check, and this function should be removed in the\n * long term. Validations should occur in the Firestore backend.\n *\n * Operators in a query must adhere to the following set of rules:\n * 1. Only one inequality per query.\n * 2. `NOT_IN` cannot be used with array, disjunctive, or `NOT_EQUAL` operators.\n */\nfunction conflictingOps(op: Operator): Operator[] {\n switch (op) {\n case Operator.NOT_EQUAL:\n return [Operator.NOT_EQUAL, Operator.NOT_IN];\n case Operator.ARRAY_CONTAINS_ANY:\n case Operator.IN:\n return [Operator.NOT_IN];\n case Operator.NOT_IN:\n return [\n Operator.ARRAY_CONTAINS_ANY,\n Operator.IN,\n Operator.NOT_IN,\n Operator.NOT_EQUAL\n ];\n default:\n return [];\n }\n}\n\nfunction validateNewFieldFilter(\n query: InternalQuery,\n fieldFilter: FieldFilter\n): void {\n const conflictingOp = findOpInsideFilters(\n query.filters,\n conflictingOps(fieldFilter.op)\n );\n if (conflictingOp !== null) {\n // Special case when it's a duplicate op to give a slightly clearer error message.\n if (conflictingOp === fieldFilter.op) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Invalid query. You cannot use more than one ' +\n `'${fieldFilter.op.toString()}' filter.`\n );\n } else {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid query. You cannot use '${fieldFilter.op.toString()}' filters ` +\n `with '${conflictingOp.toString()}' filters.`\n );\n }\n }\n}\n\nfunction validateNewFilter(query: InternalQuery, filter: Filter): void {\n let testQuery = query;\n const subFilters = filter.getFlattenedFilters();\n for (const subFilter of subFilters) {\n validateNewFieldFilter(testQuery, subFilter);\n testQuery = queryWithAddedFilter(testQuery, subFilter);\n }\n}\n\n// Checks if any of the provided filter operators are included in the given list of filters and\n// returns the first one that is, or null if none are.\nfunction findOpInsideFilters(\n filters: Filter[],\n operators: Operator[]\n): Operator | null {\n for (const filter of filters) {\n for (const fieldFilter of filter.getFlattenedFilters()) {\n if (operators.indexOf(fieldFilter.op) >= 0) {\n return fieldFilter.op;\n }\n }\n }\n return null;\n}\n\nexport function validateQueryFilterConstraint(\n functionName: string,\n queryConstraint: AppliableConstraint\n): void {\n if (\n !(queryConstraint instanceof QueryFieldFilterConstraint) &&\n !(queryConstraint instanceof QueryCompositeFilterConstraint)\n ) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Function ${functionName}() requires AppliableConstraints created with a call to 'where(...)', 'or(...)', or 'and(...)'.`\n );\n }\n}\n\nfunction validateQueryConstraintArray(\n queryConstraint: AppliableConstraint[]\n): void {\n const compositeFilterCount = queryConstraint.filter(\n filter => filter instanceof QueryCompositeFilterConstraint\n ).length;\n const fieldFilterCount = queryConstraint.filter(\n filter => filter instanceof QueryFieldFilterConstraint\n ).length;\n\n if (\n compositeFilterCount > 1 ||\n (compositeFilterCount > 0 && fieldFilterCount > 0)\n ) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'InvalidQuery. When using composite filters, you cannot use ' +\n 'more than one filter at the top level. Consider nesting the multiple ' +\n 'filters within an `and(...)` statement. For example: ' +\n 'change `query(query, where(...), or(...))` to ' +\n '`query(query, and(where(...), or(...)))`.'\n );\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DocumentData } from '@firebase/firestore-types';\n\nimport { DatabaseId } from '../core/database_info';\nimport { DocumentKey } from '../model/document_key';\nimport {\n normalizeByteString,\n normalizeNumber,\n normalizeTimestamp\n} from '../model/normalize';\nimport { ResourcePath } from '../model/path';\nimport {\n getLocalWriteTime,\n getPreviousValue\n} from '../model/server_timestamps';\nimport { TypeOrder } from '../model/type_order';\nimport { VECTOR_MAP_VECTORS_KEY, typeOrder } from '../model/values';\nimport {\n ApiClientObjectMap,\n ArrayValue as ProtoArrayValue,\n LatLng as ProtoLatLng,\n MapValue as ProtoMapValue,\n Timestamp as ProtoTimestamp,\n Value,\n Value as ProtoValue\n} from '../protos/firestore_proto_api';\nimport { isValidResourceName } from '../remote/serializer';\nimport { fail, hardAssert } from '../util/assert';\nimport { ByteString } from '../util/byte_string';\nimport { logError } from '../util/log';\nimport { forEach } from '../util/obj';\n\nimport { GeoPoint } from './geo_point';\nimport { Timestamp } from './timestamp';\nimport { VectorValue } from './vector_value';\n\nexport type ServerTimestampBehavior = 'estimate' | 'previous' | 'none';\n\n/**\n * Converts Firestore's internal types to the JavaScript types that we expose\n * to the user.\n *\n * @internal\n */\nexport abstract class AbstractUserDataWriter {\n convertValue(\n value: ProtoValue,\n serverTimestampBehavior: ServerTimestampBehavior = 'none'\n ): unknown {\n switch (typeOrder(value)) {\n case TypeOrder.NullValue:\n return null;\n case TypeOrder.BooleanValue:\n return value.booleanValue!;\n case TypeOrder.NumberValue:\n return normalizeNumber(value.integerValue || value.doubleValue);\n case TypeOrder.TimestampValue:\n return this.convertTimestamp(value.timestampValue!);\n case TypeOrder.ServerTimestampValue:\n return this.convertServerTimestamp(value, serverTimestampBehavior);\n case TypeOrder.StringValue:\n return value.stringValue!;\n case TypeOrder.BlobValue:\n return this.convertBytes(normalizeByteString(value.bytesValue!));\n case TypeOrder.RefValue:\n return this.convertReference(value.referenceValue!);\n case TypeOrder.GeoPointValue:\n return this.convertGeoPoint(value.geoPointValue!);\n case TypeOrder.ArrayValue:\n return this.convertArray(value.arrayValue!, serverTimestampBehavior);\n case TypeOrder.ObjectValue:\n return this.convertObject(value.mapValue!, serverTimestampBehavior);\n case TypeOrder.VectorValue:\n return this.convertVectorValue(value.mapValue!);\n default:\n throw fail(0xf2a2, 'Invalid value type', {\n value\n });\n }\n }\n\n private convertObject(\n mapValue: ProtoMapValue,\n serverTimestampBehavior: ServerTimestampBehavior\n ): DocumentData {\n return this.convertObjectMap(mapValue.fields, serverTimestampBehavior);\n }\n\n /**\n * @internal\n */\n convertObjectMap(\n fields: ApiClientObjectMap | undefined,\n serverTimestampBehavior: ServerTimestampBehavior = 'none'\n ): DocumentData {\n const result: DocumentData = {};\n forEach(fields, (key, value) => {\n result[key] = this.convertValue(value, serverTimestampBehavior);\n });\n return result;\n }\n\n /**\n * @internal\n */\n convertVectorValue(mapValue: ProtoMapValue): VectorValue {\n const values = mapValue.fields?.[\n VECTOR_MAP_VECTORS_KEY\n ].arrayValue?.values?.map(value => {\n return normalizeNumber(value.doubleValue);\n });\n\n return new VectorValue(values);\n }\n\n private convertGeoPoint(value: ProtoLatLng): GeoPoint {\n return new GeoPoint(\n normalizeNumber(value.latitude),\n normalizeNumber(value.longitude)\n );\n }\n\n private convertArray(\n arrayValue: ProtoArrayValue,\n serverTimestampBehavior: ServerTimestampBehavior\n ): unknown[] {\n return (arrayValue.values || []).map(value =>\n this.convertValue(value, serverTimestampBehavior)\n );\n }\n\n private convertServerTimestamp(\n value: ProtoValue,\n serverTimestampBehavior: ServerTimestampBehavior\n ): unknown {\n switch (serverTimestampBehavior) {\n case 'previous':\n const previousValue = getPreviousValue(value);\n if (previousValue == null) {\n return null;\n }\n return this.convertValue(previousValue, serverTimestampBehavior);\n case 'estimate':\n return this.convertTimestamp(getLocalWriteTime(value));\n default:\n return null;\n }\n }\n\n private convertTimestamp(value: ProtoTimestamp): Timestamp {\n const normalizedValue = normalizeTimestamp(value);\n return new Timestamp(normalizedValue.seconds, normalizedValue.nanos);\n }\n\n protected convertDocumentKey(\n name: string,\n expectedDatabaseId: DatabaseId\n ): DocumentKey {\n const resourcePath = ResourcePath.fromString(name);\n hardAssert(\n isValidResourceName(resourcePath),\n 0x25d8,\n 'ReferenceValue is not valid',\n { name }\n );\n const databaseId = new DatabaseId(resourcePath.get(1), resourcePath.get(3));\n const key = new DocumentKey(resourcePath.popFirst(5));\n\n if (!databaseId.isEqual(expectedDatabaseId)) {\n // TODO(b/64130202): Somehow support foreign references.\n logError(\n `Document ${key} contains a document ` +\n `reference within a different database (` +\n `${databaseId.projectId}/${databaseId.database}) which is not ` +\n `supported. It will be treated as a reference in the current ` +\n `database (${expectedDatabaseId.projectId}/${expectedDatabaseId.database}) ` +\n `instead.`\n );\n }\n return key;\n }\n\n protected abstract convertReference(name: string): unknown;\n\n protected abstract convertBytes(bytes: ByteString): unknown;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n DocumentData as PublicDocumentData,\n SetOptions as PublicSetOptions\n} from '@firebase/firestore-types';\nimport { getModularInstance } from '@firebase/util';\n\nimport { LimitType } from '../core/query';\nimport { DeleteMutation, Precondition } from '../model/mutation';\nimport {\n invokeBatchGetDocumentsRpc,\n invokeCommitRpc,\n invokeRunQueryRpc\n} from '../remote/datastore';\nimport { hardAssert } from '../util/assert';\nimport { ByteString } from '../util/byte_string';\nimport { cast } from '../util/input_validation';\n\nimport { Bytes } from './bytes';\nimport { getDatastore } from './components';\nimport { Firestore } from './database';\nimport { FieldPath } from './field_path';\nimport { validateHasExplicitOrderByForLimitToLast } from './query';\nimport {\n CollectionReference,\n doc,\n DocumentData,\n DocumentReference,\n PartialWithFieldValue,\n Query,\n SetOptions,\n UpdateData,\n WithFieldValue\n} from './reference';\nimport {\n DocumentSnapshot,\n QueryDocumentSnapshot,\n QuerySnapshot\n} from './snapshot';\nimport {\n newUserDataReader,\n ParsedUpdateData,\n parseSetData,\n parseUpdateData,\n parseUpdateVarargs,\n UntypedFirestoreDataConverter\n} from './user_data_reader';\nimport { AbstractUserDataWriter } from './user_data_writer';\n\n/**\n * Converts custom model object of type T into `DocumentData` by applying the\n * converter if it exists.\n *\n * This function is used when converting user objects to `DocumentData`\n * because we want to provide the user with a more specific error message if\n * their `set()` or fails due to invalid data originating from a `toFirestore()`\n * call.\n */\nexport function applyFirestoreDataConverter(\n converter: UntypedFirestoreDataConverter | null,\n value: WithFieldValue | PartialWithFieldValue,\n options?: PublicSetOptions\n): PublicDocumentData {\n let convertedValue;\n if (converter) {\n if (options && (options.merge || options.mergeFields)) {\n // Cast to `any` in order to satisfy the union type constraint on\n // toFirestore().\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n convertedValue = (converter as any).toFirestore(value, options);\n } else {\n convertedValue = converter.toFirestore(value as WithFieldValue);\n }\n } else {\n convertedValue = value as PublicDocumentData;\n }\n return convertedValue;\n}\n\nexport class LiteUserDataWriter extends AbstractUserDataWriter {\n constructor(protected firestore: Firestore) {\n super();\n }\n\n protected convertBytes(bytes: ByteString): Bytes {\n return new Bytes(bytes);\n }\n\n protected convertReference(name: string): DocumentReference {\n const key = this.convertDocumentKey(name, this.firestore._databaseId);\n return new DocumentReference(this.firestore, /* converter= */ null, key);\n }\n}\n\n/**\n * Reads the document referred to by the specified document reference.\n *\n * All documents are directly fetched from the server, even if the document was\n * previously read or modified. Recent modifications are only reflected in the\n * retrieved `DocumentSnapshot` if they have already been applied by the\n * backend. If the client is offline, the read fails. If you like to use\n * caching or see local modifications, please use the full Firestore SDK.\n *\n * @param reference - The reference of the document to fetch.\n * @returns A Promise resolved with a `DocumentSnapshot` containing the current\n * document contents.\n */\nexport function getDoc(\n reference: DocumentReference\n): Promise> {\n reference = cast>(\n reference,\n DocumentReference\n );\n const datastore = getDatastore(reference.firestore);\n const userDataWriter = new LiteUserDataWriter(reference.firestore);\n\n return invokeBatchGetDocumentsRpc(datastore, [reference._key]).then(\n result => {\n hardAssert(\n result.length === 1,\n 0x3d02,\n 'Expected a single document result'\n );\n const document = result[0];\n return new DocumentSnapshot(\n reference.firestore,\n userDataWriter,\n reference._key,\n document.isFoundDocument() ? document : null,\n reference.converter\n );\n }\n );\n}\n\n/**\n * Executes the query and returns the results as a {@link QuerySnapshot}.\n *\n * All queries are executed directly by the server, even if the query was\n * previously executed. Recent modifications are only reflected in the retrieved\n * results if they have already been applied by the backend. If the client is\n * offline, the operation fails. To see previously cached result and local\n * modifications, use the full Firestore SDK.\n *\n * @param query - The `Query` to execute.\n * @returns A Promise that will be resolved with the results of the query.\n */\nexport function getDocs(\n query: Query\n): Promise> {\n query = cast>(query, Query);\n validateHasExplicitOrderByForLimitToLast(query._query);\n\n const datastore = getDatastore(query.firestore);\n const userDataWriter = new LiteUserDataWriter(query.firestore);\n return invokeRunQueryRpc(datastore, query._query).then(result => {\n const docs = result.map(\n doc =>\n new QueryDocumentSnapshot(\n query.firestore,\n userDataWriter,\n doc.key,\n doc,\n query.converter\n )\n );\n\n if (query._query.limitType === LimitType.Last) {\n // Limit to last queries reverse the orderBy constraint that was\n // specified by the user. As such, we need to reverse the order of the\n // results to return the documents in the expected order.\n docs.reverse();\n }\n\n return new QuerySnapshot(query, docs);\n });\n}\n\n/**\n * Writes to the document referred to by the specified `DocumentReference`. If\n * the document does not yet exist, it will be created.\n *\n * The result of this write will only be reflected in document reads that occur\n * after the returned promise resolves. If the client is offline, the\n * write fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the document to write.\n * @param data - A map of the fields and values for the document.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns A `Promise` resolved once the data has been successfully written\n * to the backend.\n */\nexport function setDoc(\n reference: DocumentReference,\n data: WithFieldValue\n): Promise;\n/**\n * Writes to the document referred to by the specified `DocumentReference`. If\n * the document does not yet exist, it will be created. If you provide `merge`\n * or `mergeFields`, the provided data can be merged into an existing document.\n *\n * The result of this write will only be reflected in document reads that occur\n * after the returned promise resolves. If the client is offline, the\n * write fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the document to write.\n * @param data - A map of the fields and values for the document.\n * @param options - An object to configure the set behavior.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns A `Promise` resolved once the data has been successfully written\n * to the backend.\n */\nexport function setDoc(\n reference: DocumentReference,\n data: PartialWithFieldValue,\n options: SetOptions\n): Promise;\nexport function setDoc(\n reference: DocumentReference,\n data: PartialWithFieldValue,\n options?: SetOptions\n): Promise {\n reference = cast>(\n reference,\n DocumentReference\n );\n const convertedValue = applyFirestoreDataConverter(\n reference.converter,\n data,\n options\n );\n const dataReader = newUserDataReader(reference.firestore);\n const parsed = parseSetData(\n dataReader,\n 'setDoc',\n reference._key,\n convertedValue,\n reference.converter !== null,\n options\n );\n\n const datastore = getDatastore(reference.firestore);\n return invokeCommitRpc(datastore, [\n parsed.toMutation(reference._key, Precondition.none())\n ]);\n}\n\n/**\n * Updates fields in the document referred to by the specified\n * `DocumentReference`. The update will fail if applied to a document that does\n * not exist.\n *\n * The result of this update will only be reflected in document reads that occur\n * after the returned promise resolves. If the client is offline, the\n * update fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the document to update.\n * @param data - An object containing the fields and values with which to\n * update the document. Fields can contain dots to reference nested fields\n * within the document.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns A `Promise` resolved once the data has been successfully written\n * to the backend.\n */\nexport function updateDoc(\n reference: DocumentReference,\n data: UpdateData\n): Promise;\n/**\n * Updates fields in the document referred to by the specified\n * `DocumentReference` The update will fail if applied to a document that does\n * not exist.\n *\n * Nested fields can be updated by providing dot-separated field path\n * strings or by providing `FieldPath` objects.\n *\n * The result of this update will only be reflected in document reads that occur\n * after the returned promise resolves. If the client is offline, the\n * update fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the document to update.\n * @param field - The first field to update.\n * @param value - The first value.\n * @param moreFieldsAndValues - Additional key value pairs.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns A `Promise` resolved once the data has been successfully written\n * to the backend.\n */\nexport function updateDoc(\n reference: DocumentReference,\n field: string | FieldPath,\n value: unknown,\n ...moreFieldsAndValues: unknown[]\n): Promise;\nexport function updateDoc(\n reference: DocumentReference,\n fieldOrUpdateData: string | FieldPath | UpdateData,\n value?: unknown,\n ...moreFieldsAndValues: unknown[]\n): Promise {\n reference = cast>(\n reference,\n DocumentReference\n );\n const dataReader = newUserDataReader(reference.firestore);\n\n // For Compat types, we have to \"extract\" the underlying types before\n // performing validation.\n fieldOrUpdateData = getModularInstance(fieldOrUpdateData);\n\n let parsed: ParsedUpdateData;\n if (\n typeof fieldOrUpdateData === 'string' ||\n fieldOrUpdateData instanceof FieldPath\n ) {\n parsed = parseUpdateVarargs(\n dataReader,\n 'updateDoc',\n reference._key,\n fieldOrUpdateData,\n value,\n moreFieldsAndValues\n );\n } else {\n parsed = parseUpdateData(\n dataReader,\n 'updateDoc',\n reference._key,\n fieldOrUpdateData\n );\n }\n\n const datastore = getDatastore(reference.firestore);\n return invokeCommitRpc(datastore, [\n parsed.toMutation(reference._key, Precondition.exists(true))\n ]);\n}\n\n/**\n * Deletes the document referred to by the specified `DocumentReference`.\n *\n * The deletion will only be reflected in document reads that occur after the\n * returned promise resolves. If the client is offline, the\n * delete fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the document to delete.\n * @returns A `Promise` resolved once the document has been successfully\n * deleted from the backend.\n */\nexport function deleteDoc(\n reference: DocumentReference\n): Promise {\n reference = cast>(\n reference,\n DocumentReference\n );\n const datastore = getDatastore(reference.firestore);\n return invokeCommitRpc(datastore, [\n new DeleteMutation(reference._key, Precondition.none())\n ]);\n}\n\n/**\n * Add a new document to specified `CollectionReference` with the given data,\n * assigning it a document ID automatically.\n *\n * The result of this write will only be reflected in document reads that occur\n * after the returned promise resolves. If the client is offline, the\n * write fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the collection to add this document to.\n * @param data - An Object containing the data for the new document.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns A `Promise` resolved with a `DocumentReference` pointing to the\n * newly created document after it has been written to the backend.\n */\nexport function addDoc(\n reference: CollectionReference,\n data: WithFieldValue\n): Promise> {\n reference = cast>(\n reference,\n CollectionReference\n );\n const docRef = doc(reference);\n\n const convertedValue = applyFirestoreDataConverter(\n reference.converter,\n data as PartialWithFieldValue\n );\n\n const dataReader = newUserDataReader(reference.firestore);\n const parsed = parseSetData(\n dataReader,\n 'addDoc',\n docRef._key,\n convertedValue,\n docRef.converter !== null,\n {}\n );\n\n const datastore = getDatastore(reference.firestore);\n return invokeCommitRpc(datastore, [\n parsed.toMutation(docRef._key, Precondition.exists(false))\n ]).then(() => docRef);\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { deepEqual } from '@firebase/util';\n\nimport { AggregateImpl } from '../core/aggregate';\nimport { ApiClientObjectMap, Value } from '../protos/firestore_proto_api';\nimport { invokeRunAggregationQueryRpc } from '../remote/datastore';\nimport { cast } from '../util/input_validation';\nimport { mapToArray } from '../util/obj';\n\nimport {\n AggregateField,\n AggregateQuerySnapshot,\n AggregateSpec\n} from './aggregate_types';\nimport { getDatastore } from './components';\nimport { Firestore } from './database';\nimport { FieldPath } from './field_path';\nimport { DocumentData, Query, queryEqual } from './reference';\nimport { LiteUserDataWriter } from './reference_impl';\nimport { fieldPathFromArgument } from './user_data_reader';\n\n/**\n * Calculates the number of documents in the result set of the given query\n * without actually downloading the documents.\n *\n * Using this function to count the documents is efficient because only the\n * final count, not the documents' data, is downloaded. This function can\n * count the documents in cases where the result set is prohibitively large to\n * download entirely (thousands of documents).\n *\n * @param query The query whose result set size is calculated.\n * @returns A Promise that will be resolved with the count; the count can be\n * retrieved from `snapshot.data().count`, where `snapshot` is the\n * `AggregateQuerySnapshot` to which the returned Promise resolves.\n */\nexport function getCount(\n query: Query\n): Promise<\n AggregateQuerySnapshot<\n { count: AggregateField },\n AppModelType,\n DbModelType\n >\n> {\n const countQuerySpec: { count: AggregateField } = {\n count: count()\n };\n\n return getAggregate(query, countQuerySpec);\n}\n\n/**\n * Calculates the specified aggregations over the documents in the result\n * set of the given query without actually downloading the documents.\n *\n * Using this function to perform aggregations is efficient because only the\n * final aggregation values, not the documents' data, are downloaded. This\n * function can perform aggregations of the documents in cases where the result\n * set is prohibitively large to download entirely (thousands of documents).\n *\n * @param query The query whose result set is aggregated over.\n * @param aggregateSpec An `AggregateSpec` object that specifies the aggregates\n * to perform over the result set. The AggregateSpec specifies aliases for each\n * aggregate, which can be used to retrieve the aggregate result.\n * @example\n * ```typescript\n * const aggregateSnapshot = await getAggregate(query, {\n * countOfDocs: count(),\n * totalHours: sum('hours'),\n * averageScore: average('score')\n * });\n *\n * const countOfDocs: number = aggregateSnapshot.data().countOfDocs;\n * const totalHours: number = aggregateSnapshot.data().totalHours;\n * const averageScore: number | null = aggregateSnapshot.data().averageScore;\n * ```\n */\nexport function getAggregate<\n AggregateSpecType extends AggregateSpec,\n AppModelType,\n DbModelType extends DocumentData\n>(\n query: Query,\n aggregateSpec: AggregateSpecType\n): Promise<\n AggregateQuerySnapshot\n> {\n const firestore = cast(query.firestore, Firestore);\n const datastore = getDatastore(firestore);\n\n const internalAggregates = mapToArray(aggregateSpec, (aggregate, alias) => {\n return new AggregateImpl(\n alias,\n aggregate.aggregateType,\n aggregate._internalFieldPath\n );\n });\n\n // Run the aggregation and convert the results\n return invokeRunAggregationQueryRpc(\n datastore,\n query._query,\n internalAggregates\n ).then(aggregateResult =>\n convertToAggregateQuerySnapshot(firestore, query, aggregateResult)\n );\n}\n\nfunction convertToAggregateQuerySnapshot<\n AggregateSpecType extends AggregateSpec,\n AppModelType,\n DbModelType extends DocumentData\n>(\n firestore: Firestore,\n query: Query,\n aggregateResult: ApiClientObjectMap\n): AggregateQuerySnapshot {\n const userDataWriter = new LiteUserDataWriter(firestore);\n const querySnapshot = new AggregateQuerySnapshot<\n AggregateSpecType,\n AppModelType,\n DbModelType\n >(query, userDataWriter, aggregateResult);\n return querySnapshot;\n}\n\n/**\n * Create an AggregateField object that can be used to compute the sum of\n * a specified field over a range of documents in the result set of a query.\n * @param field Specifies the field to sum across the result set.\n */\nexport function sum(field: string | FieldPath): AggregateField {\n return new AggregateField('sum', fieldPathFromArgument('sum', field));\n}\n\n/**\n * Create an AggregateField object that can be used to compute the average of\n * a specified field over a range of documents in the result set of a query.\n * @param field Specifies the field to average across the result set.\n */\nexport function average(\n field: string | FieldPath\n): AggregateField {\n return new AggregateField('avg', fieldPathFromArgument('average', field));\n}\n\n/**\n * Create an AggregateField object that can be used to compute the count of\n * documents in the result set of a query.\n */\nexport function count(): AggregateField {\n return new AggregateField('count');\n}\n\n/**\n * Compares two 'AggregateField` instances for equality.\n *\n * @param left Compare this AggregateField to the `right`.\n * @param right Compare this AggregateField to the `left`.\n */\nexport function aggregateFieldEqual(\n left: AggregateField,\n right: AggregateField\n): boolean {\n return (\n left instanceof AggregateField &&\n right instanceof AggregateField &&\n left.aggregateType === right.aggregateType &&\n left._internalFieldPath?.canonicalString() ===\n right._internalFieldPath?.canonicalString()\n );\n}\n\n/**\n * Compares two `AggregateQuerySnapshot` instances for equality.\n *\n * Two `AggregateQuerySnapshot` instances are considered \"equal\" if they have\n * underlying queries that compare equal, and the same data.\n *\n * @param left - The first `AggregateQuerySnapshot` to compare.\n * @param right - The second `AggregateQuerySnapshot` to compare.\n *\n * @returns `true` if the objects are \"equal\", as defined above, or `false`\n * otherwise.\n */\nexport function aggregateQuerySnapshotEqual<\n AggregateSpecType extends AggregateSpec,\n AppModelType,\n DbModelType extends DocumentData\n>(\n left: AggregateQuerySnapshot,\n right: AggregateQuerySnapshot\n): boolean {\n return (\n queryEqual(left.query, right.query) && deepEqual(left.data(), right.data())\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FieldValue } from './field_value';\nimport {\n ArrayRemoveFieldValueImpl,\n ArrayUnionFieldValueImpl,\n DeleteFieldValueImpl,\n NumericIncrementFieldValueImpl,\n ServerTimestampFieldValueImpl\n} from './user_data_reader';\nimport { VectorValue } from './vector_value';\n\n/**\n * Returns a sentinel for use with {@link @firebase/firestore/lite#(updateDoc:1)} or\n * {@link @firebase/firestore/lite#(setDoc:1)} with `{merge: true}` to mark a field for deletion.\n */\nexport function deleteField(): FieldValue {\n return new DeleteFieldValueImpl('deleteField');\n}\n\n/**\n * Returns a sentinel used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link @firebase/firestore/lite#(updateDoc:1)} to\n * include a server-generated timestamp in the written data.\n */\nexport function serverTimestamp(): FieldValue {\n return new ServerTimestampFieldValueImpl('serverTimestamp');\n}\n\n/**\n * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link\n * @firebase/firestore/lite#(updateDoc:1)} that tells the server to union the given elements with any array\n * value that already exists on the server. Each specified element that doesn't\n * already exist in the array will be added to the end. If the field being\n * modified is not already an array it will be overwritten with an array\n * containing exactly the specified elements.\n *\n * @param elements - The elements to union into the array.\n * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or\n * `updateDoc()`.\n */\nexport function arrayUnion(...elements: unknown[]): FieldValue {\n // NOTE: We don't actually parse the data until it's used in set() or\n // update() since we'd need the Firestore instance to do this.\n return new ArrayUnionFieldValueImpl('arrayUnion', elements);\n}\n\n/**\n * Returns a special value that can be used with {@link (setDoc:1)} or {@link\n * updateDoc:1} that tells the server to remove the given elements from any\n * array value that already exists on the server. All instances of each element\n * specified will be removed from the array. If the field being modified is not\n * already an array it will be overwritten with an empty array.\n *\n * @param elements - The elements to remove from the array.\n * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or\n * `updateDoc()`\n */\nexport function arrayRemove(...elements: unknown[]): FieldValue {\n // NOTE: We don't actually parse the data until it's used in set() or\n // update() since we'd need the Firestore instance to do this.\n return new ArrayRemoveFieldValueImpl('arrayRemove', elements);\n}\n\n/**\n * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link\n * @firebase/firestore/lite#(updateDoc:1)} that tells the server to increment the field's current value by\n * the given value.\n *\n * If either the operand or the current field value uses floating point\n * precision, all arithmetic follows IEEE 754 semantics. If both values are\n * integers, values outside of JavaScript's safe number range\n * (`Number.MIN_SAFE_INTEGER` to `Number.MAX_SAFE_INTEGER`) are also subject to\n * precision loss. Furthermore, once processed by the Firestore backend, all\n * integer operations are capped between -2^63 and 2^63-1.\n *\n * If the current field value is not of type `number`, or if the field does not\n * yet exist, the transformation sets the field to the given value.\n *\n * @param n - The value to increment by.\n * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or\n * `updateDoc()`\n */\nexport function increment(n: number): FieldValue {\n return new NumericIncrementFieldValueImpl('increment', n);\n}\n\n/**\n * Creates a new `VectorValue` constructed with a copy of the given array of numbers.\n *\n * @param values - Create a `VectorValue` instance with a copy of this array of numbers.\n *\n * @returns A new `VectorValue` constructed with a copy of the given array of numbers.\n */\nexport function vector(values?: number[]): VectorValue {\n return new VectorValue(values);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Compat, getModularInstance } from '@firebase/util';\n\nimport { DeleteMutation, Mutation, Precondition } from '../model/mutation';\nimport { invokeCommitRpc } from '../remote/datastore';\nimport { Code, FirestoreError } from '../util/error';\nimport { cast } from '../util/input_validation';\n\nimport { getDatastore } from './components';\nimport { Firestore } from './database';\nimport { FieldPath } from './field_path';\nimport {\n DocumentData,\n DocumentReference,\n PartialWithFieldValue,\n SetOptions,\n UpdateData,\n WithFieldValue\n} from './reference';\nimport { applyFirestoreDataConverter } from './reference_impl';\nimport {\n newUserDataReader,\n parseSetData,\n parseUpdateData,\n parseUpdateVarargs,\n UserDataReader\n} from './user_data_reader';\n\n/**\n * A write batch, used to perform multiple writes as a single atomic unit.\n *\n * A `WriteBatch` object can be acquired by calling {@link writeBatch}. It\n * provides methods for adding writes to the write batch. None of the writes\n * will be committed (or visible locally) until {@link WriteBatch.commit} is\n * called.\n */\nexport class WriteBatch {\n // This is the lite version of the WriteBatch API used in the legacy SDK. The\n // class is a close copy but takes different input types.\n\n private readonly _dataReader: UserDataReader;\n private _mutations = [] as Mutation[];\n private _committed = false;\n\n /** @hideconstructor */\n constructor(\n private readonly _firestore: Firestore,\n private readonly _commitHandler: (m: Mutation[]) => Promise\n ) {\n this._dataReader = newUserDataReader(_firestore);\n }\n\n /**\n * Writes to the document referred to by the provided {@link\n * DocumentReference}. If the document does not exist yet, it will be created.\n *\n * @param documentRef - A reference to the document to be set.\n * @param data - An object of the fields and values for the document.\n * @returns This `WriteBatch` instance. Used for chaining method calls.\n */\n set(\n documentRef: DocumentReference,\n data: WithFieldValue\n ): WriteBatch;\n /**\n * Writes to the document referred to by the provided {@link\n * DocumentReference}. If the document does not exist yet, it will be created.\n * If you provide `merge` or `mergeFields`, the provided data can be merged\n * into an existing document.\n *\n * @param documentRef - A reference to the document to be set.\n * @param data - An object of the fields and values for the document.\n * @param options - An object to configure the set behavior.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns This `WriteBatch` instance. Used for chaining method calls.\n */\n set(\n documentRef: DocumentReference,\n data: PartialWithFieldValue,\n options: SetOptions\n ): WriteBatch;\n set(\n documentRef: DocumentReference,\n data: WithFieldValue | PartialWithFieldValue,\n options?: SetOptions\n ): WriteBatch {\n this._verifyNotCommitted();\n const ref = validateReference(documentRef, this._firestore);\n\n const convertedValue = applyFirestoreDataConverter(\n ref.converter,\n data,\n options\n );\n const parsed = parseSetData(\n this._dataReader,\n 'WriteBatch.set',\n ref._key,\n convertedValue,\n ref.converter !== null,\n options\n );\n this._mutations.push(parsed.toMutation(ref._key, Precondition.none()));\n return this;\n }\n\n /**\n * Updates fields in the document referred to by the provided {@link\n * DocumentReference}. The update will fail if applied to a document that does\n * not exist.\n *\n * @param documentRef - A reference to the document to be updated.\n * @param data - An object containing the fields and values with which to\n * update the document. Fields can contain dots to reference nested fields\n * within the document.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns This `WriteBatch` instance. Used for chaining method calls.\n */\n update(\n documentRef: DocumentReference,\n data: UpdateData\n ): WriteBatch;\n /**\n * Updates fields in the document referred to by this {@link\n * DocumentReference}. The update will fail if applied to a document that does\n * not exist.\n *\n * Nested fields can be update by providing dot-separated field path strings\n * or by providing `FieldPath` objects.\n *\n * @param documentRef - A reference to the document to be updated.\n * @param field - The first field to update.\n * @param value - The first value.\n * @param moreFieldsAndValues - Additional key value pairs.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns This `WriteBatch` instance. Used for chaining method calls.\n */\n update(\n documentRef: DocumentReference,\n field: string | FieldPath,\n value: unknown,\n ...moreFieldsAndValues: unknown[]\n ): WriteBatch;\n update(\n documentRef: DocumentReference,\n fieldOrUpdateData: string | FieldPath | UpdateData,\n value?: unknown,\n ...moreFieldsAndValues: unknown[]\n ): WriteBatch {\n this._verifyNotCommitted();\n const ref = validateReference(documentRef, this._firestore);\n\n // For Compat types, we have to \"extract\" the underlying types before\n // performing validation.\n fieldOrUpdateData = getModularInstance(fieldOrUpdateData);\n\n let parsed;\n if (\n typeof fieldOrUpdateData === 'string' ||\n fieldOrUpdateData instanceof FieldPath\n ) {\n parsed = parseUpdateVarargs(\n this._dataReader,\n 'WriteBatch.update',\n ref._key,\n fieldOrUpdateData,\n value,\n moreFieldsAndValues\n );\n } else {\n parsed = parseUpdateData(\n this._dataReader,\n 'WriteBatch.update',\n ref._key,\n fieldOrUpdateData\n );\n }\n\n this._mutations.push(\n parsed.toMutation(ref._key, Precondition.exists(true))\n );\n return this;\n }\n\n /**\n * Deletes the document referred to by the provided {@link DocumentReference}.\n *\n * @param documentRef - A reference to the document to be deleted.\n * @returns This `WriteBatch` instance. Used for chaining method calls.\n */\n delete(\n documentRef: DocumentReference\n ): WriteBatch {\n this._verifyNotCommitted();\n const ref = validateReference(documentRef, this._firestore);\n this._mutations = this._mutations.concat(\n new DeleteMutation(ref._key, Precondition.none())\n );\n return this;\n }\n\n /**\n * Commits all of the writes in this write batch as a single atomic unit.\n *\n * The result of these writes will only be reflected in document reads that\n * occur after the returned promise resolves. If the client is offline, the\n * write fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @returns A `Promise` resolved once all of the writes in the batch have been\n * successfully written to the backend as an atomic unit (note that it won't\n * resolve while you're offline).\n */\n commit(): Promise {\n this._verifyNotCommitted();\n this._committed = true;\n if (this._mutations.length > 0) {\n return this._commitHandler(this._mutations);\n }\n\n return Promise.resolve();\n }\n\n private _verifyNotCommitted(): void {\n if (this._committed) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'A write batch can no longer be used after commit() ' +\n 'has been called.'\n );\n }\n }\n}\n\nexport function validateReference<\n AppModelType,\n DbModelType extends DocumentData\n>(\n documentRef:\n | DocumentReference\n | Compat>,\n firestore: Firestore\n): DocumentReference {\n documentRef = getModularInstance(documentRef);\n\n if (documentRef.firestore !== firestore) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Provided document reference is from a different Firestore instance.'\n );\n } else {\n return documentRef as DocumentReference;\n }\n}\n\n/**\n * Creates a write batch, used for performing multiple writes as a single\n * atomic operation. The maximum number of writes allowed in a single WriteBatch\n * is 500.\n *\n * The result of these writes will only be reflected in document reads that\n * occur after the returned promise resolves. If the client is offline, the\n * write fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @returns A `WriteBatch` that can be used to atomically execute multiple\n * writes.\n */\nexport function writeBatch(firestore: Firestore): WriteBatch {\n firestore = cast(firestore, Firestore);\n const datastore = getDatastore(firestore);\n return new WriteBatch(firestore, writes =>\n invokeCommitRpc(datastore, writes)\n );\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ParsedSetData, ParsedUpdateData } from '../lite-api/user_data_reader';\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport {\n DeleteMutation,\n Mutation,\n Precondition,\n VerifyMutation\n} from '../model/mutation';\nimport {\n Datastore,\n invokeBatchGetDocumentsRpc,\n invokeCommitRpc\n} from '../remote/datastore';\nimport { fail, debugAssert } from '../util/assert';\nimport { Code, FirestoreError } from '../util/error';\n\nimport { SnapshotVersion } from './snapshot_version';\n\n/**\n * Internal transaction object responsible for accumulating the mutations to\n * perform and the base versions for any documents read.\n */\nexport class Transaction {\n // The version of each document that was read during this transaction.\n private readVersions = new Map();\n private mutations: Mutation[] = [];\n private committed = false;\n\n /**\n * A deferred usage error that occurred previously in this transaction that\n * will cause the transaction to fail once it actually commits.\n */\n private lastTransactionError: FirestoreError | null = null;\n\n /**\n * Set of documents that have been written in the transaction.\n *\n * When there's more than one write to the same key in a transaction, any\n * writes after the first are handled differently.\n */\n private writtenDocs: Set = new Set();\n\n constructor(private datastore: Datastore) {}\n\n async lookup(keys: DocumentKey[]): Promise {\n this.ensureCommitNotCalled();\n\n if (this.mutations.length > 0) {\n this.lastTransactionError = new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Firestore transactions require all reads to be executed before all writes.'\n );\n throw this.lastTransactionError;\n }\n const docs = await invokeBatchGetDocumentsRpc(this.datastore, keys);\n docs.forEach(doc => this.recordVersion(doc));\n return docs;\n }\n\n set(key: DocumentKey, data: ParsedSetData): void {\n this.write(data.toMutation(key, this.precondition(key)));\n this.writtenDocs.add(key.toString());\n }\n\n update(key: DocumentKey, data: ParsedUpdateData): void {\n try {\n this.write(data.toMutation(key, this.preconditionForUpdate(key)));\n } catch (e) {\n this.lastTransactionError = e as FirestoreError | null;\n }\n this.writtenDocs.add(key.toString());\n }\n\n delete(key: DocumentKey): void {\n this.write(new DeleteMutation(key, this.precondition(key)));\n this.writtenDocs.add(key.toString());\n }\n\n async commit(): Promise {\n this.ensureCommitNotCalled();\n\n if (this.lastTransactionError) {\n throw this.lastTransactionError;\n }\n const unwritten = this.readVersions;\n // For each mutation, note that the doc was written.\n this.mutations.forEach(mutation => {\n unwritten.delete(mutation.key.toString());\n });\n // For each document that was read but not written to, we want to perform\n // a `verify` operation.\n unwritten.forEach((_, path) => {\n const key = DocumentKey.fromPath(path);\n this.mutations.push(new VerifyMutation(key, this.precondition(key)));\n });\n await invokeCommitRpc(this.datastore, this.mutations);\n this.committed = true;\n }\n\n private recordVersion(doc: Document): void {\n let docVersion: SnapshotVersion;\n\n if (doc.isFoundDocument()) {\n docVersion = doc.version;\n } else if (doc.isNoDocument()) {\n // Represent a deleted doc using SnapshotVersion.min().\n docVersion = SnapshotVersion.min();\n } else {\n throw fail(0xc542, 'Document in a transaction was a ', {\n documentName: doc.constructor.name\n });\n }\n\n const existingVersion = this.readVersions.get(doc.key.toString());\n if (existingVersion) {\n if (!docVersion.isEqual(existingVersion)) {\n // This transaction will fail no matter what.\n throw new FirestoreError(\n Code.ABORTED,\n 'Document version changed between two reads.'\n );\n }\n } else {\n this.readVersions.set(doc.key.toString(), docVersion);\n }\n }\n\n /**\n * Returns the version of this document when it was read in this transaction,\n * as a precondition, or no precondition if it was not read.\n */\n private precondition(key: DocumentKey): Precondition {\n const version = this.readVersions.get(key.toString());\n if (!this.writtenDocs.has(key.toString()) && version) {\n if (version.isEqual(SnapshotVersion.min())) {\n return Precondition.exists(false);\n } else {\n return Precondition.updateTime(version);\n }\n } else {\n return Precondition.none();\n }\n }\n\n /**\n * Returns the precondition for a document if the operation is an update.\n */\n private preconditionForUpdate(key: DocumentKey): Precondition {\n const version = this.readVersions.get(key.toString());\n // The first time a document is written, we want to take into account the\n // read time and existence\n if (!this.writtenDocs.has(key.toString()) && version) {\n if (version.isEqual(SnapshotVersion.min())) {\n // The document doesn't exist, so fail the transaction.\n\n // This has to be validated locally because you can't send a\n // precondition that a document does not exist without changing the\n // semantics of the backend write to be an insert. This is the reverse\n // of what we want, since we want to assert that the document doesn't\n // exist but then send the update and have it fail. Since we can't\n // express that to the backend, we have to validate locally.\n\n // Note: this can change once we can send separate verify writes in the\n // transaction.\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n \"Can't update a document that doesn't exist.\"\n );\n }\n // Document exists, base precondition on document update time.\n return Precondition.updateTime(version);\n } else {\n // Document was not read, so we just use the preconditions for a blind\n // update.\n return Precondition.exists(true);\n }\n }\n\n private write(mutation: Mutation): void {\n this.ensureCommitNotCalled();\n this.mutations.push(mutation);\n }\n\n private ensureCommitNotCalled(): void {\n debugAssert(\n !this.committed,\n 'A transaction object cannot be used after its update callback has been invoked.'\n );\n }\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Code, FirestoreError } from '../util/error';\n\nexport const DEFAULT_TRANSACTION_OPTIONS: TransactionOptions = {\n maxAttempts: 5\n};\n\n/**\n * Options to customize transaction behavior.\n */\nexport declare interface TransactionOptions {\n /** Maximum number of attempts to commit, after which transaction fails. Default is 5. */\n readonly maxAttempts: number;\n}\n\nexport function validateTransactionOptions(options: TransactionOptions): void {\n if (options.maxAttempts < 1) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Max attempts must be at least 1'\n );\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ExponentialBackoff } from '../remote/backoff';\nimport { Datastore } from '../remote/datastore';\nimport { isPermanentError } from '../remote/rpc_error';\nimport { AsyncQueue, TimerId } from '../util/async_queue';\nimport { FirestoreError } from '../util/error';\nimport { Deferred } from '../util/promise';\nimport { isNullOrUndefined } from '../util/types';\n\nimport { Transaction } from './transaction';\nimport { TransactionOptions } from './transaction_options';\n\n/**\n * TransactionRunner encapsulates the logic needed to run and retry transactions\n * with backoff.\n */\nexport class TransactionRunner {\n private attemptsRemaining: number;\n private backoff: ExponentialBackoff;\n\n constructor(\n private readonly asyncQueue: AsyncQueue,\n private readonly datastore: Datastore,\n private readonly options: TransactionOptions,\n private readonly updateFunction: (transaction: Transaction) => Promise,\n private readonly deferred: Deferred\n ) {\n this.attemptsRemaining = options.maxAttempts;\n this.backoff = new ExponentialBackoff(\n this.asyncQueue,\n TimerId.TransactionRetry\n );\n }\n\n /** Runs the transaction and sets the result on deferred. */\n run(): void {\n this.attemptsRemaining -= 1;\n this.runWithBackOff();\n }\n\n private runWithBackOff(): void {\n this.backoff.backoffAndRun(async () => {\n const transaction = new Transaction(this.datastore);\n const userPromise = this.tryRunUpdateFunction(transaction);\n if (userPromise) {\n userPromise\n .then(result => {\n this.asyncQueue.enqueueAndForget(() => {\n return transaction\n .commit()\n .then(() => {\n this.deferred.resolve(result);\n })\n .catch(commitError => {\n this.handleTransactionError(commitError);\n });\n });\n })\n .catch(userPromiseError => {\n this.handleTransactionError(userPromiseError);\n });\n }\n });\n }\n\n private tryRunUpdateFunction(transaction: Transaction): Promise | null {\n try {\n const userPromise = this.updateFunction(transaction);\n if (\n isNullOrUndefined(userPromise) ||\n !userPromise.catch ||\n !userPromise.then\n ) {\n this.deferred.reject(\n Error('Transaction callback must return a Promise')\n );\n return null;\n }\n return userPromise;\n } catch (error) {\n // Do not retry errors thrown by user provided updateFunction.\n this.deferred.reject(error as Error);\n return null;\n }\n }\n\n private handleTransactionError(error: Error): void {\n if (this.attemptsRemaining > 0 && this.isRetryableTransactionError(error)) {\n this.attemptsRemaining -= 1;\n this.asyncQueue.enqueueAndForget(() => {\n this.runWithBackOff();\n return Promise.resolve();\n });\n } else {\n this.deferred.reject(error);\n }\n }\n\n private isRetryableTransactionError(error: Error | undefined): boolean {\n if (error?.name === 'FirebaseError') {\n // In transactions, the backend will fail outdated reads with FAILED_PRECONDITION and\n // non-matching document versions with ABORTED. These errors should be retried.\n const code = (error as FirestoreError).code;\n return (\n code === 'aborted' ||\n code === 'failed-precondition' ||\n code === 'already-exists' ||\n !isPermanentError(code)\n );\n }\n return false;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** The Platform's 'window' implementation or null if not available. */\nexport function getWindow(): Window | null {\n // `window` is not always available, e.g. in ReactNative and WebWorkers.\n // eslint-disable-next-line no-restricted-globals\n return typeof window !== 'undefined' ? window : null;\n}\n\n/** The Platform's 'document' implementation or null if not available. */\nexport function getDocument(): Document | null {\n // `document` is not always available, e.g. in ReactNative and WebWorkers.\n // eslint-disable-next-line no-restricted-globals\n return typeof document !== 'undefined' ? document : null;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isIndexedDbTransactionError } from '../local/simple_db';\n\nimport { Code, FirestoreError } from './error';\nimport { logError } from './log';\nimport { Deferred } from './promise';\n\nconst LOG_TAG = 'AsyncQueue';\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype TimerHandle = any;\n\n/**\n * Wellknown \"timer\" IDs used when scheduling delayed operations on the\n * AsyncQueue. These IDs can then be used from tests to check for the presence\n * of operations or to run them early.\n *\n * The string values are used when encoding these timer IDs in JSON spec tests.\n */\nexport const enum TimerId {\n /** All can be used with runDelayedOperationsEarly() to run all timers. */\n All = 'all',\n\n /**\n * The following 5 timers are used in persistent_stream.ts for the listen and\n * write streams. The \"Idle\" timer is used to close the stream due to\n * inactivity. The \"ConnectionBackoff\" timer is used to restart a stream once\n * the appropriate backoff delay has elapsed. The health check is used to mark\n * a stream healthy if it has not received an error during its initial setup.\n */\n ListenStreamIdle = 'listen_stream_idle',\n ListenStreamConnectionBackoff = 'listen_stream_connection_backoff',\n WriteStreamIdle = 'write_stream_idle',\n WriteStreamConnectionBackoff = 'write_stream_connection_backoff',\n HealthCheckTimeout = 'health_check_timeout',\n\n /**\n * A timer used in online_state_tracker.ts to transition from\n * OnlineState.Unknown to Offline after a set timeout, rather than waiting\n * indefinitely for success or failure.\n */\n OnlineStateTimeout = 'online_state_timeout',\n\n /**\n * A timer used to update the client metadata in IndexedDb, which is used\n * to determine the primary leaseholder.\n */\n ClientMetadataRefresh = 'client_metadata_refresh',\n\n /** A timer used to periodically attempt LRU Garbage collection */\n LruGarbageCollection = 'lru_garbage_collection',\n\n /**\n * A timer used to retry transactions. Since there can be multiple concurrent\n * transactions, multiple of these may be in the queue at a given time.\n */\n TransactionRetry = 'transaction_retry',\n\n /**\n * A timer used to retry operations scheduled via retryable AsyncQueue\n * operations.\n */\n AsyncQueueRetry = 'async_queue_retry',\n\n /**\n * A timer used to periodically attempt index backfill.\n */\n IndexBackfill = 'index_backfill'\n}\n\n/**\n * Represents an operation scheduled to be run in the future on an AsyncQueue.\n *\n * It is created via DelayedOperation.createAndSchedule().\n *\n * Supports cancellation (via cancel()) and early execution (via skipDelay()).\n *\n * Note: We implement `PromiseLike` instead of `Promise`, as the `Promise` type\n * in newer versions of TypeScript defines `finally`, which is not available in\n * IE.\n */\nexport class DelayedOperation implements PromiseLike {\n // handle for use with clearTimeout(), or null if the operation has been\n // executed or canceled already.\n private timerHandle: TimerHandle | null;\n\n private readonly deferred = new Deferred();\n\n private constructor(\n private readonly asyncQueue: AsyncQueue,\n readonly timerId: TimerId,\n readonly targetTimeMs: number,\n private readonly op: () => Promise,\n private readonly removalCallback: (op: DelayedOperation) => void\n ) {\n // It's normal for the deferred promise to be canceled (due to cancellation)\n // and so we attach a dummy catch callback to avoid\n // 'UnhandledPromiseRejectionWarning' log spam.\n this.deferred.promise.catch(err => {});\n }\n\n get promise(): Promise {\n return this.deferred.promise;\n }\n\n /**\n * Creates and returns a DelayedOperation that has been scheduled to be\n * executed on the provided asyncQueue after the provided delayMs.\n *\n * @param asyncQueue - The queue to schedule the operation on.\n * @param id - A Timer ID identifying the type of operation this is.\n * @param delayMs - The delay (ms) before the operation should be scheduled.\n * @param op - The operation to run.\n * @param removalCallback - A callback to be called synchronously once the\n * operation is executed or canceled, notifying the AsyncQueue to remove it\n * from its delayedOperations list.\n * PORTING NOTE: This exists to prevent making removeDelayedOperation() and\n * the DelayedOperation class public.\n */\n static createAndSchedule(\n asyncQueue: AsyncQueue,\n timerId: TimerId,\n delayMs: number,\n op: () => Promise,\n removalCallback: (op: DelayedOperation) => void\n ): DelayedOperation {\n const targetTime = Date.now() + delayMs;\n const delayedOp = new DelayedOperation(\n asyncQueue,\n timerId,\n targetTime,\n op,\n removalCallback\n );\n delayedOp.start(delayMs);\n return delayedOp;\n }\n\n /**\n * Starts the timer. This is called immediately after construction by\n * createAndSchedule().\n */\n private start(delayMs: number): void {\n this.timerHandle = setTimeout(() => this.handleDelayElapsed(), delayMs);\n }\n\n /**\n * Queues the operation to run immediately (if it hasn't already been run or\n * canceled).\n */\n skipDelay(): void {\n return this.handleDelayElapsed();\n }\n\n /**\n * Cancels the operation if it hasn't already been executed or canceled. The\n * promise will be rejected.\n *\n * As long as the operation has not yet been run, calling cancel() provides a\n * guarantee that the operation will not be run.\n */\n cancel(reason?: string): void {\n if (this.timerHandle !== null) {\n this.clearTimeout();\n this.deferred.reject(\n new FirestoreError(\n Code.CANCELLED,\n 'Operation cancelled' + (reason ? ': ' + reason : '')\n )\n );\n }\n }\n\n then = this.deferred.promise.then.bind(this.deferred.promise);\n\n private handleDelayElapsed(): void {\n this.asyncQueue.enqueueAndForget(() => {\n if (this.timerHandle !== null) {\n this.clearTimeout();\n return this.op().then(result => {\n return this.deferred.resolve(result);\n });\n } else {\n return Promise.resolve();\n }\n });\n }\n\n private clearTimeout(): void {\n if (this.timerHandle !== null) {\n this.removalCallback(this);\n clearTimeout(this.timerHandle);\n this.timerHandle = null;\n }\n }\n}\n\nexport interface AsyncQueue {\n // Is this AsyncQueue being shut down? If true, this instance will not enqueue\n // any new operations, Promises from enqueue requests will not resolve.\n readonly isShuttingDown: boolean;\n\n /**\n * Adds a new operation to the queue without waiting for it to complete (i.e.\n * we ignore the Promise result).\n */\n enqueueAndForget(op: () => Promise): void;\n\n /**\n * Regardless if the queue has initialized shutdown, adds a new operation to the\n * queue without waiting for it to complete (i.e. we ignore the Promise result).\n */\n enqueueAndForgetEvenWhileRestricted(\n op: () => Promise\n ): void;\n\n /**\n * Initialize the shutdown of this queue. Once this method is called, the\n * only possible way to request running an operation is through\n * `enqueueEvenWhileRestricted()`.\n *\n * @param purgeExistingTasks Whether already enqueued tasked should be\n * rejected (unless enqueued with `enqueueEvenWhileRestricted()`). Defaults\n * to false.\n */\n enterRestrictedMode(purgeExistingTasks?: boolean): void;\n\n /**\n * Adds a new operation to the queue. Returns a promise that will be resolved\n * when the promise returned by the new operation is (with its value).\n */\n enqueue(op: () => Promise): Promise;\n\n /**\n * Enqueue a retryable operation.\n *\n * A retryable operation is rescheduled with backoff if it fails with a\n * IndexedDbTransactionError (the error type used by SimpleDb). All\n * retryable operations are executed in order and only run if all prior\n * operations were retried successfully.\n */\n enqueueRetryable(op: () => Promise): void;\n\n /**\n * Schedules an operation to be queued on the AsyncQueue once the specified\n * `delayMs` has elapsed. The returned DelayedOperation can be used to cancel\n * or fast-forward the operation prior to its running.\n */\n enqueueAfterDelay(\n timerId: TimerId,\n delayMs: number,\n op: () => Promise\n ): DelayedOperation;\n\n /**\n * Verifies there's an operation currently in-progress on the AsyncQueue.\n * Unfortunately we can't verify that the running code is in the promise chain\n * of that operation, so this isn't a foolproof check, but it should be enough\n * to catch some bugs.\n */\n verifyOperationInProgress(): void;\n}\n\n/**\n * Returns a FirestoreError that can be surfaced to the user if the provided\n * error is an IndexedDbTransactionError. Re-throws the error otherwise.\n */\nexport function wrapInUserErrorIfRecoverable(\n e: Error,\n msg: string\n): FirestoreError {\n logError(LOG_TAG, `${msg}: ${e}`);\n if (isIndexedDbTransactionError(e)) {\n return new FirestoreError(Code.UNAVAILABLE, `${msg}: ${e}`);\n } else {\n throw e;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isIndexedDbTransactionError } from '../local/simple_db';\nimport { getDocument } from '../platform/dom';\nimport { ExponentialBackoff } from '../remote/backoff';\n\nimport { debugAssert, fail } from './assert';\nimport { AsyncQueue, DelayedOperation, TimerId } from './async_queue';\nimport { FirestoreError } from './error';\nimport { logDebug, logError } from './log';\nimport { Deferred } from './promise';\n\nconst LOG_TAG = 'AsyncQueue';\n\nexport class AsyncQueueImpl implements AsyncQueue {\n // The last promise in the queue.\n private tail: Promise;\n\n // A list of retryable operations. Retryable operations are run in order and\n // retried with backoff.\n private retryableOps: Array<() => Promise> = [];\n\n // Is this AsyncQueue being shut down? Once it is set to true, it will not\n // be changed again.\n private _isShuttingDown: boolean = false;\n\n // Operations scheduled to be queued in the future. Operations are\n // automatically removed after they are run or canceled.\n private delayedOperations: Array> = [];\n\n // visible for testing\n failure: FirestoreError | null = null;\n\n // Flag set while there's an outstanding AsyncQueue operation, used for\n // assertion sanity-checks.\n private operationInProgress = false;\n\n // Enabled during shutdown on Safari to prevent future access to IndexedDB.\n private skipNonRestrictedTasks = false;\n\n // List of TimerIds to fast-forward delays for.\n private timerIdsToSkip: TimerId[] = [];\n\n // Backoff timer used to schedule retries for retryable operations\n private backoff = new ExponentialBackoff(this, TimerId.AsyncQueueRetry);\n\n // Visibility handler that triggers an immediate retry of all retryable\n // operations. Meant to speed up recovery when we regain file system access\n // after page comes into foreground.\n private visibilityHandler: () => void = () => {\n const document = getDocument();\n if (document) {\n logDebug(\n LOG_TAG,\n 'Visibility state changed to ' + document.visibilityState\n );\n }\n this.backoff.skipBackoff();\n };\n\n constructor(tail: Promise = Promise.resolve()) {\n this.tail = tail;\n const document = getDocument();\n if (document && typeof document.addEventListener === 'function') {\n document.addEventListener('visibilitychange', this.visibilityHandler);\n }\n }\n\n get isShuttingDown(): boolean {\n return this._isShuttingDown;\n }\n\n /**\n * Adds a new operation to the queue without waiting for it to complete (i.e.\n * we ignore the Promise result).\n */\n enqueueAndForget(op: () => Promise): void {\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.enqueue(op);\n }\n\n enqueueAndForgetEvenWhileRestricted(\n op: () => Promise\n ): void {\n this.verifyNotFailed();\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.enqueueInternal(op);\n }\n\n enterRestrictedMode(purgeExistingTasks?: boolean): void {\n if (!this._isShuttingDown) {\n this._isShuttingDown = true;\n this.skipNonRestrictedTasks = purgeExistingTasks || false;\n const document = getDocument();\n if (document && typeof document.removeEventListener === 'function') {\n document.removeEventListener(\n 'visibilitychange',\n this.visibilityHandler\n );\n }\n }\n }\n\n enqueue(op: () => Promise): Promise {\n this.verifyNotFailed();\n if (this._isShuttingDown) {\n // Return a Promise which never resolves.\n return new Promise(() => {});\n }\n\n // Create a deferred Promise that we can return to the callee. This\n // allows us to return a \"hanging Promise\" only to the callee and still\n // advance the queue even when the operation is not run.\n const task = new Deferred();\n return this.enqueueInternal(() => {\n if (this._isShuttingDown && this.skipNonRestrictedTasks) {\n // We do not resolve 'task'\n return Promise.resolve();\n }\n\n op().then(task.resolve, task.reject);\n return task.promise;\n }).then(() => task.promise);\n }\n\n enqueueRetryable(op: () => Promise): void {\n this.enqueueAndForget(() => {\n this.retryableOps.push(op);\n return this.retryNextOp();\n });\n }\n\n /**\n * Runs the next operation from the retryable queue. If the operation fails,\n * reschedules with backoff.\n */\n private async retryNextOp(): Promise {\n if (this.retryableOps.length === 0) {\n return;\n }\n\n try {\n await this.retryableOps[0]();\n this.retryableOps.shift();\n this.backoff.reset();\n } catch (e) {\n if (isIndexedDbTransactionError(e as Error)) {\n logDebug(LOG_TAG, 'Operation failed with retryable error: ' + e);\n } else {\n throw e; // Failure will be handled by AsyncQueue\n }\n }\n\n if (this.retryableOps.length > 0) {\n // If there are additional operations, we re-schedule `retryNextOp()`.\n // This is necessary to run retryable operations that failed during\n // their initial attempt since we don't know whether they are already\n // enqueued. If, for example, `op1`, `op2`, `op3` are enqueued and `op1`\n // needs to be re-run, we will run `op1`, `op1`, `op2` using the\n // already enqueued calls to `retryNextOp()`. `op3()` will then run in the\n // call scheduled here.\n // Since `backoffAndRun()` cancels an existing backoff and schedules a\n // new backoff on every call, there is only ever a single additional\n // operation in the queue.\n this.backoff.backoffAndRun(() => this.retryNextOp());\n }\n }\n\n private enqueueInternal(op: () => Promise): Promise {\n const newTail = this.tail.then(() => {\n this.operationInProgress = true;\n return op()\n .catch((error: FirestoreError) => {\n this.failure = error;\n this.operationInProgress = false;\n const message = getMessageOrStack(error);\n logError('INTERNAL UNHANDLED ERROR: ', message);\n\n // Re-throw the error so that this.tail becomes a rejected Promise and\n // all further attempts to chain (via .then) will just short-circuit\n // and return the rejected Promise.\n throw error;\n })\n .then(result => {\n this.operationInProgress = false;\n return result;\n });\n });\n this.tail = newTail;\n return newTail;\n }\n\n enqueueAfterDelay(\n timerId: TimerId,\n delayMs: number,\n op: () => Promise\n ): DelayedOperation {\n this.verifyNotFailed();\n\n debugAssert(\n delayMs >= 0,\n `Attempted to schedule an operation with a negative delay of ${delayMs}`\n );\n\n // Fast-forward delays for timerIds that have been overridden.\n if (this.timerIdsToSkip.indexOf(timerId) > -1) {\n delayMs = 0;\n }\n\n const delayedOp = DelayedOperation.createAndSchedule(\n this,\n timerId,\n delayMs,\n op,\n removedOp =>\n this.removeDelayedOperation(removedOp as DelayedOperation)\n );\n this.delayedOperations.push(delayedOp as DelayedOperation);\n return delayedOp;\n }\n\n private verifyNotFailed(): void {\n if (this.failure) {\n fail(0xb815, 'AsyncQueue is already failed', {\n messageOrStack: getMessageOrStack(this.failure)\n });\n }\n }\n\n verifyOperationInProgress(): void {\n debugAssert(\n this.operationInProgress,\n 'verifyOpInProgress() called when no op in progress on this queue.'\n );\n }\n\n /**\n * Waits until all currently queued tasks are finished executing. Delayed\n * operations are not run.\n */\n async drain(): Promise {\n // Operations in the queue prior to draining may have enqueued additional\n // operations. Keep draining the queue until the tail is no longer advanced,\n // which indicates that no more new operations were enqueued and that all\n // operations were executed.\n let currentTail: Promise;\n do {\n currentTail = this.tail;\n await currentTail;\n } while (currentTail !== this.tail);\n }\n\n /**\n * For Tests: Determine if a delayed operation with a particular TimerId\n * exists.\n */\n containsDelayedOperation(timerId: TimerId): boolean {\n for (const op of this.delayedOperations) {\n if (op.timerId === timerId) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * For Tests: Runs some or all delayed operations early.\n *\n * @param lastTimerId - Delayed operations up to and including this TimerId\n * will be drained. Pass TimerId.All to run all delayed operations.\n * @returns a Promise that resolves once all operations have been run.\n */\n runAllDelayedOperationsUntil(lastTimerId: TimerId): Promise {\n // Note that draining may generate more delayed ops, so we do that first.\n return this.drain().then(() => {\n // Run ops in the same order they'd run if they ran naturally.\n /* eslint-disable-next-line @typescript-eslint/no-floating-promises */\n this.delayedOperations.sort((a, b) => a.targetTimeMs - b.targetTimeMs);\n\n for (const op of this.delayedOperations) {\n op.skipDelay();\n if (lastTimerId !== TimerId.All && op.timerId === lastTimerId) {\n break;\n }\n }\n\n return this.drain();\n });\n }\n\n /**\n * For Tests: Skip all subsequent delays for a timer id.\n */\n skipDelaysForTimerId(timerId: TimerId): void {\n this.timerIdsToSkip.push(timerId);\n }\n\n /** Called once a DelayedOperation is run or canceled. */\n private removeDelayedOperation(op: DelayedOperation): void {\n // NOTE: indexOf / slice are O(n), but delayedOperations is expected to be small.\n const index = this.delayedOperations.indexOf(op);\n debugAssert(index >= 0, 'Delayed operation not found.');\n /* eslint-disable-next-line @typescript-eslint/no-floating-promises */\n this.delayedOperations.splice(index, 1);\n }\n}\n\nexport function newAsyncQueue(): AsyncQueue {\n return new AsyncQueueImpl();\n}\n\n/**\n * Chrome includes Error.message in Error.stack. Other browsers do not.\n * This returns expected output of message + stack when available.\n * @param error - Error or FirestoreError\n */\nfunction getMessageOrStack(error: Error): string {\n let message = error.message || '';\n if (error.stack) {\n if (error.stack.includes(error.message)) {\n message = error.stack;\n } else {\n message = error.message + '\\n' + error.stack;\n }\n }\n return message;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getGlobal, getUA, isIndexedDBAvailable } from '@firebase/util';\n\nimport { debugAssert } from '../util/assert';\nimport { Code, FirestoreError } from '../util/error';\nimport { logDebug, logError } from '../util/log';\nimport { Deferred } from '../util/promise';\n\nimport { PersistencePromise } from './persistence_promise';\n\n// References to `indexedDB` are guarded by SimpleDb.isAvailable() and getGlobal()\n/* eslint-disable no-restricted-globals */\n\nconst LOG_TAG = 'SimpleDb';\n\n/**\n * The maximum number of retry attempts for an IndexedDb transaction that fails\n * with a DOMException.\n */\nconst TRANSACTION_RETRY_COUNT = 3;\n\n// The different modes supported by `SimpleDb.runTransaction()`\ntype SimpleDbTransactionMode = 'readonly' | 'readwrite';\n\nexport interface SimpleDbSchemaConverter {\n createOrUpgrade(\n db: IDBDatabase,\n txn: IDBTransaction,\n fromVersion: number,\n toVersion: number\n ): PersistencePromise;\n}\n\n/**\n * Wraps an IDBTransaction and exposes a store() method to get a handle to a\n * specific object store.\n */\nexport class SimpleDbTransaction {\n private aborted = false;\n\n /**\n * A `Promise` that resolves with the result of the IndexedDb transaction.\n */\n private readonly completionDeferred = new Deferred();\n\n static open(\n db: IDBDatabase,\n action: string,\n mode: IDBTransactionMode,\n objectStoreNames: string[]\n ): SimpleDbTransaction {\n try {\n return new SimpleDbTransaction(\n action,\n db.transaction(objectStoreNames, mode)\n );\n } catch (e) {\n throw new IndexedDbTransactionError(action, e as Error);\n }\n }\n\n constructor(\n private readonly action: string,\n private readonly transaction: IDBTransaction\n ) {\n this.transaction.oncomplete = () => {\n this.completionDeferred.resolve();\n };\n this.transaction.onabort = () => {\n if (transaction.error) {\n this.completionDeferred.reject(\n new IndexedDbTransactionError(action, transaction.error)\n );\n } else {\n this.completionDeferred.resolve();\n }\n };\n this.transaction.onerror = (event: Event) => {\n const error = checkForAndReportiOSError(\n (event.target as IDBRequest).error!\n );\n this.completionDeferred.reject(\n new IndexedDbTransactionError(action, error)\n );\n };\n }\n\n get completionPromise(): Promise {\n return this.completionDeferred.promise;\n }\n\n abort(error?: Error): void {\n if (error) {\n this.completionDeferred.reject(error);\n }\n\n if (!this.aborted) {\n logDebug(\n LOG_TAG,\n 'Aborting transaction:',\n error ? error.message : 'Client-initiated abort'\n );\n this.aborted = true;\n this.transaction.abort();\n }\n }\n\n maybeCommit(): void {\n // If the browser supports V3 IndexedDB, we invoke commit() explicitly to\n // speed up index DB processing if the event loop remains blocks.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const maybeV3IndexedDb = this.transaction as any;\n if (!this.aborted && typeof maybeV3IndexedDb.commit === 'function') {\n maybeV3IndexedDb.commit();\n }\n }\n\n /**\n * Returns a SimpleDbStore for the specified store. All\n * operations performed on the SimpleDbStore happen within the context of this\n * transaction and it cannot be used anymore once the transaction is\n * completed.\n *\n * Note that we can't actually enforce that the KeyType and ValueType are\n * correct, but they allow type safety through the rest of the consuming code.\n */\n store(\n storeName: string\n ): SimpleDbStore {\n const store = this.transaction.objectStore(storeName);\n debugAssert(!!store, 'Object store not part of transaction: ' + storeName);\n return new SimpleDbStore(store);\n }\n}\n\n/**\n * Provides a wrapper around IndexedDb with a simplified interface that uses\n * Promise-like return values to chain operations. Real promises cannot be used\n * since .then() continuations are executed asynchronously (e.g. via\n * .setImmediate), which would cause IndexedDB to end the transaction.\n * See PersistencePromise for more details.\n */\nexport class SimpleDb {\n private db?: IDBDatabase;\n private lastClosedDbVersion: number | null = null;\n private versionchangelistener?: (event: IDBVersionChangeEvent) => void;\n\n /** Deletes the specified database. */\n static delete(name: string): Promise {\n logDebug(LOG_TAG, 'Removing database:', name);\n const globals = getGlobal();\n return wrapRequest(\n globals.indexedDB.deleteDatabase(name)\n ).toPromise();\n }\n\n /** Returns true if IndexedDB is available in the current environment. */\n static isAvailable(): boolean {\n if (!isIndexedDBAvailable()) {\n return false;\n }\n\n if (SimpleDb.isMockPersistence()) {\n return true;\n }\n\n // We extensively use indexed array values and compound keys,\n // which IE and Edge do not support. However, they still have indexedDB\n // defined on the window, so we need to check for them here and make sure\n // to return that persistence is not enabled for those browsers.\n // For tracking support of this feature, see here:\n // https://developer.microsoft.com/en-us/microsoft-edge/platform/status/indexeddbarraysandmultientrysupport/\n\n // Check the UA string to find out the browser.\n const ua = getUA();\n\n // IE 10\n // ua = 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)';\n\n // IE 11\n // ua = 'Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko';\n\n // Edge\n // ua = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML,\n // like Gecko) Chrome/39.0.2171.71 Safari/537.36 Edge/12.0';\n\n // iOS Safari: Disable for users running iOS version < 10.\n const iOSVersion = SimpleDb.getIOSVersion(ua);\n const isUnsupportedIOS = 0 < iOSVersion && iOSVersion < 10;\n\n // Android browser: Disable for users running version < 4.5.\n const androidVersion = getAndroidVersion(ua);\n const isUnsupportedAndroid = 0 < androidVersion && androidVersion < 4.5;\n\n if (\n ua.indexOf('MSIE ') > 0 ||\n ua.indexOf('Trident/') > 0 ||\n ua.indexOf('Edge/') > 0 ||\n isUnsupportedIOS ||\n isUnsupportedAndroid\n ) {\n return false;\n } else {\n return true;\n }\n }\n\n /**\n * Returns true if the backing IndexedDB store is the Node IndexedDBShim\n * (see https://github.com/axemclion/IndexedDBShim).\n */\n static isMockPersistence(): boolean {\n return (\n typeof process !== 'undefined' &&\n process.env?.USE_MOCK_PERSISTENCE === 'YES'\n );\n }\n\n /** Helper to get a typed SimpleDbStore from a transaction. */\n static getStore(\n txn: SimpleDbTransaction,\n store: string\n ): SimpleDbStore {\n return txn.store(store);\n }\n\n // visible for testing\n /** Parse User Agent to determine iOS version. Returns -1 if not found. */\n static getIOSVersion(ua: string): number {\n const iOSVersionRegex = ua.match(/i(?:phone|pad|pod) os ([\\d_]+)/i);\n const version = iOSVersionRegex\n ? iOSVersionRegex[1].split('_').slice(0, 2).join('.')\n : '-1';\n return Number(version);\n }\n\n /*\n * Creates a new SimpleDb wrapper for IndexedDb database `name`.\n *\n * Note that `version` must not be a downgrade. IndexedDB does not support\n * downgrading the schema version. We currently do not support any way to do\n * versioning outside of IndexedDB's versioning mechanism, as only\n * version-upgrade transactions are allowed to do things like create\n * objectstores.\n */\n constructor(\n private readonly name: string,\n private readonly version: number,\n private readonly schemaConverter: SimpleDbSchemaConverter\n ) {\n debugAssert(\n SimpleDb.isAvailable(),\n 'IndexedDB not supported in current environment.'\n );\n\n const iOSVersion = SimpleDb.getIOSVersion(getUA());\n // NOTE: According to https://bugs.webkit.org/show_bug.cgi?id=197050, the\n // bug we're checking for should exist in iOS >= 12.2 and < 13, but for\n // whatever reason it's much harder to hit after 12.2 so we only proactively\n // log on 12.2.\n if (iOSVersion === 12.2) {\n logError(\n 'Firestore persistence suffers from a bug in iOS 12.2 ' +\n 'Safari that may cause your app to stop working. See ' +\n 'https://stackoverflow.com/q/56496296/110915 for details ' +\n 'and a potential workaround.'\n );\n }\n }\n\n /**\n * Opens the specified database, creating or upgrading it if necessary.\n */\n async ensureDb(action: string): Promise {\n if (!this.db) {\n logDebug(LOG_TAG, 'Opening database:', this.name);\n this.db = await new Promise((resolve, reject) => {\n // TODO(mikelehen): Investigate browser compatibility.\n // https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API/Using_IndexedDB\n // suggests IE9 and older WebKit browsers handle upgrade\n // differently. They expect setVersion, as described here:\n // https://developer.mozilla.org/en-US/docs/Web/API/IDBVersionChangeRequest/setVersion\n const request = indexedDB.open(this.name, this.version);\n\n request.onsuccess = (event: Event) => {\n const db = (event.target as IDBOpenDBRequest).result;\n resolve(db);\n };\n\n request.onblocked = () => {\n reject(\n new IndexedDbTransactionError(\n action,\n 'Cannot upgrade IndexedDB schema while another tab is open. ' +\n 'Close all tabs that access Firestore and reload this page to proceed.'\n )\n );\n };\n\n request.onerror = (event: Event) => {\n const error: DOMException = (event.target as IDBOpenDBRequest).error!;\n if (error.name === 'VersionError') {\n reject(\n new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'A newer version of the Firestore SDK was previously used and so the persisted ' +\n 'data is not compatible with the version of the SDK you are now using. The SDK ' +\n 'will operate with persistence disabled. If you need persistence, please ' +\n 're-upgrade to a newer version of the SDK or else clear the persisted IndexedDB ' +\n 'data for your app to start fresh.'\n )\n );\n } else if (error.name === 'InvalidStateError') {\n reject(\n new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'Unable to open an IndexedDB connection. This could be due to running in a ' +\n 'private browsing session on a browser whose private browsing sessions do not ' +\n 'support IndexedDB: ' +\n error\n )\n );\n } else {\n reject(new IndexedDbTransactionError(action, error));\n }\n };\n\n request.onupgradeneeded = (event: IDBVersionChangeEvent) => {\n logDebug(\n LOG_TAG,\n 'Database \"' + this.name + '\" requires upgrade from version:',\n event.oldVersion\n );\n const db = (event.target as IDBOpenDBRequest).result;\n this.schemaConverter\n .createOrUpgrade(\n db,\n request.transaction!,\n event.oldVersion,\n this.version\n )\n .next(() => {\n logDebug(\n LOG_TAG,\n 'Database upgrade to version ' + this.version + ' complete'\n );\n });\n };\n });\n }\n\n if (this.versionchangelistener) {\n this.db.onversionchange = event => this.versionchangelistener!(event);\n }\n\n return this.db;\n }\n\n setVersionChangeListener(\n versionChangeListener: (event: IDBVersionChangeEvent) => void\n ): void {\n this.versionchangelistener = versionChangeListener;\n if (this.db) {\n this.db.onversionchange = (event: IDBVersionChangeEvent) => {\n return versionChangeListener(event);\n };\n }\n }\n\n async runTransaction(\n action: string,\n mode: SimpleDbTransactionMode,\n objectStores: string[],\n transactionFn: (transaction: SimpleDbTransaction) => PersistencePromise\n ): Promise {\n const readonly = mode === 'readonly';\n let attemptNumber = 0;\n\n while (true) {\n ++attemptNumber;\n\n try {\n this.db = await this.ensureDb(action);\n\n const transaction = SimpleDbTransaction.open(\n this.db,\n action,\n readonly ? 'readonly' : 'readwrite',\n objectStores\n );\n const transactionFnResult = transactionFn(transaction)\n .next(result => {\n transaction.maybeCommit();\n return result;\n })\n .catch(error => {\n // Abort the transaction if there was an error.\n transaction.abort(error);\n // We cannot actually recover, and calling `abort()` will cause the transaction's\n // completion promise to be rejected. This in turn means that we won't use\n // `transactionFnResult` below. We return a rejection here so that we don't add the\n // possibility of returning `void` to the type of `transactionFnResult`.\n return PersistencePromise.reject(error);\n })\n .toPromise();\n\n // As noted above, errors are propagated by aborting the transaction. So\n // we swallow any error here to avoid the browser logging it as unhandled.\n transactionFnResult.catch(() => {});\n\n // Wait for the transaction to complete (i.e. IndexedDb's onsuccess event to\n // fire), but still return the original transactionFnResult back to the\n // caller.\n await transaction.completionPromise;\n return transactionFnResult;\n } catch (e) {\n const error = e as Error;\n // TODO(schmidt-sebastian): We could probably be smarter about this and\n // not retry exceptions that are likely unrecoverable (such as quota\n // exceeded errors).\n\n // Note: We cannot use an instanceof check for FirestoreException, since the\n // exception is wrapped in a generic error by our async/await handling.\n const retryable =\n error.name !== 'FirebaseError' &&\n attemptNumber < TRANSACTION_RETRY_COUNT;\n logDebug(\n LOG_TAG,\n 'Transaction failed with error:',\n error.message,\n 'Retrying:',\n retryable\n );\n\n this.close();\n\n if (!retryable) {\n return Promise.reject(error);\n }\n }\n }\n }\n\n close(): void {\n if (this.db) {\n this.db.close();\n }\n this.db = undefined;\n }\n}\n\n/** Parse User Agent to determine Android version. Returns -1 if not found. */\nexport function getAndroidVersion(ua: string): number {\n const androidVersionRegex = ua.match(/Android ([\\d.]+)/i);\n const version = androidVersionRegex\n ? androidVersionRegex[1].split('.').slice(0, 2).join('.')\n : '-1';\n return Number(version);\n}\n\n/**\n * A controller for iterating over a key range or index. It allows an iterate\n * callback to delete the currently-referenced object, or jump to a new key\n * within the key range or index.\n */\nexport class IterationController {\n private shouldStop = false;\n private nextKey: IDBValidKey | null = null;\n\n constructor(private dbCursor: IDBCursorWithValue) {}\n\n get isDone(): boolean {\n return this.shouldStop;\n }\n\n get skipToKey(): IDBValidKey | null {\n return this.nextKey;\n }\n\n set cursor(value: IDBCursorWithValue) {\n this.dbCursor = value;\n }\n\n /**\n * This function can be called to stop iteration at any point.\n */\n done(): void {\n this.shouldStop = true;\n }\n\n /**\n * This function can be called to skip to that next key, which could be\n * an index or a primary key.\n */\n skip(key: IDBValidKey): void {\n this.nextKey = key;\n }\n\n /**\n * Delete the current cursor value from the object store.\n *\n * NOTE: You CANNOT do this with a keysOnly query.\n */\n delete(): PersistencePromise {\n return wrapRequest(this.dbCursor.delete());\n }\n}\n\n/**\n * Callback used with iterate() method.\n */\nexport type IterateCallback = (\n key: KeyType,\n value: ValueType,\n control: IterationController\n) => void | PersistencePromise;\n\n/** Options available to the iterate() method. */\nexport interface IterateOptions {\n /** Index to iterate over (else primary keys will be iterated) */\n index?: string;\n\n /** IndexedDB Range to iterate over (else entire store will be iterated) */\n range?: IDBKeyRange;\n\n /** If true, values aren't read while iterating. */\n keysOnly?: boolean;\n\n /** If true, iterate over the store in reverse. */\n reverse?: boolean;\n}\n\n/** An error that wraps exceptions that thrown during IndexedDB execution. */\nexport class IndexedDbTransactionError extends FirestoreError {\n name = 'IndexedDbTransactionError';\n\n constructor(actionName: string, cause: Error | string) {\n super(\n Code.UNAVAILABLE,\n `IndexedDB transaction '${actionName}' failed: ${cause}`\n );\n }\n}\n\n/** Verifies whether `e` is an IndexedDbTransactionError. */\nexport function isIndexedDbTransactionError(e: Error): boolean {\n // Use name equality, as instanceof checks on errors don't work with errors\n // that wrap other errors.\n return e.name === 'IndexedDbTransactionError';\n}\n\n/**\n * A wrapper around an IDBObjectStore providing an API that:\n *\n * 1) Has generic KeyType / ValueType parameters to provide strongly-typed\n * methods for acting against the object store.\n * 2) Deals with IndexedDB's onsuccess / onerror event callbacks, making every\n * method return a PersistencePromise instead.\n * 3) Provides a higher-level API to avoid needing to do excessive wrapping of\n * intermediate IndexedDB types (IDBCursorWithValue, etc.)\n */\nexport class SimpleDbStore<\n KeyType extends IDBValidKey,\n ValueType extends unknown\n> {\n constructor(private store: IDBObjectStore) {}\n\n /**\n * Writes a value into the Object Store.\n *\n * @param key - Optional explicit key to use when writing the object, else the\n * key will be auto-assigned (e.g. via the defined keyPath for the store).\n * @param value - The object to write.\n */\n put(value: ValueType): PersistencePromise;\n put(key: KeyType, value: ValueType): PersistencePromise;\n put(\n keyOrValue: KeyType | ValueType,\n value?: ValueType\n ): PersistencePromise {\n let request;\n if (value !== undefined) {\n logDebug(LOG_TAG, 'PUT', this.store.name, keyOrValue, value);\n request = this.store.put(value, keyOrValue as KeyType);\n } else {\n logDebug(LOG_TAG, 'PUT', this.store.name, '', keyOrValue);\n request = this.store.put(keyOrValue as ValueType);\n }\n return wrapRequest(request);\n }\n\n /**\n * Adds a new value into an Object Store and returns the new key. Similar to\n * IndexedDb's `add()`, this method will fail on primary key collisions.\n *\n * @param value - The object to write.\n * @returns The key of the value to add.\n */\n add(value: ValueType): PersistencePromise {\n logDebug(LOG_TAG, 'ADD', this.store.name, value, value);\n const request = this.store.add(value as ValueType);\n return wrapRequest(request);\n }\n\n /**\n * Gets the object with the specified key from the specified store, or null\n * if no object exists with the specified key.\n *\n * @key The key of the object to get.\n * @returns The object with the specified key or null if no object exists.\n */\n get(key: KeyType): PersistencePromise {\n const request = this.store.get(key);\n // We're doing an unsafe cast to ValueType.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return wrapRequest(request).next(result => {\n // Normalize nonexistence to null.\n if (result === undefined) {\n result = null;\n }\n logDebug(LOG_TAG, 'GET', this.store.name, key, result);\n return result;\n });\n }\n\n delete(key: KeyType | IDBKeyRange): PersistencePromise {\n logDebug(LOG_TAG, 'DELETE', this.store.name, key);\n const request = this.store.delete(key);\n return wrapRequest(request);\n }\n\n /**\n * If we ever need more of the count variants, we can add overloads. For now,\n * all we need is to count everything in a store.\n *\n * Returns the number of rows in the store.\n */\n count(): PersistencePromise {\n logDebug(LOG_TAG, 'COUNT', this.store.name);\n const request = this.store.count();\n return wrapRequest(request);\n }\n\n /** Loads all elements from the object store. */\n loadAll(): PersistencePromise;\n /** Loads all elements for the index range from the object store. */\n loadAll(range: IDBKeyRange): PersistencePromise;\n /** Loads all elements ordered by the given index. */\n loadAll(index: string): PersistencePromise;\n /**\n * Loads all elements from the object store that fall into the provided in the\n * index range for the given index.\n */\n loadAll(index: string, range: IDBKeyRange): PersistencePromise;\n loadAll(\n indexOrRange?: string | IDBKeyRange,\n range?: IDBKeyRange\n ): PersistencePromise {\n const iterateOptions = this.options(indexOrRange, range);\n // Use `getAll()` if the browser supports IndexedDB v3, as it is roughly\n // 20% faster.\n const store = iterateOptions.index\n ? this.store.index(iterateOptions.index)\n : this.store;\n if (typeof store.getAll === 'function') {\n const request = store.getAll(iterateOptions.range);\n return new PersistencePromise((resolve, reject) => {\n request.onerror = (event: Event) => {\n reject((event.target as IDBRequest).error!);\n };\n request.onsuccess = (event: Event) => {\n resolve((event.target as IDBRequest).result);\n };\n });\n } else {\n const cursor = this.cursor(iterateOptions);\n const results: ValueType[] = [];\n return this.iterateCursor(cursor, (key, value) => {\n results.push(value);\n }).next(() => {\n return results;\n });\n }\n }\n\n /**\n * Loads the first `count` elements from the provided index range. Loads all\n * elements if no limit is provided.\n */\n loadFirst(\n range: IDBKeyRange,\n count: number | null\n ): PersistencePromise {\n const request = this.store.getAll(\n range,\n count === null ? undefined : count\n );\n return new PersistencePromise((resolve, reject) => {\n request.onerror = (event: Event) => {\n reject((event.target as IDBRequest).error!);\n };\n request.onsuccess = (event: Event) => {\n resolve((event.target as IDBRequest).result);\n };\n });\n }\n\n deleteAll(): PersistencePromise;\n deleteAll(range: IDBKeyRange): PersistencePromise;\n deleteAll(index: string, range: IDBKeyRange): PersistencePromise;\n deleteAll(\n indexOrRange?: string | IDBKeyRange,\n range?: IDBKeyRange\n ): PersistencePromise {\n logDebug(LOG_TAG, 'DELETE ALL', this.store.name);\n const options = this.options(indexOrRange, range);\n options.keysOnly = false;\n const cursor = this.cursor(options);\n return this.iterateCursor(cursor, (key, value, control) => {\n // NOTE: Calling delete() on a cursor is documented as more efficient than\n // calling delete() on an object store with a single key\n // (https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/delete),\n // however, this requires us *not* to use a keysOnly cursor\n // (https://developer.mozilla.org/en-US/docs/Web/API/IDBCursor/delete). We\n // may want to compare the performance of each method.\n return control.delete();\n });\n }\n\n /**\n * Iterates over keys and values in an object store.\n *\n * @param options - Options specifying how to iterate the objects in the\n * store.\n * @param callback - will be called for each iterated object. Iteration can be\n * canceled at any point by calling the doneFn passed to the callback.\n * The callback can return a PersistencePromise if it performs async\n * operations but note that iteration will continue without waiting for them\n * to complete.\n * @returns A PersistencePromise that resolves once all PersistencePromises\n * returned by callbacks resolve.\n */\n iterate(\n callback: IterateCallback\n ): PersistencePromise;\n iterate(\n options: IterateOptions,\n callback: IterateCallback\n ): PersistencePromise;\n iterate(\n optionsOrCallback: IterateOptions | IterateCallback,\n callback?: IterateCallback\n ): PersistencePromise {\n let options;\n if (!callback) {\n options = {};\n callback = optionsOrCallback as IterateCallback;\n } else {\n options = optionsOrCallback as IterateOptions;\n }\n const cursor = this.cursor(options);\n return this.iterateCursor(cursor, callback);\n }\n\n /**\n * Iterates over a store, but waits for the given callback to complete for\n * each entry before iterating the next entry. This allows the callback to do\n * asynchronous work to determine if this iteration should continue.\n *\n * The provided callback should return `true` to continue iteration, and\n * `false` otherwise.\n */\n iterateSerial(\n callback: (k: KeyType, v: ValueType) => PersistencePromise\n ): PersistencePromise {\n const cursorRequest = this.cursor({});\n return new PersistencePromise((resolve, reject) => {\n cursorRequest.onerror = (event: Event) => {\n const error = checkForAndReportiOSError(\n (event.target as IDBRequest).error!\n );\n reject(error);\n };\n cursorRequest.onsuccess = (event: Event) => {\n const cursor: IDBCursorWithValue = (event.target as IDBRequest).result;\n if (!cursor) {\n resolve();\n return;\n }\n\n callback(cursor.primaryKey as KeyType, cursor.value).next(\n shouldContinue => {\n if (shouldContinue) {\n cursor.continue();\n } else {\n resolve();\n }\n }\n );\n };\n });\n }\n\n private iterateCursor(\n cursorRequest: IDBRequest,\n fn: IterateCallback\n ): PersistencePromise {\n const results: Array> = [];\n return new PersistencePromise((resolve, reject) => {\n cursorRequest.onerror = (event: Event) => {\n reject((event.target as IDBRequest).error!);\n };\n cursorRequest.onsuccess = (event: Event) => {\n const cursor: IDBCursorWithValue = (event.target as IDBRequest).result;\n if (!cursor) {\n resolve();\n return;\n }\n const controller = new IterationController(cursor);\n const userResult = fn(\n cursor.primaryKey as KeyType,\n cursor.value,\n controller\n );\n if (userResult instanceof PersistencePromise) {\n const userPromise: PersistencePromise = userResult.catch(\n err => {\n controller.done();\n return PersistencePromise.reject(err);\n }\n );\n results.push(userPromise);\n }\n if (controller.isDone) {\n resolve();\n } else if (controller.skipToKey === null) {\n cursor.continue();\n } else {\n cursor.continue(controller.skipToKey);\n }\n };\n }).next(() => PersistencePromise.waitFor(results));\n }\n\n private options(\n indexOrRange?: string | IDBKeyRange,\n range?: IDBKeyRange\n ): IterateOptions {\n let indexName: string | undefined = undefined;\n if (indexOrRange !== undefined) {\n if (typeof indexOrRange === 'string') {\n indexName = indexOrRange;\n } else {\n debugAssert(\n range === undefined,\n '3rd argument must not be defined if 2nd is a range.'\n );\n range = indexOrRange;\n }\n }\n return { index: indexName, range };\n }\n\n private cursor(options: IterateOptions): IDBRequest {\n let direction: IDBCursorDirection = 'next';\n if (options.reverse) {\n direction = 'prev';\n }\n if (options.index) {\n const index = this.store.index(options.index);\n if (options.keysOnly) {\n return index.openKeyCursor(options.range, direction);\n } else {\n return index.openCursor(options.range, direction);\n }\n } else {\n return this.store.openCursor(options.range, direction);\n }\n }\n}\n\n/**\n * Wraps an IDBRequest in a PersistencePromise, using the onsuccess / onerror\n * handlers to resolve / reject the PersistencePromise as appropriate.\n */\nfunction wrapRequest(request: IDBRequest): PersistencePromise {\n return new PersistencePromise((resolve, reject) => {\n request.onsuccess = (event: Event) => {\n const result = (event.target as IDBRequest).result;\n resolve(result);\n };\n\n request.onerror = (event: Event) => {\n const error = checkForAndReportiOSError(\n (event.target as IDBRequest).error!\n );\n reject(error);\n };\n });\n}\n\n// Guard so we only report the error once.\nlet reportedIOSError = false;\nfunction checkForAndReportiOSError(error: DOMException): Error {\n const iOSVersion = SimpleDb.getIOSVersion(getUA());\n if (iOSVersion >= 12.2 && iOSVersion < 13) {\n const IOS_ERROR =\n 'An internal error was encountered in the Indexed Database server';\n if (error.message.indexOf(IOS_ERROR) >= 0) {\n // Wrap error in a more descriptive one.\n const newError = new FirestoreError(\n 'internal',\n `IOS_INDEXEDDB_BUG1: IndexedDb has thrown '${IOS_ERROR}'. This is likely ` +\n `due to an unavoidable bug in iOS. See https://stackoverflow.com/q/56496296/110915 ` +\n `for details and a potential workaround.`\n );\n if (!reportedIOSError) {\n reportedIOSError = true;\n // Throw a global exception outside of this promise chain, for the user to\n // potentially catch.\n setTimeout(() => {\n throw newError;\n }, 0);\n }\n return newError;\n }\n }\n return error;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getModularInstance } from '@firebase/util';\n\nimport { Transaction as InternalTransaction } from '../core/transaction';\nimport {\n DEFAULT_TRANSACTION_OPTIONS,\n TransactionOptions as TransactionOptionsInternal,\n validateTransactionOptions\n} from '../core/transaction_options';\nimport { TransactionRunner } from '../core/transaction_runner';\nimport { fail } from '../util/assert';\nimport { newAsyncQueue } from '../util/async_queue_impl';\nimport { cast } from '../util/input_validation';\nimport { Deferred } from '../util/promise';\n\nimport { getDatastore } from './components';\nimport { Firestore } from './database';\nimport { FieldPath } from './field_path';\nimport {\n DocumentData,\n DocumentReference,\n PartialWithFieldValue,\n SetOptions,\n UpdateData,\n WithFieldValue\n} from './reference';\nimport {\n applyFirestoreDataConverter,\n LiteUserDataWriter\n} from './reference_impl';\nimport { DocumentSnapshot } from './snapshot';\nimport { TransactionOptions } from './transaction_options';\nimport {\n newUserDataReader,\n parseSetData,\n parseUpdateData,\n parseUpdateVarargs,\n UserDataReader\n} from './user_data_reader';\nimport { validateReference } from './write_batch';\n\n// TODO(mrschmidt) Consider using `BaseTransaction` as the base class in the\n// legacy SDK.\n\n/**\n * A reference to a transaction.\n *\n * The `Transaction` object passed to a transaction's `updateFunction` provides\n * the methods to read and write data within the transaction context. See\n * {@link runTransaction}.\n */\nexport class Transaction {\n // This is the tree-shakeable version of the Transaction class used in the\n // legacy SDK. The class is a close copy but takes different input and output\n // types. The firestore-exp SDK further extends this class to return its API\n // type.\n\n private readonly _dataReader: UserDataReader;\n\n /** @hideconstructor */\n constructor(\n protected readonly _firestore: Firestore,\n private readonly _transaction: InternalTransaction\n ) {\n this._dataReader = newUserDataReader(_firestore);\n }\n\n /**\n * Reads the document referenced by the provided {@link DocumentReference}.\n *\n * @param documentRef - A reference to the document to be read.\n * @returns A `DocumentSnapshot` with the read data.\n */\n get(\n documentRef: DocumentReference\n ): Promise> {\n const ref = validateReference(documentRef, this._firestore);\n const userDataWriter = new LiteUserDataWriter(this._firestore);\n return this._transaction.lookup([ref._key]).then(docs => {\n if (!docs || docs.length !== 1) {\n return fail(0x5de9, 'Mismatch in docs returned from document lookup.');\n }\n const doc = docs[0];\n if (doc.isFoundDocument()) {\n return new DocumentSnapshot(\n this._firestore,\n userDataWriter,\n doc.key,\n doc,\n ref.converter\n );\n } else if (doc.isNoDocument()) {\n return new DocumentSnapshot(\n this._firestore,\n userDataWriter,\n ref._key,\n null,\n ref.converter\n );\n } else {\n throw fail(\n 0x4801,\n 'BatchGetDocumentsRequest returned unexpected document',\n {\n doc\n }\n );\n }\n });\n }\n\n /**\n * Writes to the document referred to by the provided {@link\n * DocumentReference}. If the document does not exist yet, it will be created.\n *\n * @param documentRef - A reference to the document to be set.\n * @param data - An object of the fields and values for the document.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns This `Transaction` instance. Used for chaining method calls.\n */\n set(\n documentRef: DocumentReference,\n data: WithFieldValue\n ): this;\n /**\n * Writes to the document referred to by the provided {@link\n * DocumentReference}. If the document does not exist yet, it will be created.\n * If you provide `merge` or `mergeFields`, the provided data can be merged\n * into an existing document.\n *\n * @param documentRef - A reference to the document to be set.\n * @param data - An object of the fields and values for the document.\n * @param options - An object to configure the set behavior.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns This `Transaction` instance. Used for chaining method calls.\n */\n set(\n documentRef: DocumentReference,\n data: PartialWithFieldValue,\n options: SetOptions\n ): this;\n set(\n documentRef: DocumentReference,\n value: PartialWithFieldValue,\n options?: SetOptions\n ): this {\n const ref = validateReference(documentRef, this._firestore);\n const convertedValue = applyFirestoreDataConverter(\n ref.converter,\n value,\n options\n );\n const parsed = parseSetData(\n this._dataReader,\n 'Transaction.set',\n ref._key,\n convertedValue,\n ref.converter !== null,\n options\n );\n this._transaction.set(ref._key, parsed);\n return this;\n }\n\n /**\n * Updates fields in the document referred to by the provided {@link\n * DocumentReference}. The update will fail if applied to a document that does\n * not exist.\n *\n * @param documentRef - A reference to the document to be updated.\n * @param data - An object containing the fields and values with which to\n * update the document. Fields can contain dots to reference nested fields\n * within the document.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns This `Transaction` instance. Used for chaining method calls.\n */\n update(\n documentRef: DocumentReference,\n data: UpdateData\n ): this;\n /**\n * Updates fields in the document referred to by the provided {@link\n * DocumentReference}. The update will fail if applied to a document that does\n * not exist.\n *\n * Nested fields can be updated by providing dot-separated field path\n * strings or by providing `FieldPath` objects.\n *\n * @param documentRef - A reference to the document to be updated.\n * @param field - The first field to update.\n * @param value - The first value.\n * @param moreFieldsAndValues - Additional key/value pairs.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns This `Transaction` instance. Used for chaining method calls.\n */\n update(\n documentRef: DocumentReference,\n field: string | FieldPath,\n value: unknown,\n ...moreFieldsAndValues: unknown[]\n ): this;\n update(\n documentRef: DocumentReference,\n fieldOrUpdateData: string | FieldPath | UpdateData,\n value?: unknown,\n ...moreFieldsAndValues: unknown[]\n ): this {\n const ref = validateReference(documentRef, this._firestore);\n\n // For Compat types, we have to \"extract\" the underlying types before\n // performing validation.\n fieldOrUpdateData = getModularInstance(fieldOrUpdateData);\n\n let parsed;\n if (\n typeof fieldOrUpdateData === 'string' ||\n fieldOrUpdateData instanceof FieldPath\n ) {\n parsed = parseUpdateVarargs(\n this._dataReader,\n 'Transaction.update',\n ref._key,\n fieldOrUpdateData,\n value,\n moreFieldsAndValues\n );\n } else {\n parsed = parseUpdateData(\n this._dataReader,\n 'Transaction.update',\n ref._key,\n fieldOrUpdateData\n );\n }\n\n this._transaction.update(ref._key, parsed);\n return this;\n }\n\n /**\n * Deletes the document referred to by the provided {@link DocumentReference}.\n *\n * @param documentRef - A reference to the document to be deleted.\n * @returns This `Transaction` instance. Used for chaining method calls.\n */\n delete(\n documentRef: DocumentReference\n ): this {\n const ref = validateReference(documentRef, this._firestore);\n this._transaction.delete(ref._key);\n return this;\n }\n}\n\n/**\n * Executes the given `updateFunction` and then attempts to commit the changes\n * applied within the transaction. If any document read within the transaction\n * has changed, Cloud Firestore retries the `updateFunction`. If it fails to\n * commit after 5 attempts, the transaction fails.\n *\n * The maximum number of writes allowed in a single transaction is 500.\n *\n * @param firestore - A reference to the Firestore database to run this\n * transaction against.\n * @param updateFunction - The function to execute within the transaction\n * context.\n * @param options - An options object to configure maximum number of attempts to\n * commit.\n * @returns If the transaction completed successfully or was explicitly aborted\n * (the `updateFunction` returned a failed promise), the promise returned by the\n * `updateFunction `is returned here. Otherwise, if the transaction failed, a\n * rejected promise with the corresponding failure error is returned.\n */\nexport function runTransaction(\n firestore: Firestore,\n updateFunction: (transaction: Transaction) => Promise,\n options?: TransactionOptions\n): Promise {\n firestore = cast(firestore, Firestore);\n const datastore = getDatastore(firestore);\n const optionsWithDefaults: TransactionOptionsInternal = {\n ...DEFAULT_TRANSACTION_OPTIONS,\n ...options\n };\n validateTransactionOptions(optionsWithDefaults);\n const deferred = new Deferred();\n new TransactionRunner(\n newAsyncQueue(),\n datastore,\n optionsWithDefaults,\n internalTransaction =>\n updateFunction(new Transaction(firestore, internalTransaction)),\n deferred\n ).run();\n return deferred.promise;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n _registerComponent,\n registerVersion,\n SDK_VERSION\n} from '@firebase/app';\nimport { Component, ComponentType } from '@firebase/component';\n\nimport { version } from '../package.json';\nimport {\n LiteAppCheckTokenProvider,\n LiteAuthCredentialsProvider\n} from '../src/api/credentials';\nimport { databaseIdFromApp } from '../src/core/database_info';\nimport { setSDKVersion } from '../src/core/version';\nimport { Firestore } from '../src/lite-api/database';\n\ndeclare module '@firebase/component' {\n interface NameServiceMapping {\n 'firestore/lite': Firestore;\n }\n}\n\nexport function registerFirestore(): void {\n setSDKVersion(`${SDK_VERSION}_lite`);\n _registerComponent(\n new Component(\n 'firestore/lite',\n (container, { instanceIdentifier: databaseId, options: settings }) => {\n const app = container.getProvider('app').getImmediate()!;\n const firestoreInstance = new Firestore(\n new LiteAuthCredentialsProvider(\n container.getProvider('auth-internal')\n ),\n new LiteAppCheckTokenProvider(\n app,\n container.getProvider('app-check-internal')\n ),\n databaseIdFromApp(app, databaseId),\n app\n );\n if (settings) {\n firestoreInstance._setSettings(settings);\n }\n return firestoreInstance;\n },\n 'PUBLIC' as ComponentType.PUBLIC\n ).setMultipleInstances(true)\n );\n // RUNTIME_ENV and BUILD_TARGET are replaced by real values during the compilation\n registerVersion('firestore-lite', version, '__RUNTIME_ENV__');\n registerVersion('firestore-lite', version, '__BUILD_TARGET__');\n}\n","/**\n * Firestore Lite\n *\n * @remarks Firestore Lite is a small online-only SDK that allows read\n * and write access to your Firestore database. All operations connect\n * directly to the backend, and `onSnapshot()` APIs are not supported.\n * @packageDocumentation\n */\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { registerFirestore } from './register';\nregisterFirestore();\n\nexport {\n aggregateQuerySnapshotEqual,\n getCount,\n getAggregate,\n count,\n sum,\n average,\n aggregateFieldEqual\n} from '../src/lite-api/aggregate';\n\nexport {\n AggregateField,\n AggregateFieldType,\n AggregateSpec,\n AggregateSpecData,\n AggregateQuerySnapshot,\n AggregateType\n} from '../src/lite-api/aggregate_types';\n\nexport { FirestoreSettings as Settings } from '../src/lite-api/settings';\n\nexport {\n Firestore as Firestore,\n EmulatorMockTokenOptions,\n initializeFirestore,\n getFirestore,\n terminate,\n connectFirestoreEmulator\n} from '../src/lite-api/database';\n\nexport {\n DocumentData,\n UpdateData,\n WithFieldValue,\n PartialWithFieldValue,\n SetOptions,\n DocumentReference,\n Query,\n CollectionReference,\n collection,\n collectionGroup,\n doc,\n refEqual,\n queryEqual\n} from '../src/lite-api/reference';\n\nexport {\n and,\n endAt,\n endBefore,\n startAt,\n startAfter,\n limit,\n limitToLast,\n where,\n or,\n orderBy,\n query,\n QueryConstraint,\n QueryConstraintType,\n QueryCompositeFilterConstraint,\n QueryFilterConstraint,\n QueryFieldFilterConstraint,\n QueryOrderByConstraint,\n QueryLimitConstraint,\n QueryNonFilterConstraint,\n QueryStartAtConstraint,\n QueryEndAtConstraint,\n OrderByDirection,\n WhereFilterOp\n} from '../src/lite-api/query';\n\nexport {\n addDoc,\n deleteDoc,\n updateDoc,\n setDoc,\n getDoc,\n getDocs\n} from '../src/lite-api/reference_impl';\n\nexport {\n Primitive,\n NestedUpdateFields,\n ChildUpdateFields,\n AddPrefixToKeys,\n UnionToIntersection\n} from '../src/lite-api/types';\n\n// TODO(firestorelite): Add tests when Queries are usable\nexport { FieldPath, documentId } from '../src/lite-api/field_path';\n\n// TODO(firestorelite): Add tests when setDoc() is available\nexport { FieldValue } from '../src/lite-api/field_value';\n\nexport {\n increment,\n arrayRemove,\n arrayUnion,\n serverTimestamp,\n deleteField,\n vector\n} from '../src/lite-api/field_value_impl';\n\nexport {\n FirestoreDataConverter,\n DocumentSnapshot,\n QueryDocumentSnapshot,\n QuerySnapshot,\n snapshotEqual\n} from '../src/lite-api/snapshot';\n\nexport { VectorValue } from '../src/lite-api/vector_value';\n\nexport { WriteBatch, writeBatch } from '../src/lite-api/write_batch';\n\nexport { TransactionOptions } from '../src/lite-api/transaction_options';\n\nexport { Transaction, runTransaction } from '../src/lite-api/transaction';\n\nexport { setLogLevel, LogLevelString as LogLevel } from '../src/util/log';\n\nexport { Bytes } from '../src/lite-api/bytes';\n\nexport { GeoPoint } from '../src/lite-api/geo_point';\n\nexport { Timestamp } from '../src/lite-api/timestamp';\n\nexport { FirestoreErrorCode, FirestoreError } from '../src/util/error';\n"],"names":["User","constructor","uid","this","isAuthenticated","toKey","isEqual","otherUser","UNAUTHENTICATED","GOOGLE_CREDENTIALS","FIRST_PARTY","MOCK_USER","SDK_VERSION","__PRIVATE_logClient","Logger","setLogLevel","logLevel","__PRIVATE_logDebug","msg","obj","LogLevel","DEBUG","args","map","__PRIVATE_argToString","debug","__PRIVATE_logError","ERROR","error","__PRIVATE_logWarn","WARN","warn","__PRIVATE_formatJSON","value","JSON","stringify","e","fail","id","__PRIVATE_messageOrContext","context","message","__PRIVATE__fail","__PRIVATE_failure","toString","undefined","Error","__PRIVATE_hardAssert","assertion","__PRIVATE_debugCast","Code","FirestoreError","FirebaseError","code","super","name","__PRIVATE_Deferred","promise","Promise","resolve","reject","__PRIVATE_OAuthToken","user","type","headers","Map","set","__PRIVATE_EmptyAuthCredentialsProvider","getToken","invalidateToken","start","asyncQueue","changeListener","enqueueRetryable","shutdown","__PRIVATE_EmulatorAuthCredentialsProvider","token","__PRIVATE_LiteAuthCredentialsProvider","__PRIVATE_authProvider","auth","onInit","then","__PRIVATE_tokenData","accessToken","getUid","__PRIVATE_FirstPartyToken","__PRIVATE_sessionIndex","__PRIVATE_iamToken","__PRIVATE_authTokenFactory","__PRIVATE_getAuthToken","__PRIVATE__headers","__PRIVATE_authHeaderTokenValue","__PRIVATE_FirstPartyAuthCredentialsProvider","AppCheckToken","length","__PRIVATE_LiteAppCheckTokenProvider","app","__PRIVATE_appCheckProvider","appCheck","__PRIVATE_serverAppAppCheckToken","_isFirebaseServerApp","settings","appCheckToken","tokenResult","DatabaseInfo","databaseId","appId","persistenceKey","host","ssl","forceLongPolling","autoDetectLongPolling","longPollingOptions","useFetchStreams","isUsingEmulator","__PRIVATE_DEFAULT_DATABASE_NAME","DatabaseId","projectId","database","empty","isDefaultDatabase","other","__PRIVATE_randomBytes","__PRIVATE_nBytes","crypto","self","bytes","Uint8Array","getRandomValues","__PRIVATE_i","Math","floor","random","__PRIVATE_AutoId","newId","__PRIVATE_chars","__PRIVATE_maxMultiple","__PRIVATE_autoId","charAt","__PRIVATE_primitiveComparator","left","right","__PRIVATE_compareUtf8Strings","min","__PRIVATE_leftChar","__PRIVATE_rightChar","__PRIVATE_isSurrogate","__PRIVATE_MIN_SURROGATE","__PRIVATE_MAX_SURROGATE","s","c","charCodeAt","__PRIVATE_arrayEquals","comparator","every","index","__PRIVATE_DOCUMENT_KEY_NAME","BasePath","segments","offset","range","len","child","nameOrPath","slice","limit","forEach","segment","push","construct","popFirst","size","popLast","firstSegment","lastSegment","get","isEmpty","isPrefixOf","isImmediateParentOf","potentialChild","fn","end","toArray","p1","p2","comparison","compareSegments","__PRIVATE_lhs","__PRIVATE_rhs","__PRIVATE_isLhsNumeric","isNumericId","__PRIVATE_isRhsNumeric","extractNumericId","compare","startsWith","endsWith","Integer","fromString","substring","ResourcePath","canonicalString","join","toUriEncodedString","encodeURIComponent","pathComponents","path","indexOf","split","filter","emptyPath","__PRIVATE_identifierRegExp","FieldPath","isValidIdentifier","test","str","replace","isKeyField","keyField","fromServerFormat","current","__PRIVATE_addCurrentSegment","__PRIVATE_inBackticks","next","DocumentKey","fromPath","fromName","collectionGroup","hasCollectionId","collectionId","getCollectionGroup","getCollectionPath","k1","k2","isDocumentKey","fromSegments","__PRIVATE_validateNonEmptyArgument","__PRIVATE_functionName","__PRIVATE_argumentName","__PRIVATE_argument","__PRIVATE_validateDocumentPath","__PRIVATE_validateCollectionPath","__PRIVATE_isPlainObject","input","Object","getPrototypeOf","prototype","__PRIVATE_valueDescription","Array","__PRIVATE_customObjectName","__PRIVATE_tryGetCustomObjectType","__PRIVATE_cast","_delegate","description","__PRIVATE_validatePositiveNumber","n","__PRIVATE_cloneLongPollingOptions","options","clone","timeoutSeconds","__PRIVATE_lastUniqueDebugId","__PRIVATE_generateUniqueDebugId","__PRIVATE_generateInitialUniqueDebugId","round","__PRIVATE_maxResult","__PRIVATE_isNullOrUndefined","__PRIVATE_isNegativeZero","__PRIVATE_LOG_TAG","__PRIVATE_RPC_NAME_URL_MAPPING","__PRIVATE_RestConnection","__PRIVATE_shouldResourcePathBeIncludedInRequest","databaseInfo","proto","__PRIVATE_baseUrl","__PRIVATE_databasePath","__PRIVATE_requestParams","__PRIVATE_invokeRPC","__PRIVATE_rpcName","__PRIVATE_req","__PRIVATE_authToken","streamId","url","__PRIVATE_makeUrl","__PRIVATE_modifyHeadersForRequest","URL","__PRIVATE_forwardCredentials","isCloudWorkstation","__PRIVATE_performRPCRequest","response","err","__PRIVATE_invokeStreamingRPC","request","__PRIVATE_expectedResponseCount","__PRIVATE_getGoogApiClientValue","key","__PRIVATE_urlRpcName","terminate","__PRIVATE_RpcCode","RpcCode","__PRIVATE_mapCodeFromHttpStatus","status","__PRIVATE_FetchConnection","__PRIVATE_openStream","body","__PRIVATE_requestJson","__PRIVATE_fetchArgs","method","credentials","fetch","statusText","ok","__PRIVATE_errorResponse","json","isArray","__PRIVATE_errorMessage","__PRIVATE_AggregateImpl","alias","aggregateType","fieldPath","__PRIVATE_objectSize","count","hasOwnProperty","call","__PRIVATE_Base64DecodeError","ByteString","binaryString","fromBase64String","base64","__PRIVATE_decodeBase64","__PRIVATE_encoded","atob","DOMException","fromUint8Array","array","__PRIVATE_binaryStringFromUint8Array","String","fromCharCode","Symbol","iterator","done","toBase64","__PRIVATE_encodeBase64","raw","btoa","toUint8Array","__PRIVATE_uint8ArrayFromBinaryString","buffer","approximateByteSize","compareTo","EMPTY_BYTE_STRING","__PRIVATE_ISO_TIMESTAMP_REG_EXP","RegExp","__PRIVATE_normalizeTimestamp","date","nanos","__PRIVATE_fraction","exec","timestamp","__PRIVATE_nanoStr","substr","Number","__PRIVATE_parsedDate","Date","seconds","getTime","__PRIVATE_normalizeNumber","__PRIVATE_normalizeByteString","blob","property","typeString","__PRIVATE_optionalValue","result","__PRIVATE_validateJSON","__PRIVATE_schema","__PRIVATE_fieldValue","__PRIVATE_MIN_SECONDS","__PRIVATE_MS_TO_NANOS","Timestamp","now","fromMillis","fromDate","milliseconds","nanoseconds","toDate","toMillis","_compareTo","toJSON","_jsonSchemaVersion","fromJSON","_jsonSchema","valueOf","__PRIVATE_adjustedSeconds","padStart","__PRIVATE_isServerTimestamp","mapValue","fields","stringValue","__PRIVATE_getPreviousValue","previousValue","__PRIVATE_getLocalWriteTime","localWriteTime","timestampValue","__PRIVATE_TYPE_KEY","__PRIVATE_MAX_VALUE_TYPE","MAX_VALUE","__type__","__PRIVATE_VECTOR_VALUE_SENTINEL","__PRIVATE_VECTOR_MAP_VECTORS_KEY","__PRIVATE_typeOrder","__PRIVATE_isMaxValue","__PRIVATE_isVectorValue","__PRIVATE_valueEquals","__PRIVATE_leftType","booleanValue","__PRIVATE_timestampEquals","__PRIVATE_leftTimestamp","__PRIVATE_rightTimestamp","__PRIVATE_blobEquals","bytesValue","referenceValue","__PRIVATE_geoPointEquals","geoPointValue","latitude","longitude","__PRIVATE_numberEquals","integerValue","__PRIVATE_n1","doubleValue","__PRIVATE_n2","isNaN","arrayValue","values","__PRIVATE_objectEquals","__PRIVATE_leftMap","__PRIVATE_rightMap","__PRIVATE_arrayValueContains","__PRIVATE_haystack","__PRIVATE_needle","find","v","__PRIVATE_valueCompare","__PRIVATE_rightType","__PRIVATE_compareNumbers","__PRIVATE_leftNumber","__PRIVATE_rightNumber","__PRIVATE_compareTimestamps","__PRIVATE_compareBlobs","__PRIVATE_leftBytes","__PRIVATE_rightBytes","__PRIVATE_compareReferences","__PRIVATE_leftPath","__PRIVATE_rightPath","__PRIVATE_leftSegments","__PRIVATE_rightSegments","__PRIVATE_compareGeoPoints","__PRIVATE_compareArrays","__PRIVATE_compareVectors","__PRIVATE_leftArrayValue","__PRIVATE_rightArrayValue","__PRIVATE_lengthCompare","__PRIVATE_compareMaps","__PRIVATE_leftKeys","keys","__PRIVATE_rightKeys","sort","__PRIVATE_keyCompare","__PRIVATE_leftArray","__PRIVATE_rightArray","__PRIVATE_refValue","__PRIVATE_isNullValue","__PRIVATE_isNanValue","__PRIVATE_isMapValue","__PRIVATE_deepClone","source","target","val","Bound","position","inclusive","__PRIVATE_boundEquals","Filter","FieldFilter","field","op","create","createKeyFieldInFilter","__PRIVATE_KeyFieldFilter","__PRIVATE_ArrayContainsFilter","__PRIVATE_InFilter","__PRIVATE_NotInFilter","__PRIVATE_ArrayContainsAnyFilter","__PRIVATE_KeyFieldInFilter","__PRIVATE_KeyFieldNotInFilter","matches","doc","data","nullValue","matchesComparison","operator","isInequality","getFlattenedFilters","getFilters","CompositeFilter","filters","__PRIVATE_memoizedFlattenedFilters","__PRIVATE_compositeFilterIsConjunction","compositeFilter","reduce","__PRIVATE_subfilter","concat","assign","__PRIVATE_filterEquals","__PRIVATE_f1","__PRIVATE_f2","__PRIVATE_fieldFilterEquals","__PRIVATE_compositeFilterEquals","__PRIVATE_f1Filter","__PRIVATE_extractDocumentKeysFromArrayValue","some","OrderBy","dir","__PRIVATE_orderByEquals","SnapshotVersion","fromTimestamp","max","toMicroseconds","toTimestamp","SortedMap","root","LLRBNode","EMPTY","insert","copy","BLACK","remove","node","cmp","__PRIVATE_prunedNodes","minKey","maxKey","inorderTraversal","action","k","__PRIVATE_descriptions","reverseTraversal","getIterator","SortedMapIterator","getIteratorFrom","getReverseIterator","getReverseIteratorFrom","startKey","isReverse","nodeStack","getNext","pop","hasNext","peek","color","RED","fixUp","removeMin","isRed","moveRedLeft","__PRIVATE_smallest","rotateRight","moveRedRight","rotateLeft","colorFlip","__PRIVATE_nl","__PRIVATE_nr","checkMaxDepth","__PRIVATE_blackDepth","check","pow","LLRBEmptyNode","SortedSet","has","elem","first","last","cb","forEachInRange","iter","forEachWhile","firstAfterOrEqual","SortedSetIterator","add","unionWith","__PRIVATE_thisIt","__PRIVATE_otherIt","__PRIVATE_thisElem","__PRIVATE_otherElem","__PRIVATE_res","targetId","FieldMask","extraFields","__PRIVATE_mergedMaskSet","covers","__PRIVATE_fieldMaskPath","l","r","ObjectValue","__PRIVATE_currentLevel","getFieldsMap","setAll","parent","__PRIVATE_upserts","__PRIVATE_deletes","__PRIVATE_fieldsMap","applyChanges","__PRIVATE_nestedValue","__PRIVATE_inserts","MutableDocument","documentType","version","readTime","createTime","documentState","newInvalidDocument","documentKey","newFoundDocument","newNoDocument","newUnknownDocument","convertToFoundDocument","convertToNoDocument","convertToUnknownDocument","setHasCommittedMutations","setHasLocalMutations","setReadTime","hasLocalMutations","hasCommittedMutations","hasPendingWrites","isValidDocument","isFoundDocument","isNoDocument","isUnknownDocument","mutableCopy","__PRIVATE_TargetImpl","orderBy","startAt","endAt","__PRIVATE_memoizedCanonicalId","__PRIVATE_newTarget","__PRIVATE_QueryImpl","explicitOrderBy","limitType","__PRIVATE_memoizedNormalizedOrderBy","__PRIVATE_memoizedTarget","__PRIVATE_memoizedAggregateTarget","__PRIVATE_isCollectionGroupQuery","query","__PRIVATE_queryNormalizedOrderBy","__PRIVATE_queryImpl","__PRIVATE_fieldsNormalized","Set","__PRIVATE_lastDirection","__PRIVATE_inequalityFields","__PRIVATE_getInequalityFilterFields","__PRIVATE_queryToTarget","__PRIVATE__queryToTarget","__PRIVATE_orderBys","__PRIVATE_queryWithAddedFilter","__PRIVATE_newFilters","__PRIVATE_queryEquals","__PRIVATE_targetEquals","__PRIVATE_toDouble","serializer","useProto3Json","Infinity","toNumber","isSafeInteger","isInteger","MAX_SAFE_INTEGER","MIN_SAFE_INTEGER","__PRIVATE_toInteger","TransformOperation","_","__PRIVATE_ServerTimestampTransform","__PRIVATE_ArrayUnionTransformOperation","elements","__PRIVATE_ArrayRemoveTransformOperation","__PRIVATE_NumericIncrementTransformOperation","__PRIVATE_operand","FieldTransform","transform","Precondition","updateTime","exists","none","isNone","Mutation","__PRIVATE_SetMutation","precondition","fieldTransforms","getFieldMask","__PRIVATE_PatchMutation","fieldMask","__PRIVATE_DeleteMutation","__PRIVATE_VerifyMutation","__PRIVATE_DIRECTIONS","__PRIVATE_dirs","__PRIVATE_OPERATORS","__PRIVATE_ops","__PRIVATE_COMPOSITE_OPERATORS","JsonProtoSerializer","toISOString","__PRIVATE_toBytes","__PRIVATE_toVersion","__PRIVATE_fromVersion","__PRIVATE_toResourceName","__PRIVATE_toResourcePath","__PRIVATE_resourcePath","__PRIVATE_fullyQualifiedPrefixPath","__PRIVATE_toName","__PRIVATE_resource","__PRIVATE_fromResourceName","__PRIVATE_isValidResourceName","__PRIVATE_extractLocalPathFromResourceName","__PRIVATE_resourceName","__PRIVATE_toMutationDocument","__PRIVATE_fromBatchGetDocumentsResponse","__PRIVATE_fromFound","found","__PRIVATE_fromMissing","missing","toMutation","mutation","update","delete","updateMask","__PRIVATE_toDocumentMask","__PRIVATE_mutationType","verify","updateTransforms","__PRIVATE_toFieldTransform","__PRIVATE_fieldTransform","setToServerValue","appendMissingElements","removeAllFromArray","increment","currentDocument","__PRIVATE_toPrecondition","__PRIVATE_toQueryTarget","__PRIVATE_queryTarget","structuredQuery","from","allDescendants","__PRIVATE_toQueryPath","where","__PRIVATE_toFilters","__PRIVATE_toFilter","__PRIVATE_toOrder","order","__PRIVATE_toPropertyOrder","__PRIVATE_toFieldPathReference","direction","__PRIVATE_toDirection","__PRIVATE_toInt32Proto","__PRIVATE_toStartAtCursor","cursor","before","__PRIVATE_toEndAtCursor","__PRIVATE_toOperatorName","__PRIVATE_toCompositeOperatorName","__PRIVATE_toUnaryOrFieldFilter","unaryFilter","fieldFilter","__PRIVATE_toCompositeFilter","__PRIVATE_protos","__PRIVATE_canonicalFields","fieldPaths","__PRIVATE_newSerializer","__PRIVATE_ExponentialBackoff","__PRIVATE_queue","timerId","__PRIVATE_initialDelayMs","__PRIVATE_backoffFactor","__PRIVATE_maxDelayMs","__PRIVATE_currentBaseMs","__PRIVATE_timerPromise","reset","__PRIVATE_resetToMax","__PRIVATE_backoffAndRun","cancel","__PRIVATE_desiredDelayWithJitterMs","__PRIVATE_jitterDelayMs","__PRIVATE_delaySoFarMs","__PRIVATE_lastAttemptTime","__PRIVATE_remainingDelayMs","enqueueAfterDelay","__PRIVATE_skipBackoff","skipDelay","Datastore","__PRIVATE_DatastoreImpl","authCredentials","appCheckCredentials","connection","__PRIVATE_terminated","__PRIVATE_verifyInitialized","all","catch","async","__PRIVATE_invokeCommitRpc","datastore","mutations","__PRIVATE_datastoreImpl","writes","m","__PRIVATE_invokeBatchGetDocumentsRpc","documents","docs","__PRIVATE_invokeRunQueryRpc","M","document","__PRIVATE_fromDocument","__PRIVATE_invokeRunAggregationQueryRpc","__PRIVATE_aggregates","nt","__PRIVATE_aliasMap","__PRIVATE_toRunAggregationQueryRequest","__PRIVATE_skipAliasing","aggregations","__PRIVATE_aggregationNum","__PRIVATE_aggregate","__PRIVATE_serverAlias","avg","sum","structuredAggregationQuery","__PRIVATE_queryToAggregateTarget","__PRIVATE_filteredResult","__PRIVATE_unmappedAggregateFields","aggregateFields","__PRIVATE_accumulator","__PRIVATE_datastoreInstances","__PRIVATE_getDatastore","firestore","_terminated","__PRIVATE_newConnection","__PRIVATE_makeDatabaseInfo","experimentalForceLongPolling","experimentalAutoDetectLongPolling","experimentalLongPollingOptions","_databaseId","_persistenceKey","_freezeSettings","__PRIVATE_newDatastore","_authCredentials","_appCheckCredentials","__PRIVATE_LRU_MINIMUM_CACHE_SIZE_BYTES","__PRIVATE_DEFAULT_HOST","__PRIVATE_DEFAULT_SSL","FirestoreSettingsImpl","emulatorOptions","ignoreUndefinedProperties","localCache","cacheSizeBytes","__PRIVATE_validateIsNotUsedTogether","optionName1","argument1","optionName2","argument2","__PRIVATE_validateLongPollingOptions","__PRIVATE_longPollingOptionsEqual","__PRIVATE_options1","__PRIVATE_options2","Firestore","_app","_settings","_settingsFrozen","_emulatorOptions","_terminateTask","_initialized","_setSettings","__PRIVATE_makeAuthCredentialsProvider","_getSettings","_getEmulatorOptions","_delete","_terminate","_restart","__PRIVATE_removeComponents","initializeFirestore","provider","_getProvider","isInitialized","initialize","instanceIdentifier","getFirestore","__PRIVATE_appOrDatabaseId","__PRIVATE_optionalDatabaseId","getApp","db","getImmediate","identifier","__PRIVATE_emulator","getDefaultEmulatorHostnameAndPort","connectFirestoreEmulator","port","__PRIVATE_useSsl","__PRIVATE_existingConfig","__PRIVATE_newHostSetting","pingServer","updateEmulatorBanner","__PRIVATE_newConfig","deepEqual","mockUserToken","createMockUserToken","sub","user_id","_removeServiceInstance","AggregateField","_internalFieldPath","AggregateQuerySnapshot","_userDataWriter","_data","convertObjectMap","Query","converter","_query","withConverter","DocumentReference","_key","_path","CollectionReference","referencePath","__PRIVATE_newQueryForPath","parentPath","collection","pathSegments","getModularInstance","__PRIVATE_absolutePath","__PRIVATE_newQueryForCollectionGroup","arguments","refEqual","queryEqual","Bytes","byteString","_byteString","fieldNames","_internalPath","__PRIVATE_InternalFieldPath","documentId","FieldValue","_methodName","GeoPoint","isFinite","_lat","_long","VectorValue","_values","__PRIVATE_isPrimitiveArrayEqual","vectorValues","element","__PRIVATE_RESERVED_FIELD_REGEX","ParsedSetData","ParsedUpdateData","__PRIVATE_isWrite","__PRIVATE_dataSource","__PRIVATE_ParseContextImpl","__PRIVATE_validatePath","__PRIVATE_contextWith","configuration","__PRIVATE_childContextForField","__PRIVATE_childPath","__PRIVATE_arrayElement","__PRIVATE_validatePathSegment","__PRIVATE_childContextForFieldPath","__PRIVATE_childContextForArray","__PRIVATE_createError","reason","methodName","__PRIVATE_hasConverter","__PRIVATE_targetDoc","contains","__PRIVATE_UserDataReader","__PRIVATE_createContext","__PRIVATE_newUserDataReader","__PRIVATE_parseSetData","__PRIVATE_userDataReader","merge","mergeFields","__PRIVATE_validatePlainObject","__PRIVATE_updateData","__PRIVATE_parseObject","__PRIVATE_validatedFieldPaths","__PRIVATE_stringOrFieldPath","__PRIVATE_fieldPathFromArgument","__PRIVATE_fieldMaskContains","__PRIVATE_DeleteFieldValueImpl","_toFieldTransform","__PRIVATE_createSentinelChildContext","__PRIVATE_ServerTimestampFieldValueImpl","__PRIVATE_ArrayUnionFieldValueImpl","__PRIVATE__elements","__PRIVATE_parseContext","__PRIVATE_parsedElements","__PRIVATE_parseData","arrayUnion","__PRIVATE_ArrayRemoveFieldValueImpl","__PRIVATE_NumericIncrementFieldValueImpl","__PRIVATE__operand","__PRIVATE_numericIncrement","__PRIVATE_parseUpdateData","__PRIVATE_fieldMaskPaths","__PRIVATE_fieldPathFromDotSeparatedString","__PRIVATE_childContext","__PRIVATE_parsedValue","mask","__PRIVATE_parseUpdateVarargs","moreFieldsAndValues","__PRIVATE_parseQueryValue","__PRIVATE_allowArrays","__PRIVATE_looksLikeJsonObject","__PRIVATE_parseSentinelFieldValue","__PRIVATE_parseArray","__PRIVATE_entryIndex","entry","__PRIVATE_parsedEntry","__PRIVATE_parseScalarValue","__PRIVATE_thisDb","__PRIVATE_otherDb","__PRIVATE_parseVectorValue","__PRIVATE_FIELD_PATH_RESERVED","search","__PRIVATE_hasPath","__PRIVATE_hasDocument","DocumentSnapshot","_firestore","_document","_converter","ref","snapshot","QueryDocumentSnapshot","fromFirestore","convertValue","QuerySnapshot","_docs","callback","thisArg","snapshotEqual","arg","AppliableConstraint","QueryConstraint","__PRIVATE_queryConstraint","__PRIVATE_additionalQueryConstraints","queryConstraints","__PRIVATE_validateQueryConstraintArray","__PRIVATE_compositeFilterCount","QueryCompositeFilterConstraint","__PRIVATE_fieldFilterCount","QueryFieldFilterConstraint","constraint","_apply","_field","_op","_value","_create","_parse","__PRIVATE_validateNewFieldFilter","__PRIVATE_reader","__PRIVATE_newQueryFilter","__PRIVATE_dataReader","__PRIVATE_validateDisjunctiveFilterElements","__PRIVATE_referenceList","__PRIVATE_parseDocumentIdValue","opStr","_queryConstraints","__PRIVATE_parsedFilters","__PRIVATE_parsedFilter","_getOperator","__PRIVATE_validateNewFilter","__PRIVATE_testQuery","__PRIVATE_subFilters","__PRIVATE_subFilter","_getQueryConstraints","or","__PRIVATE_validateQueryFilterConstraint","and","QueryOrderByConstraint","_direction","__PRIVATE_newQueryOrderBy","__PRIVATE_queryWithAddedOrderBy","__PRIVATE_newOrderBy","directionStr","QueryLimitConstraint","_limit","_limitType","__PRIVATE_queryWithLimit","limitToLast","QueryStartAtConstraint","_docOrFields","_inclusive","bound","__PRIVATE_newQueryBoundFromDocOrFields","__PRIVATE_queryWithStartAt","__PRIVATE_docOrFields","startAfter","QueryEndAtConstraint","__PRIVATE_queryWithEndAt","endBefore","__PRIVATE_newQueryBoundFromDocument","components","__PRIVATE_newQueryBoundFromFields","__PRIVATE_rawValue","__PRIVATE_wrapped","__PRIVATE_documentIdValue","__PRIVATE_conflictingOp","__PRIVATE_findOpInsideFilters","__PRIVATE_operators","__PRIVATE_conflictingOps","AbstractUserDataWriter","serverTimestampBehavior","convertTimestamp","convertServerTimestamp","convertBytes","convertReference","convertGeoPoint","convertArray","convertObject","convertVectorValue","__PRIVATE_normalizedValue","convertDocumentKey","expectedDatabaseId","__PRIVATE_applyFirestoreDataConverter","__PRIVATE_convertedValue","toFirestore","__PRIVATE_LiteUserDataWriter","getDoc","reference","userDataWriter","getDocs","__PRIVATE_validateHasExplicitOrderByForLimitToLast","reverse","setDoc","__PRIVATE_parsed","updateDoc","__PRIVATE_fieldOrUpdateData","deleteDoc","addDoc","__PRIVATE_docRef","getCount","getAggregate","aggregateSpec","__PRIVATE_internalAggregates","__PRIVATE_mapToArray","__PRIVATE_aggregateResult","__PRIVATE_convertToAggregateQuerySnapshot","__PRIVATE_querySnapshot","average","aggregateFieldEqual","aggregateQuerySnapshotEqual","deleteField","serverTimestamp","arrayRemove","vector","WriteBatch","_commitHandler","_mutations","_committed","_dataReader","documentRef","_verifyNotCommitted","__PRIVATE_validateReference","commit","writeBatch","Transaction","readVersions","committed","lastTransactionError","writtenDocs","lookup","ensureCommitNotCalled","recordVersion","write","preconditionForUpdate","__PRIVATE_unwritten","__PRIVATE_docVersion","__PRIVATE_documentName","__PRIVATE_existingVersion","__PRIVATE_DEFAULT_TRANSACTION_OPTIONS","maxAttempts","__PRIVATE_TransactionRunner","updateFunction","deferred","__PRIVATE_attemptsRemaining","__PRIVATE_backoff","__PRIVATE_run","__PRIVATE_runWithBackOff","transaction","__PRIVATE_userPromise","__PRIVATE_tryRunUpdateFunction","enqueueAndForget","__PRIVATE_commitError","__PRIVATE_handleTransactionError","__PRIVATE_userPromiseError","__PRIVATE_isRetryableTransactionError","__PRIVATE_isPermanentError","getDocument","DelayedOperation","targetTimeMs","removalCallback","bind","createAndSchedule","delayMs","__PRIVATE_targetTime","__PRIVATE_delayedOp","timerHandle","setTimeout","handleDelayElapsed","clearTimeout","__PRIVATE_AsyncQueueImpl","__PRIVATE_tail","__PRIVATE_retryableOps","__PRIVATE__isShuttingDown","__PRIVATE_delayedOperations","__PRIVATE_operationInProgress","__PRIVATE_skipNonRestrictedTasks","__PRIVATE_timerIdsToSkip","__PRIVATE_visibilityHandler","visibilityState","addEventListener","isShuttingDown","enqueue","enqueueAndForgetEvenWhileRestricted","__PRIVATE_verifyNotFailed","__PRIVATE_enqueueInternal","enterRestrictedMode","purgeExistingTasks","removeEventListener","task","__PRIVATE_retryNextOp","shift","__PRIVATE_isIndexedDbTransactionError","__PRIVATE_newTail","__PRIVATE_getMessageOrStack","__PRIVATE_removedOp","__PRIVATE_removeDelayedOperation","__PRIVATE_messageOrStack","verifyOperationInProgress","__PRIVATE_drain","__PRIVATE_currentTail","__PRIVATE_containsDelayedOperation","__PRIVATE_runAllDelayedOperationsUntil","__PRIVATE_lastTimerId","a","b","__PRIVATE_skipDelaysForTimerId","splice","stack","includes","_transaction","runTransaction","__PRIVATE_optionsWithDefaults","__PRIVATE_validateTransactionOptions","__PRIVATE_newAsyncQueue","__PRIVATE_internalTransaction","__PRIVATE_registerFirestore","__PRIVATE_setSDKVersion","_registerComponent","Component","container","getProvider","__PRIVATE_firestoreInstance","__PRIVATE_databaseIdFromApp","apply","setMultipleInstances","registerVersion"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAqBaA,IAAAA,MAAAA,IAAAA,CAAAA;AAUX,IAAA,WAAAC,CAAqBC,CAAAA,EAAAA;AAAAC,QAAAA,IAAAA,CAAGD,GAAHA,GAAAA,CAAAA,CAAAA;AAAsB,KAAA;IAE3C,eAAAE,GAAAA;AACE,QAAA,OAAmB,QAAZD,IAAKD,CAAAA,GAAAA,CAAAA;AACb,KAAA;;;;WAMD,KAAAG,GAAAA;AACE,QAAA,OAAIF,IAAKC,CAAAA,eAAAA,EAAAA,GACA,MAASD,GAAAA,IAAAA,CAAKD,GAEd,GAAA,gBAAA,CAAA;AAEV,KAAA;AAED,IAAA,OAAAI,CAAQC,CAAAA,EAAAA;QACN,OAAOA,CAAAA,CAAUL,QAAQC,IAAKD,CAAAA,GAAAA,CAAAA;AAC/B,KAAA;;;+BA5BeM,IAAAA,CAAAA,eAAAA,GAAkB,IAAIR,IAAK,CAAA,IAAA,CAAA;;;AAI3BA,IAAAA,CAAAS,qBAAqB,IAAIT,IAAAA,CAAK,2BAC9BA,IAAAU,CAAAA,WAAAA,GAAc,IAAIV,IAAK,CAAA,iBAAA,CAAA;AACvBA,IAAAW,CAAAA,SAAAA,GAAY,IAAIX,IAAK,CAAA,WAAA,CAAA,CAAA;;;;;;;;;;;;;;;;;;ACVhC,IAAIY,CAAAA,GAAAA,QAAAA,CAAAA;;;;;;;;;;;;;;;;;;ACKX,MAAMC,CAAAA,GAAY,IAAIC,MAAO,CAAA,qBAAA,CAAA,CAAA;;;;;;;;;;;;;;AAoBvB,IAAA,SAAUC,WAAYC,CAAAA,CAAAA,EAAAA;AAC1BH,IAAAA,CAAAA,CAAUE,WAAYC,CAAAA,CAAAA,CAAAA,CAAAA;AACxB,CAAA;;AAEgBC,S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,CAAOE,SAAU2E,CAAAA,cAAAA,CAAe86B,KAAM9oC,CAAAA,CAAAA,CAAIgK,OAAS,EAAA,EAAC,WACvD,EAAA,CAAA,EAAA,MAAM,IAAI7M,cAAAA,CACRD,CACA,EAAA,qDAAA,CAAA,CAAA;AAIJ,YAAA,OAAO,IAAIkE,UAAAA,CAAWpB,CAAIgK,CAAAA,OAAAA,CAAQ3I,SAAYC,EAAAA,CAAAA,CAAAA,CAAAA;AAChD,SsE3CUunC,CAAkB7oC,GAAKS,CACvBT,CAAAA,EAAAA,CAAAA,CAAAA,CAAAA;QAKF,OAHIK,CAAAA,IACFuoC,CAAkBrY,CAAAA,YAAAA,CAAalwB,CAE1BuoC,CAAAA,EAAAA,CAAAA,CAAAA;AAAiB,KAAA,GAE1B,UACAG,oBAAqB,CAAA,CAAA,CAAA,CAAA,CAAA;;AAGzBC,IAAAA,eAAAA,CAAgB,gBAAkB3oB,EAAAA,CAAAA,EAAS,EAC3C2oB,CAAAA,EAAAA,eAAAA,CAAgB,kBAAkB3oB,CAAS,EAAA,SAAA,CAAA,CAAA;AAC7C,CCzCAioB,EAAAA;;;;"} \ No newline at end of file diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/index.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/index.d.ts new file mode 100644 index 0000000..a6d5c1f --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/index.d.ts @@ -0,0 +1,2030 @@ +/** + * Firestore Lite + * + * @remarks Firestore Lite is a small online-only SDK that allows read + * and write access to your Firestore database. All operations connect + * directly to the backend, and `onSnapshot()` APIs are not supported. + * @packageDocumentation + */ +import { FirebaseApp } from '@firebase/app'; +import { LogLevelString as LogLevel } from '@firebase/logger'; +import { EmulatorMockTokenOptions } from '@firebase/util'; +import { FirebaseError } from '@firebase/util'; + +/** + * Add a new document to specified `CollectionReference` with the given data, + * assigning it a document ID automatically. + * + * The result of this write will only be reflected in document reads that occur + * after the returned promise resolves. If the client is offline, the + * write fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @param reference - A reference to the collection to add this document to. + * @param data - An Object containing the data for the new document. + * @throws Error - If the provided input is not a valid Firestore document. + * @returns A `Promise` resolved with a `DocumentReference` pointing to the + * newly created document after it has been written to the backend. + */ +export declare function addDoc(reference: CollectionReference, data: WithFieldValue): Promise>; +/** + * Returns a new map where every key is prefixed with the outer key appended + * to a dot. + */ +export declare type AddPrefixToKeys> = { + [K in keyof T & string as `${Prefix}.${K}`]+?: string extends K ? any : T[K]; +}; +/** + * Represents an aggregation that can be performed by Firestore. + */ +export declare class AggregateField { + /** A type string to uniquely identify instances of this class. */ + readonly type = "AggregateField"; + /** Indicates the aggregation operation of this AggregateField. */ + readonly aggregateType: AggregateType; +} +/** + * Compares two 'AggregateField` instances for equality. + * + * @param left Compare this AggregateField to the `right`. + * @param right Compare this AggregateField to the `left`. + */ +export declare function aggregateFieldEqual(left: AggregateField, right: AggregateField): boolean; +/** + * The union of all `AggregateField` types that are supported by Firestore. + */ +export declare type AggregateFieldType = ReturnType | ReturnType | ReturnType; +/** + * The results of executing an aggregation query. + */ +export declare class AggregateQuerySnapshot { + /** A type string to uniquely identify instances of this class. */ + readonly type = "AggregateQuerySnapshot"; + /** + * The underlying query over which the aggregations recorded in this + * `AggregateQuerySnapshot` were performed. + */ + readonly query: Query; + private constructor(); + /** + * Returns the results of the aggregations performed over the underlying + * query. + * + * The keys of the returned object will be the same as those of the + * `AggregateSpec` object specified to the aggregation method, and the values + * will be the corresponding aggregation result. + * + * @returns The results of the aggregations performed over the underlying + * query. + */ + data(): AggregateSpecData; +} +/** + * Compares two `AggregateQuerySnapshot` instances for equality. + * + * Two `AggregateQuerySnapshot` instances are considered "equal" if they have + * underlying queries that compare equal, and the same data. + * + * @param left - The first `AggregateQuerySnapshot` to compare. + * @param right - The second `AggregateQuerySnapshot` to compare. + * + * @returns `true` if the objects are "equal", as defined above, or `false` + * otherwise. + */ +export declare function aggregateQuerySnapshotEqual(left: AggregateQuerySnapshot, right: AggregateQuerySnapshot): boolean; +/** + * Specifies a set of aggregations and their aliases. + */ +export declare interface AggregateSpec { + [field: string]: AggregateFieldType; +} +/** + * A type whose keys are taken from an `AggregateSpec`, and whose values are the + * result of the aggregation performed by the corresponding `AggregateField` + * from the input `AggregateSpec`. + */ +export declare type AggregateSpecData = { + [P in keyof T]: T[P] extends AggregateField ? U : never; +}; +/** + * Union type representing the aggregate type to be performed. + */ +export declare type AggregateType = 'count' | 'avg' | 'sum'; +/** + * Creates a new {@link QueryCompositeFilterConstraint} that is a conjunction of + * the given filter constraints. A conjunction filter includes a document if it + * satisfies all of the given filters. + * + * @param queryConstraints - Optional. The list of + * {@link QueryFilterConstraint}s to perform a conjunction for. These must be + * created with calls to {@link where}, {@link or}, or {@link and}. + * @returns The newly created {@link QueryCompositeFilterConstraint}. + */ +export declare function and(...queryConstraints: QueryFilterConstraint[]): QueryCompositeFilterConstraint; +/** + * Returns a special value that can be used with {@link (setDoc:1)} or {@link + * updateDoc:1} that tells the server to remove the given elements from any + * array value that already exists on the server. All instances of each element + * specified will be removed from the array. If the field being modified is not + * already an array it will be overwritten with an empty array. + * + * @param elements - The elements to remove from the array. + * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or + * `updateDoc()` + */ +export declare function arrayRemove(...elements: unknown[]): FieldValue; +/** + * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link + * @firebase/firestore/lite#(updateDoc:1)} that tells the server to union the given elements with any array + * value that already exists on the server. Each specified element that doesn't + * already exist in the array will be added to the end. If the field being + * modified is not already an array it will be overwritten with an array + * containing exactly the specified elements. + * + * @param elements - The elements to union into the array. + * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or + * `updateDoc()`. + */ +export declare function arrayUnion(...elements: unknown[]): FieldValue; +/* Excluded from this release type: AuthTokenFactory */ +/** + * Create an AggregateField object that can be used to compute the average of + * a specified field over a range of documents in the result set of a query. + * @param field Specifies the field to average across the result set. + */ +export declare function average(field: string | FieldPath): AggregateField; +/** + * An immutable object representing an array of bytes. + */ +export declare class Bytes { + private constructor(); + /** + * Creates a new `Bytes` object from the given Base64 string, converting it to + * bytes. + * + * @param base64 - The Base64 string used to create the `Bytes` object. + */ + static fromBase64String(base64: string): Bytes; + /** + * Creates a new `Bytes` object from the given Uint8Array. + * + * @param array - The Uint8Array used to create the `Bytes` object. + */ + static fromUint8Array(array: Uint8Array): Bytes; + /** + * Returns the underlying bytes as a Base64-encoded string. + * + * @returns The Base64-encoded string created from the `Bytes` object. + */ + toBase64(): string; + /** + * Returns the underlying bytes in a new `Uint8Array`. + * + * @returns The Uint8Array created from the `Bytes` object. + */ + toUint8Array(): Uint8Array; + /** + * Returns a string representation of the `Bytes` object. + * + * @returns A string representation of the `Bytes` object. + */ + toString(): string; + /** + * Returns true if this `Bytes` object is equal to the provided one. + * + * @param other - The `Bytes` object to compare against. + * @returns true if this `Bytes` object is equal to the provided one. + */ + isEqual(other: Bytes): boolean; + /** + * Returns a JSON-serializable representation of this `Bytes` instance. + * + * @returns a JSON representation of this object. + */ + toJSON(): object; + /** + * Builds a `Bytes` instance from a JSON object created by {@link Bytes.toJSON}. + * + * @param json a JSON object represention of a `Bytes` instance + * @returns an instance of {@link Bytes} if the JSON object could be parsed. Throws a + * {@link FirestoreError} if an error occurs. + */ + static fromJSON(json: object): Bytes; +} +/** + * Helper for calculating the nested fields for a given type T1. This is needed + * to distribute union types such as `undefined | {...}` (happens for optional + * props) or `{a: A} | {b: B}`. + * + * In this use case, `V` is used to distribute the union types of `T[K]` on + * `Record`, since `T[K]` is evaluated as an expression and not distributed. + * + * See https://www.typescriptlang.org/docs/handbook/advanced-types.html#distributive-conditional-types + */ +export declare type ChildUpdateFields = V extends Record ? AddPrefixToKeys> : never; +/** + * Gets a `CollectionReference` instance that refers to the collection at + * the specified absolute path. + * + * @param firestore - A reference to the root `Firestore` instance. + * @param path - A slash-separated path to a collection. + * @param pathSegments - Additional path segments to apply relative to the first + * argument. + * @throws If the final path has an even number of segments and does not point + * to a collection. + * @returns The `CollectionReference` instance. + */ +export declare function collection(firestore: Firestore, path: string, ...pathSegments: string[]): CollectionReference; +/** + * Gets a `CollectionReference` instance that refers to a subcollection of + * `reference` at the specified relative path. + * + * @param reference - A reference to a collection. + * @param path - A slash-separated path to a collection. + * @param pathSegments - Additional path segments to apply relative to the first + * argument. + * @throws If the final path has an even number of segments and does not point + * to a collection. + * @returns The `CollectionReference` instance. + */ +export declare function collection(reference: CollectionReference, path: string, ...pathSegments: string[]): CollectionReference; +/** + * Gets a `CollectionReference` instance that refers to a subcollection of + * `reference` at the specified relative path. + * + * @param reference - A reference to a Firestore document. + * @param path - A slash-separated path to a collection. + * @param pathSegments - Additional path segments that will be applied relative + * to the first argument. + * @throws If the final path has an even number of segments and does not point + * to a collection. + * @returns The `CollectionReference` instance. + */ +export declare function collection(reference: DocumentReference, path: string, ...pathSegments: string[]): CollectionReference; +/** + * Creates and returns a new `Query` instance that includes all documents in the + * database that are contained in a collection or subcollection with the + * given `collectionId`. + * + * @param firestore - A reference to the root `Firestore` instance. + * @param collectionId - Identifies the collections to query over. Every + * collection or subcollection with this ID as the last segment of its path + * will be included. Cannot contain a slash. + * @returns The created `Query`. + */ +export declare function collectionGroup(firestore: Firestore, collectionId: string): Query; +/** + * A `CollectionReference` object can be used for adding documents, getting + * document references, and querying for documents (using {@link (query:1)}). + */ +export declare class CollectionReference extends Query { + /** The type of this Firestore reference. */ + readonly type = "collection"; + private constructor(); + /** The collection's identifier. */ + get id(): string; + /** + * A string representing the path of the referenced collection (relative + * to the root of the database). + */ + get path(): string; + /** + * A reference to the containing `DocumentReference` if this is a + * subcollection. If this isn't a subcollection, the reference is null. + */ + get parent(): DocumentReference | null; + /** + * Applies a custom data converter to this `CollectionReference`, allowing you + * to use your own custom model objects with Firestore. When you call {@link + * addDoc} with the returned `CollectionReference` instance, the provided + * converter will convert between Firestore data of type `NewDbModelType` and + * your custom type `NewAppModelType`. + * + * @param converter - Converts objects to and from Firestore. + * @returns A `CollectionReference` that uses the provided converter. + */ + withConverter(converter: FirestoreDataConverter): CollectionReference; + /** + * Removes the current converter. + * + * @param converter - `null` removes the current converter. + * @returns A `CollectionReference` that does not + * use a converter. + */ + withConverter(converter: null): CollectionReference; +} +/** + * Modify this instance to communicate with the Cloud Firestore emulator. + * + * Note: This must be called before this instance has been used to do any + * operations. + * + * @param firestore - The `Firestore` instance to configure to connect to the + * emulator. + * @param host - the emulator host (ex: localhost). + * @param port - the emulator port (ex: 9000). + * @param options.mockUserToken - the mock auth token to use for unit testing + * Security Rules. + */ +export declare function connectFirestoreEmulator(firestore: Firestore, host: string, port: number, options?: { + mockUserToken?: EmulatorMockTokenOptions | string; +}): void; +/** + * Create an AggregateField object that can be used to compute the count of + * documents in the result set of a query. + */ +export declare function count(): AggregateField; +/** + * Deletes the document referred to by the specified `DocumentReference`. + * + * The deletion will only be reflected in document reads that occur after the + * returned promise resolves. If the client is offline, the + * delete fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @param reference - A reference to the document to delete. + * @returns A `Promise` resolved once the document has been successfully + * deleted from the backend. + */ +export declare function deleteDoc(reference: DocumentReference): Promise; +/** + * Returns a sentinel for use with {@link @firebase/firestore/lite#(updateDoc:1)} or + * {@link @firebase/firestore/lite#(setDoc:1)} with `{merge: true}` to mark a field for deletion. + */ +export declare function deleteField(): FieldValue; +/** + * Gets a `DocumentReference` instance that refers to the document at the + * specified absolute path. + * + * @param firestore - A reference to the root `Firestore` instance. + * @param path - A slash-separated path to a document. + * @param pathSegments - Additional path segments that will be applied relative + * to the first argument. + * @throws If the final path has an odd number of segments and does not point to + * a document. + * @returns The `DocumentReference` instance. + */ +export declare function doc(firestore: Firestore, path: string, ...pathSegments: string[]): DocumentReference; +/** + * Gets a `DocumentReference` instance that refers to a document within + * `reference` at the specified relative path. If no path is specified, an + * automatically-generated unique ID will be used for the returned + * `DocumentReference`. + * + * @param reference - A reference to a collection. + * @param path - A slash-separated path to a document. Has to be omitted to use + * auto-generated IDs. + * @param pathSegments - Additional path segments that will be applied relative + * to the first argument. + * @throws If the final path has an odd number of segments and does not point to + * a document. + * @returns The `DocumentReference` instance. + */ +export declare function doc(reference: CollectionReference, path?: string, ...pathSegments: string[]): DocumentReference; +/** + * Gets a `DocumentReference` instance that refers to a document within + * `reference` at the specified relative path. + * + * @param reference - A reference to a Firestore document. + * @param path - A slash-separated path to a document. + * @param pathSegments - Additional path segments that will be applied relative + * to the first argument. + * @throws If the final path has an odd number of segments and does not point to + * a document. + * @returns The `DocumentReference` instance. + */ +export declare function doc(reference: DocumentReference, path: string, ...pathSegments: string[]): DocumentReference; +/** + * Document data (for use with {@link @firebase/firestore/lite#(setDoc:1)}) consists of fields mapped to + * values. + */ +export declare interface DocumentData { + /** A mapping between a field and its value. */ + [field: string]: any; +} +/** + * Returns a special sentinel `FieldPath` to refer to the ID of a document. + * It can be used in queries to sort or filter by the document ID. + */ +export declare function documentId(): FieldPath; +/** + * A `DocumentReference` refers to a document location in a Firestore database + * and can be used to write, read, or listen to the location. The document at + * the referenced location may or may not exist. + */ +export declare class DocumentReference { + /** + * If provided, the `FirestoreDataConverter` associated with this instance. + */ + readonly converter: FirestoreDataConverter | null; + /** The type of this Firestore reference. */ + readonly type = "document"; + /** + * The {@link Firestore} instance the document is in. + * This is useful for performing transactions, for example. + */ + readonly firestore: Firestore; + private constructor(); + /** + * The document's identifier within its collection. + */ + get id(): string; + /** + * A string representing the path of the referenced document (relative + * to the root of the database). + */ + get path(): string; + /** + * The collection this `DocumentReference` belongs to. + */ + get parent(): CollectionReference; + /** + * Applies a custom data converter to this `DocumentReference`, allowing you + * to use your own custom model objects with Firestore. When you call {@link + * @firebase/firestore/lite#(setDoc:1)}, {@link @firebase/firestore/lite#getDoc}, etc. with the returned `DocumentReference` + * instance, the provided converter will convert between Firestore data of + * type `NewDbModelType` and your custom type `NewAppModelType`. + * + * @param converter - Converts objects to and from Firestore. + * @returns A `DocumentReference` that uses the provided converter. + */ + withConverter(converter: FirestoreDataConverter): DocumentReference; + /** + * Removes the current converter. + * + * @param converter - `null` removes the current converter. + * @returns A `DocumentReference` that does not + * use a converter. + */ + withConverter(converter: null): DocumentReference; + /** + * Returns a JSON-serializable representation of this `DocumentReference` instance. + * + * @returns a JSON representation of this object. + */ + toJSON(): object; + /** + * Builds a `DocumentReference` instance from a JSON object created by + * {@link DocumentReference.toJSON}. + * + * @param firestore - The {@link Firestore} instance the snapshot should be loaded for. + * @param json a JSON object represention of a `DocumentReference` instance + * @returns an instance of {@link DocumentReference} if the JSON object could be parsed. Throws a + * {@link FirestoreError} if an error occurs. + */ + static fromJSON(firestore: Firestore, json: object): DocumentReference; + /** + * Builds a `DocumentReference` instance from a JSON object created by + * {@link DocumentReference.toJSON}. + * + * @param firestore - The {@link Firestore} instance the snapshot should be loaded for. + * @param json a JSON object represention of a `DocumentReference` instance + * @param converter - Converts objects to and from Firestore. + * @returns an instance of {@link DocumentReference} if the JSON object could be parsed. Throws a + * {@link FirestoreError} if an error occurs. + */ + static fromJSON(firestore: Firestore, json: object, converter: FirestoreDataConverter): DocumentReference; +} +/** + * A `DocumentSnapshot` contains data read from a document in your Firestore + * database. The data can be extracted with `.data()` or `.get()` to + * get a specific field. + * + * For a `DocumentSnapshot` that points to a non-existing document, any data + * access will return 'undefined'. You can use the `exists()` method to + * explicitly verify a document's existence. + */ +export declare class DocumentSnapshot { + protected constructor(); + /** Property of the `DocumentSnapshot` that provides the document's ID. */ + get id(): string; + /** + * The `DocumentReference` for the document included in the `DocumentSnapshot`. + */ + get ref(): DocumentReference; + /** + * Signals whether or not the document at the snapshot's location exists. + * + * @returns true if the document exists. + */ + exists(): this is QueryDocumentSnapshot; + /** + * Retrieves all fields in the document as an `Object`. Returns `undefined` if + * the document doesn't exist. + * + * @returns An `Object` containing all fields in the document or `undefined` + * if the document doesn't exist. + */ + data(): AppModelType | undefined; + /** + * Retrieves the field specified by `fieldPath`. Returns `undefined` if the + * document or field doesn't exist. + * + * @param fieldPath - The path (for example 'foo' or 'foo.bar') to a specific + * field. + * @returns The data at the specified field location or undefined if no such + * field exists in the document. + */ + get(fieldPath: string | FieldPath): any; +} +export { EmulatorMockTokenOptions }; +/** + * Creates a {@link QueryEndAtConstraint} that modifies the result set to end at + * the provided document (inclusive). The end position is relative to the order + * of the query. The document must contain all of the fields provided in the + * orderBy of the query. + * + * @param snapshot - The snapshot of the document to end at. + * @returns A {@link QueryEndAtConstraint} to pass to `query()` + */ +export declare function endAt(snapshot: DocumentSnapshot): QueryEndAtConstraint; +/** + * Creates a {@link QueryEndAtConstraint} that modifies the result set to end at + * the provided fields relative to the order of the query. The order of the field + * values must match the order of the order by clauses of the query. + * + * @param fieldValues - The field values to end this query at, in order + * of the query's order by. + * @returns A {@link QueryEndAtConstraint} to pass to `query()` + */ +export declare function endAt(...fieldValues: unknown[]): QueryEndAtConstraint; +/** + * Creates a {@link QueryEndAtConstraint} that modifies the result set to end + * before the provided document (exclusive). The end position is relative to the + * order of the query. The document must contain all of the fields provided in + * the orderBy of the query. + * + * @param snapshot - The snapshot of the document to end before. + * @returns A {@link QueryEndAtConstraint} to pass to `query()` + */ +export declare function endBefore(snapshot: DocumentSnapshot): QueryEndAtConstraint; +/** + * Creates a {@link QueryEndAtConstraint} that modifies the result set to end + * before the provided fields relative to the order of the query. The order of + * the field values must match the order of the order by clauses of the query. + * + * @param fieldValues - The field values to end this query before, in order + * of the query's order by. + * @returns A {@link QueryEndAtConstraint} to pass to `query()` + */ +export declare function endBefore(...fieldValues: unknown[]): QueryEndAtConstraint; +/** + * A `FieldPath` refers to a field in a document. The path may consist of a + * single field name (referring to a top-level field in the document), or a + * list of field names (referring to a nested field in the document). + * + * Create a `FieldPath` by providing field names. If more than one field + * name is provided, the path will point to a nested field in a document. + */ +export declare class FieldPath { + /** + * Creates a `FieldPath` from the provided field names. If more than one field + * name is provided, the path will point to a nested field in a document. + * + * @param fieldNames - A list of field names. + */ + constructor(...fieldNames: string[]); + /** + * Returns true if this `FieldPath` is equal to the provided one. + * + * @param other - The `FieldPath` to compare against. + * @returns true if this `FieldPath` is equal to the provided one. + */ + isEqual(other: FieldPath): boolean; +} +/** + * Sentinel values that can be used when writing document fields with `set()` + * or `update()`. + */ +export declare abstract class FieldValue { + private constructor(); + /** Compares `FieldValue`s for equality. */ + abstract isEqual(other: FieldValue): boolean; +} +/* Excluded from this release type: _FirebaseService */ +/** + * The Cloud Firestore service interface. + * + * Do not call this constructor directly. Instead, use {@link (getFirestore:1)}. + */ +export declare class Firestore { + /** + * Whether it's a Firestore or Firestore Lite instance. + */ + type: 'firestore-lite' | 'firestore'; + private constructor(); + /** + * The {@link @firebase/app#FirebaseApp} associated with this `Firestore` service + * instance. + */ + get app(): FirebaseApp; + /** Returns a JSON-serializable representation of this `Firestore` instance. */ + toJSON(): object; +} +/** + * Converter used by `withConverter()` to transform user objects of type + * `AppModelType` into Firestore data of type `DbModelType`. + * + * Using the converter allows you to specify generic type arguments when + * storing and retrieving objects from Firestore. + * + * In this context, an "AppModel" is a class that is used in an application to + * package together related information and functionality. Such a class could, + * for example, have properties with complex, nested data types, properties used + * for memoization, properties of types not supported by Firestore (such as + * `symbol` and `bigint`), and helper functions that perform compound + * operations. Such classes are not suitable and/or possible to store into a + * Firestore database. Instead, instances of such classes need to be converted + * to "plain old JavaScript objects" (POJOs) with exclusively primitive + * properties, potentially nested inside other POJOs or arrays of POJOs. In this + * context, this type is referred to as the "DbModel" and would be an object + * suitable for persisting into Firestore. For convenience, applications can + * implement `FirestoreDataConverter` and register the converter with Firestore + * objects, such as `DocumentReference` or `Query`, to automatically convert + * `AppModel` to `DbModel` when storing into Firestore, and convert `DbModel` + * to `AppModel` when retrieving from Firestore. + * + * @example + * + * Simple Example + * + * ```typescript + * const numberConverter = { + * toFirestore(value: WithFieldValue) { + * return { value }; + * }, + * fromFirestore(snapshot: QueryDocumentSnapshot, options: SnapshotOptions) { + * return snapshot.data(options).value as number; + * } + * }; + * + * async function simpleDemo(db: Firestore): Promise { + * const documentRef = doc(db, 'values/value123').withConverter(numberConverter); + * + * // converters are used with `setDoc`, `addDoc`, and `getDoc` + * await setDoc(documentRef, 42); + * const snapshot1 = await getDoc(documentRef); + * assertEqual(snapshot1.data(), 42); + * + * // converters are not used when writing data with `updateDoc` + * await updateDoc(documentRef, { value: 999 }); + * const snapshot2 = await getDoc(documentRef); + * assertEqual(snapshot2.data(), 999); + * } + * ``` + * + * Advanced Example + * + * ```typescript + * // The Post class is a model that is used by our application. + * // This class may have properties and methods that are specific + * // to our application execution, which do not need to be persisted + * // to Firestore. + * class Post { + * constructor( + * readonly title: string, + * readonly author: string, + * readonly lastUpdatedMillis: number + * ) {} + * toString(): string { + * return `${this.title} by ${this.author}`; + * } + * } + * + * // The PostDbModel represents how we want our posts to be stored + * // in Firestore. This DbModel has different properties (`ttl`, + * // `aut`, and `lut`) from the Post class we use in our application. + * interface PostDbModel { + * ttl: string; + * aut: { firstName: string; lastName: string }; + * lut: Timestamp; + * } + * + * // The `PostConverter` implements `FirestoreDataConverter` and specifies + * // how the Firestore SDK can convert `Post` objects to `PostDbModel` + * // objects and vice versa. + * class PostConverter implements FirestoreDataConverter { + * toFirestore(post: WithFieldValue): WithFieldValue { + * return { + * ttl: post.title, + * aut: this._autFromAuthor(post.author), + * lut: this._lutFromLastUpdatedMillis(post.lastUpdatedMillis) + * }; + * } + * + * fromFirestore(snapshot: QueryDocumentSnapshot, options: SnapshotOptions): Post { + * const data = snapshot.data(options) as PostDbModel; + * const author = `${data.aut.firstName} ${data.aut.lastName}`; + * return new Post(data.ttl, author, data.lut.toMillis()); + * } + * + * _autFromAuthor( + * author: string | FieldValue + * ): { firstName: string; lastName: string } | FieldValue { + * if (typeof author !== 'string') { + * // `author` is a FieldValue, so just return it. + * return author; + * } + * const [firstName, lastName] = author.split(' '); + * return {firstName, lastName}; + * } + * + * _lutFromLastUpdatedMillis( + * lastUpdatedMillis: number | FieldValue + * ): Timestamp | FieldValue { + * if (typeof lastUpdatedMillis !== 'number') { + * // `lastUpdatedMillis` must be a FieldValue, so just return it. + * return lastUpdatedMillis; + * } + * return Timestamp.fromMillis(lastUpdatedMillis); + * } + * } + * + * async function advancedDemo(db: Firestore): Promise { + * // Create a `DocumentReference` with a `FirestoreDataConverter`. + * const documentRef = doc(db, 'posts/post123').withConverter(new PostConverter()); + * + * // The `data` argument specified to `setDoc()` is type checked by the + * // TypeScript compiler to be compatible with `Post`. Since the `data` + * // argument is typed as `WithFieldValue` rather than just `Post`, + * // this allows properties of the `data` argument to also be special + * // Firestore values that perform server-side mutations, such as + * // `arrayRemove()`, `deleteField()`, and `serverTimestamp()`. + * await setDoc(documentRef, { + * title: 'My Life', + * author: 'Foo Bar', + * lastUpdatedMillis: serverTimestamp() + * }); + * + * // The TypeScript compiler will fail to compile if the `data` argument to + * // `setDoc()` is _not_ compatible with `WithFieldValue`. This + * // type checking prevents the caller from specifying objects with incorrect + * // properties or property values. + * // @ts-expect-error "Argument of type { ttl: string; } is not assignable + * // to parameter of type WithFieldValue" + * await setDoc(documentRef, { ttl: 'The Title' }); + * + * // When retrieving a document with `getDoc()` the `DocumentSnapshot` + * // object's `data()` method returns a `Post`, rather than a generic object, + * // which would have been returned if the `DocumentReference` did _not_ have a + * // `FirestoreDataConverter` attached to it. + * const snapshot1: DocumentSnapshot = await getDoc(documentRef); + * const post1: Post = snapshot1.data()!; + * if (post1) { + * assertEqual(post1.title, 'My Life'); + * assertEqual(post1.author, 'Foo Bar'); + * } + * + * // The `data` argument specified to `updateDoc()` is type checked by the + * // TypeScript compiler to be compatible with `PostDbModel`. Note that + * // unlike `setDoc()`, whose `data` argument must be compatible with `Post`, + * // the `data` argument to `updateDoc()` must be compatible with + * // `PostDbModel`. Similar to `setDoc()`, since the `data` argument is typed + * // as `WithFieldValue` rather than just `PostDbModel`, this + * // allows properties of the `data` argument to also be those special + * // Firestore values, like `arrayRemove()`, `deleteField()`, and + * // `serverTimestamp()`. + * await updateDoc(documentRef, { + * 'aut.firstName': 'NewFirstName', + * lut: serverTimestamp() + * }); + * + * // The TypeScript compiler will fail to compile if the `data` argument to + * // `updateDoc()` is _not_ compatible with `WithFieldValue`. + * // This type checking prevents the caller from specifying objects with + * // incorrect properties or property values. + * // @ts-expect-error "Argument of type { title: string; } is not assignable + * // to parameter of type WithFieldValue" + * await updateDoc(documentRef, { title: 'New Title' }); + * const snapshot2: DocumentSnapshot = await getDoc(documentRef); + * const post2: Post = snapshot2.data()!; + * if (post2) { + * assertEqual(post2.title, 'My Life'); + * assertEqual(post2.author, 'NewFirstName Bar'); + * } + * } + * ``` + */ +export declare interface FirestoreDataConverter { + /** + * Called by the Firestore SDK to convert a custom model object of type + * `AppModelType` into a plain JavaScript object (suitable for writing + * directly to the Firestore database) of type `DbModelType`. Used with + * {@link @firebase/firestore/lite#(setDoc:1)}, + * {@link @firebase/firestore/lite#(WriteBatch.set:1)} and + * {@link @firebase/firestore/lite#(Transaction.set:1)}. + * + * The `WithFieldValue` type extends `T` to also allow FieldValues such as + * {@link (deleteField:1)} to be used as property values. + */ + toFirestore(modelObject: WithFieldValue): WithFieldValue; + /** + * Called by the Firestore SDK to convert a custom model object of type + * `AppModelType` into a plain JavaScript object (suitable for writing + * directly to the Firestore database) of type `DbModelType`. Used with + * {@link @firebase/firestore/lite#(setDoc:1)}, + * {@link @firebase/firestore/lite#(WriteBatch.set:1)} and + * {@link @firebase/firestore/lite#(Transaction.set:1)} with `merge:true` + * or `mergeFields`. + * + * The `PartialWithFieldValue` type extends `Partial` to allow + * FieldValues such as {@link (arrayUnion:1)} to be used as property values. + * It also supports nested `Partial` by allowing nested fields to be + * omitted. + */ + toFirestore(modelObject: PartialWithFieldValue, options: SetOptions): PartialWithFieldValue; + /** + * Called by the Firestore SDK to convert Firestore data into an object of + * type `AppModelType`. You can access your data by calling: + * `snapshot.data()`. + * + * + * Generally, the data returned from `snapshot.data()` can be cast to + * `DbModelType`; however, this is not guaranteed because Firestore does not + * enforce a schema on the database. For example, writes from a previous + * version of the application or writes from another client that did not use a + * type converter could have written data with different properties and/or + * property types. The implementation will need to choose whether to + * gracefully recover from non-conforming data or throw an error. + * + * @param snapshot - A `QueryDocumentSnapshot` containing your data and + * metadata. + */ + fromFirestore(snapshot: QueryDocumentSnapshot): AppModelType; +} +/** An error returned by a Firestore operation. */ +export declare class FirestoreError extends FirebaseError { + /** + * The backend error code associated with this error. + */ + readonly code: FirestoreErrorCode; + /** + * A custom error description. + */ + readonly message: string; + /** The stack of the error. */ + readonly stack?: string; + private constructor(); +} +/** + * The set of Firestore status codes. The codes are the same at the ones + * exposed by gRPC here: + * https://github.com/grpc/grpc/blob/master/doc/statuscodes.md + * + * Possible values: + * - 'cancelled': The operation was cancelled (typically by the caller). + * - 'unknown': Unknown error or an error from a different error domain. + * - 'invalid-argument': Client specified an invalid argument. Note that this + * differs from 'failed-precondition'. 'invalid-argument' indicates + * arguments that are problematic regardless of the state of the system + * (e.g. an invalid field name). + * - 'deadline-exceeded': Deadline expired before operation could complete. + * For operations that change the state of the system, this error may be + * returned even if the operation has completed successfully. For example, + * a successful response from a server could have been delayed long enough + * for the deadline to expire. + * - 'not-found': Some requested document was not found. + * - 'already-exists': Some document that we attempted to create already + * exists. + * - 'permission-denied': The caller does not have permission to execute the + * specified operation. + * - 'resource-exhausted': Some resource has been exhausted, perhaps a + * per-user quota, or perhaps the entire file system is out of space. + * - 'failed-precondition': Operation was rejected because the system is not + * in a state required for the operation's execution. + * - 'aborted': The operation was aborted, typically due to a concurrency + * issue like transaction aborts, etc. + * - 'out-of-range': Operation was attempted past the valid range. + * - 'unimplemented': Operation is not implemented or not supported/enabled. + * - 'internal': Internal errors. Means some invariants expected by + * underlying system has been broken. If you see one of these errors, + * something is very broken. + * - 'unavailable': The service is currently unavailable. This is most likely + * a transient condition and may be corrected by retrying with a backoff. + * - 'data-loss': Unrecoverable data loss or corruption. + * - 'unauthenticated': The request does not have valid authentication + * credentials for the operation. + */ +export declare type FirestoreErrorCode = 'cancelled' | 'unknown' | 'invalid-argument' | 'deadline-exceeded' | 'not-found' | 'already-exists' | 'permission-denied' | 'resource-exhausted' | 'failed-precondition' | 'aborted' | 'out-of-range' | 'unimplemented' | 'internal' | 'unavailable' | 'data-loss' | 'unauthenticated'; +/** + * An immutable object representing a geographic location in Firestore. The + * location is represented as latitude/longitude pair. + * + * Latitude values are in the range of [-90, 90]. + * Longitude values are in the range of [-180, 180]. + */ +export declare class GeoPoint { + /** + * Creates a new immutable `GeoPoint` object with the provided latitude and + * longitude values. + * @param latitude - The latitude as number between -90 and 90. + * @param longitude - The longitude as number between -180 and 180. + */ + constructor(latitude: number, longitude: number); + /** + * The latitude of this `GeoPoint` instance. + */ + get latitude(): number; + /** + * The longitude of this `GeoPoint` instance. + */ + get longitude(): number; + /** + * Returns true if this `GeoPoint` is equal to the provided one. + * + * @param other - The `GeoPoint` to compare against. + * @returns true if this `GeoPoint` is equal to the provided one. + */ + isEqual(other: GeoPoint): boolean; + /** + * Returns a JSON-serializable representation of this `GeoPoint` instance. + * + * @returns a JSON representation of this object. + */ + toJSON(): { + latitude: number; + longitude: number; + type: string; + }; + /** + * Builds a `GeoPoint` instance from a JSON object created by {@link GeoPoint.toJSON}. + * + * @param json a JSON object represention of a `GeoPoint` instance + * @returns an instance of {@link GeoPoint} if the JSON object could be parsed. Throws a + * {@link FirestoreError} if an error occurs. + */ + static fromJSON(json: object): GeoPoint; +} +/** + * Calculates the specified aggregations over the documents in the result + * set of the given query without actually downloading the documents. + * + * Using this function to perform aggregations is efficient because only the + * final aggregation values, not the documents' data, are downloaded. This + * function can perform aggregations of the documents in cases where the result + * set is prohibitively large to download entirely (thousands of documents). + * + * @param query The query whose result set is aggregated over. + * @param aggregateSpec An `AggregateSpec` object that specifies the aggregates + * to perform over the result set. The AggregateSpec specifies aliases for each + * aggregate, which can be used to retrieve the aggregate result. + * @example + * ```typescript + * const aggregateSnapshot = await getAggregate(query, { + * countOfDocs: count(), + * totalHours: sum('hours'), + * averageScore: average('score') + * }); + * + * const countOfDocs: number = aggregateSnapshot.data().countOfDocs; + * const totalHours: number = aggregateSnapshot.data().totalHours; + * const averageScore: number | null = aggregateSnapshot.data().averageScore; + * ``` + */ +export declare function getAggregate(query: Query, aggregateSpec: AggregateSpecType): Promise>; +/** + * Calculates the number of documents in the result set of the given query + * without actually downloading the documents. + * + * Using this function to count the documents is efficient because only the + * final count, not the documents' data, is downloaded. This function can + * count the documents in cases where the result set is prohibitively large to + * download entirely (thousands of documents). + * + * @param query The query whose result set size is calculated. + * @returns A Promise that will be resolved with the count; the count can be + * retrieved from `snapshot.data().count`, where `snapshot` is the + * `AggregateQuerySnapshot` to which the returned Promise resolves. + */ +export declare function getCount(query: Query): Promise; +}, AppModelType, DbModelType>>; +/** + * Reads the document referred to by the specified document reference. + * + * All documents are directly fetched from the server, even if the document was + * previously read or modified. Recent modifications are only reflected in the + * retrieved `DocumentSnapshot` if they have already been applied by the + * backend. If the client is offline, the read fails. If you like to use + * caching or see local modifications, please use the full Firestore SDK. + * + * @param reference - The reference of the document to fetch. + * @returns A Promise resolved with a `DocumentSnapshot` containing the current + * document contents. + */ +export declare function getDoc(reference: DocumentReference): Promise>; +/** + * Executes the query and returns the results as a {@link QuerySnapshot}. + * + * All queries are executed directly by the server, even if the query was + * previously executed. Recent modifications are only reflected in the retrieved + * results if they have already been applied by the backend. If the client is + * offline, the operation fails. To see previously cached result and local + * modifications, use the full Firestore SDK. + * + * @param query - The `Query` to execute. + * @returns A Promise that will be resolved with the results of the query. + */ +export declare function getDocs(query: Query): Promise>; +/** + * Returns the existing default {@link Firestore} instance that is associated with the + * default {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new + * instance with default settings. + * + * @returns The {@link Firestore} instance of the provided app. + */ +export declare function getFirestore(): Firestore; +/** + * Returns the existing default {@link Firestore} instance that is associated with the + * provided {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new + * instance with default settings. + * + * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned {@link Firestore} + * instance is associated with. + * @returns The {@link Firestore} instance of the provided app. + */ +export declare function getFirestore(app: FirebaseApp): Firestore; +/** + * Returns the existing {@link Firestore} instance that is associated with the + * default {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new + * instance with default settings. + * + * @param databaseId - The name of the database. + * @returns The {@link Firestore} instance of the provided app. + * @beta + */ +export declare function getFirestore(databaseId: string): Firestore; +/** + * Returns the existing {@link Firestore} instance that is associated with the + * provided {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new + * instance with default settings. + * + * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned {@link Firestore} + * instance is associated with. + * @param databaseId - The name of the database. + * @returns The {@link Firestore} instance of the provided app. + * @beta + */ +export declare function getFirestore(app: FirebaseApp, databaseId: string): Firestore; +/** + * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link + * @firebase/firestore/lite#(updateDoc:1)} that tells the server to increment the field's current value by + * the given value. + * + * If either the operand or the current field value uses floating point + * precision, all arithmetic follows IEEE 754 semantics. If both values are + * integers, values outside of JavaScript's safe number range + * (`Number.MIN_SAFE_INTEGER` to `Number.MAX_SAFE_INTEGER`) are also subject to + * precision loss. Furthermore, once processed by the Firestore backend, all + * integer operations are capped between -2^63 and 2^63-1. + * + * If the current field value is not of type `number`, or if the field does not + * yet exist, the transformation sets the field to the given value. + * + * @param n - The value to increment by. + * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or + * `updateDoc()` + */ +export declare function increment(n: number): FieldValue; +/** + * Initializes a new instance of Cloud Firestore with the provided settings. + * Can only be called before any other functions, including + * {@link (getFirestore:1)}. If the custom settings are empty, this function is + * equivalent to calling {@link (getFirestore:1)}. + * + * @param app - The {@link @firebase/app#FirebaseApp} with which the `Firestore` instance will + * be associated. + * @param settings - A settings object to configure the `Firestore` instance. + * @returns A newly initialized `Firestore` instance. + */ +export declare function initializeFirestore(app: FirebaseApp, settings: Settings): Firestore; +/** + * Initializes a new instance of Cloud Firestore with the provided settings. + * Can only be called before any other functions, including + * {@link (getFirestore:1)}. If the custom settings are empty, this function is + * equivalent to calling {@link (getFirestore:1)}. + * + * @param app - The {@link @firebase/app#FirebaseApp} with which the `Firestore` instance will + * be associated. + * @param settings - A settings object to configure the `Firestore` instance. + * @param databaseId - The name of the database. + * @returns A newly initialized `Firestore` instance. + * @beta + */ +export declare function initializeFirestore(app: FirebaseApp, settings: Settings, databaseId?: string): Firestore; +/** + * Creates a {@link QueryLimitConstraint} that only returns the first matching + * documents. + * + * @param limit - The maximum number of items to return. + * @returns The created {@link QueryLimitConstraint}. + */ +export declare function limit(limit: number): QueryLimitConstraint; +/** + * Creates a {@link QueryLimitConstraint} that only returns the last matching + * documents. + * + * You must specify at least one `orderBy` clause for `limitToLast` queries, + * otherwise an exception will be thrown during execution. + * + * @param limit - The maximum number of items to return. + * @returns The created {@link QueryLimitConstraint}. + */ +export declare function limitToLast(limit: number): QueryLimitConstraint; +export { LogLevel }; +/** + * For each field (e.g. 'bar'), find all nested keys (e.g. {'bar.baz': T1, + * 'bar.qux': T2}). Intersect them together to make a single map containing + * all possible keys that are all marked as optional + */ +export declare type NestedUpdateFields> = UnionToIntersection<{ + [K in keyof T & string]: ChildUpdateFields; +}[keyof T & string]>; +/** + * Creates a new {@link QueryCompositeFilterConstraint} that is a disjunction of + * the given filter constraints. A disjunction filter includes a document if it + * satisfies any of the given filters. + * + * @param queryConstraints - Optional. The list of + * {@link QueryFilterConstraint}s to perform a disjunction for. These must be + * created with calls to {@link where}, {@link or}, or {@link and}. + * @returns The newly created {@link QueryCompositeFilterConstraint}. + */ +export declare function or(...queryConstraints: QueryFilterConstraint[]): QueryCompositeFilterConstraint; +/** + * Creates a {@link QueryOrderByConstraint} that sorts the query result by the + * specified field, optionally in descending order instead of ascending. + * + * Note: Documents that do not contain the specified field will not be present + * in the query result. + * + * @param fieldPath - The field to sort by. + * @param directionStr - Optional direction to sort by ('asc' or 'desc'). If + * not specified, order will be ascending. + * @returns The created {@link QueryOrderByConstraint}. + */ +export declare function orderBy(fieldPath: string | FieldPath, directionStr?: OrderByDirection): QueryOrderByConstraint; +/** + * The direction of a {@link orderBy} clause is specified as 'desc' or 'asc' + * (descending or ascending). + */ +export declare type OrderByDirection = 'desc' | 'asc'; +/** + * Similar to TypeScript's `Partial`, but allows nested fields to be + * omitted and FieldValues to be passed in as property values. + */ +export declare type PartialWithFieldValue = Partial | (T extends Primitive ? T : T extends {} ? { + [K in keyof T]?: PartialWithFieldValue | FieldValue; +} : never); +/** + * These types primarily exist to support the `UpdateData`, + * `WithFieldValue`, and `PartialWithFieldValue` types and are not consumed + * directly by the end developer. + */ +/** Primitive types. */ +export declare type Primitive = string | number | boolean | undefined | null; +/** + * A `Query` refers to a query which you can read or listen to. You can also + * construct refined `Query` objects by adding filters and ordering. + */ +export declare class Query { + /** + * If provided, the `FirestoreDataConverter` associated with this instance. + */ + readonly converter: FirestoreDataConverter | null; + /** The type of this Firestore reference. */ + readonly type: 'query' | 'collection'; + /** + * The `Firestore` instance for the Firestore database (useful for performing + * transactions, etc.). + */ + readonly firestore: Firestore; + protected constructor(); + /** + * Removes the current converter. + * + * @param converter - `null` removes the current converter. + * @returns A `Query` that does not use a + * converter. + */ + withConverter(converter: null): Query; + /** + * Applies a custom data converter to this query, allowing you to use your own + * custom model objects with Firestore. When you call {@link getDocs} with + * the returned query, the provided converter will convert between Firestore + * data of type `NewDbModelType` and your custom type `NewAppModelType`. + * + * @param converter - Converts objects to and from Firestore. + * @returns A `Query` that uses the provided converter. + */ + withConverter(converter: FirestoreDataConverter): Query; +} +/** + * Creates a new immutable instance of {@link Query} that is extended to also + * include additional query constraints. + * + * @param query - The {@link Query} instance to use as a base for the new + * constraints. + * @param compositeFilter - The {@link QueryCompositeFilterConstraint} to + * apply. Create {@link QueryCompositeFilterConstraint} using {@link and} or + * {@link or}. + * @param queryConstraints - Additional {@link QueryNonFilterConstraint}s to + * apply (e.g. {@link orderBy}, {@link limit}). + * @throws if any of the provided query constraints cannot be combined with the + * existing or new constraints. + */ +export declare function query(query: Query, compositeFilter: QueryCompositeFilterConstraint, ...queryConstraints: QueryNonFilterConstraint[]): Query; +/** + * Creates a new immutable instance of {@link Query} that is extended to also + * include additional query constraints. + * + * @param query - The {@link Query} instance to use as a base for the new + * constraints. + * @param queryConstraints - The list of {@link QueryConstraint}s to apply. + * @throws if any of the provided query constraints cannot be combined with the + * existing or new constraints. + */ +export declare function query(query: Query, ...queryConstraints: QueryConstraint[]): Query; +/** + * A `QueryCompositeFilterConstraint` is used to narrow the set of documents + * returned by a Firestore query by performing the logical OR or AND of multiple + * {@link QueryFieldFilterConstraint}s or {@link QueryCompositeFilterConstraint}s. + * `QueryCompositeFilterConstraint`s are created by invoking {@link or} or + * {@link and} and can then be passed to {@link (query:1)} to create a new query + * instance that also contains the `QueryCompositeFilterConstraint`. + */ +export declare class QueryCompositeFilterConstraint { + /** The type of this query constraint */ + readonly type: 'or' | 'and'; +} +/** + * A `QueryConstraint` is used to narrow the set of documents returned by a + * Firestore query. `QueryConstraint`s are created by invoking {@link where}, + * {@link orderBy}, {@link (startAt:1)}, {@link (startAfter:1)}, {@link + * (endBefore:1)}, {@link (endAt:1)}, {@link limit}, {@link limitToLast} and + * can then be passed to {@link (query:1)} to create a new query instance that + * also contains this `QueryConstraint`. + */ +export declare abstract class QueryConstraint { + /** The type of this query constraint */ + abstract readonly type: QueryConstraintType; +} +/** Describes the different query constraints available in this SDK. */ +export declare type QueryConstraintType = 'where' | 'orderBy' | 'limit' | 'limitToLast' | 'startAt' | 'startAfter' | 'endAt' | 'endBefore'; +/** + * A `QueryDocumentSnapshot` contains data read from a document in your + * Firestore database as part of a query. The document is guaranteed to exist + * and its data can be extracted with `.data()` or `.get()` to get a + * specific field. + * + * A `QueryDocumentSnapshot` offers the same API surface as a + * `DocumentSnapshot`. Since query results contain only existing documents, the + * `exists` property will always be true and `data()` will never return + * 'undefined'. + */ +export declare class QueryDocumentSnapshot extends DocumentSnapshot { + /** + * Retrieves all fields in the document as an `Object`. + * + * @override + * @returns An `Object` containing all fields in the document. + */ + data(): AppModelType; +} +/** + * A `QueryEndAtConstraint` is used to exclude documents from the end of a + * result set returned by a Firestore query. + * `QueryEndAtConstraint`s are created by invoking {@link (endAt:1)} or + * {@link (endBefore:1)} and can then be passed to {@link (query:1)} to create a new + * query instance that also contains this `QueryEndAtConstraint`. + */ +export declare class QueryEndAtConstraint extends QueryConstraint { + /** The type of this query constraint */ + readonly type: 'endBefore' | 'endAt'; +} +/** + * Returns true if the provided queries point to the same collection and apply + * the same constraints. + * + * @param left - A `Query` to compare. + * @param right - A `Query` to compare. + * @returns true if the references point to the same location in the same + * Firestore database. + */ +export declare function queryEqual(left: Query, right: Query): boolean; +/** + * A `QueryFieldFilterConstraint` is used to narrow the set of documents returned by + * a Firestore query by filtering on one or more document fields. + * `QueryFieldFilterConstraint`s are created by invoking {@link where} and can then + * be passed to {@link (query:1)} to create a new query instance that also contains + * this `QueryFieldFilterConstraint`. + */ +export declare class QueryFieldFilterConstraint extends QueryConstraint { + /** The type of this query constraint */ + readonly type = "where"; +} +/** + * `QueryFilterConstraint` is a helper union type that represents + * {@link QueryFieldFilterConstraint} and {@link QueryCompositeFilterConstraint}. + */ +export declare type QueryFilterConstraint = QueryFieldFilterConstraint | QueryCompositeFilterConstraint; +/** + * A `QueryLimitConstraint` is used to limit the number of documents returned by + * a Firestore query. + * `QueryLimitConstraint`s are created by invoking {@link limit} or + * {@link limitToLast} and can then be passed to {@link (query:1)} to create a new + * query instance that also contains this `QueryLimitConstraint`. + */ +export declare class QueryLimitConstraint extends QueryConstraint { + /** The type of this query constraint */ + readonly type: 'limit' | 'limitToLast'; +} +/** + * `QueryNonFilterConstraint` is a helper union type that represents + * QueryConstraints which are used to narrow or order the set of documents, + * but that do not explicitly filter on a document field. + * `QueryNonFilterConstraint`s are created by invoking {@link orderBy}, + * {@link (startAt:1)}, {@link (startAfter:1)}, {@link (endBefore:1)}, {@link (endAt:1)}, + * {@link limit} or {@link limitToLast} and can then be passed to {@link (query:1)} + * to create a new query instance that also contains the `QueryConstraint`. + */ +export declare type QueryNonFilterConstraint = QueryOrderByConstraint | QueryLimitConstraint | QueryStartAtConstraint | QueryEndAtConstraint; +/** + * A `QueryOrderByConstraint` is used to sort the set of documents returned by a + * Firestore query. `QueryOrderByConstraint`s are created by invoking + * {@link orderBy} and can then be passed to {@link (query:1)} to create a new query + * instance that also contains this `QueryOrderByConstraint`. + * + * Note: Documents that do not contain the orderBy field will not be present in + * the query result. + */ +export declare class QueryOrderByConstraint extends QueryConstraint { + /** The type of this query constraint */ + readonly type = "orderBy"; +} +/** + * A `QuerySnapshot` contains zero or more `DocumentSnapshot` objects + * representing the results of a query. The documents can be accessed as an + * array via the `docs` property or enumerated using the `forEach` method. The + * number of documents can be determined via the `empty` and `size` + * properties. + */ +export declare class QuerySnapshot { + /** + * The query on which you called {@link getDocs} in order to get this + * `QuerySnapshot`. + */ + readonly query: Query; + private constructor(); + /** An array of all the documents in the `QuerySnapshot`. */ + get docs(): Array>; + /** The number of documents in the `QuerySnapshot`. */ + get size(): number; + /** True if there are no documents in the `QuerySnapshot`. */ + get empty(): boolean; + /** + * Enumerates all of the documents in the `QuerySnapshot`. + * + * @param callback - A callback to be called with a `QueryDocumentSnapshot` for + * each document in the snapshot. + * @param thisArg - The `this` binding for the callback. + */ + forEach(callback: (result: QueryDocumentSnapshot) => void, thisArg?: unknown): void; +} +/** + * A `QueryStartAtConstraint` is used to exclude documents from the start of a + * result set returned by a Firestore query. + * `QueryStartAtConstraint`s are created by invoking {@link (startAt:1)} or + * {@link (startAfter:1)} and can then be passed to {@link (query:1)} to create a + * new query instance that also contains this `QueryStartAtConstraint`. + */ +export declare class QueryStartAtConstraint extends QueryConstraint { + /** The type of this query constraint */ + readonly type: 'startAt' | 'startAfter'; +} +/** + * Returns true if the provided references are equal. + * + * @param left - A reference to compare. + * @param right - A reference to compare. + * @returns true if the references point to the same location in the same + * Firestore database. + */ +export declare function refEqual(left: DocumentReference | CollectionReference, right: DocumentReference | CollectionReference): boolean; +/* Excluded from this release type: ResourcePath */ +/** + * Executes the given `updateFunction` and then attempts to commit the changes + * applied within the transaction. If any document read within the transaction + * has changed, Cloud Firestore retries the `updateFunction`. If it fails to + * commit after 5 attempts, the transaction fails. + * + * The maximum number of writes allowed in a single transaction is 500. + * + * @param firestore - A reference to the Firestore database to run this + * transaction against. + * @param updateFunction - The function to execute within the transaction + * context. + * @param options - An options object to configure maximum number of attempts to + * commit. + * @returns If the transaction completed successfully or was explicitly aborted + * (the `updateFunction` returned a failed promise), the promise returned by the + * `updateFunction `is returned here. Otherwise, if the transaction failed, a + * rejected promise with the corresponding failure error is returned. + */ +export declare function runTransaction(firestore: Firestore, updateFunction: (transaction: Transaction) => Promise, options?: TransactionOptions): Promise; +/** + * Returns a sentinel used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link @firebase/firestore/lite#(updateDoc:1)} to + * include a server-generated timestamp in the written data. + */ +export declare function serverTimestamp(): FieldValue; +/** + * Writes to the document referred to by the specified `DocumentReference`. If + * the document does not yet exist, it will be created. + * + * The result of this write will only be reflected in document reads that occur + * after the returned promise resolves. If the client is offline, the + * write fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @param reference - A reference to the document to write. + * @param data - A map of the fields and values for the document. + * @throws Error - If the provided input is not a valid Firestore document. + * @returns A `Promise` resolved once the data has been successfully written + * to the backend. + */ +export declare function setDoc(reference: DocumentReference, data: WithFieldValue): Promise; +/** + * Writes to the document referred to by the specified `DocumentReference`. If + * the document does not yet exist, it will be created. If you provide `merge` + * or `mergeFields`, the provided data can be merged into an existing document. + * + * The result of this write will only be reflected in document reads that occur + * after the returned promise resolves. If the client is offline, the + * write fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @param reference - A reference to the document to write. + * @param data - A map of the fields and values for the document. + * @param options - An object to configure the set behavior. + * @throws Error - If the provided input is not a valid Firestore document. + * @returns A `Promise` resolved once the data has been successfully written + * to the backend. + */ +export declare function setDoc(reference: DocumentReference, data: PartialWithFieldValue, options: SetOptions): Promise; +/** + * Sets the verbosity of Cloud Firestore logs (debug, error, or silent). + * + * @param logLevel - The verbosity you set for activity and error logging. Can + * be any of the following values: + * + *
    + *
  • `debug` for the most verbose logging level, primarily for + * debugging.
  • + *
  • `error` to log errors only.
  • + *
  • `silent` to turn off logging.
  • + *
+ */ +export declare function setLogLevel(logLevel: LogLevel): void; +/** + * An options object that configures the behavior of {@link @firebase/firestore/lite#(setDoc:1)}, {@link + * @firebase/firestore/lite#(WriteBatch.set:1)} and {@link @firebase/firestore/lite#(Transaction.set:1)} calls. These calls can be + * configured to perform granular merges instead of overwriting the target + * documents in their entirety by providing a `SetOptions` with `merge: true`. + * + * @param merge - Changes the behavior of a `setDoc()` call to only replace the + * values specified in its data argument. Fields omitted from the `setDoc()` + * call remain untouched. If your input sets any field to an empty map, all + * nested fields are overwritten. + * @param mergeFields - Changes the behavior of `setDoc()` calls to only replace + * the specified field paths. Any field path that is not specified is ignored + * and remains untouched. If your input sets any field to an empty map, all + * nested fields are overwritten. + */ +export declare type SetOptions = { + readonly merge?: boolean; +} | { + readonly mergeFields?: Array; +}; +/** + * Specifies custom configurations for your Cloud Firestore instance. + * You must set these before invoking any other methods. + */ +export declare interface Settings { + /** The hostname to connect to. */ + host?: string; + /** Whether to use SSL when connecting. */ + ssl?: boolean; + /** + * Whether to skip nested properties that are set to `undefined` during + * object serialization. If set to `true`, these properties are skipped + * and not written to Firestore. If set to `false` or omitted, the SDK + * throws an exception when it encounters properties of type `undefined`. + */ + ignoreUndefinedProperties?: boolean; +} +/** + * Returns true if the provided snapshots are equal. + * + * @param left - A snapshot to compare. + * @param right - A snapshot to compare. + * @returns true if the snapshots are equal. + */ +export declare function snapshotEqual(left: DocumentSnapshot | QuerySnapshot, right: DocumentSnapshot | QuerySnapshot): boolean; +/** + * Creates a {@link QueryStartAtConstraint} that modifies the result set to + * start after the provided document (exclusive). The starting position is + * relative to the order of the query. The document must contain all of the + * fields provided in the orderBy of the query. + * + * @param snapshot - The snapshot of the document to start after. + * @returns A {@link QueryStartAtConstraint} to pass to `query()` + */ +export declare function startAfter(snapshot: DocumentSnapshot): QueryStartAtConstraint; +/** + * Creates a {@link QueryStartAtConstraint} that modifies the result set to + * start after the provided fields relative to the order of the query. The order + * of the field values must match the order of the order by clauses of the query. + * + * @param fieldValues - The field values to start this query after, in order + * of the query's order by. + * @returns A {@link QueryStartAtConstraint} to pass to `query()` + */ +export declare function startAfter(...fieldValues: unknown[]): QueryStartAtConstraint; +/** + * Creates a {@link QueryStartAtConstraint} that modifies the result set to + * start at the provided document (inclusive). The starting position is relative + * to the order of the query. The document must contain all of the fields + * provided in the `orderBy` of this query. + * + * @param snapshot - The snapshot of the document to start at. + * @returns A {@link QueryStartAtConstraint} to pass to `query()`. + */ +export declare function startAt(snapshot: DocumentSnapshot): QueryStartAtConstraint; +/** + * Creates a {@link QueryStartAtConstraint} that modifies the result set to + * start at the provided fields relative to the order of the query. The order of + * the field values must match the order of the order by clauses of the query. + * + * @param fieldValues - The field values to start this query at, in order + * of the query's order by. + * @returns A {@link QueryStartAtConstraint} to pass to `query()`. + */ +export declare function startAt(...fieldValues: unknown[]): QueryStartAtConstraint; +/** + * Create an AggregateField object that can be used to compute the sum of + * a specified field over a range of documents in the result set of a query. + * @param field Specifies the field to sum across the result set. + */ +export declare function sum(field: string | FieldPath): AggregateField; +/** + * Terminates the provided `Firestore` instance. + * + * After calling `terminate()` only the `clearIndexedDbPersistence()` functions + * may be used. Any other function will throw a `FirestoreError`. Termination + * does not cancel any pending writes, and any promises that are awaiting a + * response from the server will not be resolved. + * + * To restart after termination, create a new instance of `Firestore` with + * {@link (getFirestore:1)}. + * + * Note: Under normal circumstances, calling `terminate()` is not required. This + * function is useful only when you want to force this instance to release all of + * its resources or in combination with {@link clearIndexedDbPersistence} to + * ensure that all local state is destroyed between test runs. + * + * @param firestore - The `Firestore` instance to terminate. + * @returns A `Promise` that is resolved when the instance has been successfully + * terminated. + */ +export declare function terminate(firestore: Firestore): Promise; +/** + * A `Timestamp` represents a point in time independent of any time zone or + * calendar, represented as seconds and fractions of seconds at nanosecond + * resolution in UTC Epoch time. + * + * It is encoded using the Proleptic Gregorian Calendar which extends the + * Gregorian calendar backwards to year one. It is encoded assuming all minutes + * are 60 seconds long, i.e. leap seconds are "smeared" so that no leap second + * table is needed for interpretation. Range is from 0001-01-01T00:00:00Z to + * 9999-12-31T23:59:59.999999999Z. + * + * For examples and further specifications, refer to the + * {@link https://github.com/google/protobuf/blob/master/src/google/protobuf/timestamp.proto | Timestamp definition}. + */ +export declare class Timestamp { + /** + * The number of seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z. + */ + readonly seconds: number; + /** + * The fractions of a second at nanosecond resolution.* + */ + readonly nanoseconds: number; + /** + * Creates a new timestamp with the current date, with millisecond precision. + * + * @returns a new timestamp representing the current date. + */ + static now(): Timestamp; + /** + * Creates a new timestamp from the given date. + * + * @param date - The date to initialize the `Timestamp` from. + * @returns A new `Timestamp` representing the same point in time as the given + * date. + */ + static fromDate(date: Date): Timestamp; + /** + * Creates a new timestamp from the given number of milliseconds. + * + * @param milliseconds - Number of milliseconds since Unix epoch + * 1970-01-01T00:00:00Z. + * @returns A new `Timestamp` representing the same point in time as the given + * number of milliseconds. + */ + static fromMillis(milliseconds: number): Timestamp; + /** + * Creates a new timestamp. + * + * @param seconds - The number of seconds of UTC time since Unix epoch + * 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to + * 9999-12-31T23:59:59Z inclusive. + * @param nanoseconds - The non-negative fractions of a second at nanosecond + * resolution. Negative second values with fractions must still have + * non-negative nanoseconds values that count forward in time. Must be + * from 0 to 999,999,999 inclusive. + */ + constructor( + /** + * The number of seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z. + */ + seconds: number, + /** + * The fractions of a second at nanosecond resolution.* + */ + nanoseconds: number); + /** + * Converts a `Timestamp` to a JavaScript `Date` object. This conversion + * causes a loss of precision since `Date` objects only support millisecond + * precision. + * + * @returns JavaScript `Date` object representing the same point in time as + * this `Timestamp`, with millisecond precision. + */ + toDate(): Date; + /** + * Converts a `Timestamp` to a numeric timestamp (in milliseconds since + * epoch). This operation causes a loss of precision. + * + * @returns The point in time corresponding to this timestamp, represented as + * the number of milliseconds since Unix epoch 1970-01-01T00:00:00Z. + */ + toMillis(): number; + /** + * Returns true if this `Timestamp` is equal to the provided one. + * + * @param other - The `Timestamp` to compare against. + * @returns true if this `Timestamp` is equal to the provided one. + */ + isEqual(other: Timestamp): boolean; + /** Returns a textual representation of this `Timestamp`. */ + toString(): string; + /** + * Returns a JSON-serializable representation of this `Timestamp`. + */ + toJSON(): { + seconds: number; + nanoseconds: number; + type: string; + }; + /** + * Builds a `Timestamp` instance from a JSON object created by {@link Timestamp.toJSON}. + */ + static fromJSON(json: object): Timestamp; + /** + * Converts this object to a primitive string, which allows `Timestamp` objects + * to be compared using the `>`, `<=`, `>=` and `>` operators. + */ + valueOf(): string; +} +/** + * A reference to a transaction. + * + * The `Transaction` object passed to a transaction's `updateFunction` provides + * the methods to read and write data within the transaction context. See + * {@link runTransaction}. + */ +export declare class Transaction { + private constructor(); + /** + * Reads the document referenced by the provided {@link DocumentReference}. + * + * @param documentRef - A reference to the document to be read. + * @returns A `DocumentSnapshot` with the read data. + */ + get(documentRef: DocumentReference): Promise>; + /** + * Writes to the document referred to by the provided {@link + * DocumentReference}. If the document does not exist yet, it will be created. + * + * @param documentRef - A reference to the document to be set. + * @param data - An object of the fields and values for the document. + * @throws Error - If the provided input is not a valid Firestore document. + * @returns This `Transaction` instance. Used for chaining method calls. + */ + set(documentRef: DocumentReference, data: WithFieldValue): this; + /** + * Writes to the document referred to by the provided {@link + * DocumentReference}. If the document does not exist yet, it will be created. + * If you provide `merge` or `mergeFields`, the provided data can be merged + * into an existing document. + * + * @param documentRef - A reference to the document to be set. + * @param data - An object of the fields and values for the document. + * @param options - An object to configure the set behavior. + * @throws Error - If the provided input is not a valid Firestore document. + * @returns This `Transaction` instance. Used for chaining method calls. + */ + set(documentRef: DocumentReference, data: PartialWithFieldValue, options: SetOptions): this; + /** + * Updates fields in the document referred to by the provided {@link + * DocumentReference}. The update will fail if applied to a document that does + * not exist. + * + * @param documentRef - A reference to the document to be updated. + * @param data - An object containing the fields and values with which to + * update the document. Fields can contain dots to reference nested fields + * within the document. + * @throws Error - If the provided input is not valid Firestore data. + * @returns This `Transaction` instance. Used for chaining method calls. + */ + update(documentRef: DocumentReference, data: UpdateData): this; + /** + * Updates fields in the document referred to by the provided {@link + * DocumentReference}. The update will fail if applied to a document that does + * not exist. + * + * Nested fields can be updated by providing dot-separated field path + * strings or by providing `FieldPath` objects. + * + * @param documentRef - A reference to the document to be updated. + * @param field - The first field to update. + * @param value - The first value. + * @param moreFieldsAndValues - Additional key/value pairs. + * @throws Error - If the provided input is not valid Firestore data. + * @returns This `Transaction` instance. Used for chaining method calls. + */ + update(documentRef: DocumentReference, field: string | FieldPath, value: unknown, ...moreFieldsAndValues: unknown[]): this; + /** + * Deletes the document referred to by the provided {@link DocumentReference}. + * + * @param documentRef - A reference to the document to be deleted. + * @returns This `Transaction` instance. Used for chaining method calls. + */ + delete(documentRef: DocumentReference): this; +} +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Options to customize transaction behavior. + */ +export declare interface TransactionOptions { + /** Maximum number of attempts to commit, after which transaction fails. Default is 5. */ + readonly maxAttempts?: number; +} +/** + * Given a union type `U = T1 | T2 | ...`, returns an intersected type + * `(T1 & T2 & ...)`. + * + * Uses distributive conditional types and inference from conditional types. + * This works because multiple candidates for the same type variable in + * contra-variant positions causes an intersection type to be inferred. + * https://www.typescriptlang.org/docs/handbook/advanced-types.html#type-inference-in-conditional-types + * https://stackoverflow.com/questions/50374908/transform-union-type-to-intersection-type + */ +export declare type UnionToIntersection = (U extends unknown ? (k: U) => void : never) extends (k: infer I) => void ? I : never; +/** + * Update data (for use with {@link (updateDoc:1)}) that consists of field paths + * (e.g. 'foo' or 'foo.baz') mapped to values. Fields that contain dots + * reference nested fields within the document. FieldValues can be passed in + * as property values. + */ +export declare type UpdateData = T extends Primitive ? T : T extends {} ? { + [K in keyof T]?: UpdateData | FieldValue; +} & NestedUpdateFields : Partial; +/** + * Updates fields in the document referred to by the specified + * `DocumentReference`. The update will fail if applied to a document that does + * not exist. + * + * The result of this update will only be reflected in document reads that occur + * after the returned promise resolves. If the client is offline, the + * update fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @param reference - A reference to the document to update. + * @param data - An object containing the fields and values with which to + * update the document. Fields can contain dots to reference nested fields + * within the document. + * @throws Error - If the provided input is not valid Firestore data. + * @returns A `Promise` resolved once the data has been successfully written + * to the backend. + */ +export declare function updateDoc(reference: DocumentReference, data: UpdateData): Promise; +/** + * Updates fields in the document referred to by the specified + * `DocumentReference` The update will fail if applied to a document that does + * not exist. + * + * Nested fields can be updated by providing dot-separated field path + * strings or by providing `FieldPath` objects. + * + * The result of this update will only be reflected in document reads that occur + * after the returned promise resolves. If the client is offline, the + * update fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @param reference - A reference to the document to update. + * @param field - The first field to update. + * @param value - The first value. + * @param moreFieldsAndValues - Additional key value pairs. + * @throws Error - If the provided input is not valid Firestore data. + * @returns A `Promise` resolved once the data has been successfully written + * to the backend. + */ +export declare function updateDoc(reference: DocumentReference, field: string | FieldPath, value: unknown, ...moreFieldsAndValues: unknown[]): Promise; +/** + * Creates a new `VectorValue` constructed with a copy of the given array of numbers. + * + * @param values - Create a `VectorValue` instance with a copy of this array of numbers. + * + * @returns A new `VectorValue` constructed with a copy of the given array of numbers. + */ +export declare function vector(values?: number[]): VectorValue; +/** + * Represents a vector type in Firestore documents. + * Create an instance with {@link vector}. + * + * @class VectorValue + */ +export declare class VectorValue { + /* Excluded from this release type: __constructor */ + /** + * Returns a copy of the raw number array form of the vector. + */ + toArray(): number[]; + /** + * Returns `true` if the two `VectorValue` values have the same raw number arrays, returns `false` otherwise. + */ + isEqual(other: VectorValue): boolean; + /** + * Returns a JSON-serializable representation of this `VectorValue` instance. + * + * @returns a JSON representation of this object. + */ + toJSON(): object; + /** + * Builds a `VectorValue` instance from a JSON object created by {@link VectorValue.toJSON}. + * + * @param json a JSON object represention of a `VectorValue` instance. + * @returns an instance of {@link VectorValue} if the JSON object could be parsed. Throws a + * {@link FirestoreError} if an error occurs. + */ + static fromJSON(json: object): VectorValue; +} +/** + * Creates a {@link QueryFieldFilterConstraint} that enforces that documents + * must contain the specified field and that the value should satisfy the + * relation constraint provided. + * + * @param fieldPath - The path to compare + * @param opStr - The operation string (e.g "<", "<=", "==", "<", + * "<=", "!="). + * @param value - The value for comparison + * @returns The created {@link QueryFieldFilterConstraint}. + */ +export declare function where(fieldPath: string | FieldPath, opStr: WhereFilterOp, value: unknown): QueryFieldFilterConstraint; +/** + * Filter conditions in a {@link where} clause are specified using the + * strings '<', '<=', '==', '!=', '>=', '>', 'array-contains', 'in', + * 'array-contains-any', and 'not-in'. + */ +export declare type WhereFilterOp = '<' | '<=' | '==' | '!=' | '>=' | '>' | 'array-contains' | 'in' | 'array-contains-any' | 'not-in'; +/** + * Allows FieldValues to be passed in as a property value while maintaining + * type safety. + */ +export declare type WithFieldValue = T | (T extends Primitive ? T : T extends {} ? { + [K in keyof T]: WithFieldValue | FieldValue; +} : never); +/** + * A write batch, used to perform multiple writes as a single atomic unit. + * + * A `WriteBatch` object can be acquired by calling {@link writeBatch}. It + * provides methods for adding writes to the write batch. None of the writes + * will be committed (or visible locally) until {@link WriteBatch.commit} is + * called. + */ +export declare class WriteBatch { + private constructor(); + /** + * Writes to the document referred to by the provided {@link + * DocumentReference}. If the document does not exist yet, it will be created. + * + * @param documentRef - A reference to the document to be set. + * @param data - An object of the fields and values for the document. + * @returns This `WriteBatch` instance. Used for chaining method calls. + */ + set(documentRef: DocumentReference, data: WithFieldValue): WriteBatch; + /** + * Writes to the document referred to by the provided {@link + * DocumentReference}. If the document does not exist yet, it will be created. + * If you provide `merge` or `mergeFields`, the provided data can be merged + * into an existing document. + * + * @param documentRef - A reference to the document to be set. + * @param data - An object of the fields and values for the document. + * @param options - An object to configure the set behavior. + * @throws Error - If the provided input is not a valid Firestore document. + * @returns This `WriteBatch` instance. Used for chaining method calls. + */ + set(documentRef: DocumentReference, data: PartialWithFieldValue, options: SetOptions): WriteBatch; + /** + * Updates fields in the document referred to by the provided {@link + * DocumentReference}. The update will fail if applied to a document that does + * not exist. + * + * @param documentRef - A reference to the document to be updated. + * @param data - An object containing the fields and values with which to + * update the document. Fields can contain dots to reference nested fields + * within the document. + * @throws Error - If the provided input is not valid Firestore data. + * @returns This `WriteBatch` instance. Used for chaining method calls. + */ + update(documentRef: DocumentReference, data: UpdateData): WriteBatch; + /** + * Updates fields in the document referred to by this {@link + * DocumentReference}. The update will fail if applied to a document that does + * not exist. + * + * Nested fields can be update by providing dot-separated field path strings + * or by providing `FieldPath` objects. + * + * @param documentRef - A reference to the document to be updated. + * @param field - The first field to update. + * @param value - The first value. + * @param moreFieldsAndValues - Additional key value pairs. + * @throws Error - If the provided input is not valid Firestore data. + * @returns This `WriteBatch` instance. Used for chaining method calls. + */ + update(documentRef: DocumentReference, field: string | FieldPath, value: unknown, ...moreFieldsAndValues: unknown[]): WriteBatch; + /** + * Deletes the document referred to by the provided {@link DocumentReference}. + * + * @param documentRef - A reference to the document to be deleted. + * @returns This `WriteBatch` instance. Used for chaining method calls. + */ + delete(documentRef: DocumentReference): WriteBatch; + /** + * Commits all of the writes in this write batch as a single atomic unit. + * + * The result of these writes will only be reflected in document reads that + * occur after the returned promise resolves. If the client is offline, the + * write fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @returns A `Promise` resolved once all of the writes in the batch have been + * successfully written to the backend as an atomic unit (note that it won't + * resolve while you're offline). + */ + commit(): Promise; +} +/** + * Creates a write batch, used for performing multiple writes as a single + * atomic operation. The maximum number of writes allowed in a single WriteBatch + * is 500. + * + * The result of these writes will only be reflected in document reads that + * occur after the returned promise resolves. If the client is offline, the + * write fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @returns A `WriteBatch` that can be used to atomically execute multiple + * writes. + */ +export declare function writeBatch(firestore: Firestore): WriteBatch; +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/index.node.cjs.js b/frontend-old/node_modules/@firebase/firestore/dist/lite/index.node.cjs.js new file mode 100644 index 0000000..7f23198 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/index.node.cjs.js @@ -0,0 +1,9870 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +var app = require('@firebase/app'); +var component = require('@firebase/component'); +var logger = require('@firebase/logger'); +var util$1 = require('util'); +var util = require('@firebase/util'); +var bloomBlob = require('@firebase/webchannel-wrapper/bloom-blob'); +var crypto = require('crypto'); + +const version$1 = "4.9.2"; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Simple wrapper around a nullable UID. Mostly exists to make code more + * readable. + */ +class User { + constructor(uid) { + this.uid = uid; + } + isAuthenticated() { + return this.uid != null; + } + /** + * Returns a key representing this user, suitable for inclusion in a + * dictionary. + */ + toKey() { + if (this.isAuthenticated()) { + return 'uid:' + this.uid; + } + else { + return 'anonymous-user'; + } + } + isEqual(otherUser) { + return otherUser.uid === this.uid; + } +} +/** A user with a null UID. */ +User.UNAUTHENTICATED = new User(null); +// TODO(mikelehen): Look into getting a proper uid-equivalent for +// non-FirebaseAuth providers. +User.GOOGLE_CREDENTIALS = new User('google-credentials-uid'); +User.FIRST_PARTY = new User('first-party-uid'); +User.MOCK_USER = new User('mock-user'); + +const version = "12.3.0"; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +let SDK_VERSION = version; +function setSDKVersion(version) { + SDK_VERSION = version; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Formats an object as a JSON string, suitable for logging. */ +function formatJSON(value) { + // util.inspect() results in much more readable output than JSON.stringify() + return util$1.inspect(value, { depth: 100 }); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const logClient = new logger.Logger('@firebase/firestore'); +/** + * Sets the verbosity of Cloud Firestore logs (debug, error, or silent). + * + * @param logLevel - The verbosity you set for activity and error logging. Can + * be any of the following values: + * + *
    + *
  • `debug` for the most verbose logging level, primarily for + * debugging.
  • + *
  • `error` to log errors only.
  • + *
  • `silent` to turn off logging.
  • + *
+ */ +function setLogLevel(logLevel) { + logClient.setLogLevel(logLevel); +} +function logDebug(msg, ...obj) { + if (logClient.logLevel <= logger.LogLevel.DEBUG) { + const args = obj.map(argToString); + logClient.debug(`Firestore (${SDK_VERSION}): ${msg}`, ...args); + } +} +function logError(msg, ...obj) { + if (logClient.logLevel <= logger.LogLevel.ERROR) { + const args = obj.map(argToString); + logClient.error(`Firestore (${SDK_VERSION}): ${msg}`, ...args); + } +} +/** + * @internal + */ +function logWarn(msg, ...obj) { + if (logClient.logLevel <= logger.LogLevel.WARN) { + const args = obj.map(argToString); + logClient.warn(`Firestore (${SDK_VERSION}): ${msg}`, ...args); + } +} +/** + * Converts an additional log parameter to a string representation. + */ +function argToString(obj) { + if (typeof obj === 'string') { + return obj; + } + else { + try { + return formatJSON(obj); + } + catch (e) { + // Converting to JSON failed, just log the object directly + return obj; + } + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +function fail(id, messageOrContext, context) { + let message = 'Unexpected state'; + if (typeof messageOrContext === 'string') { + message = messageOrContext; + } + else { + context = messageOrContext; + } + _fail(id, message, context); +} +function _fail(id, failure, context) { + // Log the failure in addition to throw an exception, just in case the + // exception is swallowed. + let message = `FIRESTORE (${SDK_VERSION}) INTERNAL ASSERTION FAILED: ${failure} (ID: ${id.toString(16)})`; + if (context !== undefined) { + try { + const stringContext = JSON.stringify(context); + message += ' CONTEXT: ' + stringContext; + } + catch (e) { + message += ' CONTEXT: ' + context; + } + } + logError(message); + // NOTE: We don't use FirestoreError here because these are internal failures + // that cannot be handled by the user. (Also it would create a circular + // dependency between the error and assert modules which doesn't work.) + throw new Error(message); +} +function hardAssert(assertion, id, messageOrContext, context) { + let message = 'Unexpected state'; + if (typeof messageOrContext === 'string') { + message = messageOrContext; + } + else { + context = messageOrContext; + } + if (!assertion) { + _fail(id, message, context); + } +} +/** + * Casts `obj` to `T`. In non-production builds, verifies that `obj` is an + * instance of `T` before casting. + */ +function debugCast(obj, +// eslint-disable-next-line @typescript-eslint/no-explicit-any +constructor) { + return obj; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const Code = { + // Causes are copied from: + // https://github.com/grpc/grpc/blob/bceec94ea4fc5f0085d81235d8e1c06798dc341a/include/grpc%2B%2B/impl/codegen/status_code_enum.h + /** Not an error; returned on success. */ + OK: 'ok', + /** The operation was cancelled (typically by the caller). */ + CANCELLED: 'cancelled', + /** Unknown error or an error from a different error domain. */ + UNKNOWN: 'unknown', + /** + * Client specified an invalid argument. Note that this differs from + * FAILED_PRECONDITION. INVALID_ARGUMENT indicates arguments that are + * problematic regardless of the state of the system (e.g., a malformed file + * name). + */ + INVALID_ARGUMENT: 'invalid-argument', + /** + * Deadline expired before operation could complete. For operations that + * change the state of the system, this error may be returned even if the + * operation has completed successfully. For example, a successful response + * from a server could have been delayed long enough for the deadline to + * expire. + */ + DEADLINE_EXCEEDED: 'deadline-exceeded', + /** Some requested entity (e.g., file or directory) was not found. */ + NOT_FOUND: 'not-found', + /** + * Some entity that we attempted to create (e.g., file or directory) already + * exists. + */ + ALREADY_EXISTS: 'already-exists', + /** + * The caller does not have permission to execute the specified operation. + * PERMISSION_DENIED must not be used for rejections caused by exhausting + * some resource (use RESOURCE_EXHAUSTED instead for those errors). + * PERMISSION_DENIED must not be used if the caller cannot be identified + * (use UNAUTHENTICATED instead for those errors). + */ + PERMISSION_DENIED: 'permission-denied', + /** + * The request does not have valid authentication credentials for the + * operation. + */ + UNAUTHENTICATED: 'unauthenticated', + /** + * Some resource has been exhausted, perhaps a per-user quota, or perhaps the + * entire file system is out of space. + */ + RESOURCE_EXHAUSTED: 'resource-exhausted', + /** + * Operation was rejected because the system is not in a state required for + * the operation's execution. For example, directory to be deleted may be + * non-empty, an rmdir operation is applied to a non-directory, etc. + * + * A litmus test that may help a service implementor in deciding + * between FAILED_PRECONDITION, ABORTED, and UNAVAILABLE: + * (a) Use UNAVAILABLE if the client can retry just the failing call. + * (b) Use ABORTED if the client should retry at a higher-level + * (e.g., restarting a read-modify-write sequence). + * (c) Use FAILED_PRECONDITION if the client should not retry until + * the system state has been explicitly fixed. E.g., if an "rmdir" + * fails because the directory is non-empty, FAILED_PRECONDITION + * should be returned since the client should not retry unless + * they have first fixed up the directory by deleting files from it. + * (d) Use FAILED_PRECONDITION if the client performs conditional + * REST Get/Update/Delete on a resource and the resource on the + * server does not match the condition. E.g., conflicting + * read-modify-write on the same resource. + */ + FAILED_PRECONDITION: 'failed-precondition', + /** + * The operation was aborted, typically due to a concurrency issue like + * sequencer check failures, transaction aborts, etc. + * + * See litmus test above for deciding between FAILED_PRECONDITION, ABORTED, + * and UNAVAILABLE. + */ + ABORTED: 'aborted', + /** + * Operation was attempted past the valid range. E.g., seeking or reading + * past end of file. + * + * Unlike INVALID_ARGUMENT, this error indicates a problem that may be fixed + * if the system state changes. For example, a 32-bit file system will + * generate INVALID_ARGUMENT if asked to read at an offset that is not in the + * range [0,2^32-1], but it will generate OUT_OF_RANGE if asked to read from + * an offset past the current file size. + * + * There is a fair bit of overlap between FAILED_PRECONDITION and + * OUT_OF_RANGE. We recommend using OUT_OF_RANGE (the more specific error) + * when it applies so that callers who are iterating through a space can + * easily look for an OUT_OF_RANGE error to detect when they are done. + */ + OUT_OF_RANGE: 'out-of-range', + /** Operation is not implemented or not supported/enabled in this service. */ + UNIMPLEMENTED: 'unimplemented', + /** + * Internal errors. Means some invariants expected by underlying System has + * been broken. If you see one of these errors, Something is very broken. + */ + INTERNAL: 'internal', + /** + * The service is currently unavailable. This is a most likely a transient + * condition and may be corrected by retrying with a backoff. + * + * See litmus test above for deciding between FAILED_PRECONDITION, ABORTED, + * and UNAVAILABLE. + */ + UNAVAILABLE: 'unavailable', + /** Unrecoverable data loss or corruption. */ + DATA_LOSS: 'data-loss' +}; +/** An error returned by a Firestore operation. */ +class FirestoreError extends util.FirebaseError { + /** @hideconstructor */ + constructor( + /** + * The backend error code associated with this error. + */ + code, + /** + * A custom error description. + */ + message) { + super(code, message); + this.code = code; + this.message = message; + // HACK: We write a toString property directly because Error is not a real + // class and so inheritance does not work correctly. We could alternatively + // do the same "back-door inheritance" trick that FirebaseError does. + this.toString = () => `${this.name}: [code=${this.code}]: ${this.message}`; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class Deferred { + constructor() { + this.promise = new Promise((resolve, reject) => { + this.resolve = resolve; + this.reject = reject; + }); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class OAuthToken { + constructor(value, user) { + this.user = user; + this.type = 'OAuth'; + this.headers = new Map(); + this.headers.set('Authorization', `Bearer ${value}`); + } +} +/** + * A CredentialsProvider that always yields an empty token. + * @internal + */ +class EmptyAuthCredentialsProvider { + getToken() { + return Promise.resolve(null); + } + invalidateToken() { } + start(asyncQueue, changeListener) { + // Fire with initial user. + asyncQueue.enqueueRetryable(() => changeListener(User.UNAUTHENTICATED)); + } + shutdown() { } +} +/** + * A CredentialsProvider that always returns a constant token. Used for + * emulator token mocking. + */ +class EmulatorAuthCredentialsProvider { + constructor(token) { + this.token = token; + /** + * Stores the listener registered with setChangeListener() + * This isn't actually necessary since the UID never changes, but we use this + * to verify the listen contract is adhered to in tests. + */ + this.changeListener = null; + } + getToken() { + return Promise.resolve(this.token); + } + invalidateToken() { } + start(asyncQueue, changeListener) { + this.changeListener = changeListener; + // Fire with initial user. + asyncQueue.enqueueRetryable(() => changeListener(this.token.user)); + } + shutdown() { + this.changeListener = null; + } +} +/** Credential provider for the Lite SDK. */ +class LiteAuthCredentialsProvider { + constructor(authProvider) { + this.auth = null; + authProvider.onInit(auth => { + this.auth = auth; + }); + } + getToken() { + if (!this.auth) { + return Promise.resolve(null); + } + return this.auth.getToken().then(tokenData => { + if (tokenData) { + hardAssert(typeof tokenData.accessToken === 'string', 0xa539, { tokenData }); + return new OAuthToken(tokenData.accessToken, new User(this.auth.getUid())); + } + else { + return null; + } + }); + } + invalidateToken() { } + start(asyncQueue, changeListener) { } + shutdown() { } +} +/* + * FirstPartyToken provides a fresh token each time its value + * is requested, because if the token is too old, requests will be rejected. + * Technically this may no longer be necessary since the SDK should gracefully + * recover from unauthenticated errors (see b/33147818 for context), but it's + * safer to keep the implementation as-is. + */ +class FirstPartyToken { + constructor(sessionIndex, iamToken, authTokenFactory) { + this.sessionIndex = sessionIndex; + this.iamToken = iamToken; + this.authTokenFactory = authTokenFactory; + this.type = 'FirstParty'; + this.user = User.FIRST_PARTY; + this._headers = new Map(); + } + /** + * Gets an authorization token, using a provided factory function, or return + * null. + */ + getAuthToken() { + if (this.authTokenFactory) { + return this.authTokenFactory(); + } + else { + return null; + } + } + get headers() { + this._headers.set('X-Goog-AuthUser', this.sessionIndex); + // Use array notation to prevent minification + const authHeaderTokenValue = this.getAuthToken(); + if (authHeaderTokenValue) { + this._headers.set('Authorization', authHeaderTokenValue); + } + if (this.iamToken) { + this._headers.set('X-Goog-Iam-Authorization-Token', this.iamToken); + } + return this._headers; + } +} +/* + * Provides user credentials required for the Firestore JavaScript SDK + * to authenticate the user, using technique that is only available + * to applications hosted by Google. + */ +class FirstPartyAuthCredentialsProvider { + constructor(sessionIndex, iamToken, authTokenFactory) { + this.sessionIndex = sessionIndex; + this.iamToken = iamToken; + this.authTokenFactory = authTokenFactory; + } + getToken() { + return Promise.resolve(new FirstPartyToken(this.sessionIndex, this.iamToken, this.authTokenFactory)); + } + start(asyncQueue, changeListener) { + // Fire with initial uid. + asyncQueue.enqueueRetryable(() => changeListener(User.FIRST_PARTY)); + } + shutdown() { } + invalidateToken() { } +} +class AppCheckToken { + constructor(value) { + this.value = value; + this.type = 'AppCheck'; + this.headers = new Map(); + if (value && value.length > 0) { + this.headers.set('x-firebase-appcheck', this.value); + } + } +} +/** AppCheck token provider for the Lite SDK. */ +class LiteAppCheckTokenProvider { + constructor(app$1, appCheckProvider) { + this.appCheckProvider = appCheckProvider; + this.appCheck = null; + this.serverAppAppCheckToken = null; + if (app._isFirebaseServerApp(app$1) && app$1.settings.appCheckToken) { + this.serverAppAppCheckToken = app$1.settings.appCheckToken; + } + appCheckProvider.onInit(appCheck => { + this.appCheck = appCheck; + }); + } + getToken() { + if (this.serverAppAppCheckToken) { + return Promise.resolve(new AppCheckToken(this.serverAppAppCheckToken)); + } + if (!this.appCheck) { + return Promise.resolve(null); + } + return this.appCheck.getToken().then(tokenResult => { + if (tokenResult) { + hardAssert(typeof tokenResult.token === 'string', 0x0d8e, { tokenResult }); + return new AppCheckToken(tokenResult.token); + } + else { + return null; + } + }); + } + invalidateToken() { } + start(asyncQueue, changeListener) { } + shutdown() { } +} +/** + * Builds a CredentialsProvider depending on the type of + * the credentials passed in. + */ +function makeAuthCredentialsProvider(credentials) { + if (!credentials) { + return new EmptyAuthCredentialsProvider(); + } + switch (credentials['type']) { + case 'firstParty': + return new FirstPartyAuthCredentialsProvider(credentials['sessionIndex'] || '0', credentials['iamToken'] || null, credentials['authTokenFactory'] || null); + case 'provider': + return credentials['client']; + default: + throw new FirestoreError(Code.INVALID_ARGUMENT, 'makeAuthCredentialsProvider failed due to invalid credential type'); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class DatabaseInfo { + /** + * Constructs a DatabaseInfo using the provided host, databaseId and + * persistenceKey. + * + * @param databaseId - The database to use. + * @param appId - The Firebase App Id. + * @param persistenceKey - A unique identifier for this Firestore's local + * storage (used in conjunction with the databaseId). + * @param host - The Firestore backend host to connect to. + * @param ssl - Whether to use SSL when connecting. + * @param forceLongPolling - Whether to use the forceLongPolling option + * when using WebChannel as the network transport. + * @param autoDetectLongPolling - Whether to use the detectBufferingProxy + * option when using WebChannel as the network transport. + * @param longPollingOptions Options that configure long-polling. + * @param useFetchStreams Whether to use the Fetch API instead of + * XMLHTTPRequest + */ + constructor(databaseId, appId, persistenceKey, host, ssl, forceLongPolling, autoDetectLongPolling, longPollingOptions, useFetchStreams, isUsingEmulator) { + this.databaseId = databaseId; + this.appId = appId; + this.persistenceKey = persistenceKey; + this.host = host; + this.ssl = ssl; + this.forceLongPolling = forceLongPolling; + this.autoDetectLongPolling = autoDetectLongPolling; + this.longPollingOptions = longPollingOptions; + this.useFetchStreams = useFetchStreams; + this.isUsingEmulator = isUsingEmulator; + } +} +/** The default database name for a project. */ +const DEFAULT_DATABASE_NAME = '(default)'; +/** + * Represents the database ID a Firestore client is associated with. + * @internal + */ +class DatabaseId { + constructor(projectId, database) { + this.projectId = projectId; + this.database = database ? database : DEFAULT_DATABASE_NAME; + } + static empty() { + return new DatabaseId('', ''); + } + get isDefaultDatabase() { + return this.database === DEFAULT_DATABASE_NAME; + } + isEqual(other) { + return (other instanceof DatabaseId && + other.projectId === this.projectId && + other.database === this.database); + } +} +function databaseIdFromApp(app, database) { + if (!Object.prototype.hasOwnProperty.apply(app.options, ['projectId'])) { + throw new FirestoreError(Code.INVALID_ARGUMENT, '"projectId" not provided in firebase.initializeApp.'); + } + return new DatabaseId(app.options.projectId, database); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Generates `nBytes` of random bytes. + * + * If `nBytes < 0` , an error will be thrown. + */ +function randomBytes(nBytes) { + return crypto.randomBytes(nBytes); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A utility class for generating unique alphanumeric IDs of a specified length. + * + * @internal + * Exported internally for testing purposes. + */ +class AutoId { + static newId() { + // Alphanumeric characters + const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; + // The largest byte value that is a multiple of `char.length`. + const maxMultiple = Math.floor(256 / chars.length) * chars.length; + let autoId = ''; + const targetLength = 20; + while (autoId.length < targetLength) { + const bytes = randomBytes(40); + for (let i = 0; i < bytes.length; ++i) { + // Only accept values that are [0, maxMultiple), this ensures they can + // be evenly mapped to indices of `chars` via a modulo operation. + if (autoId.length < targetLength && bytes[i] < maxMultiple) { + autoId += chars.charAt(bytes[i] % chars.length); + } + } + } + return autoId; + } +} +function primitiveComparator(left, right) { + if (left < right) { + return -1; + } + if (left > right) { + return 1; + } + return 0; +} +/** Compare strings in UTF-8 encoded byte order */ +function compareUtf8Strings(left, right) { + // Find the first differing character (a.k.a. "UTF-16 code unit") in the two strings and, + // if found, use that character to determine the relative ordering of the two strings as a + // whole. Comparing UTF-16 strings in UTF-8 byte order can be done simply and efficiently by + // comparing the UTF-16 code units (chars). This serendipitously works because of the way UTF-8 + // and UTF-16 happen to represent Unicode code points. + // + // After finding the first pair of differing characters, there are two cases: + // + // Case 1: Both characters are non-surrogates (code points less than or equal to 0xFFFF) or + // both are surrogates from a surrogate pair (that collectively represent code points greater + // than 0xFFFF). In this case their numeric order as UTF-16 code units is the same as the + // lexicographical order of their corresponding UTF-8 byte sequences. A direct comparison is + // sufficient. + // + // Case 2: One character is a surrogate and the other is not. In this case the surrogate- + // containing string is always ordered after the non-surrogate. This is because surrogates are + // used to represent code points greater than 0xFFFF which have 4-byte UTF-8 representations + // and are lexicographically greater than the 1, 2, or 3-byte representations of code points + // less than or equal to 0xFFFF. + // + // An example of why Case 2 is required is comparing the following two Unicode code points: + // + // |-----------------------|------------|---------------------|-----------------| + // | Name | Code Point | UTF-8 Encoding | UTF-16 Encoding | + // |-----------------------|------------|---------------------|-----------------| + // | Replacement Character | U+FFFD | 0xEF 0xBF 0xBD | 0xFFFD | + // | Grinning Face | U+1F600 | 0xF0 0x9F 0x98 0x80 | 0xD83D 0xDE00 | + // |-----------------------|------------|---------------------|-----------------| + // + // A lexicographical comparison of the UTF-8 encodings of these code points would order + // "Replacement Character" _before_ "Grinning Face" because 0xEF is less than 0xF0. However, a + // direct comparison of the UTF-16 code units, as would be done in case 1, would erroneously + // produce the _opposite_ ordering, because 0xFFFD is _greater than_ 0xD83D. As it turns out, + // this relative ordering holds for all comparisons of UTF-16 code points requiring a surrogate + // pair with those that do not. + const length = Math.min(left.length, right.length); + for (let i = 0; i < length; i++) { + const leftChar = left.charAt(i); + const rightChar = right.charAt(i); + if (leftChar !== rightChar) { + return isSurrogate(leftChar) === isSurrogate(rightChar) + ? primitiveComparator(leftChar, rightChar) + : isSurrogate(leftChar) + ? 1 + : -1; + } + } + // Use the lengths of the strings to determine the overall comparison result since either the + // strings were equal or one is a prefix of the other. + return primitiveComparator(left.length, right.length); +} +const MIN_SURROGATE = 0xd800; +const MAX_SURROGATE = 0xdfff; +function isSurrogate(s) { + const c = s.charCodeAt(0); + return c >= MIN_SURROGATE && c <= MAX_SURROGATE; +} +/** Helper to compare arrays using isEqual(). */ +function arrayEquals(left, right, comparator) { + if (left.length !== right.length) { + return false; + } + return left.every((value, index) => comparator(value, right[index])); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const DOCUMENT_KEY_NAME = '__name__'; +/** + * Path represents an ordered sequence of string segments. + */ +class BasePath { + constructor(segments, offset, length) { + if (offset === undefined) { + offset = 0; + } + else if (offset > segments.length) { + fail(0x027d, { + offset, + range: segments.length + }); + } + if (length === undefined) { + length = segments.length - offset; + } + else if (length > segments.length - offset) { + fail(0x06d2, { + length, + range: segments.length - offset + }); + } + this.segments = segments; + this.offset = offset; + this.len = length; + } + get length() { + return this.len; + } + isEqual(other) { + return BasePath.comparator(this, other) === 0; + } + child(nameOrPath) { + const segments = this.segments.slice(this.offset, this.limit()); + if (nameOrPath instanceof BasePath) { + nameOrPath.forEach(segment => { + segments.push(segment); + }); + } + else { + segments.push(nameOrPath); + } + return this.construct(segments); + } + /** The index of one past the last segment of the path. */ + limit() { + return this.offset + this.length; + } + popFirst(size) { + size = size === undefined ? 1 : size; + return this.construct(this.segments, this.offset + size, this.length - size); + } + popLast() { + return this.construct(this.segments, this.offset, this.length - 1); + } + firstSegment() { + return this.segments[this.offset]; + } + lastSegment() { + return this.get(this.length - 1); + } + get(index) { + return this.segments[this.offset + index]; + } + isEmpty() { + return this.length === 0; + } + isPrefixOf(other) { + if (other.length < this.length) { + return false; + } + for (let i = 0; i < this.length; i++) { + if (this.get(i) !== other.get(i)) { + return false; + } + } + return true; + } + isImmediateParentOf(potentialChild) { + if (this.length + 1 !== potentialChild.length) { + return false; + } + for (let i = 0; i < this.length; i++) { + if (this.get(i) !== potentialChild.get(i)) { + return false; + } + } + return true; + } + forEach(fn) { + for (let i = this.offset, end = this.limit(); i < end; i++) { + fn(this.segments[i]); + } + } + toArray() { + return this.segments.slice(this.offset, this.limit()); + } + /** + * Compare 2 paths segment by segment, prioritizing numeric IDs + * (e.g., "__id123__") in numeric ascending order, followed by string + * segments in lexicographical order. + */ + static comparator(p1, p2) { + const len = Math.min(p1.length, p2.length); + for (let i = 0; i < len; i++) { + const comparison = BasePath.compareSegments(p1.get(i), p2.get(i)); + if (comparison !== 0) { + return comparison; + } + } + return primitiveComparator(p1.length, p2.length); + } + static compareSegments(lhs, rhs) { + const isLhsNumeric = BasePath.isNumericId(lhs); + const isRhsNumeric = BasePath.isNumericId(rhs); + if (isLhsNumeric && !isRhsNumeric) { + // Only lhs is numeric + return -1; + } + else if (!isLhsNumeric && isRhsNumeric) { + // Only rhs is numeric + return 1; + } + else if (isLhsNumeric && isRhsNumeric) { + // both numeric + return BasePath.extractNumericId(lhs).compare(BasePath.extractNumericId(rhs)); + } + else { + // both non-numeric + return compareUtf8Strings(lhs, rhs); + } + } + // Checks if a segment is a numeric ID (starts with "__id" and ends with "__"). + static isNumericId(segment) { + return segment.startsWith('__id') && segment.endsWith('__'); + } + static extractNumericId(segment) { + return bloomBlob.Integer.fromString(segment.substring(4, segment.length - 2)); + } +} +/** + * A slash-separated path for navigating resources (documents and collections) + * within Firestore. + * + * @internal + */ +class ResourcePath extends BasePath { + construct(segments, offset, length) { + return new ResourcePath(segments, offset, length); + } + canonicalString() { + // NOTE: The client is ignorant of any path segments containing escape + // sequences (e.g. __id123__) and just passes them through raw (they exist + // for legacy reasons and should not be used frequently). + return this.toArray().join('/'); + } + toString() { + return this.canonicalString(); + } + /** + * Returns a string representation of this path + * where each path segment has been encoded with + * `encodeURIComponent`. + */ + toUriEncodedString() { + return this.toArray().map(encodeURIComponent).join('/'); + } + /** + * Creates a resource path from the given slash-delimited string. If multiple + * arguments are provided, all components are combined. Leading and trailing + * slashes from all components are ignored. + */ + static fromString(...pathComponents) { + // NOTE: The client is ignorant of any path segments containing escape + // sequences (e.g. __id123__) and just passes them through raw (they exist + // for legacy reasons and should not be used frequently). + const segments = []; + for (const path of pathComponents) { + if (path.indexOf('//') >= 0) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid segment (${path}). Paths must not contain // in them.`); + } + // Strip leading and trailing slashed. + segments.push(...path.split('/').filter(segment => segment.length > 0)); + } + return new ResourcePath(segments); + } + static emptyPath() { + return new ResourcePath([]); + } +} +const identifierRegExp = /^[_a-zA-Z][_a-zA-Z0-9]*$/; +/** + * A dot-separated path for navigating sub-objects within a document. + * @internal + */ +class FieldPath$1 extends BasePath { + construct(segments, offset, length) { + return new FieldPath$1(segments, offset, length); + } + /** + * Returns true if the string could be used as a segment in a field path + * without escaping. + */ + static isValidIdentifier(segment) { + return identifierRegExp.test(segment); + } + canonicalString() { + return this.toArray() + .map(str => { + str = str.replace(/\\/g, '\\\\').replace(/`/g, '\\`'); + if (!FieldPath$1.isValidIdentifier(str)) { + str = '`' + str + '`'; + } + return str; + }) + .join('.'); + } + toString() { + return this.canonicalString(); + } + /** + * Returns true if this field references the key of a document. + */ + isKeyField() { + return this.length === 1 && this.get(0) === DOCUMENT_KEY_NAME; + } + /** + * The field designating the key of a document. + */ + static keyField() { + return new FieldPath$1([DOCUMENT_KEY_NAME]); + } + /** + * Parses a field string from the given server-formatted string. + * + * - Splitting the empty string is not allowed (for now at least). + * - Empty segments within the string (e.g. if there are two consecutive + * separators) are not allowed. + * + * TODO(b/37244157): we should make this more strict. Right now, it allows + * non-identifier path components, even if they aren't escaped. + */ + static fromServerFormat(path) { + const segments = []; + let current = ''; + let i = 0; + const addCurrentSegment = () => { + if (current.length === 0) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid field path (${path}). Paths must not be empty, begin ` + + `with '.', end with '.', or contain '..'`); + } + segments.push(current); + current = ''; + }; + let inBackticks = false; + while (i < path.length) { + const c = path[i]; + if (c === '\\') { + if (i + 1 === path.length) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Path has trailing escape character: ' + path); + } + const next = path[i + 1]; + if (!(next === '\\' || next === '.' || next === '`')) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Path has invalid escape sequence: ' + path); + } + current += next; + i += 2; + } + else if (c === '`') { + inBackticks = !inBackticks; + i++; + } + else if (c === '.' && !inBackticks) { + addCurrentSegment(); + i++; + } + else { + current += c; + i++; + } + } + addCurrentSegment(); + if (inBackticks) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Unterminated ` in path: ' + path); + } + return new FieldPath$1(segments); + } + static emptyPath() { + return new FieldPath$1([]); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @internal + */ +class DocumentKey { + constructor(path) { + this.path = path; + } + static fromPath(path) { + return new DocumentKey(ResourcePath.fromString(path)); + } + static fromName(name) { + return new DocumentKey(ResourcePath.fromString(name).popFirst(5)); + } + static empty() { + return new DocumentKey(ResourcePath.emptyPath()); + } + get collectionGroup() { + return this.path.popLast().lastSegment(); + } + /** Returns true if the document is in the specified collectionId. */ + hasCollectionId(collectionId) { + return (this.path.length >= 2 && + this.path.get(this.path.length - 2) === collectionId); + } + /** Returns the collection group (i.e. the name of the parent collection) for this key. */ + getCollectionGroup() { + return this.path.get(this.path.length - 2); + } + /** Returns the fully qualified path to the parent collection. */ + getCollectionPath() { + return this.path.popLast(); + } + isEqual(other) { + return (other !== null && ResourcePath.comparator(this.path, other.path) === 0); + } + toString() { + return this.path.toString(); + } + static comparator(k1, k2) { + return ResourcePath.comparator(k1.path, k2.path); + } + static isDocumentKey(path) { + return path.length % 2 === 0; + } + /** + * Creates and returns a new document key with the given segments. + * + * @param segments - The segments of the path to the document + * @returns A new instance of DocumentKey + */ + static fromSegments(segments) { + return new DocumentKey(new ResourcePath(segments.slice())); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +function validateNonEmptyArgument(functionName, argumentName, argument) { + if (!argument) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `Function ${functionName}() cannot be called with an empty ${argumentName}.`); + } +} +/** + * Validates that two boolean options are not set at the same time. + * @internal + */ +function validateIsNotUsedTogether(optionName1, argument1, optionName2, argument2) { + if (argument1 === true && argument2 === true) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `${optionName1} and ${optionName2} cannot be used together.`); + } +} +/** + * Validates that `path` refers to a document (indicated by the fact it contains + * an even numbers of segments). + */ +function validateDocumentPath(path) { + if (!DocumentKey.isDocumentKey(path)) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid document reference. Document references must have an even number of segments, but ${path} has ${path.length}.`); + } +} +/** + * Validates that `path` refers to a collection (indicated by the fact it + * contains an odd numbers of segments). + */ +function validateCollectionPath(path) { + if (DocumentKey.isDocumentKey(path)) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid collection reference. Collection references must have an odd number of segments, but ${path} has ${path.length}.`); + } +} +/** + * Returns true if it's a non-null object without a custom prototype + * (i.e. excludes Array, Date, etc.). + */ +function isPlainObject(input) { + return (typeof input === 'object' && + input !== null && + (Object.getPrototypeOf(input) === Object.prototype || + Object.getPrototypeOf(input) === null)); +} +/** Returns a string describing the type / value of the provided input. */ +function valueDescription(input) { + if (input === undefined) { + return 'undefined'; + } + else if (input === null) { + return 'null'; + } + else if (typeof input === 'string') { + if (input.length > 20) { + input = `${input.substring(0, 20)}...`; + } + return JSON.stringify(input); + } + else if (typeof input === 'number' || typeof input === 'boolean') { + return '' + input; + } + else if (typeof input === 'object') { + if (input instanceof Array) { + return 'an array'; + } + else { + const customObjectName = tryGetCustomObjectType(input); + if (customObjectName) { + return `a custom ${customObjectName} object`; + } + else { + return 'an object'; + } + } + } + else if (typeof input === 'function') { + return 'a function'; + } + else { + return fail(0x3029, { type: typeof input }); + } +} +/** try to get the constructor name for an object. */ +function tryGetCustomObjectType(input) { + if (input.constructor) { + return input.constructor.name; + } + return null; +} +/** + * Casts `obj` to `T`, optionally unwrapping Compat types to expose the + * underlying instance. Throws if `obj` is not an instance of `T`. + * + * This cast is used in the Lite and Full SDK to verify instance types for + * arguments passed to the public API. + * @internal + */ +function cast(obj, +// eslint-disable-next-line @typescript-eslint/no-explicit-any +constructor) { + if ('_delegate' in obj) { + // Unwrap Compat types + // eslint-disable-next-line @typescript-eslint/no-explicit-any + obj = obj._delegate; + } + if (!(obj instanceof constructor)) { + if (constructor.name === obj.constructor.name) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Type does not match the expected instance. Did you pass a ' + + `reference from a different Firestore SDK?`); + } + else { + const description = valueDescription(obj); + throw new FirestoreError(Code.INVALID_ARGUMENT, `Expected type '${constructor.name}', but it was: ${description}`); + } + } + return obj; +} +function validatePositiveNumber(functionName, n) { + if (n <= 0) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `Function ${functionName}() requires a positive number, but it was: ${n}.`); + } +} + +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Compares two `ExperimentalLongPollingOptions` objects for equality. + */ +function longPollingOptionsEqual(options1, options2) { + return options1.timeoutSeconds === options2.timeoutSeconds; +} +/** + * Creates and returns a new `ExperimentalLongPollingOptions` with the same + * option values as the given instance. + */ +function cloneLongPollingOptions(options) { + const clone = {}; + if (options.timeoutSeconds !== undefined) { + clone.timeoutSeconds = options.timeoutSeconds; + } + return clone; +} + +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * The value returned from the most recent invocation of + * `generateUniqueDebugId()`, or null if it has never been invoked. + */ +let lastUniqueDebugId = null; +/** + * Generates and returns an initial value for `lastUniqueDebugId`. + * + * The returned value is randomly selected from a range of integers that are + * represented as 8 hexadecimal digits. This means that (within reason) any + * numbers generated by incrementing the returned number by 1 will also be + * represented by 8 hexadecimal digits. This leads to all "IDs" having the same + * length when converted to a hexadecimal string, making reading logs containing + * these IDs easier to follow. And since the return value is randomly selected + * it will help to differentiate between logs from different executions. + */ +function generateInitialUniqueDebugId() { + const minResult = 0x10000000; + const maxResult = 0x90000000; + const resultRange = maxResult - minResult; + const resultOffset = Math.round(resultRange * Math.random()); + return minResult + resultOffset; +} +/** + * Generates and returns a unique ID as a hexadecimal string. + * + * The returned ID is intended to be used in debug logging messages to help + * correlate log messages that may be spatially separated in the logs, but + * logically related. For example, a network connection could include the same + * "debug ID" string in all of its log messages to help trace a specific + * connection over time. + * + * @return the 10-character generated ID (e.g. "0xa1b2c3d4"). + */ +function generateUniqueDebugId() { + if (lastUniqueDebugId === null) { + lastUniqueDebugId = generateInitialUniqueDebugId(); + } + else { + lastUniqueDebugId++; + } + return '0x' + lastUniqueDebugId.toString(16); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const LOG_TAG$3 = 'RestConnection'; +/** + * Maps RPC names to the corresponding REST endpoint name. + * + * We use array notation to avoid mangling. + */ +const RPC_NAME_URL_MAPPING = {}; +RPC_NAME_URL_MAPPING['BatchGetDocuments'] = 'batchGet'; +RPC_NAME_URL_MAPPING['Commit'] = 'commit'; +RPC_NAME_URL_MAPPING['RunQuery'] = 'runQuery'; +RPC_NAME_URL_MAPPING['RunAggregationQuery'] = 'runAggregationQuery'; +const RPC_URL_VERSION = 'v1'; +// SDK_VERSION is updated to different value at runtime depending on the entry point, +// so we need to get its value when we need it in a function. +function getGoogApiClientValue() { + return 'gl-js/ fire/' + SDK_VERSION; +} +/** + * Base class for all Rest-based connections to the backend (WebChannel and + * HTTP). + */ +class RestConnection { + get shouldResourcePathBeIncludedInRequest() { + // Both `invokeRPC()` and `invokeStreamingRPC()` use their `path` arguments to determine + // where to run the query, and expect the `request` to NOT specify the "path". + return false; + } + constructor(databaseInfo) { + this.databaseInfo = databaseInfo; + this.databaseId = databaseInfo.databaseId; + const proto = databaseInfo.ssl ? 'https' : 'http'; + const projectId = encodeURIComponent(this.databaseId.projectId); + const databaseId = encodeURIComponent(this.databaseId.database); + this.baseUrl = proto + '://' + databaseInfo.host; + this.databasePath = `projects/${projectId}/databases/${databaseId}`; + this.requestParams = + this.databaseId.database === DEFAULT_DATABASE_NAME + ? `project_id=${projectId}` + : `project_id=${projectId}&database_id=${databaseId}`; + } + invokeRPC(rpcName, path, req, authToken, appCheckToken) { + const streamId = generateUniqueDebugId(); + const url = this.makeUrl(rpcName, path.toUriEncodedString()); + logDebug(LOG_TAG$3, `Sending RPC '${rpcName}' ${streamId}:`, url, req); + const headers = { + 'google-cloud-resource-prefix': this.databasePath, + 'x-goog-request-params': this.requestParams + }; + this.modifyHeadersForRequest(headers, authToken, appCheckToken); + const { host } = new URL(url); + const forwardCredentials = util.isCloudWorkstation(host); + return this.performRPCRequest(rpcName, url, headers, req, forwardCredentials).then(response => { + logDebug(LOG_TAG$3, `Received RPC '${rpcName}' ${streamId}: `, response); + return response; + }, (err) => { + logWarn(LOG_TAG$3, `RPC '${rpcName}' ${streamId} failed with error: `, err, 'url: ', url, 'request:', req); + throw err; + }); + } + invokeStreamingRPC(rpcName, path, request, authToken, appCheckToken, expectedResponseCount) { + // The REST API automatically aggregates all of the streamed results, so we + // can just use the normal invoke() method. + return this.invokeRPC(rpcName, path, request, authToken, appCheckToken); + } + /** + * Modifies the headers for a request, adding any authorization token if + * present and any additional headers for the request. + */ + modifyHeadersForRequest(headers, authToken, appCheckToken) { + headers['X-Goog-Api-Client'] = getGoogApiClientValue(); + // Content-Type: text/plain will avoid preflight requests which might + // mess with CORS and redirects by proxies. If we add custom headers + // we will need to change this code to potentially use the $httpOverwrite + // parameter supported by ESF to avoid triggering preflight requests. + headers['Content-Type'] = 'text/plain'; + if (this.databaseInfo.appId) { + headers['X-Firebase-GMPID'] = this.databaseInfo.appId; + } + if (authToken) { + authToken.headers.forEach((value, key) => (headers[key] = value)); + } + if (appCheckToken) { + appCheckToken.headers.forEach((value, key) => (headers[key] = value)); + } + } + makeUrl(rpcName, path) { + const urlRpcName = RPC_NAME_URL_MAPPING[rpcName]; + return `${this.baseUrl}/${RPC_URL_VERSION}/${path}:${urlRpcName}`; + } + /** + * Closes and cleans up any resources associated with the connection. This + * implementation is a no-op because there are no resources associated + * with the RestConnection that need to be cleaned up. + */ + terminate() { + // No-op + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Error Codes describing the different ways GRPC can fail. These are copied + * directly from GRPC's sources here: + * + * https://github.com/grpc/grpc/blob/bceec94ea4fc5f0085d81235d8e1c06798dc341a/include/grpc%2B%2B/impl/codegen/status_code_enum.h + * + * Important! The names of these identifiers matter because the string forms + * are used for reverse lookups from the webchannel stream. Do NOT change the + * names of these identifiers or change this into a const enum. + */ +var RpcCode; +(function (RpcCode) { + RpcCode[RpcCode["OK"] = 0] = "OK"; + RpcCode[RpcCode["CANCELLED"] = 1] = "CANCELLED"; + RpcCode[RpcCode["UNKNOWN"] = 2] = "UNKNOWN"; + RpcCode[RpcCode["INVALID_ARGUMENT"] = 3] = "INVALID_ARGUMENT"; + RpcCode[RpcCode["DEADLINE_EXCEEDED"] = 4] = "DEADLINE_EXCEEDED"; + RpcCode[RpcCode["NOT_FOUND"] = 5] = "NOT_FOUND"; + RpcCode[RpcCode["ALREADY_EXISTS"] = 6] = "ALREADY_EXISTS"; + RpcCode[RpcCode["PERMISSION_DENIED"] = 7] = "PERMISSION_DENIED"; + RpcCode[RpcCode["UNAUTHENTICATED"] = 16] = "UNAUTHENTICATED"; + RpcCode[RpcCode["RESOURCE_EXHAUSTED"] = 8] = "RESOURCE_EXHAUSTED"; + RpcCode[RpcCode["FAILED_PRECONDITION"] = 9] = "FAILED_PRECONDITION"; + RpcCode[RpcCode["ABORTED"] = 10] = "ABORTED"; + RpcCode[RpcCode["OUT_OF_RANGE"] = 11] = "OUT_OF_RANGE"; + RpcCode[RpcCode["UNIMPLEMENTED"] = 12] = "UNIMPLEMENTED"; + RpcCode[RpcCode["INTERNAL"] = 13] = "INTERNAL"; + RpcCode[RpcCode["UNAVAILABLE"] = 14] = "UNAVAILABLE"; + RpcCode[RpcCode["DATA_LOSS"] = 15] = "DATA_LOSS"; +})(RpcCode || (RpcCode = {})); +/** + * Determines whether an error code represents a permanent error when received + * in response to a non-write operation. + * + * See isPermanentWriteError for classifying write errors. + */ +function isPermanentError(code) { + switch (code) { + case Code.OK: + return fail(0xfdaa); + case Code.CANCELLED: + case Code.UNKNOWN: + case Code.DEADLINE_EXCEEDED: + case Code.RESOURCE_EXHAUSTED: + case Code.INTERNAL: + case Code.UNAVAILABLE: + // Unauthenticated means something went wrong with our token and we need + // to retry with new credentials which will happen automatically. + case Code.UNAUTHENTICATED: + return false; + case Code.INVALID_ARGUMENT: + case Code.NOT_FOUND: + case Code.ALREADY_EXISTS: + case Code.PERMISSION_DENIED: + case Code.FAILED_PRECONDITION: + // Aborted might be retried in some scenarios, but that is dependent on + // the context and should handled individually by the calling code. + // See https://cloud.google.com/apis/design/errors. + case Code.ABORTED: + case Code.OUT_OF_RANGE: + case Code.UNIMPLEMENTED: + case Code.DATA_LOSS: + return true; + default: + return fail(0x3c6b, { code }); + } +} +/** + * Converts an HTTP Status Code to the equivalent error code. + * + * @param status - An HTTP Status Code, like 200, 404, 503, etc. + * @returns The equivalent Code. Unknown status codes are mapped to + * Code.UNKNOWN. + */ +function mapCodeFromHttpStatus(status) { + if (status === undefined) { + logError('RPC_ERROR', 'HTTP error has no status'); + return Code.UNKNOWN; + } + // The canonical error codes for Google APIs [1] specify mapping onto HTTP + // status codes but the mapping is not bijective. In each case of ambiguity + // this function chooses a primary error. + // + // [1] + // https://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto + switch (status) { + case 200: // OK + return Code.OK; + case 400: // Bad Request + return Code.FAILED_PRECONDITION; + // Other possibilities based on the forward mapping + // return Code.INVALID_ARGUMENT; + // return Code.OUT_OF_RANGE; + case 401: // Unauthorized + return Code.UNAUTHENTICATED; + case 403: // Forbidden + return Code.PERMISSION_DENIED; + case 404: // Not Found + return Code.NOT_FOUND; + case 409: // Conflict + return Code.ABORTED; + // Other possibilities: + // return Code.ALREADY_EXISTS; + case 416: // Range Not Satisfiable + return Code.OUT_OF_RANGE; + case 429: // Too Many Requests + return Code.RESOURCE_EXHAUSTED; + case 499: // Client Closed Request + return Code.CANCELLED; + case 500: // Internal Server Error + return Code.UNKNOWN; + // Other possibilities: + // return Code.INTERNAL; + // return Code.DATA_LOSS; + case 501: // Unimplemented + return Code.UNIMPLEMENTED; + case 503: // Service Unavailable + return Code.UNAVAILABLE; + case 504: // Gateway Timeout + return Code.DEADLINE_EXCEEDED; + default: + if (status >= 200 && status < 300) { + return Code.OK; + } + if (status >= 400 && status < 500) { + return Code.FAILED_PRECONDITION; + } + if (status >= 500 && status < 600) { + return Code.INTERNAL; + } + return Code.UNKNOWN; + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A Rest-based connection that relies on the native HTTP stack + * (e.g. `fetch` or a polyfill). + */ +class FetchConnection extends RestConnection { + openStream(rpcName, token) { + throw new Error('Not supported by FetchConnection'); + } + async performRPCRequest(rpcName, url, headers, body, forwardCredentials) { + const requestJson = JSON.stringify(body); + let response; + try { + const fetchArgs = { + method: 'POST', + headers, + body: requestJson + }; + if (forwardCredentials) { + fetchArgs.credentials = 'include'; + } + response = await fetch(url, fetchArgs); + } + catch (e) { + const err = e; + throw new FirestoreError(mapCodeFromHttpStatus(err.status), 'Request failed with error: ' + err.statusText); + } + if (!response.ok) { + let errorResponse = await response.json(); + if (Array.isArray(errorResponse)) { + errorResponse = errorResponse[0]; + } + const errorMessage = errorResponse?.error?.message; + throw new FirestoreError(mapCodeFromHttpStatus(response.status), `Request failed with error: ${errorMessage ?? response.statusText}`); + } + return response.json(); + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Initializes the HTTP connection for the REST API. */ +function newConnection(databaseInfo) { + return new FetchConnection(databaseInfo); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +function objectSize(obj) { + let count = 0; + for (const key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + count++; + } + } + return count; +} +function forEach(obj, fn) { + for (const key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + fn(key, obj[key]); + } + } +} +function mapToArray(obj, fn) { + const result = []; + for (const key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + result.push(fn(obj[key], key, obj)); + } + } + return result; +} +function isEmpty(obj) { + for (const key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + return false; + } + } + return true; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Returns whether a variable is either undefined or null. + */ +function isNullOrUndefined(value) { + return value === null || value === undefined; +} +/** Returns whether the value represents -0. */ +function isNegativeZero(value) { + // Detect if the value is -0.0. Based on polyfill from + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is + return value === 0 && 1 / value === 1 / -0; +} +/** + * Returns whether a value is an integer and in the safe integer range + * @param value - The value to test for being an integer and in the safe range + */ +function isSafeInteger(value) { + return (typeof value === 'number' && + Number.isInteger(value) && + !isNegativeZero(value) && + value <= Number.MAX_SAFE_INTEGER && + value >= Number.MIN_SAFE_INTEGER); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Converts a Base64 encoded string to a binary string. */ +function decodeBase64(encoded) { + // Note: We used to validate the base64 string here via a regular expression. + // This was removed to improve the performance of indexing. + return Buffer.from(encoded, 'base64').toString('binary'); +} +/** Converts a binary string to a Base64 encoded string. */ +function encodeBase64(raw) { + return Buffer.from(raw, 'binary').toString('base64'); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Immutable class that represents a "proto" byte string. + * + * Proto byte strings can either be Base64-encoded strings or Uint8Arrays when + * sent on the wire. This class abstracts away this differentiation by holding + * the proto byte string in a common class that must be converted into a string + * before being sent as a proto. + * @internal + */ +class ByteString { + constructor(binaryString) { + this.binaryString = binaryString; + } + static fromBase64String(base64) { + const binaryString = decodeBase64(base64); + return new ByteString(binaryString); + } + static fromUint8Array(array) { + // TODO(indexing); Remove the copy of the byte string here as this method + // is frequently called during indexing. + const binaryString = binaryStringFromUint8Array(array); + return new ByteString(binaryString); + } + [Symbol.iterator]() { + let i = 0; + return { + next: () => { + if (i < this.binaryString.length) { + return { value: this.binaryString.charCodeAt(i++), done: false }; + } + else { + return { value: undefined, done: true }; + } + } + }; + } + toBase64() { + return encodeBase64(this.binaryString); + } + toUint8Array() { + return uint8ArrayFromBinaryString(this.binaryString); + } + approximateByteSize() { + return this.binaryString.length * 2; + } + compareTo(other) { + return primitiveComparator(this.binaryString, other.binaryString); + } + isEqual(other) { + return this.binaryString === other.binaryString; + } +} +ByteString.EMPTY_BYTE_STRING = new ByteString(''); +/** + * Helper function to convert an Uint8array to a binary string. + */ +function binaryStringFromUint8Array(array) { + let binaryString = ''; + for (let i = 0; i < array.length; ++i) { + binaryString += String.fromCharCode(array[i]); + } + return binaryString; +} +/** + * Helper function to convert a binary string to an Uint8Array. + */ +function uint8ArrayFromBinaryString(binaryString) { + const buffer = new Uint8Array(binaryString.length); + for (let i = 0; i < binaryString.length; i++) { + buffer[i] = binaryString.charCodeAt(i); + } + return buffer; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// A RegExp matching ISO 8601 UTC timestamps with optional fraction. +const ISO_TIMESTAMP_REG_EXP = new RegExp(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.(\d+))?Z$/); +/** + * Converts the possible Proto values for a timestamp value into a "seconds and + * nanos" representation. + */ +function normalizeTimestamp(date) { + hardAssert(!!date, 0x986a); + // The json interface (for the browser) will return an iso timestamp string, + // while the proto js library (for node) will return a + // google.protobuf.Timestamp instance. + if (typeof date === 'string') { + // The date string can have higher precision (nanos) than the Date class + // (millis), so we do some custom parsing here. + // Parse the nanos right out of the string. + let nanos = 0; + const fraction = ISO_TIMESTAMP_REG_EXP.exec(date); + hardAssert(!!fraction, 0xb5de, { + timestamp: date + }); + if (fraction[1]) { + // Pad the fraction out to 9 digits (nanos). + let nanoStr = fraction[1]; + nanoStr = (nanoStr + '000000000').substr(0, 9); + nanos = Number(nanoStr); + } + // Parse the date to get the seconds. + const parsedDate = new Date(date); + const seconds = Math.floor(parsedDate.getTime() / 1000); + return { seconds, nanos }; + } + else { + // TODO(b/37282237): Use strings for Proto3 timestamps + // assert(!this.options.useProto3Json, + // 'The timestamp instance format requires Proto JS.'); + const seconds = normalizeNumber(date.seconds); + const nanos = normalizeNumber(date.nanos); + return { seconds, nanos }; + } +} +/** + * Converts the possible Proto types for numbers into a JavaScript number. + * Returns 0 if the value is not numeric. + */ +function normalizeNumber(value) { + // TODO(bjornick): Handle int64 greater than 53 bits. + if (typeof value === 'number') { + return value; + } + else if (typeof value === 'string') { + return Number(value); + } + else { + return 0; + } +} +/** Converts the possible Proto types for Blobs into a ByteString. */ +function normalizeByteString(blob) { + if (typeof blob === 'string') { + return ByteString.fromBase64String(blob); + } + else { + return ByteString.fromUint8Array(blob); + } +} + +/** + * @license + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Helper function to define a JSON schema {@link Property}. + * @private + * @internal + */ +function property(typeString, optionalValue) { + const result = { + typeString + }; + if (optionalValue) { + result.value = optionalValue; + } + return result; +} +/** + * Validates the JSON object based on the provided schema, and narrows the type to the provided + * JSON schema. + * @private + * @internal + * + * @param json A JSON object to validate. + * @param scheme a {@link JsonSchema} that defines the properties to validate. + * @returns true if the JSON schema exists within the object. Throws a FirestoreError otherwise. + */ +function validateJSON(json, schema) { + if (!isPlainObject(json)) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'JSON must be an object'); + } + let error = undefined; + for (const key in schema) { + if (schema[key]) { + const typeString = schema[key].typeString; + const value = 'value' in schema[key] ? { value: schema[key].value } : undefined; + if (!(key in json)) { + error = `JSON missing required field: '${key}'`; + break; + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const fieldValue = json[key]; + if (typeString && typeof fieldValue !== typeString) { + error = `JSON field '${key}' must be a ${typeString}.`; + break; + } + else if (value !== undefined && fieldValue !== value.value) { + error = `Expected '${key}' field to equal '${value.value}'`; + break; + } + } + } + if (error) { + throw new FirestoreError(Code.INVALID_ARGUMENT, error); + } + return true; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// The earliest date supported by Firestore timestamps (0001-01-01T00:00:00Z). +const MIN_SECONDS = -62135596800; +// Number of nanoseconds in a millisecond. +const MS_TO_NANOS = 1e6; +/** + * A `Timestamp` represents a point in time independent of any time zone or + * calendar, represented as seconds and fractions of seconds at nanosecond + * resolution in UTC Epoch time. + * + * It is encoded using the Proleptic Gregorian Calendar which extends the + * Gregorian calendar backwards to year one. It is encoded assuming all minutes + * are 60 seconds long, i.e. leap seconds are "smeared" so that no leap second + * table is needed for interpretation. Range is from 0001-01-01T00:00:00Z to + * 9999-12-31T23:59:59.999999999Z. + * + * For examples and further specifications, refer to the + * {@link https://github.com/google/protobuf/blob/master/src/google/protobuf/timestamp.proto | Timestamp definition}. + */ +class Timestamp { + /** + * Creates a new timestamp with the current date, with millisecond precision. + * + * @returns a new timestamp representing the current date. + */ + static now() { + return Timestamp.fromMillis(Date.now()); + } + /** + * Creates a new timestamp from the given date. + * + * @param date - The date to initialize the `Timestamp` from. + * @returns A new `Timestamp` representing the same point in time as the given + * date. + */ + static fromDate(date) { + return Timestamp.fromMillis(date.getTime()); + } + /** + * Creates a new timestamp from the given number of milliseconds. + * + * @param milliseconds - Number of milliseconds since Unix epoch + * 1970-01-01T00:00:00Z. + * @returns A new `Timestamp` representing the same point in time as the given + * number of milliseconds. + */ + static fromMillis(milliseconds) { + const seconds = Math.floor(milliseconds / 1000); + const nanos = Math.floor((milliseconds - seconds * 1000) * MS_TO_NANOS); + return new Timestamp(seconds, nanos); + } + /** + * Creates a new timestamp. + * + * @param seconds - The number of seconds of UTC time since Unix epoch + * 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to + * 9999-12-31T23:59:59Z inclusive. + * @param nanoseconds - The non-negative fractions of a second at nanosecond + * resolution. Negative second values with fractions must still have + * non-negative nanoseconds values that count forward in time. Must be + * from 0 to 999,999,999 inclusive. + */ + constructor( + /** + * The number of seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z. + */ + seconds, + /** + * The fractions of a second at nanosecond resolution.* + */ + nanoseconds) { + this.seconds = seconds; + this.nanoseconds = nanoseconds; + if (nanoseconds < 0) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Timestamp nanoseconds out of range: ' + nanoseconds); + } + if (nanoseconds >= 1e9) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Timestamp nanoseconds out of range: ' + nanoseconds); + } + if (seconds < MIN_SECONDS) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Timestamp seconds out of range: ' + seconds); + } + // This will break in the year 10,000. + if (seconds >= 253402300800) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Timestamp seconds out of range: ' + seconds); + } + } + /** + * Converts a `Timestamp` to a JavaScript `Date` object. This conversion + * causes a loss of precision since `Date` objects only support millisecond + * precision. + * + * @returns JavaScript `Date` object representing the same point in time as + * this `Timestamp`, with millisecond precision. + */ + toDate() { + return new Date(this.toMillis()); + } + /** + * Converts a `Timestamp` to a numeric timestamp (in milliseconds since + * epoch). This operation causes a loss of precision. + * + * @returns The point in time corresponding to this timestamp, represented as + * the number of milliseconds since Unix epoch 1970-01-01T00:00:00Z. + */ + toMillis() { + return this.seconds * 1000 + this.nanoseconds / MS_TO_NANOS; + } + _compareTo(other) { + if (this.seconds === other.seconds) { + return primitiveComparator(this.nanoseconds, other.nanoseconds); + } + return primitiveComparator(this.seconds, other.seconds); + } + /** + * Returns true if this `Timestamp` is equal to the provided one. + * + * @param other - The `Timestamp` to compare against. + * @returns true if this `Timestamp` is equal to the provided one. + */ + isEqual(other) { + return (other.seconds === this.seconds && other.nanoseconds === this.nanoseconds); + } + /** Returns a textual representation of this `Timestamp`. */ + toString() { + return ('Timestamp(seconds=' + + this.seconds + + ', nanoseconds=' + + this.nanoseconds + + ')'); + } + /** + * Returns a JSON-serializable representation of this `Timestamp`. + */ + toJSON() { + return { + type: Timestamp._jsonSchemaVersion, + seconds: this.seconds, + nanoseconds: this.nanoseconds + }; + } + /** + * Builds a `Timestamp` instance from a JSON object created by {@link Timestamp.toJSON}. + */ + static fromJSON(json) { + if (validateJSON(json, Timestamp._jsonSchema)) { + return new Timestamp(json.seconds, json.nanoseconds); + } + } + /** + * Converts this object to a primitive string, which allows `Timestamp` objects + * to be compared using the `>`, `<=`, `>=` and `>` operators. + */ + valueOf() { + // This method returns a string of the form . where + // is translated to have a non-negative value and both + // and are left-padded with zeroes to be a consistent length. + // Strings with this format then have a lexicographical ordering that matches + // the expected ordering. The translation is done to avoid having + // a leading negative sign (i.e. a leading '-' character) in its string + // representation, which would affect its lexicographical ordering. + const adjustedSeconds = this.seconds - MIN_SECONDS; + // Note: Up to 12 decimal digits are required to represent all valid + // 'seconds' values. + const formattedSeconds = String(adjustedSeconds).padStart(12, '0'); + const formattedNanoseconds = String(this.nanoseconds).padStart(9, '0'); + return formattedSeconds + '.' + formattedNanoseconds; + } +} +Timestamp._jsonSchemaVersion = 'firestore/timestamp/1.0'; +Timestamp._jsonSchema = { + type: property('string', Timestamp._jsonSchemaVersion), + seconds: property('number'), + nanoseconds: property('number') +}; + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Represents a locally-applied ServerTimestamp. + * + * Server Timestamps are backed by MapValues that contain an internal field + * `__type__` with a value of `server_timestamp`. The previous value and local + * write time are stored in its `__previous_value__` and `__local_write_time__` + * fields respectively. + * + * Notes: + * - ServerTimestampValue instances are created as the result of applying a + * transform. They can only exist in the local view of a document. Therefore + * they do not need to be parsed or serialized. + * - When evaluated locally (e.g. for snapshot.data()), they by default + * evaluate to `null`. This behavior can be configured by passing custom + * FieldValueOptions to value(). + * - With respect to other ServerTimestampValues, they sort by their + * localWriteTime. + */ +const SERVER_TIMESTAMP_SENTINEL = 'server_timestamp'; +const TYPE_KEY$1 = '__type__'; +const PREVIOUS_VALUE_KEY = '__previous_value__'; +const LOCAL_WRITE_TIME_KEY = '__local_write_time__'; +function isServerTimestamp(value) { + const type = (value?.mapValue?.fields || {})[TYPE_KEY$1]?.stringValue; + return type === SERVER_TIMESTAMP_SENTINEL; +} +/** + * Returns the value of the field before this ServerTimestamp was set. + * + * Preserving the previous values allows the user to display the last resoled + * value until the backend responds with the timestamp. + */ +function getPreviousValue(value) { + const previousValue = value.mapValue.fields[PREVIOUS_VALUE_KEY]; + if (isServerTimestamp(previousValue)) { + return getPreviousValue(previousValue); + } + return previousValue; +} +/** + * Returns the local time at which this timestamp was first set. + */ +function getLocalWriteTime(value) { + const localWriteTime = normalizeTimestamp(value.mapValue.fields[LOCAL_WRITE_TIME_KEY].timestampValue); + return new Timestamp(localWriteTime.seconds, localWriteTime.nanos); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const TYPE_KEY = '__type__'; +const MAX_VALUE_TYPE = '__max__'; +const MAX_VALUE = { + mapValue: { + fields: { + '__type__': { stringValue: MAX_VALUE_TYPE } + } + } +}; +const VECTOR_VALUE_SENTINEL = '__vector__'; +const VECTOR_MAP_VECTORS_KEY = 'value'; +/** Extracts the backend's type order for the provided value. */ +function typeOrder(value) { + if ('nullValue' in value) { + return 0 /* TypeOrder.NullValue */; + } + else if ('booleanValue' in value) { + return 1 /* TypeOrder.BooleanValue */; + } + else if ('integerValue' in value || 'doubleValue' in value) { + return 2 /* TypeOrder.NumberValue */; + } + else if ('timestampValue' in value) { + return 3 /* TypeOrder.TimestampValue */; + } + else if ('stringValue' in value) { + return 5 /* TypeOrder.StringValue */; + } + else if ('bytesValue' in value) { + return 6 /* TypeOrder.BlobValue */; + } + else if ('referenceValue' in value) { + return 7 /* TypeOrder.RefValue */; + } + else if ('geoPointValue' in value) { + return 8 /* TypeOrder.GeoPointValue */; + } + else if ('arrayValue' in value) { + return 9 /* TypeOrder.ArrayValue */; + } + else if ('mapValue' in value) { + if (isServerTimestamp(value)) { + return 4 /* TypeOrder.ServerTimestampValue */; + } + else if (isMaxValue(value)) { + return 9007199254740991 /* TypeOrder.MaxValue */; + } + else if (isVectorValue(value)) { + return 10 /* TypeOrder.VectorValue */; + } + return 11 /* TypeOrder.ObjectValue */; + } + else { + return fail(0x6e87, { value }); + } +} +/** Tests `left` and `right` for equality based on the backend semantics. */ +function valueEquals(left, right) { + if (left === right) { + return true; + } + const leftType = typeOrder(left); + const rightType = typeOrder(right); + if (leftType !== rightType) { + return false; + } + switch (leftType) { + case 0 /* TypeOrder.NullValue */: + return true; + case 1 /* TypeOrder.BooleanValue */: + return left.booleanValue === right.booleanValue; + case 4 /* TypeOrder.ServerTimestampValue */: + return getLocalWriteTime(left).isEqual(getLocalWriteTime(right)); + case 3 /* TypeOrder.TimestampValue */: + return timestampEquals(left, right); + case 5 /* TypeOrder.StringValue */: + return left.stringValue === right.stringValue; + case 6 /* TypeOrder.BlobValue */: + return blobEquals(left, right); + case 7 /* TypeOrder.RefValue */: + return left.referenceValue === right.referenceValue; + case 8 /* TypeOrder.GeoPointValue */: + return geoPointEquals(left, right); + case 2 /* TypeOrder.NumberValue */: + return numberEquals(left, right); + case 9 /* TypeOrder.ArrayValue */: + return arrayEquals(left.arrayValue.values || [], right.arrayValue.values || [], valueEquals); + case 10 /* TypeOrder.VectorValue */: + case 11 /* TypeOrder.ObjectValue */: + return objectEquals(left, right); + case 9007199254740991 /* TypeOrder.MaxValue */: + return true; + default: + return fail(0xcbf8, { left }); + } +} +function timestampEquals(left, right) { + if (typeof left.timestampValue === 'string' && + typeof right.timestampValue === 'string' && + left.timestampValue.length === right.timestampValue.length) { + // Use string equality for ISO 8601 timestamps + return left.timestampValue === right.timestampValue; + } + const leftTimestamp = normalizeTimestamp(left.timestampValue); + const rightTimestamp = normalizeTimestamp(right.timestampValue); + return (leftTimestamp.seconds === rightTimestamp.seconds && + leftTimestamp.nanos === rightTimestamp.nanos); +} +function geoPointEquals(left, right) { + return (normalizeNumber(left.geoPointValue.latitude) === + normalizeNumber(right.geoPointValue.latitude) && + normalizeNumber(left.geoPointValue.longitude) === + normalizeNumber(right.geoPointValue.longitude)); +} +function blobEquals(left, right) { + return normalizeByteString(left.bytesValue).isEqual(normalizeByteString(right.bytesValue)); +} +function numberEquals(left, right) { + if ('integerValue' in left && 'integerValue' in right) { + return (normalizeNumber(left.integerValue) === normalizeNumber(right.integerValue)); + } + else if ('doubleValue' in left && 'doubleValue' in right) { + const n1 = normalizeNumber(left.doubleValue); + const n2 = normalizeNumber(right.doubleValue); + if (n1 === n2) { + return isNegativeZero(n1) === isNegativeZero(n2); + } + else { + return isNaN(n1) && isNaN(n2); + } + } + return false; +} +function objectEquals(left, right) { + const leftMap = left.mapValue.fields || {}; + const rightMap = right.mapValue.fields || {}; + if (objectSize(leftMap) !== objectSize(rightMap)) { + return false; + } + for (const key in leftMap) { + if (leftMap.hasOwnProperty(key)) { + if (rightMap[key] === undefined || + !valueEquals(leftMap[key], rightMap[key])) { + return false; + } + } + } + return true; +} +/** Returns true if the ArrayValue contains the specified element. */ +function arrayValueContains(haystack, needle) { + return ((haystack.values || []).find(v => valueEquals(v, needle)) !== undefined); +} +function valueCompare(left, right) { + if (left === right) { + return 0; + } + const leftType = typeOrder(left); + const rightType = typeOrder(right); + if (leftType !== rightType) { + return primitiveComparator(leftType, rightType); + } + switch (leftType) { + case 0 /* TypeOrder.NullValue */: + case 9007199254740991 /* TypeOrder.MaxValue */: + return 0; + case 1 /* TypeOrder.BooleanValue */: + return primitiveComparator(left.booleanValue, right.booleanValue); + case 2 /* TypeOrder.NumberValue */: + return compareNumbers(left, right); + case 3 /* TypeOrder.TimestampValue */: + return compareTimestamps(left.timestampValue, right.timestampValue); + case 4 /* TypeOrder.ServerTimestampValue */: + return compareTimestamps(getLocalWriteTime(left), getLocalWriteTime(right)); + case 5 /* TypeOrder.StringValue */: + return compareUtf8Strings(left.stringValue, right.stringValue); + case 6 /* TypeOrder.BlobValue */: + return compareBlobs(left.bytesValue, right.bytesValue); + case 7 /* TypeOrder.RefValue */: + return compareReferences(left.referenceValue, right.referenceValue); + case 8 /* TypeOrder.GeoPointValue */: + return compareGeoPoints(left.geoPointValue, right.geoPointValue); + case 9 /* TypeOrder.ArrayValue */: + return compareArrays(left.arrayValue, right.arrayValue); + case 10 /* TypeOrder.VectorValue */: + return compareVectors(left.mapValue, right.mapValue); + case 11 /* TypeOrder.ObjectValue */: + return compareMaps(left.mapValue, right.mapValue); + default: + throw fail(0x5ae0, { leftType }); + } +} +function compareNumbers(left, right) { + const leftNumber = normalizeNumber(left.integerValue || left.doubleValue); + const rightNumber = normalizeNumber(right.integerValue || right.doubleValue); + if (leftNumber < rightNumber) { + return -1; + } + else if (leftNumber > rightNumber) { + return 1; + } + else if (leftNumber === rightNumber) { + return 0; + } + else { + // one or both are NaN. + if (isNaN(leftNumber)) { + return isNaN(rightNumber) ? 0 : -1; + } + else { + return 1; + } + } +} +function compareTimestamps(left, right) { + if (typeof left === 'string' && + typeof right === 'string' && + left.length === right.length) { + return primitiveComparator(left, right); + } + const leftTimestamp = normalizeTimestamp(left); + const rightTimestamp = normalizeTimestamp(right); + const comparison = primitiveComparator(leftTimestamp.seconds, rightTimestamp.seconds); + if (comparison !== 0) { + return comparison; + } + return primitiveComparator(leftTimestamp.nanos, rightTimestamp.nanos); +} +function compareReferences(leftPath, rightPath) { + const leftSegments = leftPath.split('/'); + const rightSegments = rightPath.split('/'); + for (let i = 0; i < leftSegments.length && i < rightSegments.length; i++) { + const comparison = primitiveComparator(leftSegments[i], rightSegments[i]); + if (comparison !== 0) { + return comparison; + } + } + return primitiveComparator(leftSegments.length, rightSegments.length); +} +function compareGeoPoints(left, right) { + const comparison = primitiveComparator(normalizeNumber(left.latitude), normalizeNumber(right.latitude)); + if (comparison !== 0) { + return comparison; + } + return primitiveComparator(normalizeNumber(left.longitude), normalizeNumber(right.longitude)); +} +function compareBlobs(left, right) { + const leftBytes = normalizeByteString(left); + const rightBytes = normalizeByteString(right); + return leftBytes.compareTo(rightBytes); +} +function compareArrays(left, right) { + const leftArray = left.values || []; + const rightArray = right.values || []; + for (let i = 0; i < leftArray.length && i < rightArray.length; ++i) { + const compare = valueCompare(leftArray[i], rightArray[i]); + if (compare) { + return compare; + } + } + return primitiveComparator(leftArray.length, rightArray.length); +} +function compareVectors(left, right) { + const leftMap = left.fields || {}; + const rightMap = right.fields || {}; + // The vector is a map, but only vector value is compared. + const leftArrayValue = leftMap[VECTOR_MAP_VECTORS_KEY]?.arrayValue; + const rightArrayValue = rightMap[VECTOR_MAP_VECTORS_KEY]?.arrayValue; + const lengthCompare = primitiveComparator(leftArrayValue?.values?.length || 0, rightArrayValue?.values?.length || 0); + if (lengthCompare !== 0) { + return lengthCompare; + } + return compareArrays(leftArrayValue, rightArrayValue); +} +function compareMaps(left, right) { + if (left === MAX_VALUE.mapValue && right === MAX_VALUE.mapValue) { + return 0; + } + else if (left === MAX_VALUE.mapValue) { + return 1; + } + else if (right === MAX_VALUE.mapValue) { + return -1; + } + const leftMap = left.fields || {}; + const leftKeys = Object.keys(leftMap); + const rightMap = right.fields || {}; + const rightKeys = Object.keys(rightMap); + // Even though MapValues are likely sorted correctly based on their insertion + // order (e.g. when received from the backend), local modifications can bring + // elements out of order. We need to re-sort the elements to ensure that + // canonical IDs are independent of insertion order. + leftKeys.sort(); + rightKeys.sort(); + for (let i = 0; i < leftKeys.length && i < rightKeys.length; ++i) { + const keyCompare = compareUtf8Strings(leftKeys[i], rightKeys[i]); + if (keyCompare !== 0) { + return keyCompare; + } + const compare = valueCompare(leftMap[leftKeys[i]], rightMap[rightKeys[i]]); + if (compare !== 0) { + return compare; + } + } + return primitiveComparator(leftKeys.length, rightKeys.length); +} +/** Returns a reference value for the provided database and key. */ +function refValue(databaseId, key) { + return { + referenceValue: `projects/${databaseId.projectId}/databases/${databaseId.database}/documents/${key.path.canonicalString()}` + }; +} +/** Returns true if `value` is an ArrayValue. */ +function isArray(value) { + return !!value && 'arrayValue' in value; +} +/** Returns true if `value` is a NullValue. */ +function isNullValue(value) { + return !!value && 'nullValue' in value; +} +/** Returns true if `value` is NaN. */ +function isNanValue(value) { + return !!value && 'doubleValue' in value && isNaN(Number(value.doubleValue)); +} +/** Returns true if `value` is a MapValue. */ +function isMapValue(value) { + return !!value && 'mapValue' in value; +} +/** Returns true if `value` is a VetorValue. */ +function isVectorValue(value) { + const type = (value?.mapValue?.fields || {})[TYPE_KEY]?.stringValue; + return type === VECTOR_VALUE_SENTINEL; +} +/** Creates a deep copy of `source`. */ +function deepClone(source) { + if (source.geoPointValue) { + return { geoPointValue: { ...source.geoPointValue } }; + } + else if (source.timestampValue && + typeof source.timestampValue === 'object') { + return { timestampValue: { ...source.timestampValue } }; + } + else if (source.mapValue) { + const target = { mapValue: { fields: {} } }; + forEach(source.mapValue.fields, (key, val) => (target.mapValue.fields[key] = deepClone(val))); + return target; + } + else if (source.arrayValue) { + const target = { arrayValue: { values: [] } }; + for (let i = 0; i < (source.arrayValue.values || []).length; ++i) { + target.arrayValue.values[i] = deepClone(source.arrayValue.values[i]); + } + return target; + } + else { + return { ...source }; + } +} +/** Returns true if the Value represents the canonical {@link #MAX_VALUE} . */ +function isMaxValue(value) { + return ((((value.mapValue || {}).fields || {})['__type__'] || {}).stringValue === + MAX_VALUE_TYPE); +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Represents a bound of a query. + * + * The bound is specified with the given components representing a position and + * whether it's just before or just after the position (relative to whatever the + * query order is). + * + * The position represents a logical index position for a query. It's a prefix + * of values for the (potentially implicit) order by clauses of a query. + * + * Bound provides a function to determine whether a document comes before or + * after a bound. This is influenced by whether the position is just before or + * just after the provided values. + */ +class Bound { + constructor(position, inclusive) { + this.position = position; + this.inclusive = inclusive; + } +} +function boundEquals(left, right) { + if (left === null) { + return right === null; + } + else if (right === null) { + return false; + } + if (left.inclusive !== right.inclusive || + left.position.length !== right.position.length) { + return false; + } + for (let i = 0; i < left.position.length; i++) { + const leftPosition = left.position[i]; + const rightPosition = right.position[i]; + if (!valueEquals(leftPosition, rightPosition)) { + return false; + } + } + return true; +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class Filter { +} +class FieldFilter extends Filter { + constructor(field, op, value) { + super(); + this.field = field; + this.op = op; + this.value = value; + } + /** + * Creates a filter based on the provided arguments. + */ + static create(field, op, value) { + if (field.isKeyField()) { + if (op === "in" /* Operator.IN */ || op === "not-in" /* Operator.NOT_IN */) { + return this.createKeyFieldInFilter(field, op, value); + } + else { + return new KeyFieldFilter(field, op, value); + } + } + else if (op === "array-contains" /* Operator.ARRAY_CONTAINS */) { + return new ArrayContainsFilter(field, value); + } + else if (op === "in" /* Operator.IN */) { + return new InFilter(field, value); + } + else if (op === "not-in" /* Operator.NOT_IN */) { + return new NotInFilter(field, value); + } + else if (op === "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */) { + return new ArrayContainsAnyFilter(field, value); + } + else { + return new FieldFilter(field, op, value); + } + } + static createKeyFieldInFilter(field, op, value) { + return op === "in" /* Operator.IN */ + ? new KeyFieldInFilter(field, value) + : new KeyFieldNotInFilter(field, value); + } + matches(doc) { + const other = doc.data.field(this.field); + // Types do not have to match in NOT_EQUAL filters. + if (this.op === "!=" /* Operator.NOT_EQUAL */) { + return (other !== null && + other.nullValue === undefined && + this.matchesComparison(valueCompare(other, this.value))); + } + // Only compare types with matching backend order (such as double and int). + return (other !== null && + typeOrder(this.value) === typeOrder(other) && + this.matchesComparison(valueCompare(other, this.value))); + } + matchesComparison(comparison) { + switch (this.op) { + case "<" /* Operator.LESS_THAN */: + return comparison < 0; + case "<=" /* Operator.LESS_THAN_OR_EQUAL */: + return comparison <= 0; + case "==" /* Operator.EQUAL */: + return comparison === 0; + case "!=" /* Operator.NOT_EQUAL */: + return comparison !== 0; + case ">" /* Operator.GREATER_THAN */: + return comparison > 0; + case ">=" /* Operator.GREATER_THAN_OR_EQUAL */: + return comparison >= 0; + default: + return fail(0xb8a2, { + operator: this.op + }); + } + } + isInequality() { + return ([ + "<" /* Operator.LESS_THAN */, + "<=" /* Operator.LESS_THAN_OR_EQUAL */, + ">" /* Operator.GREATER_THAN */, + ">=" /* Operator.GREATER_THAN_OR_EQUAL */, + "!=" /* Operator.NOT_EQUAL */, + "not-in" /* Operator.NOT_IN */ + ].indexOf(this.op) >= 0); + } + getFlattenedFilters() { + return [this]; + } + getFilters() { + return [this]; + } +} +class CompositeFilter extends Filter { + constructor(filters, op) { + super(); + this.filters = filters; + this.op = op; + this.memoizedFlattenedFilters = null; + } + /** + * Creates a filter based on the provided arguments. + */ + static create(filters, op) { + return new CompositeFilter(filters, op); + } + matches(doc) { + if (compositeFilterIsConjunction(this)) { + // For conjunctions, all filters must match, so return false if any filter doesn't match. + return this.filters.find(filter => !filter.matches(doc)) === undefined; + } + else { + // For disjunctions, at least one filter should match. + return this.filters.find(filter => filter.matches(doc)) !== undefined; + } + } + getFlattenedFilters() { + if (this.memoizedFlattenedFilters !== null) { + return this.memoizedFlattenedFilters; + } + this.memoizedFlattenedFilters = this.filters.reduce((result, subfilter) => { + return result.concat(subfilter.getFlattenedFilters()); + }, []); + return this.memoizedFlattenedFilters; + } + // Returns a mutable copy of `this.filters` + getFilters() { + return Object.assign([], this.filters); + } +} +function compositeFilterIsConjunction(compositeFilter) { + return compositeFilter.op === "and" /* CompositeOperator.AND */; +} +function filterEquals(f1, f2) { + if (f1 instanceof FieldFilter) { + return fieldFilterEquals(f1, f2); + } + else if (f1 instanceof CompositeFilter) { + return compositeFilterEquals(f1, f2); + } + else { + fail(0x4bef); + } +} +function fieldFilterEquals(f1, f2) { + return (f2 instanceof FieldFilter && + f1.op === f2.op && + f1.field.isEqual(f2.field) && + valueEquals(f1.value, f2.value)); +} +function compositeFilterEquals(f1, f2) { + if (f2 instanceof CompositeFilter && + f1.op === f2.op && + f1.filters.length === f2.filters.length) { + const subFiltersMatch = f1.filters.reduce((result, f1Filter, index) => result && filterEquals(f1Filter, f2.filters[index]), true); + return subFiltersMatch; + } + return false; +} +/** Filter that matches on key fields (i.e. '__name__'). */ +class KeyFieldFilter extends FieldFilter { + constructor(field, op, value) { + super(field, op, value); + this.key = DocumentKey.fromName(value.referenceValue); + } + matches(doc) { + const comparison = DocumentKey.comparator(doc.key, this.key); + return this.matchesComparison(comparison); + } +} +/** Filter that matches on key fields within an array. */ +class KeyFieldInFilter extends FieldFilter { + constructor(field, value) { + super(field, "in" /* Operator.IN */, value); + this.keys = extractDocumentKeysFromArrayValue("in" /* Operator.IN */, value); + } + matches(doc) { + return this.keys.some(key => key.isEqual(doc.key)); + } +} +/** Filter that matches on key fields not present within an array. */ +class KeyFieldNotInFilter extends FieldFilter { + constructor(field, value) { + super(field, "not-in" /* Operator.NOT_IN */, value); + this.keys = extractDocumentKeysFromArrayValue("not-in" /* Operator.NOT_IN */, value); + } + matches(doc) { + return !this.keys.some(key => key.isEqual(doc.key)); + } +} +function extractDocumentKeysFromArrayValue(op, value) { + return (value.arrayValue?.values || []).map(v => { + return DocumentKey.fromName(v.referenceValue); + }); +} +/** A Filter that implements the array-contains operator. */ +class ArrayContainsFilter extends FieldFilter { + constructor(field, value) { + super(field, "array-contains" /* Operator.ARRAY_CONTAINS */, value); + } + matches(doc) { + const other = doc.data.field(this.field); + return isArray(other) && arrayValueContains(other.arrayValue, this.value); + } +} +/** A Filter that implements the IN operator. */ +class InFilter extends FieldFilter { + constructor(field, value) { + super(field, "in" /* Operator.IN */, value); + } + matches(doc) { + const other = doc.data.field(this.field); + return other !== null && arrayValueContains(this.value.arrayValue, other); + } +} +/** A Filter that implements the not-in operator. */ +class NotInFilter extends FieldFilter { + constructor(field, value) { + super(field, "not-in" /* Operator.NOT_IN */, value); + } + matches(doc) { + if (arrayValueContains(this.value.arrayValue, { nullValue: 'NULL_VALUE' })) { + return false; + } + const other = doc.data.field(this.field); + return (other !== null && + other.nullValue === undefined && + !arrayValueContains(this.value.arrayValue, other)); + } +} +/** A Filter that implements the array-contains-any operator. */ +class ArrayContainsAnyFilter extends FieldFilter { + constructor(field, value) { + super(field, "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */, value); + } + matches(doc) { + const other = doc.data.field(this.field); + if (!isArray(other) || !other.arrayValue.values) { + return false; + } + return other.arrayValue.values.some(val => arrayValueContains(this.value.arrayValue, val)); + } +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An ordering on a field, in some Direction. Direction defaults to ASCENDING. + */ +class OrderBy { + constructor(field, dir = "asc" /* Direction.ASCENDING */) { + this.field = field; + this.dir = dir; + } +} +function orderByEquals(left, right) { + return left.dir === right.dir && left.field.isEqual(right.field); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A version of a document in Firestore. This corresponds to the version + * timestamp, such as update_time or read_time. + */ +class SnapshotVersion { + static fromTimestamp(value) { + return new SnapshotVersion(value); + } + static min() { + return new SnapshotVersion(new Timestamp(0, 0)); + } + static max() { + return new SnapshotVersion(new Timestamp(253402300799, 1e9 - 1)); + } + constructor(timestamp) { + this.timestamp = timestamp; + } + compareTo(other) { + return this.timestamp._compareTo(other.timestamp); + } + isEqual(other) { + return this.timestamp.isEqual(other.timestamp); + } + /** Returns a number representation of the version for use in spec tests. */ + toMicroseconds() { + // Convert to microseconds. + return this.timestamp.seconds * 1e6 + this.timestamp.nanoseconds / 1000; + } + toString() { + return 'SnapshotVersion(' + this.timestamp.toString() + ')'; + } + toTimestamp() { + return this.timestamp; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// An immutable sorted map implementation, based on a Left-leaning Red-Black +// tree. +class SortedMap { + constructor(comparator, root) { + this.comparator = comparator; + this.root = root ? root : LLRBNode.EMPTY; + } + // Returns a copy of the map, with the specified key/value added or replaced. + insert(key, value) { + return new SortedMap(this.comparator, this.root + .insert(key, value, this.comparator) + .copy(null, null, LLRBNode.BLACK, null, null)); + } + // Returns a copy of the map, with the specified key removed. + remove(key) { + return new SortedMap(this.comparator, this.root + .remove(key, this.comparator) + .copy(null, null, LLRBNode.BLACK, null, null)); + } + // Returns the value of the node with the given key, or null. + get(key) { + let node = this.root; + while (!node.isEmpty()) { + const cmp = this.comparator(key, node.key); + if (cmp === 0) { + return node.value; + } + else if (cmp < 0) { + node = node.left; + } + else if (cmp > 0) { + node = node.right; + } + } + return null; + } + // Returns the index of the element in this sorted map, or -1 if it doesn't + // exist. + indexOf(key) { + // Number of nodes that were pruned when descending right + let prunedNodes = 0; + let node = this.root; + while (!node.isEmpty()) { + const cmp = this.comparator(key, node.key); + if (cmp === 0) { + return prunedNodes + node.left.size; + } + else if (cmp < 0) { + node = node.left; + } + else { + // Count all nodes left of the node plus the node itself + prunedNodes += node.left.size + 1; + node = node.right; + } + } + // Node not found + return -1; + } + isEmpty() { + return this.root.isEmpty(); + } + // Returns the total number of nodes in the map. + get size() { + return this.root.size; + } + // Returns the minimum key in the map. + minKey() { + return this.root.minKey(); + } + // Returns the maximum key in the map. + maxKey() { + return this.root.maxKey(); + } + // Traverses the map in key order and calls the specified action function + // for each key/value pair. If action returns true, traversal is aborted. + // Returns the first truthy value returned by action, or the last falsey + // value returned by action. + inorderTraversal(action) { + return this.root.inorderTraversal(action); + } + forEach(fn) { + this.inorderTraversal((k, v) => { + fn(k, v); + return false; + }); + } + toString() { + const descriptions = []; + this.inorderTraversal((k, v) => { + descriptions.push(`${k}:${v}`); + return false; + }); + return `{${descriptions.join(', ')}}`; + } + // Traverses the map in reverse key order and calls the specified action + // function for each key/value pair. If action returns true, traversal is + // aborted. + // Returns the first truthy value returned by action, or the last falsey + // value returned by action. + reverseTraversal(action) { + return this.root.reverseTraversal(action); + } + // Returns an iterator over the SortedMap. + getIterator() { + return new SortedMapIterator(this.root, null, this.comparator, false); + } + getIteratorFrom(key) { + return new SortedMapIterator(this.root, key, this.comparator, false); + } + getReverseIterator() { + return new SortedMapIterator(this.root, null, this.comparator, true); + } + getReverseIteratorFrom(key) { + return new SortedMapIterator(this.root, key, this.comparator, true); + } +} // end SortedMap +// An iterator over an LLRBNode. +class SortedMapIterator { + constructor(node, startKey, comparator, isReverse) { + this.isReverse = isReverse; + this.nodeStack = []; + let cmp = 1; + while (!node.isEmpty()) { + cmp = startKey ? comparator(node.key, startKey) : 1; + // flip the comparison if we're going in reverse + if (startKey && isReverse) { + cmp *= -1; + } + if (cmp < 0) { + // This node is less than our start key. ignore it + if (this.isReverse) { + node = node.left; + } + else { + node = node.right; + } + } + else if (cmp === 0) { + // This node is exactly equal to our start key. Push it on the stack, + // but stop iterating; + this.nodeStack.push(node); + break; + } + else { + // This node is greater than our start key, add it to the stack and move + // to the next one + this.nodeStack.push(node); + if (this.isReverse) { + node = node.right; + } + else { + node = node.left; + } + } + } + } + getNext() { + let node = this.nodeStack.pop(); + const result = { key: node.key, value: node.value }; + if (this.isReverse) { + node = node.left; + while (!node.isEmpty()) { + this.nodeStack.push(node); + node = node.right; + } + } + else { + node = node.right; + while (!node.isEmpty()) { + this.nodeStack.push(node); + node = node.left; + } + } + return result; + } + hasNext() { + return this.nodeStack.length > 0; + } + peek() { + if (this.nodeStack.length === 0) { + return null; + } + const node = this.nodeStack[this.nodeStack.length - 1]; + return { key: node.key, value: node.value }; + } +} // end SortedMapIterator +// Represents a node in a Left-leaning Red-Black tree. +class LLRBNode { + constructor(key, value, color, left, right) { + this.key = key; + this.value = value; + this.color = color != null ? color : LLRBNode.RED; + this.left = left != null ? left : LLRBNode.EMPTY; + this.right = right != null ? right : LLRBNode.EMPTY; + this.size = this.left.size + 1 + this.right.size; + } + // Returns a copy of the current node, optionally replacing pieces of it. + copy(key, value, color, left, right) { + 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); + } + isEmpty() { + return false; + } + // Traverses the tree in key order and calls the specified action function + // for each node. If action returns true, traversal is aborted. + // Returns the first truthy value returned by action, or the last falsey + // value returned by action. + inorderTraversal(action) { + return (this.left.inorderTraversal(action) || + action(this.key, this.value) || + this.right.inorderTraversal(action)); + } + // Traverses the tree in reverse key order and calls the specified action + // function for each node. If action returns true, traversal is aborted. + // Returns the first truthy value returned by action, or the last falsey + // value returned by action. + reverseTraversal(action) { + return (this.right.reverseTraversal(action) || + action(this.key, this.value) || + this.left.reverseTraversal(action)); + } + // Returns the minimum node in the tree. + min() { + if (this.left.isEmpty()) { + return this; + } + else { + return this.left.min(); + } + } + // Returns the maximum key in the tree. + minKey() { + return this.min().key; + } + // Returns the maximum key in the tree. + maxKey() { + if (this.right.isEmpty()) { + return this.key; + } + else { + return this.right.maxKey(); + } + } + // Returns new tree, with the key/value added. + insert(key, value, comparator) { + let n = this; + const cmp = comparator(key, n.key); + if (cmp < 0) { + n = n.copy(null, null, null, n.left.insert(key, value, comparator), null); + } + else if (cmp === 0) { + n = n.copy(null, value, null, null, null); + } + else { + n = n.copy(null, null, null, null, n.right.insert(key, value, comparator)); + } + return n.fixUp(); + } + removeMin() { + if (this.left.isEmpty()) { + return LLRBNode.EMPTY; + } + let n = this; + if (!n.left.isRed() && !n.left.left.isRed()) { + n = n.moveRedLeft(); + } + n = n.copy(null, null, null, n.left.removeMin(), null); + return n.fixUp(); + } + // Returns new tree, with the specified item removed. + remove(key, comparator) { + let smallest; + let n = this; + if (comparator(key, n.key) < 0) { + if (!n.left.isEmpty() && !n.left.isRed() && !n.left.left.isRed()) { + n = n.moveRedLeft(); + } + n = n.copy(null, null, null, n.left.remove(key, comparator), null); + } + else { + if (n.left.isRed()) { + n = n.rotateRight(); + } + if (!n.right.isEmpty() && !n.right.isRed() && !n.right.left.isRed()) { + n = n.moveRedRight(); + } + if (comparator(key, n.key) === 0) { + if (n.right.isEmpty()) { + return LLRBNode.EMPTY; + } + else { + smallest = n.right.min(); + n = n.copy(smallest.key, smallest.value, null, null, n.right.removeMin()); + } + } + n = n.copy(null, null, null, null, n.right.remove(key, comparator)); + } + return n.fixUp(); + } + isRed() { + return this.color; + } + // Returns new tree after performing any needed rotations. + fixUp() { + let n = this; + if (n.right.isRed() && !n.left.isRed()) { + n = n.rotateLeft(); + } + if (n.left.isRed() && n.left.left.isRed()) { + n = n.rotateRight(); + } + if (n.left.isRed() && n.right.isRed()) { + n = n.colorFlip(); + } + return n; + } + moveRedLeft() { + let n = this.colorFlip(); + if (n.right.left.isRed()) { + n = n.copy(null, null, null, null, n.right.rotateRight()); + n = n.rotateLeft(); + n = n.colorFlip(); + } + return n; + } + moveRedRight() { + let n = this.colorFlip(); + if (n.left.left.isRed()) { + n = n.rotateRight(); + n = n.colorFlip(); + } + return n; + } + rotateLeft() { + const nl = this.copy(null, null, LLRBNode.RED, null, this.right.left); + return this.right.copy(null, null, this.color, nl, null); + } + rotateRight() { + const nr = this.copy(null, null, LLRBNode.RED, this.left.right, null); + return this.left.copy(null, null, this.color, null, nr); + } + colorFlip() { + const left = this.left.copy(null, null, !this.left.color, null, null); + const right = this.right.copy(null, null, !this.right.color, null, null); + return this.copy(null, null, !this.color, left, right); + } + // For testing. + checkMaxDepth() { + const blackDepth = this.check(); + if (Math.pow(2.0, blackDepth) <= this.size + 1) { + return true; + } + else { + return false; + } + } + // In a balanced RB tree, the black-depth (number of black nodes) from root to + // leaves is equal on both sides. This function verifies that or asserts. + check() { + if (this.isRed() && this.left.isRed()) { + throw fail(0xaad2, { + key: this.key, + value: this.value + }); + } + if (this.right.isRed()) { + throw fail(0x3721, { + key: this.key, + value: this.value + }); + } + const blackDepth = this.left.check(); + if (blackDepth !== this.right.check()) { + throw fail(0x6d2d); + } + else { + return blackDepth + (this.isRed() ? 0 : 1); + } + } +} // end LLRBNode +// Empty node is shared between all LLRB trees. +// eslint-disable-next-line @typescript-eslint/no-explicit-any +LLRBNode.EMPTY = null; +LLRBNode.RED = true; +LLRBNode.BLACK = false; +// Represents an empty node (a leaf node in the Red-Black Tree). +class LLRBEmptyNode { + constructor() { + this.size = 0; + } + get key() { + throw fail(0xe1a6); + } + get value() { + throw fail(0x3f0d); + } + get color() { + throw fail(0x4157); + } + get left() { + throw fail(0x741e); + } + get right() { + throw fail(0x901e); + } + // Returns a copy of the current node. + copy(key, value, color, left, right) { + return this; + } + // Returns a copy of the tree, with the specified key/value added. + insert(key, value, comparator) { + return new LLRBNode(key, value); + } + // Returns a copy of the tree, with the specified key removed. + remove(key, comparator) { + return this; + } + isEmpty() { + return true; + } + inorderTraversal(action) { + return false; + } + reverseTraversal(action) { + return false; + } + minKey() { + return null; + } + maxKey() { + return null; + } + isRed() { + return false; + } + // For testing. + checkMaxDepth() { + return true; + } + check() { + return 0; + } +} // end LLRBEmptyNode +LLRBNode.EMPTY = new LLRBEmptyNode(); + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * SortedSet is an immutable (copy-on-write) collection that holds elements + * in order specified by the provided comparator. + * + * NOTE: if provided comparator returns 0 for two elements, we consider them to + * be equal! + */ +class SortedSet { + constructor(comparator) { + this.comparator = comparator; + this.data = new SortedMap(this.comparator); + } + has(elem) { + return this.data.get(elem) !== null; + } + first() { + return this.data.minKey(); + } + last() { + return this.data.maxKey(); + } + get size() { + return this.data.size; + } + indexOf(elem) { + return this.data.indexOf(elem); + } + /** Iterates elements in order defined by "comparator" */ + forEach(cb) { + this.data.inorderTraversal((k, v) => { + cb(k); + return false; + }); + } + /** Iterates over `elem`s such that: range[0] <= elem < range[1]. */ + forEachInRange(range, cb) { + const iter = this.data.getIteratorFrom(range[0]); + while (iter.hasNext()) { + const elem = iter.getNext(); + if (this.comparator(elem.key, range[1]) >= 0) { + return; + } + cb(elem.key); + } + } + /** + * Iterates over `elem`s such that: start <= elem until false is returned. + */ + forEachWhile(cb, start) { + let iter; + if (start !== undefined) { + iter = this.data.getIteratorFrom(start); + } + else { + iter = this.data.getIterator(); + } + while (iter.hasNext()) { + const elem = iter.getNext(); + const result = cb(elem.key); + if (!result) { + return; + } + } + } + /** Finds the least element greater than or equal to `elem`. */ + firstAfterOrEqual(elem) { + const iter = this.data.getIteratorFrom(elem); + return iter.hasNext() ? iter.getNext().key : null; + } + getIterator() { + return new SortedSetIterator(this.data.getIterator()); + } + getIteratorFrom(key) { + return new SortedSetIterator(this.data.getIteratorFrom(key)); + } + /** Inserts or updates an element */ + add(elem) { + return this.copy(this.data.remove(elem).insert(elem, true)); + } + /** Deletes an element */ + delete(elem) { + if (!this.has(elem)) { + return this; + } + return this.copy(this.data.remove(elem)); + } + isEmpty() { + return this.data.isEmpty(); + } + unionWith(other) { + let result = this; + // Make sure `result` always refers to the larger one of the two sets. + if (result.size < other.size) { + result = other; + other = this; + } + other.forEach(elem => { + result = result.add(elem); + }); + return result; + } + isEqual(other) { + if (!(other instanceof SortedSet)) { + return false; + } + if (this.size !== other.size) { + return false; + } + const thisIt = this.data.getIterator(); + const otherIt = other.data.getIterator(); + while (thisIt.hasNext()) { + const thisElem = thisIt.getNext().key; + const otherElem = otherIt.getNext().key; + if (this.comparator(thisElem, otherElem) !== 0) { + return false; + } + } + return true; + } + toArray() { + const res = []; + this.forEach(targetId => { + res.push(targetId); + }); + return res; + } + toString() { + const result = []; + this.forEach(elem => result.push(elem)); + return 'SortedSet(' + result.toString() + ')'; + } + copy(data) { + const result = new SortedSet(this.comparator); + result.data = data; + return result; + } +} +class SortedSetIterator { + constructor(iter) { + this.iter = iter; + } + getNext() { + return this.iter.getNext().key; + } + hasNext() { + return this.iter.hasNext(); + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Provides a set of fields that can be used to partially patch a document. + * FieldMask is used in conjunction with ObjectValue. + * Examples: + * foo - Overwrites foo entirely with the provided value. If foo is not + * present in the companion ObjectValue, the field is deleted. + * foo.bar - Overwrites only the field bar of the object foo. + * If foo is not an object, foo is replaced with an object + * containing foo + */ +class FieldMask { + constructor(fields) { + this.fields = fields; + // TODO(dimond): validation of FieldMask + // Sort the field mask to support `FieldMask.isEqual()` and assert below. + fields.sort(FieldPath$1.comparator); + } + static empty() { + return new FieldMask([]); + } + /** + * Returns a new FieldMask object that is the result of adding all the given + * fields paths to this field mask. + */ + unionWith(extraFields) { + let mergedMaskSet = new SortedSet(FieldPath$1.comparator); + for (const fieldPath of this.fields) { + mergedMaskSet = mergedMaskSet.add(fieldPath); + } + for (const fieldPath of extraFields) { + mergedMaskSet = mergedMaskSet.add(fieldPath); + } + return new FieldMask(mergedMaskSet.toArray()); + } + /** + * Verifies that `fieldPath` is included by at least one field in this field + * mask. + * + * This is an O(n) operation, where `n` is the size of the field mask. + */ + covers(fieldPath) { + for (const fieldMaskPath of this.fields) { + if (fieldMaskPath.isPrefixOf(fieldPath)) { + return true; + } + } + return false; + } + isEqual(other) { + return arrayEquals(this.fields, other.fields, (l, r) => l.isEqual(r)); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An ObjectValue represents a MapValue in the Firestore Proto and offers the + * ability to add and remove fields (via the ObjectValueBuilder). + */ +class ObjectValue { + constructor(value) { + this.value = value; + } + static empty() { + return new ObjectValue({ mapValue: {} }); + } + /** + * Returns the value at the given path or null. + * + * @param path - the path to search + * @returns The value at the path or null if the path is not set. + */ + field(path) { + if (path.isEmpty()) { + return this.value; + } + else { + let currentLevel = this.value; + for (let i = 0; i < path.length - 1; ++i) { + currentLevel = (currentLevel.mapValue.fields || {})[path.get(i)]; + if (!isMapValue(currentLevel)) { + return null; + } + } + currentLevel = (currentLevel.mapValue.fields || {})[path.lastSegment()]; + return currentLevel || null; + } + } + /** + * Sets the field to the provided value. + * + * @param path - The field path to set. + * @param value - The value to set. + */ + set(path, value) { + const fieldsMap = this.getFieldsMap(path.popLast()); + fieldsMap[path.lastSegment()] = deepClone(value); + } + /** + * Sets the provided fields to the provided values. + * + * @param data - A map of fields to values (or null for deletes). + */ + setAll(data) { + let parent = FieldPath$1.emptyPath(); + let upserts = {}; + let deletes = []; + data.forEach((value, path) => { + if (!parent.isImmediateParentOf(path)) { + // Insert the accumulated changes at this parent location + const fieldsMap = this.getFieldsMap(parent); + this.applyChanges(fieldsMap, upserts, deletes); + upserts = {}; + deletes = []; + parent = path.popLast(); + } + if (value) { + upserts[path.lastSegment()] = deepClone(value); + } + else { + deletes.push(path.lastSegment()); + } + }); + const fieldsMap = this.getFieldsMap(parent); + this.applyChanges(fieldsMap, upserts, deletes); + } + /** + * Removes the field at the specified path. If there is no field at the + * specified path, nothing is changed. + * + * @param path - The field path to remove. + */ + delete(path) { + const nestedValue = this.field(path.popLast()); + if (isMapValue(nestedValue) && nestedValue.mapValue.fields) { + delete nestedValue.mapValue.fields[path.lastSegment()]; + } + } + isEqual(other) { + return valueEquals(this.value, other.value); + } + /** + * Returns the map that contains the leaf element of `path`. If the parent + * entry does not yet exist, or if it is not a map, a new map will be created. + */ + getFieldsMap(path) { + let current = this.value; + if (!current.mapValue.fields) { + current.mapValue = { fields: {} }; + } + for (let i = 0; i < path.length; ++i) { + let next = current.mapValue.fields[path.get(i)]; + if (!isMapValue(next) || !next.mapValue.fields) { + next = { mapValue: { fields: {} } }; + current.mapValue.fields[path.get(i)] = next; + } + current = next; + } + return current.mapValue.fields; + } + /** + * Modifies `fieldsMap` by adding, replacing or deleting the specified + * entries. + */ + applyChanges(fieldsMap, inserts, deletes) { + forEach(inserts, (key, val) => (fieldsMap[key] = val)); + for (const field of deletes) { + delete fieldsMap[field]; + } + } + clone() { + return new ObjectValue(deepClone(this.value)); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Represents a document in Firestore with a key, version, data and whether it + * has local mutations applied to it. + * + * Documents can transition between states via `convertToFoundDocument()`, + * `convertToNoDocument()` and `convertToUnknownDocument()`. If a document does + * not transition to one of these states even after all mutations have been + * applied, `isValidDocument()` returns false and the document should be removed + * from all views. + */ +class MutableDocument { + constructor(key, documentType, version, readTime, createTime, data, documentState) { + this.key = key; + this.documentType = documentType; + this.version = version; + this.readTime = readTime; + this.createTime = createTime; + this.data = data; + this.documentState = documentState; + } + /** + * Creates a document with no known version or data, but which can serve as + * base document for mutations. + */ + static newInvalidDocument(documentKey) { + return new MutableDocument(documentKey, 0 /* DocumentType.INVALID */, + /* version */ SnapshotVersion.min(), + /* readTime */ SnapshotVersion.min(), + /* createTime */ SnapshotVersion.min(), ObjectValue.empty(), 0 /* DocumentState.SYNCED */); + } + /** + * Creates a new document that is known to exist with the given data at the + * given version. + */ + static newFoundDocument(documentKey, version, createTime, value) { + return new MutableDocument(documentKey, 1 /* DocumentType.FOUND_DOCUMENT */, + /* version */ version, + /* readTime */ SnapshotVersion.min(), + /* createTime */ createTime, value, 0 /* DocumentState.SYNCED */); + } + /** Creates a new document that is known to not exist at the given version. */ + static newNoDocument(documentKey, version) { + return new MutableDocument(documentKey, 2 /* DocumentType.NO_DOCUMENT */, + /* version */ version, + /* readTime */ SnapshotVersion.min(), + /* createTime */ SnapshotVersion.min(), ObjectValue.empty(), 0 /* DocumentState.SYNCED */); + } + /** + * Creates a new document that is known to exist at the given version but + * whose data is not known (e.g. a document that was updated without a known + * base document). + */ + static newUnknownDocument(documentKey, version) { + return new MutableDocument(documentKey, 3 /* DocumentType.UNKNOWN_DOCUMENT */, + /* version */ version, + /* readTime */ SnapshotVersion.min(), + /* createTime */ SnapshotVersion.min(), ObjectValue.empty(), 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */); + } + /** + * Changes the document type to indicate that it exists and that its version + * and data are known. + */ + convertToFoundDocument(version, value) { + // If a document is switching state from being an invalid or deleted + // document to a valid (FOUND_DOCUMENT) document, either due to receiving an + // update from Watch or due to applying a local set mutation on top + // of a deleted document, our best guess about its createTime would be the + // version at which the document transitioned to a FOUND_DOCUMENT. + if (this.createTime.isEqual(SnapshotVersion.min()) && + (this.documentType === 2 /* DocumentType.NO_DOCUMENT */ || + this.documentType === 0 /* DocumentType.INVALID */)) { + this.createTime = version; + } + this.version = version; + this.documentType = 1 /* DocumentType.FOUND_DOCUMENT */; + this.data = value; + this.documentState = 0 /* DocumentState.SYNCED */; + return this; + } + /** + * Changes the document type to indicate that it doesn't exist at the given + * version. + */ + convertToNoDocument(version) { + this.version = version; + this.documentType = 2 /* DocumentType.NO_DOCUMENT */; + this.data = ObjectValue.empty(); + this.documentState = 0 /* DocumentState.SYNCED */; + return this; + } + /** + * Changes the document type to indicate that it exists at a given version but + * that its data is not known (e.g. a document that was updated without a known + * base document). + */ + convertToUnknownDocument(version) { + this.version = version; + this.documentType = 3 /* DocumentType.UNKNOWN_DOCUMENT */; + this.data = ObjectValue.empty(); + this.documentState = 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */; + return this; + } + setHasCommittedMutations() { + this.documentState = 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */; + return this; + } + setHasLocalMutations() { + this.documentState = 1 /* DocumentState.HAS_LOCAL_MUTATIONS */; + this.version = SnapshotVersion.min(); + return this; + } + setReadTime(readTime) { + this.readTime = readTime; + return this; + } + get hasLocalMutations() { + return this.documentState === 1 /* DocumentState.HAS_LOCAL_MUTATIONS */; + } + get hasCommittedMutations() { + return this.documentState === 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */; + } + get hasPendingWrites() { + return this.hasLocalMutations || this.hasCommittedMutations; + } + isValidDocument() { + return this.documentType !== 0 /* DocumentType.INVALID */; + } + isFoundDocument() { + return this.documentType === 1 /* DocumentType.FOUND_DOCUMENT */; + } + isNoDocument() { + return this.documentType === 2 /* DocumentType.NO_DOCUMENT */; + } + isUnknownDocument() { + return this.documentType === 3 /* DocumentType.UNKNOWN_DOCUMENT */; + } + isEqual(other) { + return (other instanceof MutableDocument && + this.key.isEqual(other.key) && + this.version.isEqual(other.version) && + this.documentType === other.documentType && + this.documentState === other.documentState && + this.data.isEqual(other.data)); + } + mutableCopy() { + return new MutableDocument(this.key, this.documentType, this.version, this.readTime, this.createTime, this.data.clone(), this.documentState); + } + toString() { + return (`Document(${this.key}, ${this.version}, ${JSON.stringify(this.data.value)}, ` + + `{createTime: ${this.createTime}}), ` + + `{documentType: ${this.documentType}}), ` + + `{documentState: ${this.documentState}})`); + } +} + +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// Visible for testing +class TargetImpl { + constructor(path, collectionGroup = null, orderBy = [], filters = [], limit = null, startAt = null, endAt = null) { + this.path = path; + this.collectionGroup = collectionGroup; + this.orderBy = orderBy; + this.filters = filters; + this.limit = limit; + this.startAt = startAt; + this.endAt = endAt; + this.memoizedCanonicalId = null; + } +} +/** + * Initializes a Target with a path and optional additional query constraints. + * Path must currently be empty if this is a collection group query. + * + * NOTE: you should always construct `Target` from `Query.toTarget` instead of + * using this factory method, because `Query` provides an implicit `orderBy` + * property. + */ +function newTarget(path, collectionGroup = null, orderBy = [], filters = [], limit = null, startAt = null, endAt = null) { + return new TargetImpl(path, collectionGroup, orderBy, filters, limit, startAt, endAt); +} +function targetEquals(left, right) { + if (left.limit !== right.limit) { + return false; + } + if (left.orderBy.length !== right.orderBy.length) { + return false; + } + for (let i = 0; i < left.orderBy.length; i++) { + if (!orderByEquals(left.orderBy[i], right.orderBy[i])) { + return false; + } + } + if (left.filters.length !== right.filters.length) { + return false; + } + for (let i = 0; i < left.filters.length; i++) { + if (!filterEquals(left.filters[i], right.filters[i])) { + return false; + } + } + if (left.collectionGroup !== right.collectionGroup) { + return false; + } + if (!left.path.isEqual(right.path)) { + return false; + } + if (!boundEquals(left.startAt, right.startAt)) { + return false; + } + return boundEquals(left.endAt, right.endAt); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Query encapsulates all the query attributes we support in the SDK. It can + * be run against the LocalStore, as well as be converted to a `Target` to + * query the RemoteStore results. + * + * Visible for testing. + */ +class QueryImpl { + /** + * Initializes a Query with a path and optional additional query constraints. + * Path must currently be empty if this is a collection group query. + */ + constructor(path, collectionGroup = null, explicitOrderBy = [], filters = [], limit = null, limitType = "F" /* LimitType.First */, startAt = null, endAt = null) { + this.path = path; + this.collectionGroup = collectionGroup; + this.explicitOrderBy = explicitOrderBy; + this.filters = filters; + this.limit = limit; + this.limitType = limitType; + this.startAt = startAt; + this.endAt = endAt; + this.memoizedNormalizedOrderBy = null; + // The corresponding `Target` of this `Query` instance, for use with + // non-aggregate queries. + this.memoizedTarget = null; + // The corresponding `Target` of this `Query` instance, for use with + // aggregate queries. Unlike targets for non-aggregate queries, + // aggregate query targets do not contain normalized order-bys, they only + // contain explicit order-bys. + this.memoizedAggregateTarget = null; + if (this.startAt) ; + if (this.endAt) ; + } +} +/** Creates a new Query for a query that matches all documents at `path` */ +function newQueryForPath(path) { + return new QueryImpl(path); +} +// Returns the sorted set of inequality filter fields used in this query. +function getInequalityFilterFields(query) { + let result = new SortedSet(FieldPath$1.comparator); + query.filters.forEach((filter) => { + const subFilters = filter.getFlattenedFilters(); + subFilters.forEach((filter) => { + if (filter.isInequality()) { + result = result.add(filter.field); + } + }); + }); + return result; +} +/** + * Creates a new Query for a collection group query that matches all documents + * within the provided collection group. + */ +function newQueryForCollectionGroup(collectionId) { + return new QueryImpl(ResourcePath.emptyPath(), collectionId); +} +/** + * Returns whether the query matches a collection group rather than a specific + * collection. + */ +function isCollectionGroupQuery(query) { + return query.collectionGroup !== null; +} +/** + * Returns the normalized order-by constraint that is used to execute the Query, + * which can be different from the order-by constraints the user provided (e.g. + * the SDK and backend always orders by `__name__`). The normalized order-by + * includes implicit order-bys in addition to the explicit user provided + * order-bys. + */ +function queryNormalizedOrderBy(query) { + const queryImpl = debugCast(query); + if (queryImpl.memoizedNormalizedOrderBy === null) { + queryImpl.memoizedNormalizedOrderBy = []; + const fieldsNormalized = new Set(); + // Any explicit order by fields should be added as is. + for (const orderBy of queryImpl.explicitOrderBy) { + queryImpl.memoizedNormalizedOrderBy.push(orderBy); + fieldsNormalized.add(orderBy.field.canonicalString()); + } + // The order of the implicit ordering always matches the last explicit order by. + const lastDirection = queryImpl.explicitOrderBy.length > 0 + ? queryImpl.explicitOrderBy[queryImpl.explicitOrderBy.length - 1].dir + : "asc" /* Direction.ASCENDING */; + // Any inequality fields not explicitly ordered should be implicitly ordered in a lexicographical + // order. When there are multiple inequality filters on the same field, the field should be added + // only once. + // Note: `SortedSet` sorts the key field before other fields. However, we want the key + // field to be sorted last. + const inequalityFields = getInequalityFilterFields(queryImpl); + inequalityFields.forEach(field => { + if (!fieldsNormalized.has(field.canonicalString()) && + !field.isKeyField()) { + queryImpl.memoizedNormalizedOrderBy.push(new OrderBy(field, lastDirection)); + } + }); + // Add the document key field to the last if it is not explicitly ordered. + if (!fieldsNormalized.has(FieldPath$1.keyField().canonicalString())) { + queryImpl.memoizedNormalizedOrderBy.push(new OrderBy(FieldPath$1.keyField(), lastDirection)); + } + } + return queryImpl.memoizedNormalizedOrderBy; +} +/** + * Converts this `Query` instance to its corresponding `Target` representation. + */ +function queryToTarget(query) { + const queryImpl = debugCast(query); + if (!queryImpl.memoizedTarget) { + queryImpl.memoizedTarget = _queryToTarget(queryImpl, queryNormalizedOrderBy(query)); + } + return queryImpl.memoizedTarget; +} +/** + * Converts this `Query` instance to its corresponding `Target` representation, + * for use within an aggregate query. Unlike targets for non-aggregate queries, + * aggregate query targets do not contain normalized order-bys, they only + * contain explicit order-bys. + */ +function queryToAggregateTarget(query) { + const queryImpl = debugCast(query); + if (!queryImpl.memoizedAggregateTarget) { + // Do not include implicit order-bys for aggregate queries. + queryImpl.memoizedAggregateTarget = _queryToTarget(queryImpl, query.explicitOrderBy); + } + return queryImpl.memoizedAggregateTarget; +} +function _queryToTarget(queryImpl, orderBys) { + if (queryImpl.limitType === "F" /* LimitType.First */) { + return newTarget(queryImpl.path, queryImpl.collectionGroup, orderBys, queryImpl.filters, queryImpl.limit, queryImpl.startAt, queryImpl.endAt); + } + else { + // Flip the orderBy directions since we want the last results + orderBys = orderBys.map(orderBy => { + const dir = orderBy.dir === "desc" /* Direction.DESCENDING */ + ? "asc" /* Direction.ASCENDING */ + : "desc" /* Direction.DESCENDING */; + return new OrderBy(orderBy.field, dir); + }); + // We need to swap the cursors to match the now-flipped query ordering. + const startAt = queryImpl.endAt + ? new Bound(queryImpl.endAt.position, queryImpl.endAt.inclusive) + : null; + const endAt = queryImpl.startAt + ? new Bound(queryImpl.startAt.position, queryImpl.startAt.inclusive) + : null; + // Now return as a LimitType.First query. + return newTarget(queryImpl.path, queryImpl.collectionGroup, orderBys, queryImpl.filters, queryImpl.limit, startAt, endAt); + } +} +function queryWithAddedFilter(query, filter) { + const newFilters = query.filters.concat([filter]); + return new QueryImpl(query.path, query.collectionGroup, query.explicitOrderBy.slice(), newFilters, query.limit, query.limitType, query.startAt, query.endAt); +} +function queryWithAddedOrderBy(query, orderBy) { + // TODO(dimond): validate that orderBy does not list the same key twice. + const newOrderBy = query.explicitOrderBy.concat([orderBy]); + return new QueryImpl(query.path, query.collectionGroup, newOrderBy, query.filters.slice(), query.limit, query.limitType, query.startAt, query.endAt); +} +function queryWithLimit(query, limit, limitType) { + return new QueryImpl(query.path, query.collectionGroup, query.explicitOrderBy.slice(), query.filters.slice(), limit, limitType, query.startAt, query.endAt); +} +function queryWithStartAt(query, bound) { + return new QueryImpl(query.path, query.collectionGroup, query.explicitOrderBy.slice(), query.filters.slice(), query.limit, query.limitType, bound, query.endAt); +} +function queryWithEndAt(query, bound) { + return new QueryImpl(query.path, query.collectionGroup, query.explicitOrderBy.slice(), query.filters.slice(), query.limit, query.limitType, query.startAt, bound); +} +function queryEquals(left, right) { + return (targetEquals(queryToTarget(left), queryToTarget(right)) && + left.limitType === right.limitType); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Returns an DoubleValue for `value` that is encoded based the serializer's + * `useProto3Json` setting. + */ +function toDouble(serializer, value) { + if (serializer.useProto3Json) { + if (isNaN(value)) { + return { doubleValue: 'NaN' }; + } + else if (value === Infinity) { + return { doubleValue: 'Infinity' }; + } + else if (value === -Infinity) { + return { doubleValue: '-Infinity' }; + } + } + return { doubleValue: isNegativeZero(value) ? '-0' : value }; +} +/** + * Returns an IntegerValue for `value`. + */ +function toInteger(value) { + return { integerValue: '' + value }; +} +/** + * Returns a value for a number that's appropriate to put into a proto. + * The return value is an IntegerValue if it can safely represent the value, + * otherwise a DoubleValue is returned. + */ +function toNumber(serializer, value) { + return isSafeInteger(value) ? toInteger(value) : toDouble(serializer, value); +} + +/** + * @license + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Used to represent a field transform on a mutation. */ +class TransformOperation { + constructor() { + // Make sure that the structural type of `TransformOperation` is unique. + // See https://github.com/microsoft/TypeScript/issues/5451 + this._ = undefined; + } +} +/** Transforms a value into a server-generated timestamp. */ +class ServerTimestampTransform extends TransformOperation { +} +/** Transforms an array value via a union operation. */ +class ArrayUnionTransformOperation extends TransformOperation { + constructor(elements) { + super(); + this.elements = elements; + } +} +/** Transforms an array value via a remove operation. */ +class ArrayRemoveTransformOperation extends TransformOperation { + constructor(elements) { + super(); + this.elements = elements; + } +} +/** + * Implements the backend semantics for locally computed NUMERIC_ADD (increment) + * transforms. Converts all field values to integers or doubles, but unlike the + * backend does not cap integer values at 2^63. Instead, JavaScript number + * arithmetic is used and precision loss can occur for values greater than 2^53. + */ +class NumericIncrementTransformOperation extends TransformOperation { + constructor(serializer, operand) { + super(); + this.serializer = serializer; + this.operand = operand; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** A field path and the TransformOperation to perform upon it. */ +class FieldTransform { + constructor(field, transform) { + this.field = field; + this.transform = transform; + } +} +/** + * Encodes a precondition for a mutation. This follows the model that the + * backend accepts with the special case of an explicit "empty" precondition + * (meaning no precondition). + */ +class Precondition { + constructor(updateTime, exists) { + this.updateTime = updateTime; + this.exists = exists; + } + /** Creates a new empty Precondition. */ + static none() { + return new Precondition(); + } + /** Creates a new Precondition with an exists flag. */ + static exists(exists) { + return new Precondition(undefined, exists); + } + /** Creates a new Precondition based on a version a document exists at. */ + static updateTime(version) { + return new Precondition(version); + } + /** Returns whether this Precondition is empty. */ + get isNone() { + return this.updateTime === undefined && this.exists === undefined; + } + isEqual(other) { + return (this.exists === other.exists && + (this.updateTime + ? !!other.updateTime && this.updateTime.isEqual(other.updateTime) + : !other.updateTime)); + } +} +/** + * A mutation describes a self-contained change to a document. Mutations can + * create, replace, delete, and update subsets of documents. + * + * Mutations not only act on the value of the document but also its version. + * + * For local mutations (mutations that haven't been committed yet), we preserve + * the existing version for Set and Patch mutations. For Delete mutations, we + * reset the version to 0. + * + * Here's the expected transition table. + * + * MUTATION APPLIED TO RESULTS IN + * + * SetMutation Document(v3) Document(v3) + * SetMutation NoDocument(v3) Document(v0) + * SetMutation InvalidDocument(v0) Document(v0) + * PatchMutation Document(v3) Document(v3) + * PatchMutation NoDocument(v3) NoDocument(v3) + * PatchMutation InvalidDocument(v0) UnknownDocument(v3) + * DeleteMutation Document(v3) NoDocument(v0) + * DeleteMutation NoDocument(v3) NoDocument(v0) + * DeleteMutation InvalidDocument(v0) NoDocument(v0) + * + * For acknowledged mutations, we use the updateTime of the WriteResponse as + * the resulting version for Set and Patch mutations. As deletes have no + * explicit update time, we use the commitTime of the WriteResponse for + * Delete mutations. + * + * If a mutation is acknowledged by the backend but fails the precondition check + * locally, we transition to an `UnknownDocument` and rely on Watch to send us + * the updated version. + * + * Field transforms are used only with Patch and Set Mutations. We use the + * `updateTransforms` message to store transforms, rather than the `transforms`s + * messages. + * + * ## Subclassing Notes + * + * Every type of mutation needs to implement its own applyToRemoteDocument() and + * applyToLocalView() to implement the actual behavior of applying the mutation + * to some source document (see `setMutationApplyToRemoteDocument()` for an + * example). + */ +class Mutation { +} +/** + * A mutation that creates or replaces the document at the given key with the + * object value contents. + */ +class SetMutation extends Mutation { + constructor(key, value, precondition, fieldTransforms = []) { + super(); + this.key = key; + this.value = value; + this.precondition = precondition; + this.fieldTransforms = fieldTransforms; + this.type = 0 /* MutationType.Set */; + } + getFieldMask() { + return null; + } +} +/** + * A mutation that modifies fields of the document at the given key with the + * given values. The values are applied through a field mask: + * + * * When a field is in both the mask and the values, the corresponding field + * is updated. + * * When a field is in neither the mask nor the values, the corresponding + * field is unmodified. + * * When a field is in the mask but not in the values, the corresponding field + * is deleted. + * * When a field is not in the mask but is in the values, the values map is + * ignored. + */ +class PatchMutation extends Mutation { + constructor(key, data, fieldMask, precondition, fieldTransforms = []) { + super(); + this.key = key; + this.data = data; + this.fieldMask = fieldMask; + this.precondition = precondition; + this.fieldTransforms = fieldTransforms; + this.type = 1 /* MutationType.Patch */; + } + getFieldMask() { + return this.fieldMask; + } +} +/** A mutation that deletes the document at the given key. */ +class DeleteMutation extends Mutation { + constructor(key, precondition) { + super(); + this.key = key; + this.precondition = precondition; + this.type = 2 /* MutationType.Delete */; + this.fieldTransforms = []; + } + getFieldMask() { + return null; + } +} +/** + * A mutation that verifies the existence of the document at the given key with + * the provided precondition. + * + * The `verify` operation is only used in Transactions, and this class serves + * primarily to facilitate serialization into protos. + */ +class VerifyMutation extends Mutation { + constructor(key, precondition) { + super(); + this.key = key; + this.precondition = precondition; + this.type = 3 /* MutationType.Verify */; + this.fieldTransforms = []; + } + getFieldMask() { + return null; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const DIRECTIONS = (() => { + const dirs = {}; + dirs["asc" /* Direction.ASCENDING */] = 'ASCENDING'; + dirs["desc" /* Direction.DESCENDING */] = 'DESCENDING'; + return dirs; +})(); +const OPERATORS = (() => { + const ops = {}; + ops["<" /* Operator.LESS_THAN */] = 'LESS_THAN'; + ops["<=" /* Operator.LESS_THAN_OR_EQUAL */] = 'LESS_THAN_OR_EQUAL'; + ops[">" /* Operator.GREATER_THAN */] = 'GREATER_THAN'; + ops[">=" /* Operator.GREATER_THAN_OR_EQUAL */] = 'GREATER_THAN_OR_EQUAL'; + ops["==" /* Operator.EQUAL */] = 'EQUAL'; + ops["!=" /* Operator.NOT_EQUAL */] = 'NOT_EQUAL'; + ops["array-contains" /* Operator.ARRAY_CONTAINS */] = 'ARRAY_CONTAINS'; + ops["in" /* Operator.IN */] = 'IN'; + ops["not-in" /* Operator.NOT_IN */] = 'NOT_IN'; + ops["array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */] = 'ARRAY_CONTAINS_ANY'; + return ops; +})(); +const COMPOSITE_OPERATORS = (() => { + const ops = {}; + ops["and" /* CompositeOperator.AND */] = 'AND'; + ops["or" /* CompositeOperator.OR */] = 'OR'; + return ops; +})(); +function assertPresent(value, description) { +} +/** + * This class generates JsonObject values for the Datastore API suitable for + * sending to either GRPC stub methods or via the JSON/HTTP REST API. + * + * The serializer supports both Protobuf.js and Proto3 JSON formats. By + * setting `useProto3Json` to true, the serializer will use the Proto3 JSON + * format. + * + * For a description of the Proto3 JSON format check + * https://developers.google.com/protocol-buffers/docs/proto3#json + * + * TODO(klimt): We can remove the databaseId argument if we keep the full + * resource name in documents. + */ +class JsonProtoSerializer { + constructor(databaseId, useProto3Json) { + this.databaseId = databaseId; + this.useProto3Json = useProto3Json; + } +} +/** + * Returns a value for a number (or null) that's appropriate to put into + * a google.protobuf.Int32Value proto. + * DO NOT USE THIS FOR ANYTHING ELSE. + * This method cheats. It's typed as returning "number" because that's what + * our generated proto interfaces say Int32Value must be. But GRPC actually + * expects a { value: } struct. + */ +function toInt32Proto(serializer, val) { + if (serializer.useProto3Json || isNullOrUndefined(val)) { + return val; + } + else { + return { value: val }; + } +} +/** + * Returns a value for a Date that's appropriate to put into a proto. + */ +function toTimestamp(serializer, timestamp) { + if (serializer.useProto3Json) { + // Serialize to ISO-8601 date format, but with full nano resolution. + // Since JS Date has only millis, let's only use it for the seconds and + // then manually add the fractions to the end. + const jsDateStr = new Date(timestamp.seconds * 1000).toISOString(); + // Remove .xxx frac part and Z in the end. + const strUntilSeconds = jsDateStr.replace(/\.\d*/, '').replace('Z', ''); + // Pad the fraction out to 9 digits (nanos). + const nanoStr = ('000000000' + timestamp.nanoseconds).slice(-9); + return `${strUntilSeconds}.${nanoStr}Z`; + } + else { + return { + seconds: '' + timestamp.seconds, + nanos: timestamp.nanoseconds + // eslint-disable-next-line @typescript-eslint/no-explicit-any + }; + } +} +/** + * Returns a Timestamp typed object given protobuf timestamp value. + */ +function fromTimestamp(date) { + const timestamp = normalizeTimestamp(date); + return new Timestamp(timestamp.seconds, timestamp.nanos); +} +/** + * Returns a value for bytes that's appropriate to put in a proto. + * + * Visible for testing. + */ +function toBytes(serializer, bytes) { + if (serializer.useProto3Json) { + return bytes.toBase64(); + } + else { + return bytes.toUint8Array(); + } +} +function toVersion(serializer, version) { + return toTimestamp(serializer, version.toTimestamp()); +} +function fromVersion(version) { + hardAssert(!!version, 0xc050); + return SnapshotVersion.fromTimestamp(fromTimestamp(version)); +} +function toResourceName(databaseId, path) { + return toResourcePath(databaseId, path).canonicalString(); +} +function toResourcePath(databaseId, path) { + const resourcePath = fullyQualifiedPrefixPath(databaseId).child('documents'); + return path === undefined ? resourcePath : resourcePath.child(path); +} +function fromResourceName(name) { + const resource = ResourcePath.fromString(name); + hardAssert(isValidResourceName(resource), 0x27ce, { key: resource.toString() }); + return resource; +} +function toName(serializer, key) { + return toResourceName(serializer.databaseId, key.path); +} +function fromName(serializer, name) { + const resource = fromResourceName(name); + if (resource.get(1) !== serializer.databaseId.projectId) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Tried to deserialize key from different project: ' + + resource.get(1) + + ' vs ' + + serializer.databaseId.projectId); + } + if (resource.get(3) !== serializer.databaseId.database) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Tried to deserialize key from different database: ' + + resource.get(3) + + ' vs ' + + serializer.databaseId.database); + } + return new DocumentKey(extractLocalPathFromResourceName(resource)); +} +function toQueryPath(serializer, path) { + return toResourceName(serializer.databaseId, path); +} +function fullyQualifiedPrefixPath(databaseId) { + return new ResourcePath([ + 'projects', + databaseId.projectId, + 'databases', + databaseId.database + ]); +} +function extractLocalPathFromResourceName(resourceName) { + hardAssert(resourceName.length > 4 && resourceName.get(4) === 'documents', 0x71a3, { key: resourceName.toString() }); + return resourceName.popFirst(5); +} +/** Creates a Document proto from key and fields (but no create/update time) */ +function toMutationDocument(serializer, key, fields) { + return { + name: toName(serializer, key), + fields: fields.value.mapValue.fields + }; +} +function fromDocument(serializer, document, hasCommittedMutations) { + const key = fromName(serializer, document.name); + const version = fromVersion(document.updateTime); + // If we read a document from persistence that is missing createTime, it's due + // to older SDK versions not storing this information. In such cases, we'll + // set the createTime to zero. This can be removed in the long term. + const createTime = document.createTime + ? fromVersion(document.createTime) + : SnapshotVersion.min(); + const data = new ObjectValue({ mapValue: { fields: document.fields } }); + const result = MutableDocument.newFoundDocument(key, version, createTime, data); + if (hasCommittedMutations) { + result.setHasCommittedMutations(); + } + return hasCommittedMutations ? result.setHasCommittedMutations() : result; +} +function fromFound(serializer, doc) { + hardAssert(!!doc.found, 0xaa33); + assertPresent(doc.found.name); + assertPresent(doc.found.updateTime); + const key = fromName(serializer, doc.found.name); + const version = fromVersion(doc.found.updateTime); + const createTime = doc.found.createTime + ? fromVersion(doc.found.createTime) + : SnapshotVersion.min(); + const data = new ObjectValue({ mapValue: { fields: doc.found.fields } }); + return MutableDocument.newFoundDocument(key, version, createTime, data); +} +function fromMissing(serializer, result) { + hardAssert(!!result.missing, 0x0f36); + hardAssert(!!result.readTime, 0x5995); + const key = fromName(serializer, result.missing); + const version = fromVersion(result.readTime); + return MutableDocument.newNoDocument(key, version); +} +function fromBatchGetDocumentsResponse(serializer, result) { + if ('found' in result) { + return fromFound(serializer, result); + } + else if ('missing' in result) { + return fromMissing(serializer, result); + } + return fail(0x1c42, { result }); +} +function toMutation(serializer, mutation) { + let result; + if (mutation instanceof SetMutation) { + result = { + update: toMutationDocument(serializer, mutation.key, mutation.value) + }; + } + else if (mutation instanceof DeleteMutation) { + result = { delete: toName(serializer, mutation.key) }; + } + else if (mutation instanceof PatchMutation) { + result = { + update: toMutationDocument(serializer, mutation.key, mutation.data), + updateMask: toDocumentMask(mutation.fieldMask) + }; + } + else if (mutation instanceof VerifyMutation) { + result = { + verify: toName(serializer, mutation.key) + }; + } + else { + return fail(0x40d7, { + mutationType: mutation.type + }); + } + if (mutation.fieldTransforms.length > 0) { + result.updateTransforms = mutation.fieldTransforms.map(transform => toFieldTransform(serializer, transform)); + } + if (!mutation.precondition.isNone) { + result.currentDocument = toPrecondition(serializer, mutation.precondition); + } + return result; +} +function toPrecondition(serializer, precondition) { + if (precondition.updateTime !== undefined) { + return { + updateTime: toVersion(serializer, precondition.updateTime) + }; + } + else if (precondition.exists !== undefined) { + return { exists: precondition.exists }; + } + else { + return fail(0x6b69); + } +} +function toFieldTransform(serializer, fieldTransform) { + const transform = fieldTransform.transform; + if (transform instanceof ServerTimestampTransform) { + return { + fieldPath: fieldTransform.field.canonicalString(), + setToServerValue: 'REQUEST_TIME' + }; + } + else if (transform instanceof ArrayUnionTransformOperation) { + return { + fieldPath: fieldTransform.field.canonicalString(), + appendMissingElements: { + values: transform.elements + } + }; + } + else if (transform instanceof ArrayRemoveTransformOperation) { + return { + fieldPath: fieldTransform.field.canonicalString(), + removeAllFromArray: { + values: transform.elements + } + }; + } + else if (transform instanceof NumericIncrementTransformOperation) { + return { + fieldPath: fieldTransform.field.canonicalString(), + increment: transform.operand + }; + } + else { + throw fail(0x51c2, { + transform: fieldTransform.transform + }); + } +} +function toQueryTarget(serializer, target) { + // Dissect the path into parent, collectionId, and optional key filter. + const queryTarget = { structuredQuery: {} }; + const path = target.path; + let parent; + if (target.collectionGroup !== null) { + parent = path; + queryTarget.structuredQuery.from = [ + { + collectionId: target.collectionGroup, + allDescendants: true + } + ]; + } + else { + parent = path.popLast(); + queryTarget.structuredQuery.from = [{ collectionId: path.lastSegment() }]; + } + queryTarget.parent = toQueryPath(serializer, parent); + const where = toFilters(target.filters); + if (where) { + queryTarget.structuredQuery.where = where; + } + const orderBy = toOrder(target.orderBy); + if (orderBy) { + queryTarget.structuredQuery.orderBy = orderBy; + } + const limit = toInt32Proto(serializer, target.limit); + if (limit !== null) { + queryTarget.structuredQuery.limit = limit; + } + if (target.startAt) { + queryTarget.structuredQuery.startAt = toStartAtCursor(target.startAt); + } + if (target.endAt) { + queryTarget.structuredQuery.endAt = toEndAtCursor(target.endAt); + } + return { queryTarget, parent }; +} +function toRunAggregationQueryRequest(serializer, target, aggregates, skipAliasing) { + const { queryTarget, parent } = toQueryTarget(serializer, target); + const aliasMap = {}; + const aggregations = []; + let aggregationNum = 0; + aggregates.forEach(aggregate => { + // Map all client-side aliases to a unique short-form + // alias. This avoids issues with client-side aliases that + // exceed the 1500-byte string size limit. + const serverAlias = skipAliasing + ? aggregate.alias + : `aggregate_${aggregationNum++}`; + aliasMap[serverAlias] = aggregate.alias; + if (aggregate.aggregateType === 'count') { + aggregations.push({ + alias: serverAlias, + count: {} + }); + } + else if (aggregate.aggregateType === 'avg') { + aggregations.push({ + alias: serverAlias, + avg: { + field: toFieldPathReference(aggregate.fieldPath) + } + }); + } + else if (aggregate.aggregateType === 'sum') { + aggregations.push({ + alias: serverAlias, + sum: { + field: toFieldPathReference(aggregate.fieldPath) + } + }); + } + }); + return { + request: { + structuredAggregationQuery: { + aggregations, + structuredQuery: queryTarget.structuredQuery + }, + parent: queryTarget.parent + }, + aliasMap, + parent + }; +} +function toFilters(filters) { + if (filters.length === 0) { + return; + } + return toFilter(CompositeFilter.create(filters, "and" /* CompositeOperator.AND */)); +} +function toOrder(orderBys) { + if (orderBys.length === 0) { + return; + } + return orderBys.map(order => toPropertyOrder(order)); +} +function toStartAtCursor(cursor) { + return { + before: cursor.inclusive, + values: cursor.position + }; +} +function toEndAtCursor(cursor) { + return { + before: !cursor.inclusive, + values: cursor.position + }; +} +// visible for testing +function toDirection(dir) { + return DIRECTIONS[dir]; +} +// visible for testing +function toOperatorName(op) { + return OPERATORS[op]; +} +function toCompositeOperatorName(op) { + return COMPOSITE_OPERATORS[op]; +} +function toFieldPathReference(path) { + return { fieldPath: path.canonicalString() }; +} +// visible for testing +function toPropertyOrder(orderBy) { + return { + field: toFieldPathReference(orderBy.field), + direction: toDirection(orderBy.dir) + }; +} +// visible for testing +function toFilter(filter) { + if (filter instanceof FieldFilter) { + return toUnaryOrFieldFilter(filter); + } + else if (filter instanceof CompositeFilter) { + return toCompositeFilter(filter); + } + else { + return fail(0xd65d, { filter }); + } +} +function toCompositeFilter(filter) { + const protos = filter.getFilters().map(filter => toFilter(filter)); + if (protos.length === 1) { + return protos[0]; + } + return { + compositeFilter: { + op: toCompositeOperatorName(filter.op), + filters: protos + } + }; +} +function toUnaryOrFieldFilter(filter) { + if (filter.op === "==" /* Operator.EQUAL */) { + if (isNanValue(filter.value)) { + return { + unaryFilter: { + field: toFieldPathReference(filter.field), + op: 'IS_NAN' + } + }; + } + else if (isNullValue(filter.value)) { + return { + unaryFilter: { + field: toFieldPathReference(filter.field), + op: 'IS_NULL' + } + }; + } + } + else if (filter.op === "!=" /* Operator.NOT_EQUAL */) { + if (isNanValue(filter.value)) { + return { + unaryFilter: { + field: toFieldPathReference(filter.field), + op: 'IS_NOT_NAN' + } + }; + } + else if (isNullValue(filter.value)) { + return { + unaryFilter: { + field: toFieldPathReference(filter.field), + op: 'IS_NOT_NULL' + } + }; + } + } + return { + fieldFilter: { + field: toFieldPathReference(filter.field), + op: toOperatorName(filter.op), + value: filter.value + } + }; +} +function toDocumentMask(fieldMask) { + const canonicalFields = []; + fieldMask.fields.forEach(field => canonicalFields.push(field.canonicalString())); + return { + fieldPaths: canonicalFields + }; +} +function isValidResourceName(path) { + // Resource names have at least 4 components (project ID, database ID) + return (path.length >= 4 && + path.get(0) === 'projects' && + path.get(2) === 'databases'); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +function newSerializer(databaseId) { + return new JsonProtoSerializer(databaseId, /* useProto3Json= */ true); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const LOG_TAG$2 = 'ExponentialBackoff'; +/** + * Initial backoff time in milliseconds after an error. + * Set to 1s according to https://cloud.google.com/apis/design/errors. + */ +const DEFAULT_BACKOFF_INITIAL_DELAY_MS = 1000; +const DEFAULT_BACKOFF_FACTOR = 1.5; +/** Maximum backoff time in milliseconds */ +const DEFAULT_BACKOFF_MAX_DELAY_MS = 60 * 1000; +/** + * A helper for running delayed tasks following an exponential backoff curve + * between attempts. + * + * Each delay is made up of a "base" delay which follows the exponential + * backoff curve, and a +/- 50% "jitter" that is calculated and added to the + * base delay. This prevents clients from accidentally synchronizing their + * delays causing spikes of load to the backend. + */ +class ExponentialBackoff { + constructor( + /** + * The AsyncQueue to run backoff operations on. + */ + queue, + /** + * The ID to use when scheduling backoff operations on the AsyncQueue. + */ + timerId, + /** + * The initial delay (used as the base delay on the first retry attempt). + * Note that jitter will still be applied, so the actual delay could be as + * little as 0.5*initialDelayMs. + */ + initialDelayMs = DEFAULT_BACKOFF_INITIAL_DELAY_MS, + /** + * The multiplier to use to determine the extended base delay after each + * attempt. + */ + backoffFactor = DEFAULT_BACKOFF_FACTOR, + /** + * The maximum base delay after which no further backoff is performed. + * Note that jitter will still be applied, so the actual delay could be as + * much as 1.5*maxDelayMs. + */ + maxDelayMs = DEFAULT_BACKOFF_MAX_DELAY_MS) { + this.queue = queue; + this.timerId = timerId; + this.initialDelayMs = initialDelayMs; + this.backoffFactor = backoffFactor; + this.maxDelayMs = maxDelayMs; + this.currentBaseMs = 0; + this.timerPromise = null; + /** The last backoff attempt, as epoch milliseconds. */ + this.lastAttemptTime = Date.now(); + this.reset(); + } + /** + * Resets the backoff delay. + * + * The very next backoffAndWait() will have no delay. If it is called again + * (i.e. due to an error), initialDelayMs (plus jitter) will be used, and + * subsequent ones will increase according to the backoffFactor. + */ + reset() { + this.currentBaseMs = 0; + } + /** + * Resets the backoff delay to the maximum delay (e.g. for use after a + * RESOURCE_EXHAUSTED error). + */ + resetToMax() { + this.currentBaseMs = this.maxDelayMs; + } + /** + * Returns a promise that resolves after currentDelayMs, and increases the + * delay for any subsequent attempts. If there was a pending backoff operation + * already, it will be canceled. + */ + backoffAndRun(op) { + // Cancel any pending backoff operation. + this.cancel(); + // First schedule using the current base (which may be 0 and should be + // honored as such). + const desiredDelayWithJitterMs = Math.floor(this.currentBaseMs + this.jitterDelayMs()); + // Guard against lastAttemptTime being in the future due to a clock change. + const delaySoFarMs = Math.max(0, Date.now() - this.lastAttemptTime); + // Guard against the backoff delay already being past. + const remainingDelayMs = Math.max(0, desiredDelayWithJitterMs - delaySoFarMs); + if (remainingDelayMs > 0) { + logDebug(LOG_TAG$2, `Backing off for ${remainingDelayMs} ms ` + + `(base delay: ${this.currentBaseMs} ms, ` + + `delay with jitter: ${desiredDelayWithJitterMs} ms, ` + + `last attempt: ${delaySoFarMs} ms ago)`); + } + this.timerPromise = this.queue.enqueueAfterDelay(this.timerId, remainingDelayMs, () => { + this.lastAttemptTime = Date.now(); + return op(); + }); + // Apply backoff factor to determine next delay and ensure it is within + // bounds. + this.currentBaseMs *= this.backoffFactor; + if (this.currentBaseMs < this.initialDelayMs) { + this.currentBaseMs = this.initialDelayMs; + } + if (this.currentBaseMs > this.maxDelayMs) { + this.currentBaseMs = this.maxDelayMs; + } + } + skipBackoff() { + if (this.timerPromise !== null) { + this.timerPromise.skipDelay(); + this.timerPromise = null; + } + } + cancel() { + if (this.timerPromise !== null) { + this.timerPromise.cancel(); + this.timerPromise = null; + } + } + /** Returns a random value in the range [-currentBaseMs/2, currentBaseMs/2] */ + jitterDelayMs() { + return (Math.random() - 0.5) * this.currentBaseMs; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Datastore and its related methods are a wrapper around the external Google + * Cloud Datastore grpc API, which provides an interface that is more convenient + * for the rest of the client SDK architecture to consume. + */ +class Datastore { +} +/** + * An implementation of Datastore that exposes additional state for internal + * consumption. + */ +class DatastoreImpl extends Datastore { + constructor(authCredentials, appCheckCredentials, connection, serializer) { + super(); + this.authCredentials = authCredentials; + this.appCheckCredentials = appCheckCredentials; + this.connection = connection; + this.serializer = serializer; + this.terminated = false; + } + verifyInitialized() { + if (this.terminated) { + throw new FirestoreError(Code.FAILED_PRECONDITION, 'The client has already been terminated.'); + } + } + /** Invokes the provided RPC with auth and AppCheck tokens. */ + invokeRPC(rpcName, databaseId, resourcePath, request) { + this.verifyInitialized(); + return Promise.all([ + this.authCredentials.getToken(), + this.appCheckCredentials.getToken() + ]) + .then(([authToken, appCheckToken]) => { + return this.connection.invokeRPC(rpcName, toResourcePath(databaseId, resourcePath), request, authToken, appCheckToken); + }) + .catch((error) => { + if (error.name === 'FirebaseError') { + if (error.code === Code.UNAUTHENTICATED) { + this.authCredentials.invalidateToken(); + this.appCheckCredentials.invalidateToken(); + } + throw error; + } + else { + throw new FirestoreError(Code.UNKNOWN, error.toString()); + } + }); + } + /** Invokes the provided RPC with streamed results with auth and AppCheck tokens. */ + invokeStreamingRPC(rpcName, databaseId, resourcePath, request, expectedResponseCount) { + this.verifyInitialized(); + return Promise.all([ + this.authCredentials.getToken(), + this.appCheckCredentials.getToken() + ]) + .then(([authToken, appCheckToken]) => { + return this.connection.invokeStreamingRPC(rpcName, toResourcePath(databaseId, resourcePath), request, authToken, appCheckToken, expectedResponseCount); + }) + .catch((error) => { + if (error.name === 'FirebaseError') { + if (error.code === Code.UNAUTHENTICATED) { + this.authCredentials.invalidateToken(); + this.appCheckCredentials.invalidateToken(); + } + throw error; + } + else { + throw new FirestoreError(Code.UNKNOWN, error.toString()); + } + }); + } + terminate() { + this.terminated = true; + this.connection.terminate(); + } +} +// TODO(firestorexp): Make sure there is only one Datastore instance per +// firestore-exp client. +function newDatastore(authCredentials, appCheckCredentials, connection, serializer) { + return new DatastoreImpl(authCredentials, appCheckCredentials, connection, serializer); +} +async function invokeCommitRpc(datastore, mutations) { + const datastoreImpl = debugCast(datastore); + const request = { + writes: mutations.map(m => toMutation(datastoreImpl.serializer, m)) + }; + await datastoreImpl.invokeRPC('Commit', datastoreImpl.serializer.databaseId, ResourcePath.emptyPath(), request); +} +async function invokeBatchGetDocumentsRpc(datastore, keys) { + const datastoreImpl = debugCast(datastore); + const request = { + documents: keys.map(k => toName(datastoreImpl.serializer, k)) + }; + const response = await datastoreImpl.invokeStreamingRPC('BatchGetDocuments', datastoreImpl.serializer.databaseId, ResourcePath.emptyPath(), request, keys.length); + const docs = new Map(); + response.forEach(proto => { + const doc = fromBatchGetDocumentsResponse(datastoreImpl.serializer, proto); + docs.set(doc.key.toString(), doc); + }); + const result = []; + keys.forEach(key => { + const doc = docs.get(key.toString()); + hardAssert(!!doc, 0xd7c2, { + key + }); + result.push(doc); + }); + return result; +} +async function invokeRunQueryRpc(datastore, query) { + const datastoreImpl = debugCast(datastore); + const { queryTarget, parent } = toQueryTarget(datastoreImpl.serializer, queryToTarget(query)); + const response = await datastoreImpl.invokeStreamingRPC('RunQuery', datastoreImpl.serializer.databaseId, parent, { + structuredQuery: queryTarget.structuredQuery + }); + return (response + // Omit RunQueryResponses that only contain readTimes. + .filter(proto => !!proto.document) + .map(proto => fromDocument(datastoreImpl.serializer, proto.document, undefined))); +} +async function invokeRunAggregationQueryRpc(datastore, query, aggregates) { + const datastoreImpl = debugCast(datastore); + const { request, aliasMap, parent } = toRunAggregationQueryRequest(datastoreImpl.serializer, queryToAggregateTarget(query), aggregates); + if (!datastoreImpl.connection.shouldResourcePathBeIncludedInRequest) { + delete request.parent; + } + const response = await datastoreImpl.invokeStreamingRPC('RunAggregationQuery', datastoreImpl.serializer.databaseId, parent, request, + /*expectedResponseCount=*/ 1); + // Omit RunAggregationQueryResponse that only contain readTimes. + const filteredResult = response.filter(proto => !!proto.result); + hardAssert(filteredResult.length === 1, 0xfcd7); + // Remap the short-form aliases that were sent to the server + // to the client-side aliases. Users will access the results + // using the client-side alias. + const unmappedAggregateFields = filteredResult[0].result?.aggregateFields; + const remappedFields = Object.keys(unmappedAggregateFields).reduce((accumulator, key) => { + accumulator[aliasMap[key]] = unmappedAggregateFields[key]; + return accumulator; + }, {}); + return remappedFields; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const LOG_TAG$1 = 'ComponentProvider'; +/** + * An instance map that ensures only one Datastore exists per Firestore + * instance. + */ +const datastoreInstances = new Map(); +/** + * Returns an initialized and started Datastore for the given Firestore + * instance. Callers must invoke removeComponents() when the Firestore + * instance is terminated. + */ +function getDatastore(firestore) { + if (firestore._terminated) { + throw new FirestoreError(Code.FAILED_PRECONDITION, 'The client has already been terminated.'); + } + if (!datastoreInstances.has(firestore)) { + logDebug(LOG_TAG$1, 'Initializing Datastore'); + const databaseInfo = makeDatabaseInfo(firestore._databaseId, firestore.app.options.appId || '', firestore._persistenceKey, firestore._freezeSettings()); + const connection = newConnection(databaseInfo); + const serializer = newSerializer(firestore._databaseId); + const datastore = newDatastore(firestore._authCredentials, firestore._appCheckCredentials, connection, serializer); + datastoreInstances.set(firestore, datastore); + } + return datastoreInstances.get(firestore); +} +/** + * Removes all components associated with the provided instance. Must be called + * when the `Firestore` instance is terminated. + */ +function removeComponents(firestore) { + const datastore = datastoreInstances.get(firestore); + if (datastore) { + logDebug(LOG_TAG$1, 'Removing Datastore'); + datastoreInstances.delete(firestore); + datastore.terminate(); + } +} +function makeDatabaseInfo(databaseId, appId, persistenceKey, settings) { + return new DatabaseInfo(databaseId, appId, persistenceKey, settings.host, settings.ssl, settings.experimentalForceLongPolling, settings.experimentalAutoDetectLongPolling, cloneLongPollingOptions(settings.experimentalLongPollingOptions), settings.useFetchStreams, settings.isUsingEmulator); +} + +/** + * @license + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const LRU_COLLECTION_DISABLED = -1; +const LRU_DEFAULT_CACHE_SIZE_BYTES = 40 * 1024 * 1024; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Verifies whether `e` is an IndexedDbTransactionError. */ +function isIndexedDbTransactionError(e) { + // Use name equality, as instanceof checks on errors don't work with errors + // that wrap other errors. + return e.name === 'IndexedDbTransactionError'; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const LRU_MINIMUM_CACHE_SIZE_BYTES = 1 * 1024 * 1024; + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// settings() defaults: +const DEFAULT_HOST = 'firestore.googleapis.com'; +const DEFAULT_SSL = true; +// The minimum long-polling timeout is hardcoded on the server. The value here +// should be kept in sync with the value used by the server, as the server will +// silently ignore a value below the minimum and fall back to the default. +// Googlers see b/266868871 for relevant discussion. +const MIN_LONG_POLLING_TIMEOUT_SECONDS = 5; +// No maximum long-polling timeout is configured in the server, and defaults to +// 30 seconds, which is what Watch appears to use. +// Googlers see b/266868871 for relevant discussion. +const MAX_LONG_POLLING_TIMEOUT_SECONDS = 30; +// Whether long-polling auto-detected is enabled by default. +const DEFAULT_AUTO_DETECT_LONG_POLLING = true; +/** + * A concrete type describing all the values that can be applied via a + * user-supplied `FirestoreSettings` object. This is a separate type so that + * defaults can be supplied and the value can be checked for equality. + */ +class FirestoreSettingsImpl { + constructor(settings) { + if (settings.host === undefined) { + if (settings.ssl !== undefined) { + throw new FirestoreError(Code.INVALID_ARGUMENT, "Can't provide ssl option if host option is not set"); + } + this.host = DEFAULT_HOST; + this.ssl = DEFAULT_SSL; + } + else { + this.host = settings.host; + this.ssl = settings.ssl ?? DEFAULT_SSL; + } + this.isUsingEmulator = settings.emulatorOptions !== undefined; + this.credentials = settings.credentials; + this.ignoreUndefinedProperties = !!settings.ignoreUndefinedProperties; + this.localCache = settings.localCache; + if (settings.cacheSizeBytes === undefined) { + this.cacheSizeBytes = LRU_DEFAULT_CACHE_SIZE_BYTES; + } + else { + if (settings.cacheSizeBytes !== LRU_COLLECTION_DISABLED && + settings.cacheSizeBytes < LRU_MINIMUM_CACHE_SIZE_BYTES) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `cacheSizeBytes must be at least ${LRU_MINIMUM_CACHE_SIZE_BYTES}`); + } + else { + this.cacheSizeBytes = settings.cacheSizeBytes; + } + } + validateIsNotUsedTogether('experimentalForceLongPolling', settings.experimentalForceLongPolling, 'experimentalAutoDetectLongPolling', settings.experimentalAutoDetectLongPolling); + this.experimentalForceLongPolling = !!settings.experimentalForceLongPolling; + if (this.experimentalForceLongPolling) { + this.experimentalAutoDetectLongPolling = false; + } + else if (settings.experimentalAutoDetectLongPolling === undefined) { + this.experimentalAutoDetectLongPolling = DEFAULT_AUTO_DETECT_LONG_POLLING; + } + else { + // For backwards compatibility, coerce the value to boolean even though + // the TypeScript compiler has narrowed the type to boolean already. + // noinspection PointlessBooleanExpressionJS + this.experimentalAutoDetectLongPolling = + !!settings.experimentalAutoDetectLongPolling; + } + this.experimentalLongPollingOptions = cloneLongPollingOptions(settings.experimentalLongPollingOptions ?? {}); + validateLongPollingOptions(this.experimentalLongPollingOptions); + this.useFetchStreams = !!settings.useFetchStreams; + } + isEqual(other) { + return (this.host === other.host && + this.ssl === other.ssl && + this.credentials === other.credentials && + this.cacheSizeBytes === other.cacheSizeBytes && + this.experimentalForceLongPolling === + other.experimentalForceLongPolling && + this.experimentalAutoDetectLongPolling === + other.experimentalAutoDetectLongPolling && + longPollingOptionsEqual(this.experimentalLongPollingOptions, other.experimentalLongPollingOptions) && + this.ignoreUndefinedProperties === other.ignoreUndefinedProperties && + this.useFetchStreams === other.useFetchStreams); + } +} +function validateLongPollingOptions(options) { + if (options.timeoutSeconds !== undefined) { + if (isNaN(options.timeoutSeconds)) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `invalid long polling timeout: ` + + `${options.timeoutSeconds} (must not be NaN)`); + } + if (options.timeoutSeconds < MIN_LONG_POLLING_TIMEOUT_SECONDS) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `invalid long polling timeout: ${options.timeoutSeconds} ` + + `(minimum allowed value is ${MIN_LONG_POLLING_TIMEOUT_SECONDS})`); + } + if (options.timeoutSeconds > MAX_LONG_POLLING_TIMEOUT_SECONDS) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `invalid long polling timeout: ${options.timeoutSeconds} ` + + `(maximum allowed value is ${MAX_LONG_POLLING_TIMEOUT_SECONDS})`); + } + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * The Cloud Firestore service interface. + * + * Do not call this constructor directly. Instead, use {@link (getFirestore:1)}. + */ +class Firestore { + /** @hideconstructor */ + constructor(_authCredentials, _appCheckCredentials, _databaseId, _app) { + this._authCredentials = _authCredentials; + this._appCheckCredentials = _appCheckCredentials; + this._databaseId = _databaseId; + this._app = _app; + /** + * Whether it's a Firestore or Firestore Lite instance. + */ + this.type = 'firestore-lite'; + this._persistenceKey = '(lite)'; + this._settings = new FirestoreSettingsImpl({}); + this._settingsFrozen = false; + this._emulatorOptions = {}; + // A task that is assigned when the terminate() is invoked and resolved when + // all components have shut down. Otherwise, Firestore is not terminated, + // which can mean either the FirestoreClient is in the process of starting, + // or restarting. + this._terminateTask = 'notTerminated'; + } + /** + * The {@link @firebase/app#FirebaseApp} associated with this `Firestore` service + * instance. + */ + get app() { + if (!this._app) { + throw new FirestoreError(Code.FAILED_PRECONDITION, "Firestore was not initialized using the Firebase SDK. 'app' is " + + 'not available'); + } + return this._app; + } + get _initialized() { + return this._settingsFrozen; + } + get _terminated() { + return this._terminateTask !== 'notTerminated'; + } + _setSettings(settings) { + if (this._settingsFrozen) { + throw new FirestoreError(Code.FAILED_PRECONDITION, 'Firestore has already been started and its settings can no longer ' + + 'be changed. You can only modify settings before calling any other ' + + 'methods on a Firestore object.'); + } + this._settings = new FirestoreSettingsImpl(settings); + this._emulatorOptions = settings.emulatorOptions || {}; + if (settings.credentials !== undefined) { + this._authCredentials = makeAuthCredentialsProvider(settings.credentials); + } + } + _getSettings() { + return this._settings; + } + _getEmulatorOptions() { + return this._emulatorOptions; + } + _freezeSettings() { + this._settingsFrozen = true; + return this._settings; + } + _delete() { + // The `_terminateTask` must be assigned future that completes when + // terminate is complete. The existence of this future puts SDK in state + // that will not accept further API interaction. + if (this._terminateTask === 'notTerminated') { + this._terminateTask = this._terminate(); + } + return this._terminateTask; + } + async _restart() { + // The `_terminateTask` must equal 'notTerminated' after restart to + // signal that client is in a state that accepts API calls. + if (this._terminateTask === 'notTerminated') { + await this._terminate(); + } + else { + this._terminateTask = 'notTerminated'; + } + } + /** Returns a JSON-serializable representation of this `Firestore` instance. */ + toJSON() { + return { + app: this._app, + databaseId: this._databaseId, + settings: this._settings + }; + } + /** + * Terminates all components used by this client. Subclasses can override + * this method to clean up their own dependencies, but must also call this + * method. + * + * Only ever called once. + */ + _terminate() { + removeComponents(this); + return Promise.resolve(); + } +} +function initializeFirestore(app$1, settings, databaseId) { + if (!databaseId) { + databaseId = DEFAULT_DATABASE_NAME; + } + const provider = app._getProvider(app$1, 'firestore/lite'); + if (provider.isInitialized(databaseId)) { + throw new FirestoreError(Code.FAILED_PRECONDITION, 'Firestore can only be initialized once per app.'); + } + return provider.initialize({ + options: settings, + instanceIdentifier: databaseId + }); +} +function getFirestore(appOrDatabaseId, optionalDatabaseId) { + const app$1 = typeof appOrDatabaseId === 'object' ? appOrDatabaseId : app.getApp(); + const databaseId = typeof appOrDatabaseId === 'string' + ? appOrDatabaseId + : optionalDatabaseId || '(default)'; + const db = app._getProvider(app$1, 'firestore/lite').getImmediate({ + identifier: databaseId + }); + if (!db._initialized) { + const emulator = util.getDefaultEmulatorHostnameAndPort('firestore'); + if (emulator) { + connectFirestoreEmulator(db, ...emulator); + } + } + return db; +} +/** + * Modify this instance to communicate with the Cloud Firestore emulator. + * + * Note: This must be called before this instance has been used to do any + * operations. + * + * @param firestore - The `Firestore` instance to configure to connect to the + * emulator. + * @param host - the emulator host (ex: localhost). + * @param port - the emulator port (ex: 9000). + * @param options.mockUserToken - the mock auth token to use for unit testing + * Security Rules. + */ +function connectFirestoreEmulator(firestore, host, port, options = {}) { + firestore = cast(firestore, Firestore); + const useSsl = util.isCloudWorkstation(host); + const settings = firestore._getSettings(); + const existingConfig = { + ...settings, + emulatorOptions: firestore._getEmulatorOptions() + }; + const newHostSetting = `${host}:${port}`; + if (useSsl) { + void util.pingServer(`https://${newHostSetting}`); + util.updateEmulatorBanner('Firestore', true); + } + if (settings.host !== DEFAULT_HOST && settings.host !== newHostSetting) { + logWarn('Host has been set in both settings() and connectFirestoreEmulator(), emulator host ' + + 'will be used.'); + } + const newConfig = { + ...settings, + host: newHostSetting, + ssl: useSsl, + emulatorOptions: options + }; + // No-op if the new configuration matches the current configuration. This supports SSR + // enviornments which might call `connectFirestoreEmulator` multiple times as a standard practice. + if (util.deepEqual(newConfig, existingConfig)) { + return; + } + firestore._setSettings(newConfig); + if (options.mockUserToken) { + let token; + let user; + if (typeof options.mockUserToken === 'string') { + token = options.mockUserToken; + user = User.MOCK_USER; + } + else { + // Let createMockUserToken validate first (catches common mistakes like + // invalid field "uid" and missing field "sub" / "user_id".) + token = util.createMockUserToken(options.mockUserToken, firestore._app?.options.projectId); + const uid = options.mockUserToken.sub || options.mockUserToken.user_id; + if (!uid) { + throw new FirestoreError(Code.INVALID_ARGUMENT, "mockUserToken must contain 'sub' or 'user_id' field!"); + } + user = new User(uid); + } + firestore._authCredentials = new EmulatorAuthCredentialsProvider(new OAuthToken(token, user)); + } +} +/** + * Terminates the provided `Firestore` instance. + * + * After calling `terminate()` only the `clearIndexedDbPersistence()` functions + * may be used. Any other function will throw a `FirestoreError`. Termination + * does not cancel any pending writes, and any promises that are awaiting a + * response from the server will not be resolved. + * + * To restart after termination, create a new instance of `Firestore` with + * {@link (getFirestore:1)}. + * + * Note: Under normal circumstances, calling `terminate()` is not required. This + * function is useful only when you want to force this instance to release all of + * its resources or in combination with {@link clearIndexedDbPersistence} to + * ensure that all local state is destroyed between test runs. + * + * @param firestore - The `Firestore` instance to terminate. + * @returns A `Promise` that is resolved when the instance has been successfully + * terminated. + */ +function terminate(firestore) { + firestore = cast(firestore, Firestore); + app._removeServiceInstance(firestore.app, 'firestore/lite'); + return firestore._delete(); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +function registerFirestore() { + setSDKVersion(`${app.SDK_VERSION}_lite`); + app._registerComponent(new component.Component('firestore/lite', (container, { instanceIdentifier: databaseId, options: settings }) => { + const app = container.getProvider('app').getImmediate(); + const firestoreInstance = new Firestore(new LiteAuthCredentialsProvider(container.getProvider('auth-internal')), new LiteAppCheckTokenProvider(app, container.getProvider('app-check-internal')), databaseIdFromApp(app, databaseId), app); + if (settings) { + firestoreInstance._setSettings(settings); + } + return firestoreInstance; + }, 'PUBLIC').setMultipleInstances(true)); + // RUNTIME_ENV and BUILD_TARGET are replaced by real values during the compilation + app.registerVersion('firestore-lite', version$1, 'node'); + app.registerVersion('firestore-lite', version$1, 'cjs2020'); +} + +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Concrete implementation of the Aggregate type. + */ +class AggregateImpl { + constructor(alias, aggregateType, fieldPath) { + this.alias = alias; + this.aggregateType = aggregateType; + this.fieldPath = fieldPath; + } +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Represents an aggregation that can be performed by Firestore. + */ +// eslint-disable-next-line @typescript-eslint/no-unused-vars +class AggregateField { + /** + * Create a new AggregateField + * @param aggregateType Specifies the type of aggregation operation to perform. + * @param _internalFieldPath Optionally specifies the field that is aggregated. + * @internal + */ + constructor(aggregateType = 'count', _internalFieldPath) { + this._internalFieldPath = _internalFieldPath; + /** A type string to uniquely identify instances of this class. */ + this.type = 'AggregateField'; + this.aggregateType = aggregateType; + } +} +/** + * The results of executing an aggregation query. + */ +class AggregateQuerySnapshot { + /** @hideconstructor */ + constructor(query, _userDataWriter, _data) { + this._userDataWriter = _userDataWriter; + this._data = _data; + /** A type string to uniquely identify instances of this class. */ + this.type = 'AggregateQuerySnapshot'; + this.query = query; + } + /** + * Returns the results of the aggregations performed over the underlying + * query. + * + * The keys of the returned object will be the same as those of the + * `AggregateSpec` object specified to the aggregation method, and the values + * will be the corresponding aggregation result. + * + * @returns The results of the aggregations performed over the underlying + * query. + */ + data() { + return this._userDataWriter.convertObjectMap(this._data); + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A `Query` refers to a query which you can read or listen to. You can also + * construct refined `Query` objects by adding filters and ordering. + */ +class Query { + // This is the lite version of the Query class in the main SDK. + /** @hideconstructor protected */ + constructor(firestore, + /** + * If provided, the `FirestoreDataConverter` associated with this instance. + */ + converter, _query) { + this.converter = converter; + this._query = _query; + /** The type of this Firestore reference. */ + this.type = 'query'; + this.firestore = firestore; + } + withConverter(converter) { + return new Query(this.firestore, converter, this._query); + } +} +/** + * A `DocumentReference` refers to a document location in a Firestore database + * and can be used to write, read, or listen to the location. The document at + * the referenced location may or may not exist. + */ +class DocumentReference { + /** @hideconstructor */ + constructor(firestore, + /** + * If provided, the `FirestoreDataConverter` associated with this instance. + */ + converter, _key) { + this.converter = converter; + this._key = _key; + /** The type of this Firestore reference. */ + this.type = 'document'; + this.firestore = firestore; + } + get _path() { + return this._key.path; + } + /** + * The document's identifier within its collection. + */ + get id() { + return this._key.path.lastSegment(); + } + /** + * A string representing the path of the referenced document (relative + * to the root of the database). + */ + get path() { + return this._key.path.canonicalString(); + } + /** + * The collection this `DocumentReference` belongs to. + */ + get parent() { + return new CollectionReference(this.firestore, this.converter, this._key.path.popLast()); + } + withConverter(converter) { + return new DocumentReference(this.firestore, converter, this._key); + } + /** + * Returns a JSON-serializable representation of this `DocumentReference` instance. + * + * @returns a JSON representation of this object. + */ + toJSON() { + return { + type: DocumentReference._jsonSchemaVersion, + referencePath: this._key.toString() + }; + } + static fromJSON(firestore, json, converter) { + if (validateJSON(json, DocumentReference._jsonSchema)) { + return new DocumentReference(firestore, converter ? converter : null, new DocumentKey(ResourcePath.fromString(json.referencePath))); + } + } +} +DocumentReference._jsonSchemaVersion = 'firestore/documentReference/1.0'; +DocumentReference._jsonSchema = { + type: property('string', DocumentReference._jsonSchemaVersion), + referencePath: property('string') +}; +/** + * A `CollectionReference` object can be used for adding documents, getting + * document references, and querying for documents (using {@link (query:1)}). + */ +class CollectionReference extends Query { + /** @hideconstructor */ + constructor(firestore, converter, _path) { + super(firestore, converter, newQueryForPath(_path)); + this._path = _path; + /** The type of this Firestore reference. */ + this.type = 'collection'; + } + /** The collection's identifier. */ + get id() { + return this._query.path.lastSegment(); + } + /** + * A string representing the path of the referenced collection (relative + * to the root of the database). + */ + get path() { + return this._query.path.canonicalString(); + } + /** + * A reference to the containing `DocumentReference` if this is a + * subcollection. If this isn't a subcollection, the reference is null. + */ + get parent() { + const parentPath = this._path.popLast(); + if (parentPath.isEmpty()) { + return null; + } + else { + return new DocumentReference(this.firestore, + /* converter= */ null, new DocumentKey(parentPath)); + } + } + withConverter(converter) { + return new CollectionReference(this.firestore, converter, this._path); + } +} +function collection(parent, path, ...pathSegments) { + parent = util.getModularInstance(parent); + validateNonEmptyArgument('collection', 'path', path); + if (parent instanceof Firestore) { + const absolutePath = ResourcePath.fromString(path, ...pathSegments); + validateCollectionPath(absolutePath); + return new CollectionReference(parent, /* converter= */ null, absolutePath); + } + else { + if (!(parent instanceof DocumentReference) && + !(parent instanceof CollectionReference)) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Expected first argument to collection() to be a CollectionReference, ' + + 'a DocumentReference or FirebaseFirestore'); + } + const absolutePath = parent._path.child(ResourcePath.fromString(path, ...pathSegments)); + validateCollectionPath(absolutePath); + return new CollectionReference(parent.firestore, + /* converter= */ null, absolutePath); + } +} +// TODO(firestorelite): Consider using ErrorFactory - +// https://github.com/firebase/firebase-js-sdk/blob/0131e1f/packages/util/src/errors.ts#L106 +/** + * Creates and returns a new `Query` instance that includes all documents in the + * database that are contained in a collection or subcollection with the + * given `collectionId`. + * + * @param firestore - A reference to the root `Firestore` instance. + * @param collectionId - Identifies the collections to query over. Every + * collection or subcollection with this ID as the last segment of its path + * will be included. Cannot contain a slash. + * @returns The created `Query`. + */ +function collectionGroup(firestore, collectionId) { + firestore = cast(firestore, Firestore); + validateNonEmptyArgument('collectionGroup', 'collection id', collectionId); + if (collectionId.indexOf('/') >= 0) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid collection ID '${collectionId}' passed to function ` + + `collectionGroup(). Collection IDs must not contain '/'.`); + } + return new Query(firestore, + /* converter= */ null, newQueryForCollectionGroup(collectionId)); +} +function doc(parent, path, ...pathSegments) { + parent = util.getModularInstance(parent); + // We allow omission of 'pathString' but explicitly prohibit passing in both + // 'undefined' and 'null'. + if (arguments.length === 1) { + path = AutoId.newId(); + } + validateNonEmptyArgument('doc', 'path', path); + if (parent instanceof Firestore) { + const absolutePath = ResourcePath.fromString(path, ...pathSegments); + validateDocumentPath(absolutePath); + return new DocumentReference(parent, + /* converter= */ null, new DocumentKey(absolutePath)); + } + else { + if (!(parent instanceof DocumentReference) && + !(parent instanceof CollectionReference)) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Expected first argument to collection() to be a CollectionReference, ' + + 'a DocumentReference or FirebaseFirestore'); + } + const absolutePath = parent._path.child(ResourcePath.fromString(path, ...pathSegments)); + validateDocumentPath(absolutePath); + return new DocumentReference(parent.firestore, parent instanceof CollectionReference ? parent.converter : null, new DocumentKey(absolutePath)); + } +} +/** + * Returns true if the provided references are equal. + * + * @param left - A reference to compare. + * @param right - A reference to compare. + * @returns true if the references point to the same location in the same + * Firestore database. + */ +function refEqual(left, right) { + left = util.getModularInstance(left); + right = util.getModularInstance(right); + if ((left instanceof DocumentReference || + left instanceof CollectionReference) && + (right instanceof DocumentReference || right instanceof CollectionReference)) { + return (left.firestore === right.firestore && + left.path === right.path && + left.converter === right.converter); + } + return false; +} +/** + * Returns true if the provided queries point to the same collection and apply + * the same constraints. + * + * @param left - A `Query` to compare. + * @param right - A `Query` to compare. + * @returns true if the references point to the same location in the same + * Firestore database. + */ +function queryEqual(left, right) { + left = util.getModularInstance(left); + right = util.getModularInstance(right); + if (left instanceof Query && right instanceof Query) { + return (left.firestore === right.firestore && + queryEquals(left._query, right._query) && + left.converter === right.converter); + } + return false; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An immutable object representing an array of bytes. + */ +class Bytes { + /** @hideconstructor */ + constructor(byteString) { + this._byteString = byteString; + } + /** + * Creates a new `Bytes` object from the given Base64 string, converting it to + * bytes. + * + * @param base64 - The Base64 string used to create the `Bytes` object. + */ + static fromBase64String(base64) { + try { + return new Bytes(ByteString.fromBase64String(base64)); + } + catch (e) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Failed to construct data from Base64 string: ' + e); + } + } + /** + * Creates a new `Bytes` object from the given Uint8Array. + * + * @param array - The Uint8Array used to create the `Bytes` object. + */ + static fromUint8Array(array) { + return new Bytes(ByteString.fromUint8Array(array)); + } + /** + * Returns the underlying bytes as a Base64-encoded string. + * + * @returns The Base64-encoded string created from the `Bytes` object. + */ + toBase64() { + return this._byteString.toBase64(); + } + /** + * Returns the underlying bytes in a new `Uint8Array`. + * + * @returns The Uint8Array created from the `Bytes` object. + */ + toUint8Array() { + return this._byteString.toUint8Array(); + } + /** + * Returns a string representation of the `Bytes` object. + * + * @returns A string representation of the `Bytes` object. + */ + toString() { + return 'Bytes(base64: ' + this.toBase64() + ')'; + } + /** + * Returns true if this `Bytes` object is equal to the provided one. + * + * @param other - The `Bytes` object to compare against. + * @returns true if this `Bytes` object is equal to the provided one. + */ + isEqual(other) { + return this._byteString.isEqual(other._byteString); + } + /** + * Returns a JSON-serializable representation of this `Bytes` instance. + * + * @returns a JSON representation of this object. + */ + toJSON() { + return { + type: Bytes._jsonSchemaVersion, + bytes: this.toBase64() + }; + } + /** + * Builds a `Bytes` instance from a JSON object created by {@link Bytes.toJSON}. + * + * @param json a JSON object represention of a `Bytes` instance + * @returns an instance of {@link Bytes} if the JSON object could be parsed. Throws a + * {@link FirestoreError} if an error occurs. + */ + static fromJSON(json) { + if (validateJSON(json, Bytes._jsonSchema)) { + return Bytes.fromBase64String(json.bytes); + } + } +} +Bytes._jsonSchemaVersion = 'firestore/bytes/1.0'; +Bytes._jsonSchema = { + type: property('string', Bytes._jsonSchemaVersion), + bytes: property('string') +}; + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A `FieldPath` refers to a field in a document. The path may consist of a + * single field name (referring to a top-level field in the document), or a + * list of field names (referring to a nested field in the document). + * + * Create a `FieldPath` by providing field names. If more than one field + * name is provided, the path will point to a nested field in a document. + */ +class FieldPath { + /** + * Creates a `FieldPath` from the provided field names. If more than one field + * name is provided, the path will point to a nested field in a document. + * + * @param fieldNames - A list of field names. + */ + constructor(...fieldNames) { + for (let i = 0; i < fieldNames.length; ++i) { + if (fieldNames[i].length === 0) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid field name at argument $(i + 1). ` + + 'Field names must not be empty.'); + } + } + this._internalPath = new FieldPath$1(fieldNames); + } + /** + * Returns true if this `FieldPath` is equal to the provided one. + * + * @param other - The `FieldPath` to compare against. + * @returns true if this `FieldPath` is equal to the provided one. + */ + isEqual(other) { + return this._internalPath.isEqual(other._internalPath); + } +} +/** + * Returns a special sentinel `FieldPath` to refer to the ID of a document. + * It can be used in queries to sort or filter by the document ID. + */ +function documentId() { + return new FieldPath(DOCUMENT_KEY_NAME); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Sentinel values that can be used when writing document fields with `set()` + * or `update()`. + */ +class FieldValue { + /** + * @param _methodName - The public API endpoint that returns this class. + * @hideconstructor + */ + constructor(_methodName) { + this._methodName = _methodName; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An immutable object representing a geographic location in Firestore. The + * location is represented as latitude/longitude pair. + * + * Latitude values are in the range of [-90, 90]. + * Longitude values are in the range of [-180, 180]. + */ +class GeoPoint { + /** + * Creates a new immutable `GeoPoint` object with the provided latitude and + * longitude values. + * @param latitude - The latitude as number between -90 and 90. + * @param longitude - The longitude as number between -180 and 180. + */ + constructor(latitude, longitude) { + if (!isFinite(latitude) || latitude < -90 || latitude > 90) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Latitude must be a number between -90 and 90, but was: ' + latitude); + } + if (!isFinite(longitude) || longitude < -180 || longitude > 180) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Longitude must be a number between -180 and 180, but was: ' + longitude); + } + this._lat = latitude; + this._long = longitude; + } + /** + * The latitude of this `GeoPoint` instance. + */ + get latitude() { + return this._lat; + } + /** + * The longitude of this `GeoPoint` instance. + */ + get longitude() { + return this._long; + } + /** + * Returns true if this `GeoPoint` is equal to the provided one. + * + * @param other - The `GeoPoint` to compare against. + * @returns true if this `GeoPoint` is equal to the provided one. + */ + isEqual(other) { + return this._lat === other._lat && this._long === other._long; + } + /** + * Actually private to JS consumers of our API, so this function is prefixed + * with an underscore. + */ + _compareTo(other) { + return (primitiveComparator(this._lat, other._lat) || + primitiveComparator(this._long, other._long)); + } + /** + * Returns a JSON-serializable representation of this `GeoPoint` instance. + * + * @returns a JSON representation of this object. + */ + toJSON() { + return { + latitude: this._lat, + longitude: this._long, + type: GeoPoint._jsonSchemaVersion + }; + } + /** + * Builds a `GeoPoint` instance from a JSON object created by {@link GeoPoint.toJSON}. + * + * @param json a JSON object represention of a `GeoPoint` instance + * @returns an instance of {@link GeoPoint} if the JSON object could be parsed. Throws a + * {@link FirestoreError} if an error occurs. + */ + static fromJSON(json) { + if (validateJSON(json, GeoPoint._jsonSchema)) { + return new GeoPoint(json.latitude, json.longitude); + } + } +} +GeoPoint._jsonSchemaVersion = 'firestore/geoPoint/1.0'; +GeoPoint._jsonSchema = { + type: property('string', GeoPoint._jsonSchemaVersion), + latitude: property('number'), + longitude: property('number') +}; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Verifies equality for an array of primitives. + * + * @private + * @internal + * @param left Array of primitives. + * @param right Array of primitives. + * @return True if arrays are equal. + */ +function isPrimitiveArrayEqual(left, right) { + if (left.length !== right.length) { + return false; + } + for (let i = 0; i < left.length; ++i) { + if (left[i] !== right[i]) { + return false; + } + } + return true; +} + +/** + * @license + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Represents a vector type in Firestore documents. + * Create an instance with {@link vector}. + * + * @class VectorValue + */ +class VectorValue { + /** + * @private + * @internal + */ + constructor(values) { + // Making a copy of the parameter. + this._values = (values || []).map(n => n); + } + /** + * Returns a copy of the raw number array form of the vector. + */ + toArray() { + return this._values.map(n => n); + } + /** + * Returns `true` if the two `VectorValue` values have the same raw number arrays, returns `false` otherwise. + */ + isEqual(other) { + return isPrimitiveArrayEqual(this._values, other._values); + } + /** + * Returns a JSON-serializable representation of this `VectorValue` instance. + * + * @returns a JSON representation of this object. + */ + toJSON() { + return { + type: VectorValue._jsonSchemaVersion, + vectorValues: this._values + }; + } + /** + * Builds a `VectorValue` instance from a JSON object created by {@link VectorValue.toJSON}. + * + * @param json a JSON object represention of a `VectorValue` instance. + * @returns an instance of {@link VectorValue} if the JSON object could be parsed. Throws a + * {@link FirestoreError} if an error occurs. + */ + static fromJSON(json) { + if (validateJSON(json, VectorValue._jsonSchema)) { + if (Array.isArray(json.vectorValues) && + json.vectorValues.every(element => typeof element === 'number')) { + return new VectorValue(json.vectorValues); + } + throw new FirestoreError(Code.INVALID_ARGUMENT, "Expected 'vectorValues' field to be a number array"); + } + } +} +VectorValue._jsonSchemaVersion = 'firestore/vectorValue/1.0'; +VectorValue._jsonSchema = { + type: property('string', VectorValue._jsonSchemaVersion), + vectorValues: property('object') +}; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const RESERVED_FIELD_REGEX = /^__.*__$/; +/** The result of parsing document data (e.g. for a setData call). */ +class ParsedSetData { + constructor(data, fieldMask, fieldTransforms) { + this.data = data; + this.fieldMask = fieldMask; + this.fieldTransforms = fieldTransforms; + } + toMutation(key, precondition) { + if (this.fieldMask !== null) { + return new PatchMutation(key, this.data, this.fieldMask, precondition, this.fieldTransforms); + } + else { + return new SetMutation(key, this.data, precondition, this.fieldTransforms); + } + } +} +/** The result of parsing "update" data (i.e. for an updateData call). */ +class ParsedUpdateData { + constructor(data, + // The fieldMask does not include document transforms. + fieldMask, fieldTransforms) { + this.data = data; + this.fieldMask = fieldMask; + this.fieldTransforms = fieldTransforms; + } + toMutation(key, precondition) { + return new PatchMutation(key, this.data, this.fieldMask, precondition, this.fieldTransforms); + } +} +function isWrite(dataSource) { + switch (dataSource) { + case 0 /* UserDataSource.Set */: // fall through + case 2 /* UserDataSource.MergeSet */: // fall through + case 1 /* UserDataSource.Update */: + return true; + case 3 /* UserDataSource.Argument */: + case 4 /* UserDataSource.ArrayArgument */: + return false; + default: + throw fail(0x9c4b, { + dataSource + }); + } +} +/** A "context" object passed around while parsing user data. */ +class ParseContextImpl { + /** + * Initializes a ParseContext with the given source and path. + * + * @param settings - The settings for the parser. + * @param databaseId - The database ID of the Firestore instance. + * @param serializer - The serializer to use to generate the Value proto. + * @param ignoreUndefinedProperties - Whether to ignore undefined properties + * rather than throw. + * @param fieldTransforms - A mutable list of field transforms encountered + * while parsing the data. + * @param fieldMask - A mutable list of field paths encountered while parsing + * the data. + * + * TODO(b/34871131): We don't support array paths right now, so path can be + * null to indicate the context represents any location within an array (in + * which case certain features will not work and errors will be somewhat + * compromised). + */ + constructor(settings, databaseId, serializer, ignoreUndefinedProperties, fieldTransforms, fieldMask) { + this.settings = settings; + this.databaseId = databaseId; + this.serializer = serializer; + this.ignoreUndefinedProperties = ignoreUndefinedProperties; + // Minor hack: If fieldTransforms is undefined, we assume this is an + // external call and we need to validate the entire path. + if (fieldTransforms === undefined) { + this.validatePath(); + } + this.fieldTransforms = fieldTransforms || []; + this.fieldMask = fieldMask || []; + } + get path() { + return this.settings.path; + } + get dataSource() { + return this.settings.dataSource; + } + /** Returns a new context with the specified settings overwritten. */ + contextWith(configuration) { + return new ParseContextImpl({ ...this.settings, ...configuration }, this.databaseId, this.serializer, this.ignoreUndefinedProperties, this.fieldTransforms, this.fieldMask); + } + childContextForField(field) { + const childPath = this.path?.child(field); + const context = this.contextWith({ path: childPath, arrayElement: false }); + context.validatePathSegment(field); + return context; + } + childContextForFieldPath(field) { + const childPath = this.path?.child(field); + const context = this.contextWith({ path: childPath, arrayElement: false }); + context.validatePath(); + return context; + } + childContextForArray(index) { + // TODO(b/34871131): We don't support array paths right now; so make path + // undefined. + return this.contextWith({ path: undefined, arrayElement: true }); + } + createError(reason) { + return createError(reason, this.settings.methodName, this.settings.hasConverter || false, this.path, this.settings.targetDoc); + } + /** Returns 'true' if 'fieldPath' was traversed when creating this context. */ + contains(fieldPath) { + return (this.fieldMask.find(field => fieldPath.isPrefixOf(field)) !== undefined || + this.fieldTransforms.find(transform => fieldPath.isPrefixOf(transform.field)) !== undefined); + } + validatePath() { + // TODO(b/34871131): Remove null check once we have proper paths for fields + // within arrays. + if (!this.path) { + return; + } + for (let i = 0; i < this.path.length; i++) { + this.validatePathSegment(this.path.get(i)); + } + } + validatePathSegment(segment) { + if (segment.length === 0) { + throw this.createError('Document fields must not be empty'); + } + if (isWrite(this.dataSource) && RESERVED_FIELD_REGEX.test(segment)) { + throw this.createError('Document fields cannot begin and end with "__"'); + } + } +} +/** + * Helper for parsing raw user input (provided via the API) into internal model + * classes. + */ +class UserDataReader { + constructor(databaseId, ignoreUndefinedProperties, serializer) { + this.databaseId = databaseId; + this.ignoreUndefinedProperties = ignoreUndefinedProperties; + this.serializer = serializer || newSerializer(databaseId); + } + /** Creates a new top-level parse context. */ + createContext(dataSource, methodName, targetDoc, hasConverter = false) { + return new ParseContextImpl({ + dataSource, + methodName, + targetDoc, + path: FieldPath$1.emptyPath(), + arrayElement: false, + hasConverter + }, this.databaseId, this.serializer, this.ignoreUndefinedProperties); + } +} +function newUserDataReader(firestore) { + const settings = firestore._freezeSettings(); + const serializer = newSerializer(firestore._databaseId); + return new UserDataReader(firestore._databaseId, !!settings.ignoreUndefinedProperties, serializer); +} +/** Parse document data from a set() call. */ +function parseSetData(userDataReader, methodName, targetDoc, input, hasConverter, options = {}) { + const context = userDataReader.createContext(options.merge || options.mergeFields + ? 2 /* UserDataSource.MergeSet */ + : 0 /* UserDataSource.Set */, methodName, targetDoc, hasConverter); + validatePlainObject('Data must be an object, but it was:', context, input); + const updateData = parseObject(input, context); + let fieldMask; + let fieldTransforms; + if (options.merge) { + fieldMask = new FieldMask(context.fieldMask); + fieldTransforms = context.fieldTransforms; + } + else if (options.mergeFields) { + const validatedFieldPaths = []; + for (const stringOrFieldPath of options.mergeFields) { + const fieldPath = fieldPathFromArgument$1(methodName, stringOrFieldPath, targetDoc); + if (!context.contains(fieldPath)) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `Field '${fieldPath}' is specified in your field mask but missing from your input data.`); + } + if (!fieldMaskContains(validatedFieldPaths, fieldPath)) { + validatedFieldPaths.push(fieldPath); + } + } + fieldMask = new FieldMask(validatedFieldPaths); + fieldTransforms = context.fieldTransforms.filter(transform => fieldMask.covers(transform.field)); + } + else { + fieldMask = null; + fieldTransforms = context.fieldTransforms; + } + return new ParsedSetData(new ObjectValue(updateData), fieldMask, fieldTransforms); +} +class DeleteFieldValueImpl extends FieldValue { + _toFieldTransform(context) { + if (context.dataSource === 2 /* UserDataSource.MergeSet */) { + // No transform to add for a delete, but we need to add it to our + // fieldMask so it gets deleted. + context.fieldMask.push(context.path); + } + else if (context.dataSource === 1 /* UserDataSource.Update */) { + throw context.createError(`${this._methodName}() can only appear at the top level ` + + 'of your update data'); + } + else { + // We shouldn't encounter delete sentinels for queries or non-merge set() calls. + throw context.createError(`${this._methodName}() cannot be used with set() unless you pass ` + + '{merge:true}'); + } + return null; + } + isEqual(other) { + return other instanceof DeleteFieldValueImpl; + } +} +/** + * Creates a child context for parsing SerializableFieldValues. + * + * This is different than calling `ParseContext.contextWith` because it keeps + * the fieldTransforms and fieldMask separate. + * + * The created context has its `dataSource` set to `UserDataSource.Argument`. + * Although these values are used with writes, any elements in these FieldValues + * are not considered writes since they cannot contain any FieldValue sentinels, + * etc. + * + * @param fieldValue - The sentinel FieldValue for which to create a child + * context. + * @param context - The parent context. + * @param arrayElement - Whether or not the FieldValue has an array. + */ +function createSentinelChildContext(fieldValue, context, arrayElement) { + return new ParseContextImpl({ + dataSource: 3 /* UserDataSource.Argument */, + targetDoc: context.settings.targetDoc, + methodName: fieldValue._methodName, + arrayElement + }, context.databaseId, context.serializer, context.ignoreUndefinedProperties); +} +class ServerTimestampFieldValueImpl extends FieldValue { + _toFieldTransform(context) { + return new FieldTransform(context.path, new ServerTimestampTransform()); + } + isEqual(other) { + return other instanceof ServerTimestampFieldValueImpl; + } +} +class ArrayUnionFieldValueImpl extends FieldValue { + constructor(methodName, _elements) { + super(methodName); + this._elements = _elements; + } + _toFieldTransform(context) { + const parseContext = createSentinelChildContext(this, context, + /*array=*/ true); + const parsedElements = this._elements.map(element => parseData(element, parseContext)); + const arrayUnion = new ArrayUnionTransformOperation(parsedElements); + return new FieldTransform(context.path, arrayUnion); + } + isEqual(other) { + return (other instanceof ArrayUnionFieldValueImpl && + util.deepEqual(this._elements, other._elements)); + } +} +class ArrayRemoveFieldValueImpl extends FieldValue { + constructor(methodName, _elements) { + super(methodName); + this._elements = _elements; + } + _toFieldTransform(context) { + const parseContext = createSentinelChildContext(this, context, + /*array=*/ true); + const parsedElements = this._elements.map(element => parseData(element, parseContext)); + const arrayUnion = new ArrayRemoveTransformOperation(parsedElements); + return new FieldTransform(context.path, arrayUnion); + } + isEqual(other) { + return (other instanceof ArrayRemoveFieldValueImpl && + util.deepEqual(this._elements, other._elements)); + } +} +class NumericIncrementFieldValueImpl extends FieldValue { + constructor(methodName, _operand) { + super(methodName); + this._operand = _operand; + } + _toFieldTransform(context) { + const numericIncrement = new NumericIncrementTransformOperation(context.serializer, toNumber(context.serializer, this._operand)); + return new FieldTransform(context.path, numericIncrement); + } + isEqual(other) { + return (other instanceof NumericIncrementFieldValueImpl && + this._operand === other._operand); + } +} +/** Parse update data from an update() call. */ +function parseUpdateData(userDataReader, methodName, targetDoc, input) { + const context = userDataReader.createContext(1 /* UserDataSource.Update */, methodName, targetDoc); + validatePlainObject('Data must be an object, but it was:', context, input); + const fieldMaskPaths = []; + const updateData = ObjectValue.empty(); + forEach(input, (key, value) => { + const path = fieldPathFromDotSeparatedString(methodName, key, targetDoc); + // For Compat types, we have to "extract" the underlying types before + // performing validation. + value = util.getModularInstance(value); + const childContext = context.childContextForFieldPath(path); + if (value instanceof DeleteFieldValueImpl) { + // Add it to the field mask, but don't add anything to updateData. + fieldMaskPaths.push(path); + } + else { + const parsedValue = parseData(value, childContext); + if (parsedValue != null) { + fieldMaskPaths.push(path); + updateData.set(path, parsedValue); + } + } + }); + const mask = new FieldMask(fieldMaskPaths); + return new ParsedUpdateData(updateData, mask, context.fieldTransforms); +} +/** Parse update data from a list of field/value arguments. */ +function parseUpdateVarargs(userDataReader, methodName, targetDoc, field, value, moreFieldsAndValues) { + const context = userDataReader.createContext(1 /* UserDataSource.Update */, methodName, targetDoc); + const keys = [fieldPathFromArgument$1(methodName, field, targetDoc)]; + const values = [value]; + if (moreFieldsAndValues.length % 2 !== 0) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `Function ${methodName}() needs to be called with an even number ` + + 'of arguments that alternate between field names and values.'); + } + for (let i = 0; i < moreFieldsAndValues.length; i += 2) { + keys.push(fieldPathFromArgument$1(methodName, moreFieldsAndValues[i])); + values.push(moreFieldsAndValues[i + 1]); + } + const fieldMaskPaths = []; + const updateData = ObjectValue.empty(); + // We iterate in reverse order to pick the last value for a field if the + // user specified the field multiple times. + for (let i = keys.length - 1; i >= 0; --i) { + if (!fieldMaskContains(fieldMaskPaths, keys[i])) { + const path = keys[i]; + let value = values[i]; + // For Compat types, we have to "extract" the underlying types before + // performing validation. + value = util.getModularInstance(value); + const childContext = context.childContextForFieldPath(path); + if (value instanceof DeleteFieldValueImpl) { + // Add it to the field mask, but don't add anything to updateData. + fieldMaskPaths.push(path); + } + else { + const parsedValue = parseData(value, childContext); + if (parsedValue != null) { + fieldMaskPaths.push(path); + updateData.set(path, parsedValue); + } + } + } + } + const mask = new FieldMask(fieldMaskPaths); + return new ParsedUpdateData(updateData, mask, context.fieldTransforms); +} +/** + * Parse a "query value" (e.g. value in a where filter or a value in a cursor + * bound). + * + * @param allowArrays - Whether the query value is an array that may directly + * contain additional arrays (e.g. the operand of an `in` query). + */ +function parseQueryValue(userDataReader, methodName, input, allowArrays = false) { + const context = userDataReader.createContext(allowArrays ? 4 /* UserDataSource.ArrayArgument */ : 3 /* UserDataSource.Argument */, methodName); + const parsed = parseData(input, context); + return parsed; +} +/** + * Parses user data to Protobuf Values. + * + * @param input - Data to be parsed. + * @param context - A context object representing the current path being parsed, + * the source of the data being parsed, etc. + * @returns The parsed value, or null if the value was a FieldValue sentinel + * that should not be included in the resulting parsed data. + */ +function parseData(input, context) { + // Unwrap the API type from the Compat SDK. This will return the API type + // from firestore-exp. + input = util.getModularInstance(input); + if (looksLikeJsonObject(input)) { + validatePlainObject('Unsupported field value:', context, input); + return parseObject(input, context); + } + else if (input instanceof FieldValue) { + // FieldValues usually parse into transforms (except deleteField()) + // in which case we do not want to include this field in our parsed data + // (as doing so will overwrite the field directly prior to the transform + // trying to transform it). So we don't add this location to + // context.fieldMask and we return null as our parsing result. + parseSentinelFieldValue(input, context); + return null; + } + else if (input === undefined && context.ignoreUndefinedProperties) { + // If the input is undefined it can never participate in the fieldMask, so + // don't handle this below. If `ignoreUndefinedProperties` is false, + // `parseScalarValue` will reject an undefined value. + return null; + } + else { + // If context.path is null we are inside an array and we don't support + // field mask paths more granular than the top-level array. + if (context.path) { + context.fieldMask.push(context.path); + } + if (input instanceof Array) { + // TODO(b/34871131): Include the path containing the array in the error + // message. + // In the case of IN queries, the parsed data is an array (representing + // the set of values to be included for the IN query) that may directly + // contain additional arrays (each representing an individual field + // value), so we disable this validation. + if (context.settings.arrayElement && + context.dataSource !== 4 /* UserDataSource.ArrayArgument */) { + throw context.createError('Nested arrays are not supported'); + } + return parseArray(input, context); + } + else { + return parseScalarValue(input, context); + } + } +} +function parseObject(obj, context) { + const fields = {}; + if (isEmpty(obj)) { + // If we encounter an empty object, we explicitly add it to the update + // mask to ensure that the server creates a map entry. + if (context.path && context.path.length > 0) { + context.fieldMask.push(context.path); + } + } + else { + forEach(obj, (key, val) => { + const parsedValue = parseData(val, context.childContextForField(key)); + if (parsedValue != null) { + fields[key] = parsedValue; + } + }); + } + return { mapValue: { fields } }; +} +function parseArray(array, context) { + const values = []; + let entryIndex = 0; + for (const entry of array) { + let parsedEntry = parseData(entry, context.childContextForArray(entryIndex)); + if (parsedEntry == null) { + // Just include nulls in the array for fields being replaced with a + // sentinel. + parsedEntry = { nullValue: 'NULL_VALUE' }; + } + values.push(parsedEntry); + entryIndex++; + } + return { arrayValue: { values } }; +} +/** + * "Parses" the provided FieldValueImpl, adding any necessary transforms to + * context.fieldTransforms. + */ +function parseSentinelFieldValue(value, context) { + // Sentinels are only supported with writes, and not within arrays. + if (!isWrite(context.dataSource)) { + throw context.createError(`${value._methodName}() can only be used with update() and set()`); + } + if (!context.path) { + throw context.createError(`${value._methodName}() is not currently supported inside arrays`); + } + const fieldTransform = value._toFieldTransform(context); + if (fieldTransform) { + context.fieldTransforms.push(fieldTransform); + } +} +/** + * Helper to parse a scalar value (i.e. not an Object, Array, or FieldValue) + * + * @returns The parsed value + */ +function parseScalarValue(value, context) { + value = util.getModularInstance(value); + if (value === null) { + return { nullValue: 'NULL_VALUE' }; + } + else if (typeof value === 'number') { + return toNumber(context.serializer, value); + } + else if (typeof value === 'boolean') { + return { booleanValue: value }; + } + else if (typeof value === 'string') { + return { stringValue: value }; + } + else if (value instanceof Date) { + const timestamp = Timestamp.fromDate(value); + return { + timestampValue: toTimestamp(context.serializer, timestamp) + }; + } + else if (value instanceof Timestamp) { + // Firestore backend truncates precision down to microseconds. To ensure + // offline mode works the same with regards to truncation, perform the + // truncation immediately without waiting for the backend to do that. + const timestamp = new Timestamp(value.seconds, Math.floor(value.nanoseconds / 1000) * 1000); + return { + timestampValue: toTimestamp(context.serializer, timestamp) + }; + } + else if (value instanceof GeoPoint) { + return { + geoPointValue: { + latitude: value.latitude, + longitude: value.longitude + } + }; + } + else if (value instanceof Bytes) { + return { bytesValue: toBytes(context.serializer, value._byteString) }; + } + else if (value instanceof DocumentReference) { + const thisDb = context.databaseId; + const otherDb = value.firestore._databaseId; + if (!otherDb.isEqual(thisDb)) { + throw context.createError('Document reference is for database ' + + `${otherDb.projectId}/${otherDb.database} but should be ` + + `for database ${thisDb.projectId}/${thisDb.database}`); + } + return { + referenceValue: toResourceName(value.firestore._databaseId || context.databaseId, value._key.path) + }; + } + else if (value instanceof VectorValue) { + return parseVectorValue(value, context); + } + else { + throw context.createError(`Unsupported field value: ${valueDescription(value)}`); + } +} +/** + * Creates a new VectorValue proto value (using the internal format). + */ +function parseVectorValue(value, context) { + const mapValue = { + fields: { + [TYPE_KEY]: { + stringValue: VECTOR_VALUE_SENTINEL + }, + [VECTOR_MAP_VECTORS_KEY]: { + arrayValue: { + values: value.toArray().map(value => { + if (typeof value !== 'number') { + throw context.createError('VectorValues must only contain numeric values.'); + } + return toDouble(context.serializer, value); + }) + } + } + } + }; + return { mapValue }; +} +/** + * Checks whether an object looks like a JSON object that should be converted + * into a struct. Normal class/prototype instances are considered to look like + * JSON objects since they should be converted to a struct value. Arrays, Dates, + * GeoPoints, etc. are not considered to look like JSON objects since they map + * to specific FieldValue types other than ObjectValue. + */ +function looksLikeJsonObject(input) { + return (typeof input === 'object' && + input !== null && + !(input instanceof Array) && + !(input instanceof Date) && + !(input instanceof Timestamp) && + !(input instanceof GeoPoint) && + !(input instanceof Bytes) && + !(input instanceof DocumentReference) && + !(input instanceof FieldValue) && + !(input instanceof VectorValue)); +} +function validatePlainObject(message, context, input) { + if (!looksLikeJsonObject(input) || !isPlainObject(input)) { + const description = valueDescription(input); + if (description === 'an object') { + // Massage the error if it was an object. + throw context.createError(message + ' a custom object'); + } + else { + throw context.createError(message + ' ' + description); + } + } +} +/** + * Helper that calls fromDotSeparatedString() but wraps any error thrown. + */ +function fieldPathFromArgument$1(methodName, path, targetDoc) { + // If required, replace the FieldPath Compat class with the firestore-exp + // FieldPath. + path = util.getModularInstance(path); + if (path instanceof FieldPath) { + return path._internalPath; + } + else if (typeof path === 'string') { + return fieldPathFromDotSeparatedString(methodName, path); + } + else { + const message = 'Field path arguments must be of type string or '; + throw createError(message, methodName, + /* hasConverter= */ false, + /* path= */ undefined, targetDoc); + } +} +/** + * Matches any characters in a field path string that are reserved. + */ +const FIELD_PATH_RESERVED = new RegExp('[~\\*/\\[\\]]'); +/** + * Wraps fromDotSeparatedString with an error message about the method that + * was thrown. + * @param methodName - The publicly visible method name + * @param path - The dot-separated string form of a field path which will be + * split on dots. + * @param targetDoc - The document against which the field path will be + * evaluated. + */ +function fieldPathFromDotSeparatedString(methodName, path, targetDoc) { + const found = path.search(FIELD_PATH_RESERVED); + if (found >= 0) { + throw createError(`Invalid field path (${path}). Paths must not contain ` + + `'~', '*', '/', '[', or ']'`, methodName, + /* hasConverter= */ false, + /* path= */ undefined, targetDoc); + } + try { + return new FieldPath(...path.split('.'))._internalPath; + } + catch (e) { + throw createError(`Invalid field path (${path}). Paths must not be empty, ` + + `begin with '.', end with '.', or contain '..'`, methodName, + /* hasConverter= */ false, + /* path= */ undefined, targetDoc); + } +} +function createError(reason, methodName, hasConverter, path, targetDoc) { + const hasPath = path && !path.isEmpty(); + const hasDocument = targetDoc !== undefined; + let message = `Function ${methodName}() called with invalid data`; + if (hasConverter) { + message += ' (via `toFirestore()`)'; + } + message += '. '; + let description = ''; + if (hasPath || hasDocument) { + description += ' (found'; + if (hasPath) { + description += ` in field ${path}`; + } + if (hasDocument) { + description += ` in document ${targetDoc}`; + } + description += ')'; + } + return new FirestoreError(Code.INVALID_ARGUMENT, message + reason + description); +} +/** Checks `haystack` if FieldPath `needle` is present. Runs in O(n). */ +function fieldMaskContains(haystack, needle) { + return haystack.some(v => v.isEqual(needle)); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A `DocumentSnapshot` contains data read from a document in your Firestore + * database. The data can be extracted with `.data()` or `.get()` to + * get a specific field. + * + * For a `DocumentSnapshot` that points to a non-existing document, any data + * access will return 'undefined'. You can use the `exists()` method to + * explicitly verify a document's existence. + */ +class DocumentSnapshot { + // Note: This class is stripped down version of the DocumentSnapshot in + // the legacy SDK. The changes are: + // - No support for SnapshotMetadata. + // - No support for SnapshotOptions. + /** @hideconstructor protected */ + constructor(_firestore, _userDataWriter, _key, _document, _converter) { + this._firestore = _firestore; + this._userDataWriter = _userDataWriter; + this._key = _key; + this._document = _document; + this._converter = _converter; + } + /** Property of the `DocumentSnapshot` that provides the document's ID. */ + get id() { + return this._key.path.lastSegment(); + } + /** + * The `DocumentReference` for the document included in the `DocumentSnapshot`. + */ + get ref() { + return new DocumentReference(this._firestore, this._converter, this._key); + } + /** + * Signals whether or not the document at the snapshot's location exists. + * + * @returns true if the document exists. + */ + exists() { + return this._document !== null; + } + /** + * Retrieves all fields in the document as an `Object`. Returns `undefined` if + * the document doesn't exist. + * + * @returns An `Object` containing all fields in the document or `undefined` + * if the document doesn't exist. + */ + data() { + if (!this._document) { + return undefined; + } + else if (this._converter) { + // We only want to use the converter and create a new DocumentSnapshot + // if a converter has been provided. + const snapshot = new QueryDocumentSnapshot(this._firestore, this._userDataWriter, this._key, this._document, + /* converter= */ null); + return this._converter.fromFirestore(snapshot); + } + else { + return this._userDataWriter.convertValue(this._document.data.value); + } + } + /** + * Retrieves the field specified by `fieldPath`. Returns `undefined` if the + * document or field doesn't exist. + * + * @param fieldPath - The path (for example 'foo' or 'foo.bar') to a specific + * field. + * @returns The data at the specified field location or undefined if no such + * field exists in the document. + */ + // We are using `any` here to avoid an explicit cast by our users. + // eslint-disable-next-line @typescript-eslint/no-explicit-any + get(fieldPath) { + if (this._document) { + const value = this._document.data.field(fieldPathFromArgument('DocumentSnapshot.get', fieldPath)); + if (value !== null) { + return this._userDataWriter.convertValue(value); + } + } + return undefined; + } +} +/** + * A `QueryDocumentSnapshot` contains data read from a document in your + * Firestore database as part of a query. The document is guaranteed to exist + * and its data can be extracted with `.data()` or `.get()` to get a + * specific field. + * + * A `QueryDocumentSnapshot` offers the same API surface as a + * `DocumentSnapshot`. Since query results contain only existing documents, the + * `exists` property will always be true and `data()` will never return + * 'undefined'. + */ +class QueryDocumentSnapshot extends DocumentSnapshot { + /** + * Retrieves all fields in the document as an `Object`. + * + * @override + * @returns An `Object` containing all fields in the document. + */ + data() { + return super.data(); + } +} +/** + * A `QuerySnapshot` contains zero or more `DocumentSnapshot` objects + * representing the results of a query. The documents can be accessed as an + * array via the `docs` property or enumerated using the `forEach` method. The + * number of documents can be determined via the `empty` and `size` + * properties. + */ +class QuerySnapshot { + /** @hideconstructor */ + constructor(_query, _docs) { + this._docs = _docs; + this.query = _query; + } + /** An array of all the documents in the `QuerySnapshot`. */ + get docs() { + return [...this._docs]; + } + /** The number of documents in the `QuerySnapshot`. */ + get size() { + return this.docs.length; + } + /** True if there are no documents in the `QuerySnapshot`. */ + get empty() { + return this.docs.length === 0; + } + /** + * Enumerates all of the documents in the `QuerySnapshot`. + * + * @param callback - A callback to be called with a `QueryDocumentSnapshot` for + * each document in the snapshot. + * @param thisArg - The `this` binding for the callback. + */ + forEach(callback, thisArg) { + this._docs.forEach(callback, thisArg); + } +} +/** + * Returns true if the provided snapshots are equal. + * + * @param left - A snapshot to compare. + * @param right - A snapshot to compare. + * @returns true if the snapshots are equal. + */ +function snapshotEqual(left, right) { + left = util.getModularInstance(left); + right = util.getModularInstance(right); + if (left instanceof DocumentSnapshot && right instanceof DocumentSnapshot) { + return (left._firestore === right._firestore && + left._key.isEqual(right._key) && + (left._document === null + ? right._document === null + : left._document.isEqual(right._document)) && + left._converter === right._converter); + } + else if (left instanceof QuerySnapshot && right instanceof QuerySnapshot) { + return (queryEqual(left.query, right.query) && + arrayEquals(left.docs, right.docs, snapshotEqual)); + } + return false; +} +/** + * Helper that calls `fromDotSeparatedString()` but wraps any error thrown. + */ +function fieldPathFromArgument(methodName, arg) { + if (typeof arg === 'string') { + return fieldPathFromDotSeparatedString(methodName, arg); + } + else if (arg instanceof FieldPath) { + return arg._internalPath; + } + else { + return arg._delegate._internalPath; + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +function validateHasExplicitOrderByForLimitToLast(query) { + if (query.limitType === "L" /* LimitType.Last */ && + query.explicitOrderBy.length === 0) { + throw new FirestoreError(Code.UNIMPLEMENTED, 'limitToLast() queries require specifying at least one orderBy() clause'); + } +} +/** + * An `AppliableConstraint` is an abstraction of a constraint that can be applied + * to a Firestore query. + */ +class AppliableConstraint { +} +/** + * A `QueryConstraint` is used to narrow the set of documents returned by a + * Firestore query. `QueryConstraint`s are created by invoking {@link where}, + * {@link orderBy}, {@link (startAt:1)}, {@link (startAfter:1)}, {@link + * (endBefore:1)}, {@link (endAt:1)}, {@link limit}, {@link limitToLast} and + * can then be passed to {@link (query:1)} to create a new query instance that + * also contains this `QueryConstraint`. + */ +class QueryConstraint extends AppliableConstraint { +} +function query(query, queryConstraint, ...additionalQueryConstraints) { + let queryConstraints = []; + if (queryConstraint instanceof AppliableConstraint) { + queryConstraints.push(queryConstraint); + } + queryConstraints = queryConstraints.concat(additionalQueryConstraints); + validateQueryConstraintArray(queryConstraints); + for (const constraint of queryConstraints) { + query = constraint._apply(query); + } + return query; +} +/** + * A `QueryFieldFilterConstraint` is used to narrow the set of documents returned by + * a Firestore query by filtering on one or more document fields. + * `QueryFieldFilterConstraint`s are created by invoking {@link where} and can then + * be passed to {@link (query:1)} to create a new query instance that also contains + * this `QueryFieldFilterConstraint`. + */ +class QueryFieldFilterConstraint extends QueryConstraint { + /** + * @internal + */ + constructor(_field, _op, _value) { + super(); + this._field = _field; + this._op = _op; + this._value = _value; + /** The type of this query constraint */ + this.type = 'where'; + } + static _create(_field, _op, _value) { + return new QueryFieldFilterConstraint(_field, _op, _value); + } + _apply(query) { + const filter = this._parse(query); + validateNewFieldFilter(query._query, filter); + return new Query(query.firestore, query.converter, queryWithAddedFilter(query._query, filter)); + } + _parse(query) { + const reader = newUserDataReader(query.firestore); + const filter = newQueryFilter(query._query, 'where', reader, query.firestore._databaseId, this._field, this._op, this._value); + return filter; + } +} +/** + * Creates a {@link QueryFieldFilterConstraint} that enforces that documents + * must contain the specified field and that the value should satisfy the + * relation constraint provided. + * + * @param fieldPath - The path to compare + * @param opStr - The operation string (e.g "<", "<=", "==", "<", + * "<=", "!="). + * @param value - The value for comparison + * @returns The created {@link QueryFieldFilterConstraint}. + */ +function where(fieldPath, opStr, value) { + const op = opStr; + const field = fieldPathFromArgument('where', fieldPath); + return QueryFieldFilterConstraint._create(field, op, value); +} +/** + * A `QueryCompositeFilterConstraint` is used to narrow the set of documents + * returned by a Firestore query by performing the logical OR or AND of multiple + * {@link QueryFieldFilterConstraint}s or {@link QueryCompositeFilterConstraint}s. + * `QueryCompositeFilterConstraint`s are created by invoking {@link or} or + * {@link and} and can then be passed to {@link (query:1)} to create a new query + * instance that also contains the `QueryCompositeFilterConstraint`. + */ +class QueryCompositeFilterConstraint extends AppliableConstraint { + /** + * @internal + */ + constructor( + /** The type of this query constraint */ + type, _queryConstraints) { + super(); + this.type = type; + this._queryConstraints = _queryConstraints; + } + static _create(type, _queryConstraints) { + return new QueryCompositeFilterConstraint(type, _queryConstraints); + } + _parse(query) { + const parsedFilters = this._queryConstraints + .map(queryConstraint => { + return queryConstraint._parse(query); + }) + .filter(parsedFilter => parsedFilter.getFilters().length > 0); + if (parsedFilters.length === 1) { + return parsedFilters[0]; + } + return CompositeFilter.create(parsedFilters, this._getOperator()); + } + _apply(query) { + const parsedFilter = this._parse(query); + if (parsedFilter.getFilters().length === 0) { + // Return the existing query if not adding any more filters (e.g. an empty + // composite filter). + return query; + } + validateNewFilter(query._query, parsedFilter); + return new Query(query.firestore, query.converter, queryWithAddedFilter(query._query, parsedFilter)); + } + _getQueryConstraints() { + return this._queryConstraints; + } + _getOperator() { + return this.type === 'and' ? "and" /* CompositeOperator.AND */ : "or" /* CompositeOperator.OR */; + } +} +/** + * Creates a new {@link QueryCompositeFilterConstraint} that is a disjunction of + * the given filter constraints. A disjunction filter includes a document if it + * satisfies any of the given filters. + * + * @param queryConstraints - Optional. The list of + * {@link QueryFilterConstraint}s to perform a disjunction for. These must be + * created with calls to {@link where}, {@link or}, or {@link and}. + * @returns The newly created {@link QueryCompositeFilterConstraint}. + */ +function or(...queryConstraints) { + // Only support QueryFilterConstraints + queryConstraints.forEach(queryConstraint => validateQueryFilterConstraint('or', queryConstraint)); + return QueryCompositeFilterConstraint._create("or" /* CompositeOperator.OR */, queryConstraints); +} +/** + * Creates a new {@link QueryCompositeFilterConstraint} that is a conjunction of + * the given filter constraints. A conjunction filter includes a document if it + * satisfies all of the given filters. + * + * @param queryConstraints - Optional. The list of + * {@link QueryFilterConstraint}s to perform a conjunction for. These must be + * created with calls to {@link where}, {@link or}, or {@link and}. + * @returns The newly created {@link QueryCompositeFilterConstraint}. + */ +function and(...queryConstraints) { + // Only support QueryFilterConstraints + queryConstraints.forEach(queryConstraint => validateQueryFilterConstraint('and', queryConstraint)); + return QueryCompositeFilterConstraint._create("and" /* CompositeOperator.AND */, queryConstraints); +} +/** + * A `QueryOrderByConstraint` is used to sort the set of documents returned by a + * Firestore query. `QueryOrderByConstraint`s are created by invoking + * {@link orderBy} and can then be passed to {@link (query:1)} to create a new query + * instance that also contains this `QueryOrderByConstraint`. + * + * Note: Documents that do not contain the orderBy field will not be present in + * the query result. + */ +class QueryOrderByConstraint extends QueryConstraint { + /** + * @internal + */ + constructor(_field, _direction) { + super(); + this._field = _field; + this._direction = _direction; + /** The type of this query constraint */ + this.type = 'orderBy'; + } + static _create(_field, _direction) { + return new QueryOrderByConstraint(_field, _direction); + } + _apply(query) { + const orderBy = newQueryOrderBy(query._query, this._field, this._direction); + return new Query(query.firestore, query.converter, queryWithAddedOrderBy(query._query, orderBy)); + } +} +/** + * Creates a {@link QueryOrderByConstraint} that sorts the query result by the + * specified field, optionally in descending order instead of ascending. + * + * Note: Documents that do not contain the specified field will not be present + * in the query result. + * + * @param fieldPath - The field to sort by. + * @param directionStr - Optional direction to sort by ('asc' or 'desc'). If + * not specified, order will be ascending. + * @returns The created {@link QueryOrderByConstraint}. + */ +function orderBy(fieldPath, directionStr = 'asc') { + const direction = directionStr; + const path = fieldPathFromArgument('orderBy', fieldPath); + return QueryOrderByConstraint._create(path, direction); +} +/** + * A `QueryLimitConstraint` is used to limit the number of documents returned by + * a Firestore query. + * `QueryLimitConstraint`s are created by invoking {@link limit} or + * {@link limitToLast} and can then be passed to {@link (query:1)} to create a new + * query instance that also contains this `QueryLimitConstraint`. + */ +class QueryLimitConstraint extends QueryConstraint { + /** + * @internal + */ + constructor( + /** The type of this query constraint */ + type, _limit, _limitType) { + super(); + this.type = type; + this._limit = _limit; + this._limitType = _limitType; + } + static _create(type, _limit, _limitType) { + return new QueryLimitConstraint(type, _limit, _limitType); + } + _apply(query) { + return new Query(query.firestore, query.converter, queryWithLimit(query._query, this._limit, this._limitType)); + } +} +/** + * Creates a {@link QueryLimitConstraint} that only returns the first matching + * documents. + * + * @param limit - The maximum number of items to return. + * @returns The created {@link QueryLimitConstraint}. + */ +function limit(limit) { + validatePositiveNumber('limit', limit); + return QueryLimitConstraint._create('limit', limit, "F" /* LimitType.First */); +} +/** + * Creates a {@link QueryLimitConstraint} that only returns the last matching + * documents. + * + * You must specify at least one `orderBy` clause for `limitToLast` queries, + * otherwise an exception will be thrown during execution. + * + * @param limit - The maximum number of items to return. + * @returns The created {@link QueryLimitConstraint}. + */ +function limitToLast(limit) { + validatePositiveNumber('limitToLast', limit); + return QueryLimitConstraint._create('limitToLast', limit, "L" /* LimitType.Last */); +} +/** + * A `QueryStartAtConstraint` is used to exclude documents from the start of a + * result set returned by a Firestore query. + * `QueryStartAtConstraint`s are created by invoking {@link (startAt:1)} or + * {@link (startAfter:1)} and can then be passed to {@link (query:1)} to create a + * new query instance that also contains this `QueryStartAtConstraint`. + */ +class QueryStartAtConstraint extends QueryConstraint { + /** + * @internal + */ + constructor( + /** The type of this query constraint */ + type, _docOrFields, _inclusive) { + super(); + this.type = type; + this._docOrFields = _docOrFields; + this._inclusive = _inclusive; + } + static _create(type, _docOrFields, _inclusive) { + return new QueryStartAtConstraint(type, _docOrFields, _inclusive); + } + _apply(query) { + const bound = newQueryBoundFromDocOrFields(query, this.type, this._docOrFields, this._inclusive); + return new Query(query.firestore, query.converter, queryWithStartAt(query._query, bound)); + } +} +function startAt(...docOrFields) { + return QueryStartAtConstraint._create('startAt', docOrFields, + /*inclusive=*/ true); +} +function startAfter(...docOrFields) { + return QueryStartAtConstraint._create('startAfter', docOrFields, + /*inclusive=*/ false); +} +/** + * A `QueryEndAtConstraint` is used to exclude documents from the end of a + * result set returned by a Firestore query. + * `QueryEndAtConstraint`s are created by invoking {@link (endAt:1)} or + * {@link (endBefore:1)} and can then be passed to {@link (query:1)} to create a new + * query instance that also contains this `QueryEndAtConstraint`. + */ +class QueryEndAtConstraint extends QueryConstraint { + /** + * @internal + */ + constructor( + /** The type of this query constraint */ + type, _docOrFields, _inclusive) { + super(); + this.type = type; + this._docOrFields = _docOrFields; + this._inclusive = _inclusive; + } + static _create(type, _docOrFields, _inclusive) { + return new QueryEndAtConstraint(type, _docOrFields, _inclusive); + } + _apply(query) { + const bound = newQueryBoundFromDocOrFields(query, this.type, this._docOrFields, this._inclusive); + return new Query(query.firestore, query.converter, queryWithEndAt(query._query, bound)); + } +} +function endBefore(...docOrFields) { + return QueryEndAtConstraint._create('endBefore', docOrFields, + /*inclusive=*/ false); +} +function endAt(...docOrFields) { + return QueryEndAtConstraint._create('endAt', docOrFields, + /*inclusive=*/ true); +} +/** Helper function to create a bound from a document or fields */ +function newQueryBoundFromDocOrFields(query, methodName, docOrFields, inclusive) { + docOrFields[0] = util.getModularInstance(docOrFields[0]); + if (docOrFields[0] instanceof DocumentSnapshot) { + return newQueryBoundFromDocument(query._query, query.firestore._databaseId, methodName, docOrFields[0]._document, inclusive); + } + else { + const reader = newUserDataReader(query.firestore); + return newQueryBoundFromFields(query._query, query.firestore._databaseId, reader, methodName, docOrFields, inclusive); + } +} +function newQueryFilter(query, methodName, dataReader, databaseId, fieldPath, op, value) { + let fieldValue; + if (fieldPath.isKeyField()) { + if (op === "array-contains" /* Operator.ARRAY_CONTAINS */ || op === "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid Query. You can't perform '${op}' queries on documentId().`); + } + else if (op === "in" /* Operator.IN */ || op === "not-in" /* Operator.NOT_IN */) { + validateDisjunctiveFilterElements(value, op); + const referenceList = []; + for (const arrayValue of value) { + referenceList.push(parseDocumentIdValue(databaseId, query, arrayValue)); + } + fieldValue = { arrayValue: { values: referenceList } }; + } + else { + fieldValue = parseDocumentIdValue(databaseId, query, value); + } + } + else { + if (op === "in" /* Operator.IN */ || + op === "not-in" /* Operator.NOT_IN */ || + op === "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */) { + validateDisjunctiveFilterElements(value, op); + } + fieldValue = parseQueryValue(dataReader, methodName, value, + /* allowArrays= */ op === "in" /* Operator.IN */ || op === "not-in" /* Operator.NOT_IN */); + } + const filter = FieldFilter.create(fieldPath, op, fieldValue); + return filter; +} +function newQueryOrderBy(query, fieldPath, direction) { + if (query.startAt !== null) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid query. You must not call startAt() or startAfter() before ' + + 'calling orderBy().'); + } + if (query.endAt !== null) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid query. You must not call endAt() or endBefore() before ' + + 'calling orderBy().'); + } + const orderBy = new OrderBy(fieldPath, direction); + return orderBy; +} +/** + * Create a `Bound` from a query and a document. + * + * Note that the `Bound` will always include the key of the document + * and so only the provided document will compare equal to the returned + * position. + * + * Will throw if the document does not contain all fields of the order by + * of the query or if any of the fields in the order by are an uncommitted + * server timestamp. + */ +function newQueryBoundFromDocument(query, databaseId, methodName, doc, inclusive) { + if (!doc) { + throw new FirestoreError(Code.NOT_FOUND, `Can't use a DocumentSnapshot that doesn't exist for ` + + `${methodName}().`); + } + const components = []; + // Because people expect to continue/end a query at the exact document + // provided, we need to use the implicit sort order rather than the explicit + // sort order, because it's guaranteed to contain the document key. That way + // the position becomes unambiguous and the query continues/ends exactly at + // the provided document. Without the key (by using the explicit sort + // orders), multiple documents could match the position, yielding duplicate + // results. + for (const orderBy of queryNormalizedOrderBy(query)) { + if (orderBy.field.isKeyField()) { + components.push(refValue(databaseId, doc.key)); + } + else { + const value = doc.data.field(orderBy.field); + if (isServerTimestamp(value)) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid query. You are trying to start or end a query using a ' + + 'document for which the field "' + + orderBy.field + + '" is an uncommitted server timestamp. (Since the value of ' + + 'this field is unknown, you cannot start/end a query with it.)'); + } + else if (value !== null) { + components.push(value); + } + else { + const field = orderBy.field.canonicalString(); + throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid query. You are trying to start or end a query using a ` + + `document for which the field '${field}' (used as the ` + + `orderBy) does not exist.`); + } + } + } + return new Bound(components, inclusive); +} +/** + * Converts a list of field values to a `Bound` for the given query. + */ +function newQueryBoundFromFields(query, databaseId, dataReader, methodName, values, inclusive) { + // Use explicit order by's because it has to match the query the user made + const orderBy = query.explicitOrderBy; + if (values.length > orderBy.length) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `Too many arguments provided to ${methodName}(). ` + + `The number of arguments must be less than or equal to the ` + + `number of orderBy() clauses`); + } + const components = []; + for (let i = 0; i < values.length; i++) { + const rawValue = values[i]; + const orderByComponent = orderBy[i]; + if (orderByComponent.field.isKeyField()) { + if (typeof rawValue !== 'string') { + throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid query. Expected a string for document ID in ` + + `${methodName}(), but got a ${typeof rawValue}`); + } + if (!isCollectionGroupQuery(query) && rawValue.indexOf('/') !== -1) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid query. When querying a collection and ordering by documentId(), ` + + `the value passed to ${methodName}() must be a plain document ID, but ` + + `'${rawValue}' contains a slash.`); + } + const path = query.path.child(ResourcePath.fromString(rawValue)); + if (!DocumentKey.isDocumentKey(path)) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid query. When querying a collection group and ordering by ` + + `documentId(), the value passed to ${methodName}() must result in a ` + + `valid document path, but '${path}' is not because it contains an odd number ` + + `of segments.`); + } + const key = new DocumentKey(path); + components.push(refValue(databaseId, key)); + } + else { + const wrapped = parseQueryValue(dataReader, methodName, rawValue); + components.push(wrapped); + } + } + return new Bound(components, inclusive); +} +/** + * Parses the given `documentIdValue` into a `ReferenceValue`, throwing + * appropriate errors if the value is anything other than a `DocumentReference` + * or `string`, or if the string is malformed. + */ +function parseDocumentIdValue(databaseId, query, documentIdValue) { + documentIdValue = util.getModularInstance(documentIdValue); + if (typeof documentIdValue === 'string') { + if (documentIdValue === '') { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid query. When querying with documentId(), you ' + + 'must provide a valid document ID, but it was an empty string.'); + } + if (!isCollectionGroupQuery(query) && documentIdValue.indexOf('/') !== -1) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid query. When querying a collection by ` + + `documentId(), you must provide a plain document ID, but ` + + `'${documentIdValue}' contains a '/' character.`); + } + const path = query.path.child(ResourcePath.fromString(documentIdValue)); + if (!DocumentKey.isDocumentKey(path)) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid query. When querying a collection group by ` + + `documentId(), the value provided must result in a valid document path, ` + + `but '${path}' is not because it has an odd number of segments (${path.length}).`); + } + return refValue(databaseId, new DocumentKey(path)); + } + else if (documentIdValue instanceof DocumentReference) { + return refValue(databaseId, documentIdValue._key); + } + else { + throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid query. When querying with documentId(), you must provide a valid ` + + `string or a DocumentReference, but it was: ` + + `${valueDescription(documentIdValue)}.`); + } +} +/** + * Validates that the value passed into a disjunctive filter satisfies all + * array requirements. + */ +function validateDisjunctiveFilterElements(value, operator) { + if (!Array.isArray(value) || value.length === 0) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid Query. A non-empty array is required for ' + + `'${operator.toString()}' filters.`); + } +} +/** + * Given an operator, returns the set of operators that cannot be used with it. + * + * This is not a comprehensive check, and this function should be removed in the + * long term. Validations should occur in the Firestore backend. + * + * Operators in a query must adhere to the following set of rules: + * 1. Only one inequality per query. + * 2. `NOT_IN` cannot be used with array, disjunctive, or `NOT_EQUAL` operators. + */ +function conflictingOps(op) { + switch (op) { + case "!=" /* Operator.NOT_EQUAL */: + return ["!=" /* Operator.NOT_EQUAL */, "not-in" /* Operator.NOT_IN */]; + case "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */: + case "in" /* Operator.IN */: + return ["not-in" /* Operator.NOT_IN */]; + case "not-in" /* Operator.NOT_IN */: + return [ + "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */, + "in" /* Operator.IN */, + "not-in" /* Operator.NOT_IN */, + "!=" /* Operator.NOT_EQUAL */ + ]; + default: + return []; + } +} +function validateNewFieldFilter(query, fieldFilter) { + const conflictingOp = findOpInsideFilters(query.filters, conflictingOps(fieldFilter.op)); + if (conflictingOp !== null) { + // Special case when it's a duplicate op to give a slightly clearer error message. + if (conflictingOp === fieldFilter.op) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid query. You cannot use more than one ' + + `'${fieldFilter.op.toString()}' filter.`); + } + else { + throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid query. You cannot use '${fieldFilter.op.toString()}' filters ` + + `with '${conflictingOp.toString()}' filters.`); + } + } +} +function validateNewFilter(query, filter) { + let testQuery = query; + const subFilters = filter.getFlattenedFilters(); + for (const subFilter of subFilters) { + validateNewFieldFilter(testQuery, subFilter); + testQuery = queryWithAddedFilter(testQuery, subFilter); + } +} +// Checks if any of the provided filter operators are included in the given list of filters and +// returns the first one that is, or null if none are. +function findOpInsideFilters(filters, operators) { + for (const filter of filters) { + for (const fieldFilter of filter.getFlattenedFilters()) { + if (operators.indexOf(fieldFilter.op) >= 0) { + return fieldFilter.op; + } + } + } + return null; +} +function validateQueryFilterConstraint(functionName, queryConstraint) { + if (!(queryConstraint instanceof QueryFieldFilterConstraint) && + !(queryConstraint instanceof QueryCompositeFilterConstraint)) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `Function ${functionName}() requires AppliableConstraints created with a call to 'where(...)', 'or(...)', or 'and(...)'.`); + } +} +function validateQueryConstraintArray(queryConstraint) { + const compositeFilterCount = queryConstraint.filter(filter => filter instanceof QueryCompositeFilterConstraint).length; + const fieldFilterCount = queryConstraint.filter(filter => filter instanceof QueryFieldFilterConstraint).length; + if (compositeFilterCount > 1 || + (compositeFilterCount > 0 && fieldFilterCount > 0)) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'InvalidQuery. When using composite filters, you cannot use ' + + 'more than one filter at the top level. Consider nesting the multiple ' + + 'filters within an `and(...)` statement. For example: ' + + 'change `query(query, where(...), or(...))` to ' + + '`query(query, and(where(...), or(...)))`.'); + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Converts Firestore's internal types to the JavaScript types that we expose + * to the user. + * + * @internal + */ +class AbstractUserDataWriter { + convertValue(value, serverTimestampBehavior = 'none') { + switch (typeOrder(value)) { + case 0 /* TypeOrder.NullValue */: + return null; + case 1 /* TypeOrder.BooleanValue */: + return value.booleanValue; + case 2 /* TypeOrder.NumberValue */: + return normalizeNumber(value.integerValue || value.doubleValue); + case 3 /* TypeOrder.TimestampValue */: + return this.convertTimestamp(value.timestampValue); + case 4 /* TypeOrder.ServerTimestampValue */: + return this.convertServerTimestamp(value, serverTimestampBehavior); + case 5 /* TypeOrder.StringValue */: + return value.stringValue; + case 6 /* TypeOrder.BlobValue */: + return this.convertBytes(normalizeByteString(value.bytesValue)); + case 7 /* TypeOrder.RefValue */: + return this.convertReference(value.referenceValue); + case 8 /* TypeOrder.GeoPointValue */: + return this.convertGeoPoint(value.geoPointValue); + case 9 /* TypeOrder.ArrayValue */: + return this.convertArray(value.arrayValue, serverTimestampBehavior); + case 11 /* TypeOrder.ObjectValue */: + return this.convertObject(value.mapValue, serverTimestampBehavior); + case 10 /* TypeOrder.VectorValue */: + return this.convertVectorValue(value.mapValue); + default: + throw fail(0xf2a2, { + value + }); + } + } + convertObject(mapValue, serverTimestampBehavior) { + return this.convertObjectMap(mapValue.fields, serverTimestampBehavior); + } + /** + * @internal + */ + convertObjectMap(fields, serverTimestampBehavior = 'none') { + const result = {}; + forEach(fields, (key, value) => { + result[key] = this.convertValue(value, serverTimestampBehavior); + }); + return result; + } + /** + * @internal + */ + convertVectorValue(mapValue) { + const values = mapValue.fields?.[VECTOR_MAP_VECTORS_KEY].arrayValue?.values?.map(value => { + return normalizeNumber(value.doubleValue); + }); + return new VectorValue(values); + } + convertGeoPoint(value) { + return new GeoPoint(normalizeNumber(value.latitude), normalizeNumber(value.longitude)); + } + convertArray(arrayValue, serverTimestampBehavior) { + return (arrayValue.values || []).map(value => this.convertValue(value, serverTimestampBehavior)); + } + convertServerTimestamp(value, serverTimestampBehavior) { + switch (serverTimestampBehavior) { + case 'previous': + const previousValue = getPreviousValue(value); + if (previousValue == null) { + return null; + } + return this.convertValue(previousValue, serverTimestampBehavior); + case 'estimate': + return this.convertTimestamp(getLocalWriteTime(value)); + default: + return null; + } + } + convertTimestamp(value) { + const normalizedValue = normalizeTimestamp(value); + return new Timestamp(normalizedValue.seconds, normalizedValue.nanos); + } + convertDocumentKey(name, expectedDatabaseId) { + const resourcePath = ResourcePath.fromString(name); + hardAssert(isValidResourceName(resourcePath), 0x25d8, { name }); + const databaseId = new DatabaseId(resourcePath.get(1), resourcePath.get(3)); + const key = new DocumentKey(resourcePath.popFirst(5)); + if (!databaseId.isEqual(expectedDatabaseId)) { + // TODO(b/64130202): Somehow support foreign references. + logError(`Document ${key} contains a document ` + + `reference within a different database (` + + `${databaseId.projectId}/${databaseId.database}) which is not ` + + `supported. It will be treated as a reference in the current ` + + `database (${expectedDatabaseId.projectId}/${expectedDatabaseId.database}) ` + + `instead.`); + } + return key; + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Converts custom model object of type T into `DocumentData` by applying the + * converter if it exists. + * + * This function is used when converting user objects to `DocumentData` + * because we want to provide the user with a more specific error message if + * their `set()` or fails due to invalid data originating from a `toFirestore()` + * call. + */ +function applyFirestoreDataConverter(converter, value, options) { + let convertedValue; + if (converter) { + if (options && (options.merge || options.mergeFields)) { + // Cast to `any` in order to satisfy the union type constraint on + // toFirestore(). + // eslint-disable-next-line @typescript-eslint/no-explicit-any + convertedValue = converter.toFirestore(value, options); + } + else { + convertedValue = converter.toFirestore(value); + } + } + else { + convertedValue = value; + } + return convertedValue; +} +class LiteUserDataWriter extends AbstractUserDataWriter { + constructor(firestore) { + super(); + this.firestore = firestore; + } + convertBytes(bytes) { + return new Bytes(bytes); + } + convertReference(name) { + const key = this.convertDocumentKey(name, this.firestore._databaseId); + return new DocumentReference(this.firestore, /* converter= */ null, key); + } +} +/** + * Reads the document referred to by the specified document reference. + * + * All documents are directly fetched from the server, even if the document was + * previously read or modified. Recent modifications are only reflected in the + * retrieved `DocumentSnapshot` if they have already been applied by the + * backend. If the client is offline, the read fails. If you like to use + * caching or see local modifications, please use the full Firestore SDK. + * + * @param reference - The reference of the document to fetch. + * @returns A Promise resolved with a `DocumentSnapshot` containing the current + * document contents. + */ +function getDoc(reference) { + reference = cast(reference, DocumentReference); + const datastore = getDatastore(reference.firestore); + const userDataWriter = new LiteUserDataWriter(reference.firestore); + return invokeBatchGetDocumentsRpc(datastore, [reference._key]).then(result => { + hardAssert(result.length === 1, 0x3d02); + const document = result[0]; + return new DocumentSnapshot(reference.firestore, userDataWriter, reference._key, document.isFoundDocument() ? document : null, reference.converter); + }); +} +/** + * Executes the query and returns the results as a {@link QuerySnapshot}. + * + * All queries are executed directly by the server, even if the query was + * previously executed. Recent modifications are only reflected in the retrieved + * results if they have already been applied by the backend. If the client is + * offline, the operation fails. To see previously cached result and local + * modifications, use the full Firestore SDK. + * + * @param query - The `Query` to execute. + * @returns A Promise that will be resolved with the results of the query. + */ +function getDocs(query) { + query = cast(query, Query); + validateHasExplicitOrderByForLimitToLast(query._query); + const datastore = getDatastore(query.firestore); + const userDataWriter = new LiteUserDataWriter(query.firestore); + return invokeRunQueryRpc(datastore, query._query).then(result => { + const docs = result.map(doc => new QueryDocumentSnapshot(query.firestore, userDataWriter, doc.key, doc, query.converter)); + if (query._query.limitType === "L" /* LimitType.Last */) { + // Limit to last queries reverse the orderBy constraint that was + // specified by the user. As such, we need to reverse the order of the + // results to return the documents in the expected order. + docs.reverse(); + } + return new QuerySnapshot(query, docs); + }); +} +function setDoc(reference, data, options) { + reference = cast(reference, DocumentReference); + const convertedValue = applyFirestoreDataConverter(reference.converter, data, options); + const dataReader = newUserDataReader(reference.firestore); + const parsed = parseSetData(dataReader, 'setDoc', reference._key, convertedValue, reference.converter !== null, options); + const datastore = getDatastore(reference.firestore); + return invokeCommitRpc(datastore, [ + parsed.toMutation(reference._key, Precondition.none()) + ]); +} +function updateDoc(reference, fieldOrUpdateData, value, ...moreFieldsAndValues) { + reference = cast(reference, DocumentReference); + const dataReader = newUserDataReader(reference.firestore); + // For Compat types, we have to "extract" the underlying types before + // performing validation. + fieldOrUpdateData = util.getModularInstance(fieldOrUpdateData); + let parsed; + if (typeof fieldOrUpdateData === 'string' || + fieldOrUpdateData instanceof FieldPath) { + parsed = parseUpdateVarargs(dataReader, 'updateDoc', reference._key, fieldOrUpdateData, value, moreFieldsAndValues); + } + else { + parsed = parseUpdateData(dataReader, 'updateDoc', reference._key, fieldOrUpdateData); + } + const datastore = getDatastore(reference.firestore); + return invokeCommitRpc(datastore, [ + parsed.toMutation(reference._key, Precondition.exists(true)) + ]); +} +/** + * Deletes the document referred to by the specified `DocumentReference`. + * + * The deletion will only be reflected in document reads that occur after the + * returned promise resolves. If the client is offline, the + * delete fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @param reference - A reference to the document to delete. + * @returns A `Promise` resolved once the document has been successfully + * deleted from the backend. + */ +function deleteDoc(reference) { + reference = cast(reference, DocumentReference); + const datastore = getDatastore(reference.firestore); + return invokeCommitRpc(datastore, [ + new DeleteMutation(reference._key, Precondition.none()) + ]); +} +/** + * Add a new document to specified `CollectionReference` with the given data, + * assigning it a document ID automatically. + * + * The result of this write will only be reflected in document reads that occur + * after the returned promise resolves. If the client is offline, the + * write fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @param reference - A reference to the collection to add this document to. + * @param data - An Object containing the data for the new document. + * @throws Error - If the provided input is not a valid Firestore document. + * @returns A `Promise` resolved with a `DocumentReference` pointing to the + * newly created document after it has been written to the backend. + */ +function addDoc(reference, data) { + reference = cast(reference, CollectionReference); + const docRef = doc(reference); + const convertedValue = applyFirestoreDataConverter(reference.converter, data); + const dataReader = newUserDataReader(reference.firestore); + const parsed = parseSetData(dataReader, 'addDoc', docRef._key, convertedValue, docRef.converter !== null, {}); + const datastore = getDatastore(reference.firestore); + return invokeCommitRpc(datastore, [ + parsed.toMutation(docRef._key, Precondition.exists(false)) + ]).then(() => docRef); +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Calculates the number of documents in the result set of the given query + * without actually downloading the documents. + * + * Using this function to count the documents is efficient because only the + * final count, not the documents' data, is downloaded. This function can + * count the documents in cases where the result set is prohibitively large to + * download entirely (thousands of documents). + * + * @param query The query whose result set size is calculated. + * @returns A Promise that will be resolved with the count; the count can be + * retrieved from `snapshot.data().count`, where `snapshot` is the + * `AggregateQuerySnapshot` to which the returned Promise resolves. + */ +function getCount(query) { + const countQuerySpec = { + count: count() + }; + return getAggregate(query, countQuerySpec); +} +/** + * Calculates the specified aggregations over the documents in the result + * set of the given query without actually downloading the documents. + * + * Using this function to perform aggregations is efficient because only the + * final aggregation values, not the documents' data, are downloaded. This + * function can perform aggregations of the documents in cases where the result + * set is prohibitively large to download entirely (thousands of documents). + * + * @param query The query whose result set is aggregated over. + * @param aggregateSpec An `AggregateSpec` object that specifies the aggregates + * to perform over the result set. The AggregateSpec specifies aliases for each + * aggregate, which can be used to retrieve the aggregate result. + * @example + * ```typescript + * const aggregateSnapshot = await getAggregate(query, { + * countOfDocs: count(), + * totalHours: sum('hours'), + * averageScore: average('score') + * }); + * + * const countOfDocs: number = aggregateSnapshot.data().countOfDocs; + * const totalHours: number = aggregateSnapshot.data().totalHours; + * const averageScore: number | null = aggregateSnapshot.data().averageScore; + * ``` + */ +function getAggregate(query, aggregateSpec) { + const firestore = cast(query.firestore, Firestore); + const datastore = getDatastore(firestore); + const internalAggregates = mapToArray(aggregateSpec, (aggregate, alias) => { + return new AggregateImpl(alias, aggregate.aggregateType, aggregate._internalFieldPath); + }); + // Run the aggregation and convert the results + return invokeRunAggregationQueryRpc(datastore, query._query, internalAggregates).then(aggregateResult => convertToAggregateQuerySnapshot(firestore, query, aggregateResult)); +} +function convertToAggregateQuerySnapshot(firestore, query, aggregateResult) { + const userDataWriter = new LiteUserDataWriter(firestore); + const querySnapshot = new AggregateQuerySnapshot(query, userDataWriter, aggregateResult); + return querySnapshot; +} +/** + * Create an AggregateField object that can be used to compute the sum of + * a specified field over a range of documents in the result set of a query. + * @param field Specifies the field to sum across the result set. + */ +function sum(field) { + return new AggregateField('sum', fieldPathFromArgument$1('sum', field)); +} +/** + * Create an AggregateField object that can be used to compute the average of + * a specified field over a range of documents in the result set of a query. + * @param field Specifies the field to average across the result set. + */ +function average(field) { + return new AggregateField('avg', fieldPathFromArgument$1('average', field)); +} +/** + * Create an AggregateField object that can be used to compute the count of + * documents in the result set of a query. + */ +function count() { + return new AggregateField('count'); +} +/** + * Compares two 'AggregateField` instances for equality. + * + * @param left Compare this AggregateField to the `right`. + * @param right Compare this AggregateField to the `left`. + */ +function aggregateFieldEqual(left, right) { + return (left instanceof AggregateField && + right instanceof AggregateField && + left.aggregateType === right.aggregateType && + left._internalFieldPath?.canonicalString() === + right._internalFieldPath?.canonicalString()); +} +/** + * Compares two `AggregateQuerySnapshot` instances for equality. + * + * Two `AggregateQuerySnapshot` instances are considered "equal" if they have + * underlying queries that compare equal, and the same data. + * + * @param left - The first `AggregateQuerySnapshot` to compare. + * @param right - The second `AggregateQuerySnapshot` to compare. + * + * @returns `true` if the objects are "equal", as defined above, or `false` + * otherwise. + */ +function aggregateQuerySnapshotEqual(left, right) { + return (queryEqual(left.query, right.query) && util.deepEqual(left.data(), right.data())); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Returns a sentinel for use with {@link @firebase/firestore/lite#(updateDoc:1)} or + * {@link @firebase/firestore/lite#(setDoc:1)} with `{merge: true}` to mark a field for deletion. + */ +function deleteField() { + return new DeleteFieldValueImpl('deleteField'); +} +/** + * Returns a sentinel used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link @firebase/firestore/lite#(updateDoc:1)} to + * include a server-generated timestamp in the written data. + */ +function serverTimestamp() { + return new ServerTimestampFieldValueImpl('serverTimestamp'); +} +/** + * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link + * @firebase/firestore/lite#(updateDoc:1)} that tells the server to union the given elements with any array + * value that already exists on the server. Each specified element that doesn't + * already exist in the array will be added to the end. If the field being + * modified is not already an array it will be overwritten with an array + * containing exactly the specified elements. + * + * @param elements - The elements to union into the array. + * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or + * `updateDoc()`. + */ +function arrayUnion(...elements) { + // NOTE: We don't actually parse the data until it's used in set() or + // update() since we'd need the Firestore instance to do this. + return new ArrayUnionFieldValueImpl('arrayUnion', elements); +} +/** + * Returns a special value that can be used with {@link (setDoc:1)} or {@link + * updateDoc:1} that tells the server to remove the given elements from any + * array value that already exists on the server. All instances of each element + * specified will be removed from the array. If the field being modified is not + * already an array it will be overwritten with an empty array. + * + * @param elements - The elements to remove from the array. + * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or + * `updateDoc()` + */ +function arrayRemove(...elements) { + // NOTE: We don't actually parse the data until it's used in set() or + // update() since we'd need the Firestore instance to do this. + return new ArrayRemoveFieldValueImpl('arrayRemove', elements); +} +/** + * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link + * @firebase/firestore/lite#(updateDoc:1)} that tells the server to increment the field's current value by + * the given value. + * + * If either the operand or the current field value uses floating point + * precision, all arithmetic follows IEEE 754 semantics. If both values are + * integers, values outside of JavaScript's safe number range + * (`Number.MIN_SAFE_INTEGER` to `Number.MAX_SAFE_INTEGER`) are also subject to + * precision loss. Furthermore, once processed by the Firestore backend, all + * integer operations are capped between -2^63 and 2^63-1. + * + * If the current field value is not of type `number`, or if the field does not + * yet exist, the transformation sets the field to the given value. + * + * @param n - The value to increment by. + * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or + * `updateDoc()` + */ +function increment(n) { + return new NumericIncrementFieldValueImpl('increment', n); +} +/** + * Creates a new `VectorValue` constructed with a copy of the given array of numbers. + * + * @param values - Create a `VectorValue` instance with a copy of this array of numbers. + * + * @returns A new `VectorValue` constructed with a copy of the given array of numbers. + */ +function vector(values) { + return new VectorValue(values); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A write batch, used to perform multiple writes as a single atomic unit. + * + * A `WriteBatch` object can be acquired by calling {@link writeBatch}. It + * provides methods for adding writes to the write batch. None of the writes + * will be committed (or visible locally) until {@link WriteBatch.commit} is + * called. + */ +class WriteBatch { + /** @hideconstructor */ + constructor(_firestore, _commitHandler) { + this._firestore = _firestore; + this._commitHandler = _commitHandler; + this._mutations = []; + this._committed = false; + this._dataReader = newUserDataReader(_firestore); + } + set(documentRef, data, options) { + this._verifyNotCommitted(); + const ref = validateReference(documentRef, this._firestore); + const convertedValue = applyFirestoreDataConverter(ref.converter, data, options); + const parsed = parseSetData(this._dataReader, 'WriteBatch.set', ref._key, convertedValue, ref.converter !== null, options); + this._mutations.push(parsed.toMutation(ref._key, Precondition.none())); + return this; + } + update(documentRef, fieldOrUpdateData, value, ...moreFieldsAndValues) { + this._verifyNotCommitted(); + const ref = validateReference(documentRef, this._firestore); + // For Compat types, we have to "extract" the underlying types before + // performing validation. + fieldOrUpdateData = util.getModularInstance(fieldOrUpdateData); + let parsed; + if (typeof fieldOrUpdateData === 'string' || + fieldOrUpdateData instanceof FieldPath) { + parsed = parseUpdateVarargs(this._dataReader, 'WriteBatch.update', ref._key, fieldOrUpdateData, value, moreFieldsAndValues); + } + else { + parsed = parseUpdateData(this._dataReader, 'WriteBatch.update', ref._key, fieldOrUpdateData); + } + this._mutations.push(parsed.toMutation(ref._key, Precondition.exists(true))); + return this; + } + /** + * Deletes the document referred to by the provided {@link DocumentReference}. + * + * @param documentRef - A reference to the document to be deleted. + * @returns This `WriteBatch` instance. Used for chaining method calls. + */ + delete(documentRef) { + this._verifyNotCommitted(); + const ref = validateReference(documentRef, this._firestore); + this._mutations = this._mutations.concat(new DeleteMutation(ref._key, Precondition.none())); + return this; + } + /** + * Commits all of the writes in this write batch as a single atomic unit. + * + * The result of these writes will only be reflected in document reads that + * occur after the returned promise resolves. If the client is offline, the + * write fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @returns A `Promise` resolved once all of the writes in the batch have been + * successfully written to the backend as an atomic unit (note that it won't + * resolve while you're offline). + */ + commit() { + this._verifyNotCommitted(); + this._committed = true; + if (this._mutations.length > 0) { + return this._commitHandler(this._mutations); + } + return Promise.resolve(); + } + _verifyNotCommitted() { + if (this._committed) { + throw new FirestoreError(Code.FAILED_PRECONDITION, 'A write batch can no longer be used after commit() ' + + 'has been called.'); + } + } +} +function validateReference(documentRef, firestore) { + documentRef = util.getModularInstance(documentRef); + if (documentRef.firestore !== firestore) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Provided document reference is from a different Firestore instance.'); + } + else { + return documentRef; + } +} +/** + * Creates a write batch, used for performing multiple writes as a single + * atomic operation. The maximum number of writes allowed in a single WriteBatch + * is 500. + * + * The result of these writes will only be reflected in document reads that + * occur after the returned promise resolves. If the client is offline, the + * write fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @returns A `WriteBatch` that can be used to atomically execute multiple + * writes. + */ +function writeBatch(firestore) { + firestore = cast(firestore, Firestore); + const datastore = getDatastore(firestore); + return new WriteBatch(firestore, writes => invokeCommitRpc(datastore, writes)); +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const DEFAULT_TRANSACTION_OPTIONS = { + maxAttempts: 5 +}; +function validateTransactionOptions(options) { + if (options.maxAttempts < 1) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Max attempts must be at least 1'); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Internal transaction object responsible for accumulating the mutations to + * perform and the base versions for any documents read. + */ +class Transaction$1 { + constructor(datastore) { + this.datastore = datastore; + // The version of each document that was read during this transaction. + this.readVersions = new Map(); + this.mutations = []; + this.committed = false; + /** + * A deferred usage error that occurred previously in this transaction that + * will cause the transaction to fail once it actually commits. + */ + this.lastTransactionError = null; + /** + * Set of documents that have been written in the transaction. + * + * When there's more than one write to the same key in a transaction, any + * writes after the first are handled differently. + */ + this.writtenDocs = new Set(); + } + async lookup(keys) { + this.ensureCommitNotCalled(); + if (this.mutations.length > 0) { + this.lastTransactionError = new FirestoreError(Code.INVALID_ARGUMENT, 'Firestore transactions require all reads to be executed before all writes.'); + throw this.lastTransactionError; + } + const docs = await invokeBatchGetDocumentsRpc(this.datastore, keys); + docs.forEach(doc => this.recordVersion(doc)); + return docs; + } + set(key, data) { + this.write(data.toMutation(key, this.precondition(key))); + this.writtenDocs.add(key.toString()); + } + update(key, data) { + try { + this.write(data.toMutation(key, this.preconditionForUpdate(key))); + } + catch (e) { + this.lastTransactionError = e; + } + this.writtenDocs.add(key.toString()); + } + delete(key) { + this.write(new DeleteMutation(key, this.precondition(key))); + this.writtenDocs.add(key.toString()); + } + async commit() { + this.ensureCommitNotCalled(); + if (this.lastTransactionError) { + throw this.lastTransactionError; + } + const unwritten = this.readVersions; + // For each mutation, note that the doc was written. + this.mutations.forEach(mutation => { + unwritten.delete(mutation.key.toString()); + }); + // For each document that was read but not written to, we want to perform + // a `verify` operation. + unwritten.forEach((_, path) => { + const key = DocumentKey.fromPath(path); + this.mutations.push(new VerifyMutation(key, this.precondition(key))); + }); + await invokeCommitRpc(this.datastore, this.mutations); + this.committed = true; + } + recordVersion(doc) { + let docVersion; + if (doc.isFoundDocument()) { + docVersion = doc.version; + } + else if (doc.isNoDocument()) { + // Represent a deleted doc using SnapshotVersion.min(). + docVersion = SnapshotVersion.min(); + } + else { + throw fail(0xc542, { + documentName: doc.constructor.name + }); + } + const existingVersion = this.readVersions.get(doc.key.toString()); + if (existingVersion) { + if (!docVersion.isEqual(existingVersion)) { + // This transaction will fail no matter what. + throw new FirestoreError(Code.ABORTED, 'Document version changed between two reads.'); + } + } + else { + this.readVersions.set(doc.key.toString(), docVersion); + } + } + /** + * Returns the version of this document when it was read in this transaction, + * as a precondition, or no precondition if it was not read. + */ + precondition(key) { + const version = this.readVersions.get(key.toString()); + if (!this.writtenDocs.has(key.toString()) && version) { + if (version.isEqual(SnapshotVersion.min())) { + return Precondition.exists(false); + } + else { + return Precondition.updateTime(version); + } + } + else { + return Precondition.none(); + } + } + /** + * Returns the precondition for a document if the operation is an update. + */ + preconditionForUpdate(key) { + const version = this.readVersions.get(key.toString()); + // The first time a document is written, we want to take into account the + // read time and existence + if (!this.writtenDocs.has(key.toString()) && version) { + if (version.isEqual(SnapshotVersion.min())) { + // The document doesn't exist, so fail the transaction. + // This has to be validated locally because you can't send a + // precondition that a document does not exist without changing the + // semantics of the backend write to be an insert. This is the reverse + // of what we want, since we want to assert that the document doesn't + // exist but then send the update and have it fail. Since we can't + // express that to the backend, we have to validate locally. + // Note: this can change once we can send separate verify writes in the + // transaction. + throw new FirestoreError(Code.INVALID_ARGUMENT, "Can't update a document that doesn't exist."); + } + // Document exists, base precondition on document update time. + return Precondition.updateTime(version); + } + else { + // Document was not read, so we just use the preconditions for a blind + // update. + return Precondition.exists(true); + } + } + write(mutation) { + this.ensureCommitNotCalled(); + this.mutations.push(mutation); + } + ensureCommitNotCalled() { + } +} + +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * TransactionRunner encapsulates the logic needed to run and retry transactions + * with backoff. + */ +class TransactionRunner { + constructor(asyncQueue, datastore, options, updateFunction, deferred) { + this.asyncQueue = asyncQueue; + this.datastore = datastore; + this.options = options; + this.updateFunction = updateFunction; + this.deferred = deferred; + this.attemptsRemaining = options.maxAttempts; + this.backoff = new ExponentialBackoff(this.asyncQueue, "transaction_retry" /* TimerId.TransactionRetry */); + } + /** Runs the transaction and sets the result on deferred. */ + run() { + this.attemptsRemaining -= 1; + this.runWithBackOff(); + } + runWithBackOff() { + this.backoff.backoffAndRun(async () => { + const transaction = new Transaction$1(this.datastore); + const userPromise = this.tryRunUpdateFunction(transaction); + if (userPromise) { + userPromise + .then(result => { + this.asyncQueue.enqueueAndForget(() => { + return transaction + .commit() + .then(() => { + this.deferred.resolve(result); + }) + .catch(commitError => { + this.handleTransactionError(commitError); + }); + }); + }) + .catch(userPromiseError => { + this.handleTransactionError(userPromiseError); + }); + } + }); + } + tryRunUpdateFunction(transaction) { + try { + const userPromise = this.updateFunction(transaction); + if (isNullOrUndefined(userPromise) || + !userPromise.catch || + !userPromise.then) { + this.deferred.reject(Error('Transaction callback must return a Promise')); + return null; + } + return userPromise; + } + catch (error) { + // Do not retry errors thrown by user provided updateFunction. + this.deferred.reject(error); + return null; + } + } + handleTransactionError(error) { + if (this.attemptsRemaining > 0 && this.isRetryableTransactionError(error)) { + this.attemptsRemaining -= 1; + this.asyncQueue.enqueueAndForget(() => { + this.runWithBackOff(); + return Promise.resolve(); + }); + } + else { + this.deferred.reject(error); + } + } + isRetryableTransactionError(error) { + if (error?.name === 'FirebaseError') { + // In transactions, the backend will fail outdated reads with FAILED_PRECONDITION and + // non-matching document versions with ABORTED. These errors should be retried. + const code = error.code; + return (code === 'aborted' || + code === 'failed-precondition' || + code === 'already-exists' || + !isPermanentError(code)); + } + return false; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Represents an operation scheduled to be run in the future on an AsyncQueue. + * + * It is created via DelayedOperation.createAndSchedule(). + * + * Supports cancellation (via cancel()) and early execution (via skipDelay()). + * + * Note: We implement `PromiseLike` instead of `Promise`, as the `Promise` type + * in newer versions of TypeScript defines `finally`, which is not available in + * IE. + */ +class DelayedOperation { + constructor(asyncQueue, timerId, targetTimeMs, op, removalCallback) { + this.asyncQueue = asyncQueue; + this.timerId = timerId; + this.targetTimeMs = targetTimeMs; + this.op = op; + this.removalCallback = removalCallback; + this.deferred = new Deferred(); + this.then = this.deferred.promise.then.bind(this.deferred.promise); + // It's normal for the deferred promise to be canceled (due to cancellation) + // and so we attach a dummy catch callback to avoid + // 'UnhandledPromiseRejectionWarning' log spam. + this.deferred.promise.catch(err => { }); + } + get promise() { + return this.deferred.promise; + } + /** + * Creates and returns a DelayedOperation that has been scheduled to be + * executed on the provided asyncQueue after the provided delayMs. + * + * @param asyncQueue - The queue to schedule the operation on. + * @param id - A Timer ID identifying the type of operation this is. + * @param delayMs - The delay (ms) before the operation should be scheduled. + * @param op - The operation to run. + * @param removalCallback - A callback to be called synchronously once the + * operation is executed or canceled, notifying the AsyncQueue to remove it + * from its delayedOperations list. + * PORTING NOTE: This exists to prevent making removeDelayedOperation() and + * the DelayedOperation class public. + */ + static createAndSchedule(asyncQueue, timerId, delayMs, op, removalCallback) { + const targetTime = Date.now() + delayMs; + const delayedOp = new DelayedOperation(asyncQueue, timerId, targetTime, op, removalCallback); + delayedOp.start(delayMs); + return delayedOp; + } + /** + * Starts the timer. This is called immediately after construction by + * createAndSchedule(). + */ + start(delayMs) { + this.timerHandle = setTimeout(() => this.handleDelayElapsed(), delayMs); + } + /** + * Queues the operation to run immediately (if it hasn't already been run or + * canceled). + */ + skipDelay() { + return this.handleDelayElapsed(); + } + /** + * Cancels the operation if it hasn't already been executed or canceled. The + * promise will be rejected. + * + * As long as the operation has not yet been run, calling cancel() provides a + * guarantee that the operation will not be run. + */ + cancel(reason) { + if (this.timerHandle !== null) { + this.clearTimeout(); + this.deferred.reject(new FirestoreError(Code.CANCELLED, 'Operation cancelled' + (reason ? ': ' + reason : ''))); + } + } + handleDelayElapsed() { + this.asyncQueue.enqueueAndForget(() => { + if (this.timerHandle !== null) { + this.clearTimeout(); + return this.op().then(result => { + return this.deferred.resolve(result); + }); + } + else { + return Promise.resolve(); + } + }); + } + clearTimeout() { + if (this.timerHandle !== null) { + this.removalCallback(this); + clearTimeout(this.timerHandle); + this.timerHandle = null; + } + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const LOG_TAG = 'AsyncQueue'; +class AsyncQueueImpl { + constructor(tail = Promise.resolve()) { + // A list of retryable operations. Retryable operations are run in order and + // retried with backoff. + this.retryableOps = []; + // Is this AsyncQueue being shut down? Once it is set to true, it will not + // be changed again. + this._isShuttingDown = false; + // Operations scheduled to be queued in the future. Operations are + // automatically removed after they are run or canceled. + this.delayedOperations = []; + // visible for testing + this.failure = null; + // Flag set while there's an outstanding AsyncQueue operation, used for + // assertion sanity-checks. + this.operationInProgress = false; + // Enabled during shutdown on Safari to prevent future access to IndexedDB. + this.skipNonRestrictedTasks = false; + // List of TimerIds to fast-forward delays for. + this.timerIdsToSkip = []; + // Backoff timer used to schedule retries for retryable operations + this.backoff = new ExponentialBackoff(this, "async_queue_retry" /* TimerId.AsyncQueueRetry */); + // Visibility handler that triggers an immediate retry of all retryable + // operations. Meant to speed up recovery when we regain file system access + // after page comes into foreground. + this.visibilityHandler = () => { + this.backoff.skipBackoff(); + }; + this.tail = tail; + } + get isShuttingDown() { + return this._isShuttingDown; + } + /** + * Adds a new operation to the queue without waiting for it to complete (i.e. + * we ignore the Promise result). + */ + enqueueAndForget(op) { + // eslint-disable-next-line @typescript-eslint/no-floating-promises + this.enqueue(op); + } + enqueueAndForgetEvenWhileRestricted(op) { + this.verifyNotFailed(); + // eslint-disable-next-line @typescript-eslint/no-floating-promises + this.enqueueInternal(op); + } + enterRestrictedMode(purgeExistingTasks) { + if (!this._isShuttingDown) { + this._isShuttingDown = true; + this.skipNonRestrictedTasks = purgeExistingTasks || false; + } + } + enqueue(op) { + this.verifyNotFailed(); + if (this._isShuttingDown) { + // Return a Promise which never resolves. + return new Promise(() => { }); + } + // Create a deferred Promise that we can return to the callee. This + // allows us to return a "hanging Promise" only to the callee and still + // advance the queue even when the operation is not run. + const task = new Deferred(); + return this.enqueueInternal(() => { + if (this._isShuttingDown && this.skipNonRestrictedTasks) { + // We do not resolve 'task' + return Promise.resolve(); + } + op().then(task.resolve, task.reject); + return task.promise; + }).then(() => task.promise); + } + enqueueRetryable(op) { + this.enqueueAndForget(() => { + this.retryableOps.push(op); + return this.retryNextOp(); + }); + } + /** + * Runs the next operation from the retryable queue. If the operation fails, + * reschedules with backoff. + */ + async retryNextOp() { + if (this.retryableOps.length === 0) { + return; + } + try { + await this.retryableOps[0](); + this.retryableOps.shift(); + this.backoff.reset(); + } + catch (e) { + if (isIndexedDbTransactionError(e)) { + logDebug(LOG_TAG, 'Operation failed with retryable error: ' + e); + } + else { + throw e; // Failure will be handled by AsyncQueue + } + } + if (this.retryableOps.length > 0) { + // If there are additional operations, we re-schedule `retryNextOp()`. + // This is necessary to run retryable operations that failed during + // their initial attempt since we don't know whether they are already + // enqueued. If, for example, `op1`, `op2`, `op3` are enqueued and `op1` + // needs to be re-run, we will run `op1`, `op1`, `op2` using the + // already enqueued calls to `retryNextOp()`. `op3()` will then run in the + // call scheduled here. + // Since `backoffAndRun()` cancels an existing backoff and schedules a + // new backoff on every call, there is only ever a single additional + // operation in the queue. + this.backoff.backoffAndRun(() => this.retryNextOp()); + } + } + enqueueInternal(op) { + const newTail = this.tail.then(() => { + this.operationInProgress = true; + return op() + .catch((error) => { + this.failure = error; + this.operationInProgress = false; + const message = getMessageOrStack(error); + logError('INTERNAL UNHANDLED ERROR: ', message); + // Re-throw the error so that this.tail becomes a rejected Promise and + // all further attempts to chain (via .then) will just short-circuit + // and return the rejected Promise. + throw error; + }) + .then(result => { + this.operationInProgress = false; + return result; + }); + }); + this.tail = newTail; + return newTail; + } + enqueueAfterDelay(timerId, delayMs, op) { + this.verifyNotFailed(); + // Fast-forward delays for timerIds that have been overridden. + if (this.timerIdsToSkip.indexOf(timerId) > -1) { + delayMs = 0; + } + const delayedOp = DelayedOperation.createAndSchedule(this, timerId, delayMs, op, removedOp => this.removeDelayedOperation(removedOp)); + this.delayedOperations.push(delayedOp); + return delayedOp; + } + verifyNotFailed() { + if (this.failure) { + fail(0xb815, { + messageOrStack: getMessageOrStack(this.failure) + }); + } + } + verifyOperationInProgress() { + } + /** + * Waits until all currently queued tasks are finished executing. Delayed + * operations are not run. + */ + async drain() { + // Operations in the queue prior to draining may have enqueued additional + // operations. Keep draining the queue until the tail is no longer advanced, + // which indicates that no more new operations were enqueued and that all + // operations were executed. + let currentTail; + do { + currentTail = this.tail; + await currentTail; + } while (currentTail !== this.tail); + } + /** + * For Tests: Determine if a delayed operation with a particular TimerId + * exists. + */ + containsDelayedOperation(timerId) { + for (const op of this.delayedOperations) { + if (op.timerId === timerId) { + return true; + } + } + return false; + } + /** + * For Tests: Runs some or all delayed operations early. + * + * @param lastTimerId - Delayed operations up to and including this TimerId + * will be drained. Pass TimerId.All to run all delayed operations. + * @returns a Promise that resolves once all operations have been run. + */ + runAllDelayedOperationsUntil(lastTimerId) { + // Note that draining may generate more delayed ops, so we do that first. + return this.drain().then(() => { + // Run ops in the same order they'd run if they ran naturally. + /* eslint-disable-next-line @typescript-eslint/no-floating-promises */ + this.delayedOperations.sort((a, b) => a.targetTimeMs - b.targetTimeMs); + for (const op of this.delayedOperations) { + op.skipDelay(); + if (lastTimerId !== "all" /* TimerId.All */ && op.timerId === lastTimerId) { + break; + } + } + return this.drain(); + }); + } + /** + * For Tests: Skip all subsequent delays for a timer id. + */ + skipDelaysForTimerId(timerId) { + this.timerIdsToSkip.push(timerId); + } + /** Called once a DelayedOperation is run or canceled. */ + removeDelayedOperation(op) { + // NOTE: indexOf / slice are O(n), but delayedOperations is expected to be small. + const index = this.delayedOperations.indexOf(op); + /* eslint-disable-next-line @typescript-eslint/no-floating-promises */ + this.delayedOperations.splice(index, 1); + } +} +function newAsyncQueue() { + return new AsyncQueueImpl(); +} +/** + * Chrome includes Error.message in Error.stack. Other browsers do not. + * This returns expected output of message + stack when available. + * @param error - Error or FirestoreError + */ +function getMessageOrStack(error) { + let message = error.message || ''; + if (error.stack) { + if (error.stack.includes(error.message)) { + message = error.stack; + } + else { + message = error.message + '\n' + error.stack; + } + } + return message; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// TODO(mrschmidt) Consider using `BaseTransaction` as the base class in the +// legacy SDK. +/** + * A reference to a transaction. + * + * The `Transaction` object passed to a transaction's `updateFunction` provides + * the methods to read and write data within the transaction context. See + * {@link runTransaction}. + */ +class Transaction { + /** @hideconstructor */ + constructor(_firestore, _transaction) { + this._firestore = _firestore; + this._transaction = _transaction; + this._dataReader = newUserDataReader(_firestore); + } + /** + * Reads the document referenced by the provided {@link DocumentReference}. + * + * @param documentRef - A reference to the document to be read. + * @returns A `DocumentSnapshot` with the read data. + */ + get(documentRef) { + const ref = validateReference(documentRef, this._firestore); + const userDataWriter = new LiteUserDataWriter(this._firestore); + return this._transaction.lookup([ref._key]).then(docs => { + if (!docs || docs.length !== 1) { + return fail(0x5de9); + } + const doc = docs[0]; + if (doc.isFoundDocument()) { + return new DocumentSnapshot(this._firestore, userDataWriter, doc.key, doc, ref.converter); + } + else if (doc.isNoDocument()) { + return new DocumentSnapshot(this._firestore, userDataWriter, ref._key, null, ref.converter); + } + else { + throw fail(0x4801, { + doc + }); + } + }); + } + set(documentRef, value, options) { + const ref = validateReference(documentRef, this._firestore); + const convertedValue = applyFirestoreDataConverter(ref.converter, value, options); + const parsed = parseSetData(this._dataReader, 'Transaction.set', ref._key, convertedValue, ref.converter !== null, options); + this._transaction.set(ref._key, parsed); + return this; + } + update(documentRef, fieldOrUpdateData, value, ...moreFieldsAndValues) { + const ref = validateReference(documentRef, this._firestore); + // For Compat types, we have to "extract" the underlying types before + // performing validation. + fieldOrUpdateData = util.getModularInstance(fieldOrUpdateData); + let parsed; + if (typeof fieldOrUpdateData === 'string' || + fieldOrUpdateData instanceof FieldPath) { + parsed = parseUpdateVarargs(this._dataReader, 'Transaction.update', ref._key, fieldOrUpdateData, value, moreFieldsAndValues); + } + else { + parsed = parseUpdateData(this._dataReader, 'Transaction.update', ref._key, fieldOrUpdateData); + } + this._transaction.update(ref._key, parsed); + return this; + } + /** + * Deletes the document referred to by the provided {@link DocumentReference}. + * + * @param documentRef - A reference to the document to be deleted. + * @returns This `Transaction` instance. Used for chaining method calls. + */ + delete(documentRef) { + const ref = validateReference(documentRef, this._firestore); + this._transaction.delete(ref._key); + return this; + } +} +/** + * Executes the given `updateFunction` and then attempts to commit the changes + * applied within the transaction. If any document read within the transaction + * has changed, Cloud Firestore retries the `updateFunction`. If it fails to + * commit after 5 attempts, the transaction fails. + * + * The maximum number of writes allowed in a single transaction is 500. + * + * @param firestore - A reference to the Firestore database to run this + * transaction against. + * @param updateFunction - The function to execute within the transaction + * context. + * @param options - An options object to configure maximum number of attempts to + * commit. + * @returns If the transaction completed successfully or was explicitly aborted + * (the `updateFunction` returned a failed promise), the promise returned by the + * `updateFunction `is returned here. Otherwise, if the transaction failed, a + * rejected promise with the corresponding failure error is returned. + */ +function runTransaction(firestore, updateFunction, options) { + firestore = cast(firestore, Firestore); + const datastore = getDatastore(firestore); + const optionsWithDefaults = { + ...DEFAULT_TRANSACTION_OPTIONS, + ...options + }; + validateTransactionOptions(optionsWithDefaults); + const deferred = new Deferred(); + new TransactionRunner(newAsyncQueue(), datastore, optionsWithDefaults, internalTransaction => updateFunction(new Transaction(firestore, internalTransaction)), deferred).run(); + return deferred.promise; +} + +/** + * Firestore Lite + * + * @remarks Firestore Lite is a small online-only SDK that allows read + * and write access to your Firestore database. All operations connect + * directly to the backend, and `onSnapshot()` APIs are not supported. + * @packageDocumentation + */ +registerFirestore(); + +exports.AggregateField = AggregateField; +exports.AggregateQuerySnapshot = AggregateQuerySnapshot; +exports.Bytes = Bytes; +exports.CollectionReference = CollectionReference; +exports.DocumentReference = DocumentReference; +exports.DocumentSnapshot = DocumentSnapshot; +exports.FieldPath = FieldPath; +exports.FieldValue = FieldValue; +exports.Firestore = Firestore; +exports.FirestoreError = FirestoreError; +exports.GeoPoint = GeoPoint; +exports.Query = Query; +exports.QueryCompositeFilterConstraint = QueryCompositeFilterConstraint; +exports.QueryConstraint = QueryConstraint; +exports.QueryDocumentSnapshot = QueryDocumentSnapshot; +exports.QueryEndAtConstraint = QueryEndAtConstraint; +exports.QueryFieldFilterConstraint = QueryFieldFilterConstraint; +exports.QueryLimitConstraint = QueryLimitConstraint; +exports.QueryOrderByConstraint = QueryOrderByConstraint; +exports.QuerySnapshot = QuerySnapshot; +exports.QueryStartAtConstraint = QueryStartAtConstraint; +exports.Timestamp = Timestamp; +exports.Transaction = Transaction; +exports.VectorValue = VectorValue; +exports.WriteBatch = WriteBatch; +exports.addDoc = addDoc; +exports.aggregateFieldEqual = aggregateFieldEqual; +exports.aggregateQuerySnapshotEqual = aggregateQuerySnapshotEqual; +exports.and = and; +exports.arrayRemove = arrayRemove; +exports.arrayUnion = arrayUnion; +exports.average = average; +exports.collection = collection; +exports.collectionGroup = collectionGroup; +exports.connectFirestoreEmulator = connectFirestoreEmulator; +exports.count = count; +exports.deleteDoc = deleteDoc; +exports.deleteField = deleteField; +exports.doc = doc; +exports.documentId = documentId; +exports.endAt = endAt; +exports.endBefore = endBefore; +exports.getAggregate = getAggregate; +exports.getCount = getCount; +exports.getDoc = getDoc; +exports.getDocs = getDocs; +exports.getFirestore = getFirestore; +exports.increment = increment; +exports.initializeFirestore = initializeFirestore; +exports.limit = limit; +exports.limitToLast = limitToLast; +exports.or = or; +exports.orderBy = orderBy; +exports.query = query; +exports.queryEqual = queryEqual; +exports.refEqual = refEqual; +exports.runTransaction = runTransaction; +exports.serverTimestamp = serverTimestamp; +exports.setDoc = setDoc; +exports.setLogLevel = setLogLevel; +exports.snapshotEqual = snapshotEqual; +exports.startAfter = startAfter; +exports.startAt = startAt; +exports.sum = sum; +exports.terminate = terminate; +exports.updateDoc = updateDoc; +exports.vector = vector; +exports.where = where; +exports.writeBatch = writeBatch; +//# sourceMappingURL=index.node.cjs.js.map diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/index.node.cjs.js.map b/frontend-old/node_modules/@firebase/firestore/dist/lite/index.node.cjs.js.map new file mode 100644 index 0000000..105f83b --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/index.node.cjs.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.node.cjs.js","sources":["../../src/auth/user.ts","../../src/core/version.ts","../../src/platform/node/format_json.ts","../../src/util/log.ts","../../src/util/assert.ts","../../src/util/error.ts","../../src/util/promise.ts","../../src/api/credentials.ts","../../src/core/database_info.ts","../../src/platform/node/random_bytes.ts","../../src/util/misc.ts","../../src/model/path.ts","../../src/model/document_key.ts","../../src/util/input_validation.ts","../../src/api/long_polling_options.ts","../../src/util/debug_uid.ts","../../src/remote/rest_connection.ts","../../src/remote/rpc_error.ts","../../src/platform/browser_lite/fetch_connection.ts","../../src/platform/node_lite/connection.ts","../../src/util/obj.ts","../../src/util/types.ts","../../src/platform/node/base64.ts","../../src/util/byte_string.ts","../../src/model/normalize.ts","../../src/util/json_validation.ts","../../src/lite-api/timestamp.ts","../../src/model/server_timestamps.ts","../../src/model/values.ts","../../src/core/bound.ts","../../src/core/filter.ts","../../src/core/order_by.ts","../../src/core/snapshot_version.ts","../../src/util/sorted_map.ts","../../src/util/sorted_set.ts","../../src/model/field_mask.ts","../../src/model/object_value.ts","../../src/model/document.ts","../../src/core/target.ts","../../src/core/query.ts","../../src/remote/number_serializer.ts","../../src/model/transform_operation.ts","../../src/model/mutation.ts","../../src/remote/serializer.ts","../../src/platform/browser/serializer.ts","../../src/remote/backoff.ts","../../src/remote/datastore.ts","../../src/lite-api/components.ts","../../src/local/lru_garbage_collector.ts","../../src/local/simple_db.ts","../../src/local/lru_garbage_collector_impl.ts","../../src/lite-api/settings.ts","../../src/lite-api/database.ts","../../lite/register.ts","../../src/core/aggregate.ts","../../src/lite-api/aggregate_types.ts","../../src/lite-api/reference.ts","../../src/lite-api/bytes.ts","../../src/lite-api/field_path.ts","../../src/lite-api/field_value.ts","../../src/lite-api/geo_point.ts","../../src/util/array.ts","../../src/lite-api/vector_value.ts","../../src/lite-api/user_data_reader.ts","../../src/lite-api/snapshot.ts","../../src/lite-api/query.ts","../../src/lite-api/user_data_writer.ts","../../src/lite-api/reference_impl.ts","../../src/lite-api/aggregate.ts","../../src/lite-api/field_value_impl.ts","../../src/lite-api/write_batch.ts","../../src/core/transaction_options.ts","../../src/core/transaction.ts","../../src/core/transaction_runner.ts","../../src/util/async_queue.ts","../../src/util/async_queue_impl.ts","../../src/lite-api/transaction.ts","../../lite/index.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Simple wrapper around a nullable UID. Mostly exists to make code more\n * readable.\n */\nexport class User {\n /** A user with a null UID. */\n static readonly UNAUTHENTICATED = new User(null);\n\n // TODO(mikelehen): Look into getting a proper uid-equivalent for\n // non-FirebaseAuth providers.\n static readonly GOOGLE_CREDENTIALS = new User('google-credentials-uid');\n static readonly FIRST_PARTY = new User('first-party-uid');\n static readonly MOCK_USER = new User('mock-user');\n\n constructor(readonly uid: string | null) {}\n\n isAuthenticated(): boolean {\n return this.uid != null;\n }\n\n /**\n * Returns a key representing this user, suitable for inclusion in a\n * dictionary.\n */\n toKey(): string {\n if (this.isAuthenticated()) {\n return 'uid:' + this.uid;\n } else {\n return 'anonymous-user';\n }\n }\n\n isEqual(otherUser: User): boolean {\n return otherUser.uid === this.uid;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** The semver (www.semver.org) version of the SDK. */\nimport { version } from '../../../firebase/package.json';\nexport let SDK_VERSION = version;\nexport function setSDKVersion(version: string): void {\n SDK_VERSION = version;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { inspect } from 'util';\n\n/** Formats an object as a JSON string, suitable for logging. */\nexport function formatJSON(value: unknown): string {\n // util.inspect() results in much more readable output than JSON.stringify()\n return inspect(value, { depth: 100 });\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Logger, LogLevel, LogLevelString } from '@firebase/logger';\n\nimport { SDK_VERSION } from '../core/version';\nimport { formatJSON } from '../platform/format_json';\n\nexport { LogLevel, LogLevelString };\n\nconst logClient = new Logger('@firebase/firestore');\n\n// Helper methods are needed because variables can't be exported as read/write\nexport function getLogLevel(): LogLevel {\n return logClient.logLevel;\n}\n\n/**\n * Sets the verbosity of Cloud Firestore logs (debug, error, or silent).\n *\n * @param logLevel - The verbosity you set for activity and error logging. Can\n * be any of the following values:\n *\n *
    \n *
  • `debug` for the most verbose logging level, primarily for\n * debugging.
  • \n *
  • `error` to log errors only.
  • \n *
  • `silent` to turn off logging.
  • \n *
\n */\nexport function setLogLevel(logLevel: LogLevelString): void {\n logClient.setLogLevel(logLevel);\n}\n\nexport function logDebug(msg: string, ...obj: unknown[]): void {\n if (logClient.logLevel <= LogLevel.DEBUG) {\n const args = obj.map(argToString);\n logClient.debug(`Firestore (${SDK_VERSION}): ${msg}`, ...args);\n }\n}\n\nexport function logError(msg: string, ...obj: unknown[]): void {\n if (logClient.logLevel <= LogLevel.ERROR) {\n const args = obj.map(argToString);\n logClient.error(`Firestore (${SDK_VERSION}): ${msg}`, ...args);\n }\n}\n\n/**\n * @internal\n */\nexport function logWarn(msg: string, ...obj: unknown[]): void {\n if (logClient.logLevel <= LogLevel.WARN) {\n const args = obj.map(argToString);\n logClient.warn(`Firestore (${SDK_VERSION}): ${msg}`, ...args);\n }\n}\n\n/**\n * Converts an additional log parameter to a string representation.\n */\nfunction argToString(obj: unknown): string | unknown {\n if (typeof obj === 'string') {\n return obj;\n } else {\n try {\n return formatJSON(obj);\n } catch (e) {\n // Converting to JSON failed, just log the object directly\n return obj;\n }\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SDK_VERSION } from '../core/version';\n\nimport { logError } from './log';\n\n/**\n * Unconditionally fails, throwing an Error with the given message.\n * Messages are stripped in production builds.\n *\n * Returns `never` and can be used in expressions:\n * @example\n * let futureVar = fail('not implemented yet');\n *\n * @param code generate a new unique value with `yarn assertion-id:generate`\n * Search for an existing value using `yarn assertion-id:find X`\n */\nexport function fail(\n code: number,\n message: string,\n context?: Record\n): never;\n\n/**\n * Unconditionally fails, throwing an Error with the given message.\n * Messages are stripped in production builds.\n *\n * Returns `never` and can be used in expressions:\n * @example\n * let futureVar = fail('not implemented yet');\n *\n * @param id generate a new unique value with `yarn assertion-id:generate`\n * Search for an existing value using `yarn assertion-id:find X`\n */\nexport function fail(id: number, context?: Record): never;\n\nexport function fail(\n id: number,\n messageOrContext?: string | Record,\n context?: Record\n): never {\n let message = 'Unexpected state';\n if (typeof messageOrContext === 'string') {\n message = messageOrContext;\n } else {\n context = messageOrContext;\n }\n _fail(id, message, context);\n}\n\nfunction _fail(\n id: number,\n failure: string,\n context?: Record\n): never {\n // Log the failure in addition to throw an exception, just in case the\n // exception is swallowed.\n let message = `FIRESTORE (${SDK_VERSION}) INTERNAL ASSERTION FAILED: ${failure} (ID: ${id.toString(\n 16\n )})`;\n if (context !== undefined) {\n try {\n const stringContext = JSON.stringify(context);\n message += ' CONTEXT: ' + stringContext;\n } catch (e) {\n message += ' CONTEXT: ' + context;\n }\n }\n logError(message);\n\n // NOTE: We don't use FirestoreError here because these are internal failures\n // that cannot be handled by the user. (Also it would create a circular\n // dependency between the error and assert modules which doesn't work.)\n throw new Error(message);\n}\n\n/**\n * Fails if the given assertion condition is false, throwing an Error with the\n * given message if it did.\n *\n * Messages are stripped in production builds.\n *\n * @param id generate a new unique value with `yarn assertion-idgenerate`.\n * Search for an existing value using `yarn assertion-id:find X`\n */\nexport function hardAssert(\n assertion: boolean,\n id: number,\n message: string,\n context?: Record\n): asserts assertion;\n\n/**\n * Fails if the given assertion condition is false, throwing an Error with the\n * given message if it did.\n *\n * Messages are stripped in production builds.\n *\n * @param id generate a new unique value with `yarn assertion-id:generate`.\n * Search for an existing value using `yarn assertion-id:find X`\n */\nexport function hardAssert(\n assertion: boolean,\n id: number,\n context?: Record\n): asserts assertion;\n\nexport function hardAssert(\n assertion: boolean,\n id: number,\n messageOrContext?: string | Record,\n context?: Record\n): asserts assertion {\n let message = 'Unexpected state';\n if (typeof messageOrContext === 'string') {\n message = messageOrContext;\n } else {\n context = messageOrContext;\n }\n\n if (!assertion) {\n _fail(id, message, context);\n }\n}\n\n/**\n * Fails if the given assertion condition is false, throwing an Error with the\n * given message if it did.\n *\n * The code of callsites invoking this function are stripped out in production\n * builds. Any side-effects of code within the debugAssert() invocation will not\n * happen in this case.\n *\n * @internal\n */\nexport function debugAssert(\n assertion: boolean,\n message: string\n): asserts assertion {\n if (!assertion) {\n fail(0xdeb6, message);\n }\n}\n\n/**\n * Casts `obj` to `T`. In non-production builds, verifies that `obj` is an\n * instance of `T` before casting.\n */\nexport function debugCast(\n obj: object,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n constructor: { new (...args: any[]): T }\n): T | never {\n debugAssert(\n obj instanceof constructor,\n `Expected type '${constructor.name}', but was '${obj.constructor.name}'`\n );\n return obj as T;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseError } from '@firebase/util';\n\n/**\n * The set of Firestore status codes. The codes are the same at the ones\n * exposed by gRPC here:\n * https://github.com/grpc/grpc/blob/master/doc/statuscodes.md\n *\n * Possible values:\n * - 'cancelled': The operation was cancelled (typically by the caller).\n * - 'unknown': Unknown error or an error from a different error domain.\n * - 'invalid-argument': Client specified an invalid argument. Note that this\n * differs from 'failed-precondition'. 'invalid-argument' indicates\n * arguments that are problematic regardless of the state of the system\n * (e.g. an invalid field name).\n * - 'deadline-exceeded': Deadline expired before operation could complete.\n * For operations that change the state of the system, this error may be\n * returned even if the operation has completed successfully. For example,\n * a successful response from a server could have been delayed long enough\n * for the deadline to expire.\n * - 'not-found': Some requested document was not found.\n * - 'already-exists': Some document that we attempted to create already\n * exists.\n * - 'permission-denied': The caller does not have permission to execute the\n * specified operation.\n * - 'resource-exhausted': Some resource has been exhausted, perhaps a\n * per-user quota, or perhaps the entire file system is out of space.\n * - 'failed-precondition': Operation was rejected because the system is not\n * in a state required for the operation's execution.\n * - 'aborted': The operation was aborted, typically due to a concurrency\n * issue like transaction aborts, etc.\n * - 'out-of-range': Operation was attempted past the valid range.\n * - 'unimplemented': Operation is not implemented or not supported/enabled.\n * - 'internal': Internal errors. Means some invariants expected by\n * underlying system has been broken. If you see one of these errors,\n * something is very broken.\n * - 'unavailable': The service is currently unavailable. This is most likely\n * a transient condition and may be corrected by retrying with a backoff.\n * - 'data-loss': Unrecoverable data loss or corruption.\n * - 'unauthenticated': The request does not have valid authentication\n * credentials for the operation.\n */\nexport type FirestoreErrorCode =\n | 'cancelled'\n | 'unknown'\n | 'invalid-argument'\n | 'deadline-exceeded'\n | 'not-found'\n | 'already-exists'\n | 'permission-denied'\n | 'resource-exhausted'\n | 'failed-precondition'\n | 'aborted'\n | 'out-of-range'\n | 'unimplemented'\n | 'internal'\n | 'unavailable'\n | 'data-loss'\n | 'unauthenticated';\n\n/**\n * Error Codes describing the different ways Firestore can fail. These come\n * directly from GRPC.\n */\nexport type Code = FirestoreErrorCode;\n\nexport const Code = {\n // Causes are copied from:\n // https://github.com/grpc/grpc/blob/bceec94ea4fc5f0085d81235d8e1c06798dc341a/include/grpc%2B%2B/impl/codegen/status_code_enum.h\n /** Not an error; returned on success. */\n OK: 'ok' as FirestoreErrorCode,\n\n /** The operation was cancelled (typically by the caller). */\n CANCELLED: 'cancelled' as FirestoreErrorCode,\n\n /** Unknown error or an error from a different error domain. */\n UNKNOWN: 'unknown' as FirestoreErrorCode,\n\n /**\n * Client specified an invalid argument. Note that this differs from\n * FAILED_PRECONDITION. INVALID_ARGUMENT indicates arguments that are\n * problematic regardless of the state of the system (e.g., a malformed file\n * name).\n */\n INVALID_ARGUMENT: 'invalid-argument' as FirestoreErrorCode,\n\n /**\n * Deadline expired before operation could complete. For operations that\n * change the state of the system, this error may be returned even if the\n * operation has completed successfully. For example, a successful response\n * from a server could have been delayed long enough for the deadline to\n * expire.\n */\n DEADLINE_EXCEEDED: 'deadline-exceeded' as FirestoreErrorCode,\n\n /** Some requested entity (e.g., file or directory) was not found. */\n NOT_FOUND: 'not-found' as FirestoreErrorCode,\n\n /**\n * Some entity that we attempted to create (e.g., file or directory) already\n * exists.\n */\n ALREADY_EXISTS: 'already-exists' as FirestoreErrorCode,\n\n /**\n * The caller does not have permission to execute the specified operation.\n * PERMISSION_DENIED must not be used for rejections caused by exhausting\n * some resource (use RESOURCE_EXHAUSTED instead for those errors).\n * PERMISSION_DENIED must not be used if the caller cannot be identified\n * (use UNAUTHENTICATED instead for those errors).\n */\n PERMISSION_DENIED: 'permission-denied' as FirestoreErrorCode,\n\n /**\n * The request does not have valid authentication credentials for the\n * operation.\n */\n UNAUTHENTICATED: 'unauthenticated' as FirestoreErrorCode,\n\n /**\n * Some resource has been exhausted, perhaps a per-user quota, or perhaps the\n * entire file system is out of space.\n */\n RESOURCE_EXHAUSTED: 'resource-exhausted' as FirestoreErrorCode,\n\n /**\n * Operation was rejected because the system is not in a state required for\n * the operation's execution. For example, directory to be deleted may be\n * non-empty, an rmdir operation is applied to a non-directory, etc.\n *\n * A litmus test that may help a service implementor in deciding\n * between FAILED_PRECONDITION, ABORTED, and UNAVAILABLE:\n * (a) Use UNAVAILABLE if the client can retry just the failing call.\n * (b) Use ABORTED if the client should retry at a higher-level\n * (e.g., restarting a read-modify-write sequence).\n * (c) Use FAILED_PRECONDITION if the client should not retry until\n * the system state has been explicitly fixed. E.g., if an \"rmdir\"\n * fails because the directory is non-empty, FAILED_PRECONDITION\n * should be returned since the client should not retry unless\n * they have first fixed up the directory by deleting files from it.\n * (d) Use FAILED_PRECONDITION if the client performs conditional\n * REST Get/Update/Delete on a resource and the resource on the\n * server does not match the condition. E.g., conflicting\n * read-modify-write on the same resource.\n */\n FAILED_PRECONDITION: 'failed-precondition' as FirestoreErrorCode,\n\n /**\n * The operation was aborted, typically due to a concurrency issue like\n * sequencer check failures, transaction aborts, etc.\n *\n * See litmus test above for deciding between FAILED_PRECONDITION, ABORTED,\n * and UNAVAILABLE.\n */\n ABORTED: 'aborted' as FirestoreErrorCode,\n\n /**\n * Operation was attempted past the valid range. E.g., seeking or reading\n * past end of file.\n *\n * Unlike INVALID_ARGUMENT, this error indicates a problem that may be fixed\n * if the system state changes. For example, a 32-bit file system will\n * generate INVALID_ARGUMENT if asked to read at an offset that is not in the\n * range [0,2^32-1], but it will generate OUT_OF_RANGE if asked to read from\n * an offset past the current file size.\n *\n * There is a fair bit of overlap between FAILED_PRECONDITION and\n * OUT_OF_RANGE. We recommend using OUT_OF_RANGE (the more specific error)\n * when it applies so that callers who are iterating through a space can\n * easily look for an OUT_OF_RANGE error to detect when they are done.\n */\n OUT_OF_RANGE: 'out-of-range' as FirestoreErrorCode,\n\n /** Operation is not implemented or not supported/enabled in this service. */\n UNIMPLEMENTED: 'unimplemented' as FirestoreErrorCode,\n\n /**\n * Internal errors. Means some invariants expected by underlying System has\n * been broken. If you see one of these errors, Something is very broken.\n */\n INTERNAL: 'internal' as FirestoreErrorCode,\n\n /**\n * The service is currently unavailable. This is a most likely a transient\n * condition and may be corrected by retrying with a backoff.\n *\n * See litmus test above for deciding between FAILED_PRECONDITION, ABORTED,\n * and UNAVAILABLE.\n */\n UNAVAILABLE: 'unavailable' as FirestoreErrorCode,\n\n /** Unrecoverable data loss or corruption. */\n DATA_LOSS: 'data-loss' as FirestoreErrorCode\n};\n\n/** An error returned by a Firestore operation. */\nexport class FirestoreError extends FirebaseError {\n /** The stack of the error. */\n readonly stack?: string;\n\n /** @hideconstructor */\n constructor(\n /**\n * The backend error code associated with this error.\n */\n readonly code: FirestoreErrorCode,\n /**\n * A custom error description.\n */\n readonly message: string\n ) {\n super(code, message);\n\n // HACK: We write a toString property directly because Error is not a real\n // class and so inheritance does not work correctly. We could alternatively\n // do the same \"back-door inheritance\" trick that FirebaseError does.\n this.toString = () => `${this.name}: [code=${this.code}]: ${this.message}`;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport interface Resolver {\n (value: R | Promise): void;\n}\n\nexport interface Rejecter {\n (reason?: Error): void;\n}\n\nexport class Deferred {\n promise: Promise;\n // Assigned synchronously in constructor by Promise constructor callback.\n resolve!: Resolver;\n reject!: Rejecter;\n\n constructor() {\n this.promise = new Promise((resolve: Resolver, reject: Rejecter) => {\n this.resolve = resolve;\n this.reject = reject;\n });\n }\n}\n\n/**\n * Takes an array of values and a function from a value to a Promise. The function is run on each\n * value sequentially, waiting for the previous promise to resolve before starting the next one.\n * The returned promise resolves once the function has been run on all values.\n */\nexport function sequence(\n values: T[],\n fn: (value: T) => Promise\n): Promise {\n let p = Promise.resolve();\n for (const value of values) {\n p = p.then(() => fn(value));\n }\n return p;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseApp, _isFirebaseServerApp } from '@firebase/app';\nimport {\n AppCheckInternalComponentName,\n AppCheckTokenListener,\n AppCheckTokenResult,\n FirebaseAppCheckInternal\n} from '@firebase/app-check-interop-types';\nimport {\n FirebaseAuthInternal,\n FirebaseAuthInternalName\n} from '@firebase/auth-interop-types';\nimport { Provider } from '@firebase/component';\n\nimport { User } from '../auth/user';\nimport { debugAssert, hardAssert } from '../util/assert';\nimport { AsyncQueue } from '../util/async_queue';\nimport { Code, FirestoreError } from '../util/error';\nimport { logDebug } from '../util/log';\nimport { Deferred } from '../util/promise';\n\n// TODO(mikelehen): This should be split into multiple files and probably\n// moved to an auth/ folder to match other platforms.\n\n/**\n * @internal\n */\nexport type AuthTokenFactory = () => string;\n\n/**\n * @internal\n */\nexport interface FirstPartyCredentialsSettings {\n // These are external types. Prevent minification.\n ['type']: 'firstParty';\n ['sessionIndex']: string;\n ['iamToken']: string | null;\n ['authTokenFactory']: AuthTokenFactory | null;\n}\n\nexport interface ProviderCredentialsSettings {\n // These are external types. Prevent minification.\n ['type']: 'provider';\n ['client']: CredentialsProvider;\n}\n\n/** Settings for private credentials */\nexport type CredentialsSettings =\n | FirstPartyCredentialsSettings\n | ProviderCredentialsSettings;\n\nexport type TokenType = 'OAuth' | 'FirstParty' | 'AppCheck';\nexport interface Token {\n /** Type of token. */\n type: TokenType;\n\n /**\n * The user with which the token is associated (used for persisting user\n * state on disk, etc.).\n * This will be null for Tokens of the type 'AppCheck'.\n */\n user?: User;\n\n /** Header values to set for this token */\n headers: Map;\n}\n\nexport class OAuthToken implements Token {\n type = 'OAuth' as TokenType;\n headers = new Map();\n\n constructor(value: string, public user: User) {\n this.headers.set('Authorization', `Bearer ${value}`);\n }\n}\n\n/**\n * A Listener for credential change events. The listener should fetch a new\n * token and may need to invalidate other state if the current user has also\n * changed.\n */\nexport type CredentialChangeListener = (credential: T) => Promise;\n\n/**\n * Provides methods for getting the uid and token for the current user and\n * listening for changes.\n */\nexport interface CredentialsProvider {\n /**\n * Starts the credentials provider and specifies a listener to be notified of\n * credential changes (sign-in / sign-out, token changes). It is immediately\n * called once with the initial user.\n *\n * The change listener is invoked on the provided AsyncQueue.\n */\n start(\n asyncQueue: AsyncQueue,\n changeListener: CredentialChangeListener\n ): void;\n\n /** Requests a token for the current user. */\n getToken(): Promise;\n\n /**\n * Marks the last retrieved token as invalid, making the next GetToken request\n * force-refresh the token.\n */\n invalidateToken(): void;\n\n shutdown(): void;\n}\n\n/**\n * A CredentialsProvider that always yields an empty token.\n * @internal\n */\nexport class EmptyAuthCredentialsProvider implements CredentialsProvider {\n getToken(): Promise {\n return Promise.resolve(null);\n }\n\n invalidateToken(): void {}\n\n start(\n asyncQueue: AsyncQueue,\n changeListener: CredentialChangeListener\n ): void {\n // Fire with initial user.\n asyncQueue.enqueueRetryable(() => changeListener(User.UNAUTHENTICATED));\n }\n\n shutdown(): void {}\n}\n\n/**\n * A CredentialsProvider that always returns a constant token. Used for\n * emulator token mocking.\n */\nexport class EmulatorAuthCredentialsProvider\n implements CredentialsProvider\n{\n constructor(private token: Token) {}\n\n /**\n * Stores the listener registered with setChangeListener()\n * This isn't actually necessary since the UID never changes, but we use this\n * to verify the listen contract is adhered to in tests.\n */\n private changeListener: CredentialChangeListener | null = null;\n\n getToken(): Promise {\n return Promise.resolve(this.token);\n }\n\n invalidateToken(): void {}\n\n start(\n asyncQueue: AsyncQueue,\n changeListener: CredentialChangeListener\n ): void {\n debugAssert(\n !this.changeListener,\n 'Can only call setChangeListener() once.'\n );\n this.changeListener = changeListener;\n // Fire with initial user.\n asyncQueue.enqueueRetryable(() => changeListener(this.token.user!));\n }\n\n shutdown(): void {\n this.changeListener = null;\n }\n}\n\n/** Credential provider for the Lite SDK. */\nexport class LiteAuthCredentialsProvider implements CredentialsProvider {\n private auth: FirebaseAuthInternal | null = null;\n\n constructor(authProvider: Provider) {\n authProvider.onInit(auth => {\n this.auth = auth;\n });\n }\n\n getToken(): Promise {\n if (!this.auth) {\n return Promise.resolve(null);\n }\n\n return this.auth.getToken().then(tokenData => {\n if (tokenData) {\n hardAssert(\n typeof tokenData.accessToken === 'string',\n 0xa539,\n 'Invalid tokenData returned from getToken()',\n { tokenData }\n );\n return new OAuthToken(\n tokenData.accessToken,\n new User(this.auth!.getUid())\n );\n } else {\n return null;\n }\n });\n }\n\n invalidateToken(): void {}\n\n start(\n asyncQueue: AsyncQueue,\n changeListener: CredentialChangeListener\n ): void {}\n\n shutdown(): void {}\n}\n\nexport class FirebaseAuthCredentialsProvider\n implements CredentialsProvider\n{\n /**\n * The auth token listener registered with FirebaseApp, retained here so we\n * can unregister it.\n */\n private tokenListener: (() => void) | undefined;\n\n /** Tracks the current User. */\n private currentUser: User = User.UNAUTHENTICATED;\n\n /**\n * Counter used to detect if the token changed while a getToken request was\n * outstanding.\n */\n private tokenCounter = 0;\n\n private forceRefresh = false;\n\n private auth: FirebaseAuthInternal | null = null;\n\n constructor(private authProvider: Provider) {}\n\n start(\n asyncQueue: AsyncQueue,\n changeListener: CredentialChangeListener\n ): void {\n hardAssert(\n this.tokenListener === undefined,\n 0xa540,\n 'Token listener already added'\n );\n let lastTokenId = this.tokenCounter;\n\n // A change listener that prevents double-firing for the same token change.\n const guardedChangeListener: (user: User) => Promise = user => {\n if (this.tokenCounter !== lastTokenId) {\n lastTokenId = this.tokenCounter;\n return changeListener(user);\n } else {\n return Promise.resolve();\n }\n };\n\n // A promise that can be waited on to block on the next token change.\n // This promise is re-created after each change.\n let nextToken = new Deferred();\n\n this.tokenListener = () => {\n this.tokenCounter++;\n this.currentUser = this.getUser();\n nextToken.resolve();\n nextToken = new Deferred();\n asyncQueue.enqueueRetryable(() =>\n guardedChangeListener(this.currentUser)\n );\n };\n\n const awaitNextToken: () => void = () => {\n const currentTokenAttempt = nextToken;\n asyncQueue.enqueueRetryable(async () => {\n await currentTokenAttempt.promise;\n await guardedChangeListener(this.currentUser);\n });\n };\n\n const registerAuth = (auth: FirebaseAuthInternal): void => {\n logDebug('FirebaseAuthCredentialsProvider', 'Auth detected');\n this.auth = auth;\n if (this.tokenListener) {\n this.auth.addAuthTokenListener(this.tokenListener);\n awaitNextToken();\n }\n };\n\n this.authProvider.onInit(auth => registerAuth(auth));\n\n // Our users can initialize Auth right after Firestore, so we give it\n // a chance to register itself with the component framework before we\n // determine whether to start up in unauthenticated mode.\n setTimeout(() => {\n if (!this.auth) {\n const auth = this.authProvider.getImmediate({ optional: true });\n if (auth) {\n registerAuth(auth);\n } else {\n // If auth is still not available, proceed with `null` user\n logDebug('FirebaseAuthCredentialsProvider', 'Auth not yet detected');\n nextToken.resolve();\n nextToken = new Deferred();\n }\n }\n }, 0);\n\n awaitNextToken();\n }\n\n getToken(): Promise {\n debugAssert(\n this.tokenListener != null,\n 'FirebaseAuthCredentialsProvider not started.'\n );\n\n // Take note of the current value of the tokenCounter so that this method\n // can fail (with an ABORTED error) if there is a token change while the\n // request is outstanding.\n const initialTokenCounter = this.tokenCounter;\n const forceRefresh = this.forceRefresh;\n this.forceRefresh = false;\n\n if (!this.auth) {\n return Promise.resolve(null);\n }\n\n return this.auth.getToken(forceRefresh).then(tokenData => {\n // Cancel the request since the token changed while the request was\n // outstanding so the response is potentially for a previous user (which\n // user, we can't be sure).\n if (this.tokenCounter !== initialTokenCounter) {\n logDebug(\n 'FirebaseAuthCredentialsProvider',\n 'getToken aborted due to token change.'\n );\n return this.getToken();\n } else {\n if (tokenData) {\n hardAssert(\n typeof tokenData.accessToken === 'string',\n 0x7c5d,\n 'Invalid tokenData returned from getToken()',\n { tokenData }\n );\n return new OAuthToken(tokenData.accessToken, this.currentUser);\n } else {\n return null;\n }\n }\n });\n }\n\n invalidateToken(): void {\n this.forceRefresh = true;\n }\n\n shutdown(): void {\n if (this.auth && this.tokenListener) {\n this.auth.removeAuthTokenListener(this.tokenListener);\n }\n this.tokenListener = undefined;\n }\n\n // Auth.getUid() can return null even with a user logged in. It is because\n // getUid() is synchronous, but the auth code populating Uid is asynchronous.\n // This method should only be called in the AuthTokenListener callback\n // to guarantee to get the actual user.\n private getUser(): User {\n const currentUid = this.auth && this.auth.getUid();\n hardAssert(\n currentUid === null || typeof currentUid === 'string',\n 0x0807,\n 'Received invalid UID',\n { currentUid }\n );\n return new User(currentUid);\n }\n}\n\n/*\n * FirstPartyToken provides a fresh token each time its value\n * is requested, because if the token is too old, requests will be rejected.\n * Technically this may no longer be necessary since the SDK should gracefully\n * recover from unauthenticated errors (see b/33147818 for context), but it's\n * safer to keep the implementation as-is.\n */\nexport class FirstPartyToken implements Token {\n type = 'FirstParty' as TokenType;\n user = User.FIRST_PARTY;\n private _headers = new Map();\n\n constructor(\n private readonly sessionIndex: string,\n private readonly iamToken: string | null,\n private readonly authTokenFactory: AuthTokenFactory | null\n ) {}\n\n /**\n * Gets an authorization token, using a provided factory function, or return\n * null.\n */\n private getAuthToken(): string | null {\n if (this.authTokenFactory) {\n return this.authTokenFactory();\n } else {\n return null;\n }\n }\n\n get headers(): Map {\n this._headers.set('X-Goog-AuthUser', this.sessionIndex);\n // Use array notation to prevent minification\n const authHeaderTokenValue = this.getAuthToken();\n if (authHeaderTokenValue) {\n this._headers.set('Authorization', authHeaderTokenValue);\n }\n if (this.iamToken) {\n this._headers.set('X-Goog-Iam-Authorization-Token', this.iamToken);\n }\n\n return this._headers;\n }\n}\n\n/*\n * Provides user credentials required for the Firestore JavaScript SDK\n * to authenticate the user, using technique that is only available\n * to applications hosted by Google.\n */\nexport class FirstPartyAuthCredentialsProvider\n implements CredentialsProvider\n{\n constructor(\n private sessionIndex: string,\n private iamToken: string | null,\n private authTokenFactory: AuthTokenFactory | null\n ) {}\n\n getToken(): Promise {\n return Promise.resolve(\n new FirstPartyToken(\n this.sessionIndex,\n this.iamToken,\n this.authTokenFactory\n )\n );\n }\n\n start(\n asyncQueue: AsyncQueue,\n changeListener: CredentialChangeListener\n ): void {\n // Fire with initial uid.\n asyncQueue.enqueueRetryable(() => changeListener(User.FIRST_PARTY));\n }\n\n shutdown(): void {}\n\n invalidateToken(): void {}\n}\n\nexport class AppCheckToken implements Token {\n type = 'AppCheck' as TokenType;\n headers = new Map();\n\n constructor(private value: string) {\n if (value && value.length > 0) {\n this.headers.set('x-firebase-appcheck', this.value);\n }\n }\n}\n\nexport class FirebaseAppCheckTokenProvider\n implements CredentialsProvider\n{\n /**\n * The AppCheck token listener registered with FirebaseApp, retained here so\n * we can unregister it.\n */\n private tokenListener: AppCheckTokenListener | undefined;\n private forceRefresh = false;\n private appCheck: FirebaseAppCheckInternal | null = null;\n private latestAppCheckToken: string | null = null;\n private serverAppAppCheckToken: string | null = null;\n\n constructor(\n app: FirebaseApp,\n private appCheckProvider: Provider\n ) {\n if (_isFirebaseServerApp(app) && app.settings.appCheckToken) {\n this.serverAppAppCheckToken = app.settings.appCheckToken;\n }\n }\n\n start(\n asyncQueue: AsyncQueue,\n changeListener: CredentialChangeListener\n ): void {\n hardAssert(\n this.tokenListener === undefined,\n 0x0db8,\n 'Token listener already added'\n );\n\n const onTokenChanged: (\n tokenResult: AppCheckTokenResult\n ) => Promise = tokenResult => {\n if (tokenResult.error != null) {\n logDebug(\n 'FirebaseAppCheckTokenProvider',\n `Error getting App Check token; using placeholder token instead. Error: ${tokenResult.error.message}`\n );\n }\n const tokenUpdated = tokenResult.token !== this.latestAppCheckToken;\n this.latestAppCheckToken = tokenResult.token;\n logDebug(\n 'FirebaseAppCheckTokenProvider',\n `Received ${tokenUpdated ? 'new' : 'existing'} token.`\n );\n return tokenUpdated\n ? changeListener(tokenResult.token)\n : Promise.resolve();\n };\n\n this.tokenListener = (tokenResult: AppCheckTokenResult) => {\n asyncQueue.enqueueRetryable(() => onTokenChanged(tokenResult));\n };\n\n const registerAppCheck = (appCheck: FirebaseAppCheckInternal): void => {\n logDebug('FirebaseAppCheckTokenProvider', 'AppCheck detected');\n this.appCheck = appCheck;\n if (this.tokenListener) {\n this.appCheck.addTokenListener(this.tokenListener);\n }\n };\n\n this.appCheckProvider.onInit(appCheck => registerAppCheck(appCheck));\n\n // Our users can initialize AppCheck after Firestore, so we give it\n // a chance to register itself with the component framework.\n setTimeout(() => {\n if (!this.appCheck) {\n const appCheck = this.appCheckProvider.getImmediate({ optional: true });\n if (appCheck) {\n registerAppCheck(appCheck);\n } else {\n // If AppCheck is still not available, proceed without it.\n logDebug(\n 'FirebaseAppCheckTokenProvider',\n 'AppCheck not yet detected'\n );\n }\n }\n }, 0);\n }\n\n getToken(): Promise {\n if (this.serverAppAppCheckToken) {\n return Promise.resolve(new AppCheckToken(this.serverAppAppCheckToken));\n }\n debugAssert(\n this.tokenListener != null,\n 'FirebaseAppCheckTokenProvider not started.'\n );\n\n const forceRefresh = this.forceRefresh;\n this.forceRefresh = false;\n\n if (!this.appCheck) {\n return Promise.resolve(null);\n }\n\n return this.appCheck.getToken(forceRefresh).then(tokenResult => {\n if (tokenResult) {\n hardAssert(\n typeof tokenResult.token === 'string',\n 0xae0e,\n 'Invalid tokenResult returned from getToken()',\n { tokenResult }\n );\n this.latestAppCheckToken = tokenResult.token;\n return new AppCheckToken(tokenResult.token);\n } else {\n return null;\n }\n });\n }\n\n invalidateToken(): void {\n this.forceRefresh = true;\n }\n\n shutdown(): void {\n if (this.appCheck && this.tokenListener) {\n this.appCheck.removeTokenListener(this.tokenListener);\n }\n this.tokenListener = undefined;\n }\n}\n\n/**\n * An AppCheck token provider that always yields an empty token.\n * @internal\n */\nexport class EmptyAppCheckTokenProvider implements CredentialsProvider {\n getToken(): Promise {\n return Promise.resolve(new AppCheckToken(''));\n }\n\n invalidateToken(): void {}\n\n start(\n asyncQueue: AsyncQueue,\n changeListener: CredentialChangeListener\n ): void {}\n\n shutdown(): void {}\n}\n\n/** AppCheck token provider for the Lite SDK. */\nexport class LiteAppCheckTokenProvider implements CredentialsProvider {\n private appCheck: FirebaseAppCheckInternal | null = null;\n private serverAppAppCheckToken: string | null = null;\n\n constructor(\n app: FirebaseApp,\n private appCheckProvider: Provider\n ) {\n if (_isFirebaseServerApp(app) && app.settings.appCheckToken) {\n this.serverAppAppCheckToken = app.settings.appCheckToken;\n }\n appCheckProvider.onInit(appCheck => {\n this.appCheck = appCheck;\n });\n }\n\n getToken(): Promise {\n if (this.serverAppAppCheckToken) {\n return Promise.resolve(new AppCheckToken(this.serverAppAppCheckToken));\n }\n\n if (!this.appCheck) {\n return Promise.resolve(null);\n }\n\n return this.appCheck.getToken().then(tokenResult => {\n if (tokenResult) {\n hardAssert(\n typeof tokenResult.token === 'string',\n 0x0d8e,\n 'Invalid tokenResult returned from getToken()',\n { tokenResult }\n );\n return new AppCheckToken(tokenResult.token);\n } else {\n return null;\n }\n });\n }\n\n invalidateToken(): void {}\n\n start(\n asyncQueue: AsyncQueue,\n changeListener: CredentialChangeListener\n ): void {}\n\n shutdown(): void {}\n}\n\n/**\n * Builds a CredentialsProvider depending on the type of\n * the credentials passed in.\n */\nexport function makeAuthCredentialsProvider(\n credentials?: CredentialsSettings\n): CredentialsProvider {\n if (!credentials) {\n return new EmptyAuthCredentialsProvider();\n }\n switch (credentials['type']) {\n case 'firstParty':\n return new FirstPartyAuthCredentialsProvider(\n credentials['sessionIndex'] || '0',\n credentials['iamToken'] || null,\n credentials['authTokenFactory'] || null\n );\n\n case 'provider':\n return credentials['client'];\n\n default:\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'makeAuthCredentialsProvider failed due to invalid credential type'\n );\n }\n}\n","import { FirebaseApp } from '@firebase/app';\n\nimport { ExperimentalLongPollingOptions } from '../api/long_polling_options';\nimport { Code, FirestoreError } from '../util/error';\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport class DatabaseInfo {\n /**\n * Constructs a DatabaseInfo using the provided host, databaseId and\n * persistenceKey.\n *\n * @param databaseId - The database to use.\n * @param appId - The Firebase App Id.\n * @param persistenceKey - A unique identifier for this Firestore's local\n * storage (used in conjunction with the databaseId).\n * @param host - The Firestore backend host to connect to.\n * @param ssl - Whether to use SSL when connecting.\n * @param forceLongPolling - Whether to use the forceLongPolling option\n * when using WebChannel as the network transport.\n * @param autoDetectLongPolling - Whether to use the detectBufferingProxy\n * option when using WebChannel as the network transport.\n * @param longPollingOptions Options that configure long-polling.\n * @param useFetchStreams Whether to use the Fetch API instead of\n * XMLHTTPRequest\n */\n constructor(\n readonly databaseId: DatabaseId,\n readonly appId: string,\n readonly persistenceKey: string,\n readonly host: string,\n readonly ssl: boolean,\n readonly forceLongPolling: boolean,\n readonly autoDetectLongPolling: boolean,\n readonly longPollingOptions: ExperimentalLongPollingOptions,\n readonly useFetchStreams: boolean,\n readonly isUsingEmulator: boolean\n ) {}\n}\n\n/** The default database name for a project. */\nexport const DEFAULT_DATABASE_NAME = '(default)';\n\n/**\n * Represents the database ID a Firestore client is associated with.\n * @internal\n */\nexport class DatabaseId {\n readonly database: string;\n constructor(readonly projectId: string, database?: string) {\n this.database = database ? database : DEFAULT_DATABASE_NAME;\n }\n\n static empty(): DatabaseId {\n return new DatabaseId('', '');\n }\n\n get isDefaultDatabase(): boolean {\n return this.database === DEFAULT_DATABASE_NAME;\n }\n\n isEqual(other: {}): boolean {\n return (\n other instanceof DatabaseId &&\n other.projectId === this.projectId &&\n other.database === this.database\n );\n }\n}\n\nexport function databaseIdFromApp(\n app: FirebaseApp,\n database?: string\n): DatabaseId {\n if (!Object.prototype.hasOwnProperty.apply(app.options, ['projectId'])) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n '\"projectId\" not provided in firebase.initializeApp.'\n );\n }\n\n return new DatabaseId(app.options.projectId!, database);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { randomBytes as generateRandomBytes } from 'crypto';\n\nimport { debugAssert } from '../../util/assert';\n\n/**\n * Generates `nBytes` of random bytes.\n *\n * If `nBytes < 0` , an error will be thrown.\n */\nexport function randomBytes(nBytes: number): Uint8Array {\n debugAssert(nBytes >= 0, `Expecting non-negative nBytes, got: ${nBytes}`);\n return generateRandomBytes(nBytes);\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { randomBytes } from '../platform/random_bytes';\n\nimport { debugAssert } from './assert';\n\nexport type EventHandler = (value: E) => void;\nexport interface Indexable {\n [k: string]: unknown;\n}\n\n/**\n * A utility class for generating unique alphanumeric IDs of a specified length.\n *\n * @internal\n * Exported internally for testing purposes.\n */\nexport class AutoId {\n static newId(): string {\n // Alphanumeric characters\n const chars =\n 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';\n // The largest byte value that is a multiple of `char.length`.\n const maxMultiple = Math.floor(256 / chars.length) * chars.length;\n debugAssert(\n 0 < maxMultiple && maxMultiple < 256,\n `Expect maxMultiple to be (0, 256), but got ${maxMultiple}`\n );\n\n let autoId = '';\n const targetLength = 20;\n while (autoId.length < targetLength) {\n const bytes = randomBytes(40);\n for (let i = 0; i < bytes.length; ++i) {\n // Only accept values that are [0, maxMultiple), this ensures they can\n // be evenly mapped to indices of `chars` via a modulo operation.\n if (autoId.length < targetLength && bytes[i] < maxMultiple) {\n autoId += chars.charAt(bytes[i] % chars.length);\n }\n }\n }\n debugAssert(autoId.length === targetLength, 'Invalid auto ID: ' + autoId);\n\n return autoId;\n }\n}\n\nexport function primitiveComparator(left: T, right: T): number {\n if (left < right) {\n return -1;\n }\n if (left > right) {\n return 1;\n }\n return 0;\n}\n\nexport interface Equatable {\n isEqual(other: T): boolean;\n}\n\n/** Compare strings in UTF-8 encoded byte order */\nexport function compareUtf8Strings(left: string, right: string): number {\n // Find the first differing character (a.k.a. \"UTF-16 code unit\") in the two strings and,\n // if found, use that character to determine the relative ordering of the two strings as a\n // whole. Comparing UTF-16 strings in UTF-8 byte order can be done simply and efficiently by\n // comparing the UTF-16 code units (chars). This serendipitously works because of the way UTF-8\n // and UTF-16 happen to represent Unicode code points.\n //\n // After finding the first pair of differing characters, there are two cases:\n //\n // Case 1: Both characters are non-surrogates (code points less than or equal to 0xFFFF) or\n // both are surrogates from a surrogate pair (that collectively represent code points greater\n // than 0xFFFF). In this case their numeric order as UTF-16 code units is the same as the\n // lexicographical order of their corresponding UTF-8 byte sequences. A direct comparison is\n // sufficient.\n //\n // Case 2: One character is a surrogate and the other is not. In this case the surrogate-\n // containing string is always ordered after the non-surrogate. This is because surrogates are\n // used to represent code points greater than 0xFFFF which have 4-byte UTF-8 representations\n // and are lexicographically greater than the 1, 2, or 3-byte representations of code points\n // less than or equal to 0xFFFF.\n //\n // An example of why Case 2 is required is comparing the following two Unicode code points:\n //\n // |-----------------------|------------|---------------------|-----------------|\n // | Name | Code Point | UTF-8 Encoding | UTF-16 Encoding |\n // |-----------------------|------------|---------------------|-----------------|\n // | Replacement Character | U+FFFD | 0xEF 0xBF 0xBD | 0xFFFD |\n // | Grinning Face | U+1F600 | 0xF0 0x9F 0x98 0x80 | 0xD83D 0xDE00 |\n // |-----------------------|------------|---------------------|-----------------|\n //\n // A lexicographical comparison of the UTF-8 encodings of these code points would order\n // \"Replacement Character\" _before_ \"Grinning Face\" because 0xEF is less than 0xF0. However, a\n // direct comparison of the UTF-16 code units, as would be done in case 1, would erroneously\n // produce the _opposite_ ordering, because 0xFFFD is _greater than_ 0xD83D. As it turns out,\n // this relative ordering holds for all comparisons of UTF-16 code points requiring a surrogate\n // pair with those that do not.\n const length = Math.min(left.length, right.length);\n for (let i = 0; i < length; i++) {\n const leftChar = left.charAt(i);\n const rightChar = right.charAt(i);\n if (leftChar !== rightChar) {\n return isSurrogate(leftChar) === isSurrogate(rightChar)\n ? primitiveComparator(leftChar, rightChar)\n : isSurrogate(leftChar)\n ? 1\n : -1;\n }\n }\n\n // Use the lengths of the strings to determine the overall comparison result since either the\n // strings were equal or one is a prefix of the other.\n return primitiveComparator(left.length, right.length);\n}\n\nconst MIN_SURROGATE = 0xd800;\nconst MAX_SURROGATE = 0xdfff;\n\nexport function isSurrogate(s: string): boolean {\n debugAssert(s.length === 1, `s.length == ${s.length}, but expected 1`);\n const c = s.charCodeAt(0);\n return c >= MIN_SURROGATE && c <= MAX_SURROGATE;\n}\n\nexport interface Iterable {\n forEach: (cb: (v: V) => void) => void;\n}\n\n/** Helper to compare arrays using isEqual(). */\nexport function arrayEquals(\n left: T[],\n right: T[],\n comparator: (l: T, r: T) => boolean\n): boolean {\n if (left.length !== right.length) {\n return false;\n }\n return left.every((value, index) => comparator(value, right[index]));\n}\n/**\n * Returns the immediate lexicographically-following string. This is useful to\n * construct an inclusive range for indexeddb iterators.\n */\nexport function immediateSuccessor(s: string): string {\n // Return the input string, with an additional NUL byte appended.\n return s + '\\0';\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Integer } from '@firebase/webchannel-wrapper/bloom-blob';\n\nimport { debugAssert, fail } from '../util/assert';\nimport { Code, FirestoreError } from '../util/error';\nimport { compareUtf8Strings, primitiveComparator } from '../util/misc';\n\nexport const DOCUMENT_KEY_NAME = '__name__';\n\n/**\n * Path represents an ordered sequence of string segments.\n */\nabstract class BasePath> {\n private segments: string[];\n private offset: number;\n private len: number;\n\n constructor(segments: string[], offset?: number, length?: number) {\n if (offset === undefined) {\n offset = 0;\n } else if (offset > segments.length) {\n fail(0x027d, 'offset out of range', {\n offset,\n range: segments.length\n });\n }\n\n if (length === undefined) {\n length = segments.length - offset;\n } else if (length > segments.length - offset) {\n fail(0x06d2, 'length out of range', {\n length,\n range: segments.length - offset\n });\n }\n this.segments = segments;\n this.offset = offset;\n this.len = length;\n }\n\n /**\n * Abstract constructor method to construct an instance of B with the given\n * parameters.\n */\n protected abstract construct(\n segments: string[],\n offset?: number,\n length?: number\n ): B;\n\n /**\n * Returns a String representation.\n *\n * Implementing classes are required to provide deterministic implementations as\n * the String representation is used to obtain canonical Query IDs.\n */\n abstract toString(): string;\n\n get length(): number {\n return this.len;\n }\n\n isEqual(other: B): boolean {\n return BasePath.comparator(this, other) === 0;\n }\n\n child(nameOrPath: string | B): B {\n const segments = this.segments.slice(this.offset, this.limit());\n if (nameOrPath instanceof BasePath) {\n nameOrPath.forEach(segment => {\n segments.push(segment);\n });\n } else {\n segments.push(nameOrPath);\n }\n return this.construct(segments);\n }\n\n /** The index of one past the last segment of the path. */\n private limit(): number {\n return this.offset + this.length;\n }\n\n popFirst(size?: number): B {\n size = size === undefined ? 1 : size;\n debugAssert(\n this.length >= size,\n \"Can't call popFirst() with less segments\"\n );\n return this.construct(\n this.segments,\n this.offset + size,\n this.length - size\n );\n }\n\n popLast(): B {\n debugAssert(!this.isEmpty(), \"Can't call popLast() on empty path\");\n return this.construct(this.segments, this.offset, this.length - 1);\n }\n\n firstSegment(): string {\n debugAssert(!this.isEmpty(), \"Can't call firstSegment() on empty path\");\n return this.segments[this.offset];\n }\n\n lastSegment(): string {\n debugAssert(!this.isEmpty(), \"Can't call lastSegment() on empty path\");\n return this.get(this.length - 1);\n }\n\n get(index: number): string {\n debugAssert(index < this.length, 'Index out of range');\n return this.segments[this.offset + index];\n }\n\n isEmpty(): boolean {\n return this.length === 0;\n }\n\n isPrefixOf(other: this): boolean {\n if (other.length < this.length) {\n return false;\n }\n\n for (let i = 0; i < this.length; i++) {\n if (this.get(i) !== other.get(i)) {\n return false;\n }\n }\n\n return true;\n }\n\n isImmediateParentOf(potentialChild: this): boolean {\n if (this.length + 1 !== potentialChild.length) {\n return false;\n }\n\n for (let i = 0; i < this.length; i++) {\n if (this.get(i) !== potentialChild.get(i)) {\n return false;\n }\n }\n\n return true;\n }\n\n forEach(fn: (segment: string) => void): void {\n for (let i = this.offset, end = this.limit(); i < end; i++) {\n fn(this.segments[i]);\n }\n }\n\n toArray(): string[] {\n return this.segments.slice(this.offset, this.limit());\n }\n\n /**\n * Compare 2 paths segment by segment, prioritizing numeric IDs\n * (e.g., \"__id123__\") in numeric ascending order, followed by string\n * segments in lexicographical order.\n */\n static comparator>(\n p1: BasePath,\n p2: BasePath\n ): number {\n const len = Math.min(p1.length, p2.length);\n for (let i = 0; i < len; i++) {\n const comparison = BasePath.compareSegments(p1.get(i), p2.get(i));\n if (comparison !== 0) {\n return comparison;\n }\n }\n return primitiveComparator(p1.length, p2.length);\n }\n\n private static compareSegments(lhs: string, rhs: string): number {\n const isLhsNumeric = BasePath.isNumericId(lhs);\n const isRhsNumeric = BasePath.isNumericId(rhs);\n\n if (isLhsNumeric && !isRhsNumeric) {\n // Only lhs is numeric\n return -1;\n } else if (!isLhsNumeric && isRhsNumeric) {\n // Only rhs is numeric\n return 1;\n } else if (isLhsNumeric && isRhsNumeric) {\n // both numeric\n return BasePath.extractNumericId(lhs).compare(\n BasePath.extractNumericId(rhs)\n );\n } else {\n // both non-numeric\n return compareUtf8Strings(lhs, rhs);\n }\n }\n\n // Checks if a segment is a numeric ID (starts with \"__id\" and ends with \"__\").\n private static isNumericId(segment: string): boolean {\n return segment.startsWith('__id') && segment.endsWith('__');\n }\n\n private static extractNumericId(segment: string): Integer {\n return Integer.fromString(segment.substring(4, segment.length - 2));\n }\n}\n\n/**\n * A slash-separated path for navigating resources (documents and collections)\n * within Firestore.\n *\n * @internal\n */\nexport class ResourcePath extends BasePath {\n protected construct(\n segments: string[],\n offset?: number,\n length?: number\n ): ResourcePath {\n return new ResourcePath(segments, offset, length);\n }\n\n canonicalString(): string {\n // NOTE: The client is ignorant of any path segments containing escape\n // sequences (e.g. __id123__) and just passes them through raw (they exist\n // for legacy reasons and should not be used frequently).\n\n return this.toArray().join('/');\n }\n\n toString(): string {\n return this.canonicalString();\n }\n\n /**\n * Returns a string representation of this path\n * where each path segment has been encoded with\n * `encodeURIComponent`.\n */\n toUriEncodedString(): string {\n return this.toArray().map(encodeURIComponent).join('/');\n }\n\n /**\n * Creates a resource path from the given slash-delimited string. If multiple\n * arguments are provided, all components are combined. Leading and trailing\n * slashes from all components are ignored.\n */\n static fromString(...pathComponents: string[]): ResourcePath {\n // NOTE: The client is ignorant of any path segments containing escape\n // sequences (e.g. __id123__) and just passes them through raw (they exist\n // for legacy reasons and should not be used frequently).\n\n const segments: string[] = [];\n for (const path of pathComponents) {\n if (path.indexOf('//') >= 0) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid segment (${path}). Paths must not contain // in them.`\n );\n }\n // Strip leading and trailing slashed.\n segments.push(...path.split('/').filter(segment => segment.length > 0));\n }\n\n return new ResourcePath(segments);\n }\n\n static emptyPath(): ResourcePath {\n return new ResourcePath([]);\n }\n}\n\nconst identifierRegExp = /^[_a-zA-Z][_a-zA-Z0-9]*$/;\n\n/**\n * A dot-separated path for navigating sub-objects within a document.\n * @internal\n */\nexport class FieldPath extends BasePath {\n protected construct(\n segments: string[],\n offset?: number,\n length?: number\n ): FieldPath {\n return new FieldPath(segments, offset, length);\n }\n\n /**\n * Returns true if the string could be used as a segment in a field path\n * without escaping.\n */\n private static isValidIdentifier(segment: string): boolean {\n return identifierRegExp.test(segment);\n }\n\n canonicalString(): string {\n return this.toArray()\n .map(str => {\n str = str.replace(/\\\\/g, '\\\\\\\\').replace(/`/g, '\\\\`');\n if (!FieldPath.isValidIdentifier(str)) {\n str = '`' + str + '`';\n }\n return str;\n })\n .join('.');\n }\n\n toString(): string {\n return this.canonicalString();\n }\n\n /**\n * Returns true if this field references the key of a document.\n */\n isKeyField(): boolean {\n return this.length === 1 && this.get(0) === DOCUMENT_KEY_NAME;\n }\n\n /**\n * The field designating the key of a document.\n */\n static keyField(): FieldPath {\n return new FieldPath([DOCUMENT_KEY_NAME]);\n }\n\n /**\n * Parses a field string from the given server-formatted string.\n *\n * - Splitting the empty string is not allowed (for now at least).\n * - Empty segments within the string (e.g. if there are two consecutive\n * separators) are not allowed.\n *\n * TODO(b/37244157): we should make this more strict. Right now, it allows\n * non-identifier path components, even if they aren't escaped.\n */\n static fromServerFormat(path: string): FieldPath {\n const segments: string[] = [];\n let current = '';\n let i = 0;\n\n const addCurrentSegment = (): void => {\n if (current.length === 0) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid field path (${path}). Paths must not be empty, begin ` +\n `with '.', end with '.', or contain '..'`\n );\n }\n segments.push(current);\n current = '';\n };\n\n let inBackticks = false;\n\n while (i < path.length) {\n const c = path[i];\n if (c === '\\\\') {\n if (i + 1 === path.length) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Path has trailing escape character: ' + path\n );\n }\n const next = path[i + 1];\n if (!(next === '\\\\' || next === '.' || next === '`')) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Path has invalid escape sequence: ' + path\n );\n }\n current += next;\n i += 2;\n } else if (c === '`') {\n inBackticks = !inBackticks;\n i++;\n } else if (c === '.' && !inBackticks) {\n addCurrentSegment();\n i++;\n } else {\n current += c;\n i++;\n }\n }\n addCurrentSegment();\n\n if (inBackticks) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Unterminated ` in path: ' + path\n );\n }\n\n return new FieldPath(segments);\n }\n\n static emptyPath(): FieldPath {\n return new FieldPath([]);\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { debugAssert } from '../util/assert';\n\nimport { ResourcePath } from './path';\n\n/**\n * @internal\n */\nexport class DocumentKey {\n constructor(readonly path: ResourcePath) {\n debugAssert(\n DocumentKey.isDocumentKey(path),\n 'Invalid DocumentKey with an odd number of segments: ' +\n path.toArray().join('/')\n );\n }\n\n static fromPath(path: string): DocumentKey {\n return new DocumentKey(ResourcePath.fromString(path));\n }\n\n static fromName(name: string): DocumentKey {\n return new DocumentKey(ResourcePath.fromString(name).popFirst(5));\n }\n\n static empty(): DocumentKey {\n return new DocumentKey(ResourcePath.emptyPath());\n }\n\n get collectionGroup(): string {\n debugAssert(\n !this.path.isEmpty(),\n 'Cannot get collection group for empty key'\n );\n return this.path.popLast().lastSegment();\n }\n\n /** Returns true if the document is in the specified collectionId. */\n hasCollectionId(collectionId: string): boolean {\n return (\n this.path.length >= 2 &&\n this.path.get(this.path.length - 2) === collectionId\n );\n }\n\n /** Returns the collection group (i.e. the name of the parent collection) for this key. */\n getCollectionGroup(): string {\n debugAssert(\n !this.path.isEmpty(),\n 'Cannot get collection group for empty key'\n );\n return this.path.get(this.path.length - 2);\n }\n\n /** Returns the fully qualified path to the parent collection. */\n getCollectionPath(): ResourcePath {\n return this.path.popLast();\n }\n\n isEqual(other: DocumentKey | null): boolean {\n return (\n other !== null && ResourcePath.comparator(this.path, other.path) === 0\n );\n }\n\n toString(): string {\n return this.path.toString();\n }\n\n static comparator(k1: DocumentKey, k2: DocumentKey): number {\n return ResourcePath.comparator(k1.path, k2.path);\n }\n\n static isDocumentKey(path: ResourcePath): boolean {\n return path.length % 2 === 0;\n }\n\n /**\n * Creates and returns a new document key with the given segments.\n *\n * @param segments - The segments of the path to the document\n * @returns A new instance of DocumentKey\n */\n static fromSegments(segments: string[]): DocumentKey {\n return new DocumentKey(new ResourcePath(segments.slice()));\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DocumentKey } from '../model/document_key';\nimport { ResourcePath } from '../model/path';\n\nimport { fail } from './assert';\nimport { Code, FirestoreError } from './error';\n\n/** Types accepted by validateType() and related methods for validation. */\nexport type ValidationType =\n | 'undefined'\n | 'object'\n | 'function'\n | 'boolean'\n | 'number'\n | 'string'\n | 'non-empty string';\n\nexport function validateNonEmptyArgument(\n functionName: string,\n argumentName: string,\n argument?: string\n): asserts argument is string {\n if (!argument) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Function ${functionName}() cannot be called with an empty ${argumentName}.`\n );\n }\n}\n\n/**\n * Validates that two boolean options are not set at the same time.\n * @internal\n */\nexport function validateIsNotUsedTogether(\n optionName1: string,\n argument1: boolean | undefined,\n optionName2: string,\n argument2: boolean | undefined\n): void {\n if (argument1 === true && argument2 === true) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `${optionName1} and ${optionName2} cannot be used together.`\n );\n }\n}\n\n/**\n * Validates that `path` refers to a document (indicated by the fact it contains\n * an even numbers of segments).\n */\nexport function validateDocumentPath(path: ResourcePath): void {\n if (!DocumentKey.isDocumentKey(path)) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid document reference. Document references must have an even number of segments, but ${path} has ${path.length}.`\n );\n }\n}\n\n/**\n * Validates that `path` refers to a collection (indicated by the fact it\n * contains an odd numbers of segments).\n */\nexport function validateCollectionPath(path: ResourcePath): void {\n if (DocumentKey.isDocumentKey(path)) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid collection reference. Collection references must have an odd number of segments, but ${path} has ${path.length}.`\n );\n }\n}\n\n/**\n * Returns true if it's a non-null object without a custom prototype\n * (i.e. excludes Array, Date, etc.).\n */\nexport function isPlainObject(input: unknown): boolean {\n return (\n typeof input === 'object' &&\n input !== null &&\n (Object.getPrototypeOf(input) === Object.prototype ||\n Object.getPrototypeOf(input) === null)\n );\n}\n\n/** Returns a string describing the type / value of the provided input. */\nexport function valueDescription(input: unknown): string {\n if (input === undefined) {\n return 'undefined';\n } else if (input === null) {\n return 'null';\n } else if (typeof input === 'string') {\n if (input.length > 20) {\n input = `${input.substring(0, 20)}...`;\n }\n return JSON.stringify(input);\n } else if (typeof input === 'number' || typeof input === 'boolean') {\n return '' + input;\n } else if (typeof input === 'object') {\n if (input instanceof Array) {\n return 'an array';\n } else {\n const customObjectName = tryGetCustomObjectType(input!);\n if (customObjectName) {\n return `a custom ${customObjectName} object`;\n } else {\n return 'an object';\n }\n }\n } else if (typeof input === 'function') {\n return 'a function';\n } else {\n return fail(0x3029, 'Unknown wrong type', { type: typeof input });\n }\n}\n\n/** try to get the constructor name for an object. */\nexport function tryGetCustomObjectType(input: object): string | null {\n if (input.constructor) {\n return input.constructor.name;\n }\n return null;\n}\n\n/**\n * Casts `obj` to `T`, optionally unwrapping Compat types to expose the\n * underlying instance. Throws if `obj` is not an instance of `T`.\n *\n * This cast is used in the Lite and Full SDK to verify instance types for\n * arguments passed to the public API.\n * @internal\n */\nexport function cast(\n obj: object,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n constructor: { new (...args: any[]): T }\n): T | never {\n if ('_delegate' in obj) {\n // Unwrap Compat types\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n obj = (obj as any)._delegate;\n }\n\n if (!(obj instanceof constructor)) {\n if (constructor.name === obj.constructor.name) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Type does not match the expected instance. Did you pass a ' +\n `reference from a different Firestore SDK?`\n );\n } else {\n const description = valueDescription(obj);\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Expected type '${constructor.name}', but it was: ${description}`\n );\n }\n }\n return obj as T;\n}\n\nexport function validatePositiveNumber(functionName: string, n: number): void {\n if (n <= 0) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Function ${functionName}() requires a positive number, but it was: ${n}.`\n );\n }\n}\n","/**\n * @license\n * Copyright 2023 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Options that configure the SDK’s underlying network transport (WebChannel)\n * when long-polling is used.\n *\n * Note: This interface is \"experimental\" and is subject to change.\n *\n * See `FirestoreSettings.experimentalAutoDetectLongPolling`,\n * `FirestoreSettings.experimentalForceLongPolling`, and\n * `FirestoreSettings.experimentalLongPollingOptions`.\n */\nexport interface ExperimentalLongPollingOptions {\n /**\n * The desired maximum timeout interval, in seconds, to complete a\n * long-polling GET response. Valid values are between 5 and 30, inclusive.\n * Floating point values are allowed and will be rounded to the nearest\n * millisecond.\n *\n * By default, when long-polling is used the \"hanging GET\" request sent by\n * the client times out after 30 seconds. To request a different timeout\n * from the server, set this setting with the desired timeout.\n *\n * Changing the default timeout may be useful, for example, if the buffering\n * proxy that necessitated enabling long-polling in the first place has a\n * shorter timeout for hanging GET requests, in which case setting the\n * long-polling timeout to a shorter value, such as 25 seconds, may fix\n * prematurely-closed hanging GET requests.\n * For example, see https://github.com/firebase/firebase-js-sdk/issues/6987.\n */\n timeoutSeconds?: number;\n}\n\n/**\n * Compares two `ExperimentalLongPollingOptions` objects for equality.\n */\nexport function longPollingOptionsEqual(\n options1: ExperimentalLongPollingOptions,\n options2: ExperimentalLongPollingOptions\n): boolean {\n return options1.timeoutSeconds === options2.timeoutSeconds;\n}\n\n/**\n * Creates and returns a new `ExperimentalLongPollingOptions` with the same\n * option values as the given instance.\n */\nexport function cloneLongPollingOptions(\n options: ExperimentalLongPollingOptions\n): ExperimentalLongPollingOptions {\n const clone: ExperimentalLongPollingOptions = {};\n\n if (options.timeoutSeconds !== undefined) {\n clone.timeoutSeconds = options.timeoutSeconds;\n }\n\n return clone;\n}\n","/**\n * @license\n * Copyright 2023 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * The value returned from the most recent invocation of\n * `generateUniqueDebugId()`, or null if it has never been invoked.\n */\nlet lastUniqueDebugId: number | null = null;\n\n/**\n * Generates and returns an initial value for `lastUniqueDebugId`.\n *\n * The returned value is randomly selected from a range of integers that are\n * represented as 8 hexadecimal digits. This means that (within reason) any\n * numbers generated by incrementing the returned number by 1 will also be\n * represented by 8 hexadecimal digits. This leads to all \"IDs\" having the same\n * length when converted to a hexadecimal string, making reading logs containing\n * these IDs easier to follow. And since the return value is randomly selected\n * it will help to differentiate between logs from different executions.\n */\nfunction generateInitialUniqueDebugId(): number {\n const minResult = 0x10000000;\n const maxResult = 0x90000000;\n const resultRange = maxResult - minResult;\n const resultOffset = Math.round(resultRange * Math.random());\n return minResult + resultOffset;\n}\n\n/**\n * Generates and returns a unique ID as a hexadecimal string.\n *\n * The returned ID is intended to be used in debug logging messages to help\n * correlate log messages that may be spatially separated in the logs, but\n * logically related. For example, a network connection could include the same\n * \"debug ID\" string in all of its log messages to help trace a specific\n * connection over time.\n *\n * @return the 10-character generated ID (e.g. \"0xa1b2c3d4\").\n */\nexport function generateUniqueDebugId(): string {\n if (lastUniqueDebugId === null) {\n lastUniqueDebugId = generateInitialUniqueDebugId();\n } else {\n lastUniqueDebugId++;\n }\n return '0x' + lastUniqueDebugId.toString(16);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isCloudWorkstation } from '@firebase/util';\n\nimport { SDK_VERSION } from '../../src/core/version';\nimport { Token } from '../api/credentials';\nimport {\n DatabaseId,\n DatabaseInfo,\n DEFAULT_DATABASE_NAME\n} from '../core/database_info';\nimport { ResourcePath } from '../model/path';\nimport { debugAssert } from '../util/assert';\nimport { generateUniqueDebugId } from '../util/debug_uid';\nimport { FirestoreError } from '../util/error';\nimport { logDebug, logWarn } from '../util/log';\nimport { StringMap } from '../util/types';\n\nimport { Connection, Stream } from './connection';\n\nconst LOG_TAG = 'RestConnection';\n\n/**\n * Maps RPC names to the corresponding REST endpoint name.\n *\n * We use array notation to avoid mangling.\n */\nconst RPC_NAME_URL_MAPPING: StringMap = {};\n\nRPC_NAME_URL_MAPPING['BatchGetDocuments'] = 'batchGet';\nRPC_NAME_URL_MAPPING['Commit'] = 'commit';\nRPC_NAME_URL_MAPPING['RunQuery'] = 'runQuery';\nRPC_NAME_URL_MAPPING['RunAggregationQuery'] = 'runAggregationQuery';\n\nconst RPC_URL_VERSION = 'v1';\n\n// SDK_VERSION is updated to different value at runtime depending on the entry point,\n// so we need to get its value when we need it in a function.\nfunction getGoogApiClientValue(): string {\n return 'gl-js/ fire/' + SDK_VERSION;\n}\n/**\n * Base class for all Rest-based connections to the backend (WebChannel and\n * HTTP).\n */\nexport abstract class RestConnection implements Connection {\n protected readonly databaseId: DatabaseId;\n protected readonly baseUrl: string;\n private readonly databasePath: string;\n private readonly requestParams: string;\n\n get shouldResourcePathBeIncludedInRequest(): boolean {\n // Both `invokeRPC()` and `invokeStreamingRPC()` use their `path` arguments to determine\n // where to run the query, and expect the `request` to NOT specify the \"path\".\n return false;\n }\n\n constructor(private readonly databaseInfo: DatabaseInfo) {\n this.databaseId = databaseInfo.databaseId;\n const proto = databaseInfo.ssl ? 'https' : 'http';\n const projectId = encodeURIComponent(this.databaseId.projectId);\n const databaseId = encodeURIComponent(this.databaseId.database);\n this.baseUrl = proto + '://' + databaseInfo.host;\n this.databasePath = `projects/${projectId}/databases/${databaseId}`;\n this.requestParams =\n this.databaseId.database === DEFAULT_DATABASE_NAME\n ? `project_id=${projectId}`\n : `project_id=${projectId}&database_id=${databaseId}`;\n }\n\n invokeRPC(\n rpcName: string,\n path: ResourcePath,\n req: Req,\n authToken: Token | null,\n appCheckToken: Token | null\n ): Promise {\n const streamId = generateUniqueDebugId();\n const url = this.makeUrl(rpcName, path.toUriEncodedString());\n logDebug(LOG_TAG, `Sending RPC '${rpcName}' ${streamId}:`, url, req);\n\n const headers: StringMap = {\n 'google-cloud-resource-prefix': this.databasePath,\n 'x-goog-request-params': this.requestParams\n };\n this.modifyHeadersForRequest(headers, authToken, appCheckToken);\n\n const { host } = new URL(url);\n const forwardCredentials = isCloudWorkstation(host);\n return this.performRPCRequest(\n rpcName,\n url,\n headers,\n req,\n forwardCredentials\n ).then(\n response => {\n logDebug(LOG_TAG, `Received RPC '${rpcName}' ${streamId}: `, response);\n return response;\n },\n (err: FirestoreError) => {\n logWarn(\n LOG_TAG,\n `RPC '${rpcName}' ${streamId} failed with error: `,\n err,\n 'url: ',\n url,\n 'request:',\n req\n );\n throw err;\n }\n );\n }\n\n invokeStreamingRPC(\n rpcName: string,\n path: ResourcePath,\n request: Req,\n authToken: Token | null,\n appCheckToken: Token | null,\n expectedResponseCount?: number\n ): Promise {\n // The REST API automatically aggregates all of the streamed results, so we\n // can just use the normal invoke() method.\n return this.invokeRPC(\n rpcName,\n path,\n request,\n authToken,\n appCheckToken\n );\n }\n\n abstract openStream(\n rpcName: string,\n authToken: Token | null,\n appCheckToken: Token | null\n ): Stream;\n\n /**\n * Modifies the headers for a request, adding any authorization token if\n * present and any additional headers for the request.\n */\n protected modifyHeadersForRequest(\n headers: StringMap,\n authToken: Token | null,\n appCheckToken: Token | null\n ): void {\n headers['X-Goog-Api-Client'] = getGoogApiClientValue();\n\n // Content-Type: text/plain will avoid preflight requests which might\n // mess with CORS and redirects by proxies. If we add custom headers\n // we will need to change this code to potentially use the $httpOverwrite\n // parameter supported by ESF to avoid triggering preflight requests.\n headers['Content-Type'] = 'text/plain';\n\n if (this.databaseInfo.appId) {\n headers['X-Firebase-GMPID'] = this.databaseInfo.appId;\n }\n\n if (authToken) {\n authToken.headers.forEach((value, key) => (headers[key] = value));\n }\n if (appCheckToken) {\n appCheckToken.headers.forEach((value, key) => (headers[key] = value));\n }\n }\n\n /**\n * Performs an RPC request using an implementation specific networking layer.\n */\n protected abstract performRPCRequest(\n rpcName: string,\n url: string,\n headers: StringMap,\n body: Req,\n _forwardCredentials: boolean\n ): Promise;\n\n private makeUrl(rpcName: string, path: string): string {\n const urlRpcName = RPC_NAME_URL_MAPPING[rpcName];\n debugAssert(\n urlRpcName !== undefined,\n 'Unknown REST mapping for: ' + rpcName\n );\n return `${this.baseUrl}/${RPC_URL_VERSION}/${path}:${urlRpcName}`;\n }\n\n /**\n * Closes and cleans up any resources associated with the connection. This\n * implementation is a no-op because there are no resources associated\n * with the RestConnection that need to be cleaned up.\n */\n terminate(): void {\n // No-op\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { fail } from '../util/assert';\nimport { Code } from '../util/error';\nimport { logError } from '../util/log';\n\n/**\n * Error Codes describing the different ways GRPC can fail. These are copied\n * directly from GRPC's sources here:\n *\n * https://github.com/grpc/grpc/blob/bceec94ea4fc5f0085d81235d8e1c06798dc341a/include/grpc%2B%2B/impl/codegen/status_code_enum.h\n *\n * Important! The names of these identifiers matter because the string forms\n * are used for reverse lookups from the webchannel stream. Do NOT change the\n * names of these identifiers or change this into a const enum.\n */\nenum RpcCode {\n OK = 0,\n CANCELLED = 1,\n UNKNOWN = 2,\n INVALID_ARGUMENT = 3,\n DEADLINE_EXCEEDED = 4,\n NOT_FOUND = 5,\n ALREADY_EXISTS = 6,\n PERMISSION_DENIED = 7,\n UNAUTHENTICATED = 16,\n RESOURCE_EXHAUSTED = 8,\n FAILED_PRECONDITION = 9,\n ABORTED = 10,\n OUT_OF_RANGE = 11,\n UNIMPLEMENTED = 12,\n INTERNAL = 13,\n UNAVAILABLE = 14,\n DATA_LOSS = 15\n}\n\n/**\n * Determines whether an error code represents a permanent error when received\n * in response to a non-write operation.\n *\n * See isPermanentWriteError for classifying write errors.\n */\nexport function isPermanentError(code: Code): boolean {\n switch (code) {\n case Code.OK:\n return fail(0xfdaa, 'Treated status OK as error');\n case Code.CANCELLED:\n case Code.UNKNOWN:\n case Code.DEADLINE_EXCEEDED:\n case Code.RESOURCE_EXHAUSTED:\n case Code.INTERNAL:\n case Code.UNAVAILABLE:\n // Unauthenticated means something went wrong with our token and we need\n // to retry with new credentials which will happen automatically.\n case Code.UNAUTHENTICATED:\n return false;\n case Code.INVALID_ARGUMENT:\n case Code.NOT_FOUND:\n case Code.ALREADY_EXISTS:\n case Code.PERMISSION_DENIED:\n case Code.FAILED_PRECONDITION:\n // Aborted might be retried in some scenarios, but that is dependent on\n // the context and should handled individually by the calling code.\n // See https://cloud.google.com/apis/design/errors.\n case Code.ABORTED:\n case Code.OUT_OF_RANGE:\n case Code.UNIMPLEMENTED:\n case Code.DATA_LOSS:\n return true;\n default:\n return fail(0x3c6b, 'Unknown status code', { code });\n }\n}\n\n/**\n * Determines whether an error code represents a permanent error when received\n * in response to a write operation.\n *\n * Write operations must be handled specially because as of b/119437764, ABORTED\n * errors on the write stream should be retried too (even though ABORTED errors\n * are not generally retryable).\n *\n * Note that during the initial handshake on the write stream an ABORTED error\n * signals that we should discard our stream token (i.e. it is permanent). This\n * means a handshake error should be classified with isPermanentError, above.\n */\nexport function isPermanentWriteError(code: Code): boolean {\n return isPermanentError(code) && code !== Code.ABORTED;\n}\n\n/**\n * Maps an error Code from a GRPC status identifier like 'NOT_FOUND'.\n *\n * @returns The Code equivalent to the given status string or undefined if\n * there is no match.\n */\nexport function mapCodeFromRpcStatus(status: string): Code | undefined {\n // lookup by string\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const code: RpcCode = RpcCode[status as any] as any;\n if (code === undefined) {\n return undefined;\n }\n\n return mapCodeFromRpcCode(code);\n}\n\n/**\n * Maps an error Code from GRPC status code number, like 0, 1, or 14. These\n * are not the same as HTTP status codes.\n *\n * @returns The Code equivalent to the given GRPC status code. Fails if there\n * is no match.\n */\nexport function mapCodeFromRpcCode(code: number | undefined): Code {\n if (code === undefined) {\n // This shouldn't normally happen, but in certain error cases (like trying\n // to send invalid proto messages) we may get an error with no GRPC code.\n logError('GRPC error has no .code');\n return Code.UNKNOWN;\n }\n\n switch (code) {\n case RpcCode.OK:\n return Code.OK;\n case RpcCode.CANCELLED:\n return Code.CANCELLED;\n case RpcCode.UNKNOWN:\n return Code.UNKNOWN;\n case RpcCode.DEADLINE_EXCEEDED:\n return Code.DEADLINE_EXCEEDED;\n case RpcCode.RESOURCE_EXHAUSTED:\n return Code.RESOURCE_EXHAUSTED;\n case RpcCode.INTERNAL:\n return Code.INTERNAL;\n case RpcCode.UNAVAILABLE:\n return Code.UNAVAILABLE;\n case RpcCode.UNAUTHENTICATED:\n return Code.UNAUTHENTICATED;\n case RpcCode.INVALID_ARGUMENT:\n return Code.INVALID_ARGUMENT;\n case RpcCode.NOT_FOUND:\n return Code.NOT_FOUND;\n case RpcCode.ALREADY_EXISTS:\n return Code.ALREADY_EXISTS;\n case RpcCode.PERMISSION_DENIED:\n return Code.PERMISSION_DENIED;\n case RpcCode.FAILED_PRECONDITION:\n return Code.FAILED_PRECONDITION;\n case RpcCode.ABORTED:\n return Code.ABORTED;\n case RpcCode.OUT_OF_RANGE:\n return Code.OUT_OF_RANGE;\n case RpcCode.UNIMPLEMENTED:\n return Code.UNIMPLEMENTED;\n case RpcCode.DATA_LOSS:\n return Code.DATA_LOSS;\n default:\n return fail(0x999b, 'Unknown status code', { code });\n }\n}\n\n/**\n * Maps an RPC code from a Code. This is the reverse operation from\n * mapCodeFromRpcCode and should really only be used in tests.\n */\nexport function mapRpcCodeFromCode(code: Code | undefined): number {\n if (code === undefined) {\n return RpcCode.OK;\n }\n\n switch (code) {\n case Code.OK:\n return RpcCode.OK;\n case Code.CANCELLED:\n return RpcCode.CANCELLED;\n case Code.UNKNOWN:\n return RpcCode.UNKNOWN;\n case Code.DEADLINE_EXCEEDED:\n return RpcCode.DEADLINE_EXCEEDED;\n case Code.RESOURCE_EXHAUSTED:\n return RpcCode.RESOURCE_EXHAUSTED;\n case Code.INTERNAL:\n return RpcCode.INTERNAL;\n case Code.UNAVAILABLE:\n return RpcCode.UNAVAILABLE;\n case Code.UNAUTHENTICATED:\n return RpcCode.UNAUTHENTICATED;\n case Code.INVALID_ARGUMENT:\n return RpcCode.INVALID_ARGUMENT;\n case Code.NOT_FOUND:\n return RpcCode.NOT_FOUND;\n case Code.ALREADY_EXISTS:\n return RpcCode.ALREADY_EXISTS;\n case Code.PERMISSION_DENIED:\n return RpcCode.PERMISSION_DENIED;\n case Code.FAILED_PRECONDITION:\n return RpcCode.FAILED_PRECONDITION;\n case Code.ABORTED:\n return RpcCode.ABORTED;\n case Code.OUT_OF_RANGE:\n return RpcCode.OUT_OF_RANGE;\n case Code.UNIMPLEMENTED:\n return RpcCode.UNIMPLEMENTED;\n case Code.DATA_LOSS:\n return RpcCode.DATA_LOSS;\n default:\n return fail(0x3019, 'Unknown status code', { code });\n }\n}\n\n/**\n * Converts an HTTP Status Code to the equivalent error code.\n *\n * @param status - An HTTP Status Code, like 200, 404, 503, etc.\n * @returns The equivalent Code. Unknown status codes are mapped to\n * Code.UNKNOWN.\n */\nexport function mapCodeFromHttpStatus(status?: number): Code {\n if (status === undefined) {\n logError('RPC_ERROR', 'HTTP error has no status');\n return Code.UNKNOWN;\n }\n\n // The canonical error codes for Google APIs [1] specify mapping onto HTTP\n // status codes but the mapping is not bijective. In each case of ambiguity\n // this function chooses a primary error.\n //\n // [1]\n // https://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto\n switch (status) {\n case 200: // OK\n return Code.OK;\n\n case 400: // Bad Request\n return Code.FAILED_PRECONDITION;\n // Other possibilities based on the forward mapping\n // return Code.INVALID_ARGUMENT;\n // return Code.OUT_OF_RANGE;\n\n case 401: // Unauthorized\n return Code.UNAUTHENTICATED;\n\n case 403: // Forbidden\n return Code.PERMISSION_DENIED;\n\n case 404: // Not Found\n return Code.NOT_FOUND;\n\n case 409: // Conflict\n return Code.ABORTED;\n // Other possibilities:\n // return Code.ALREADY_EXISTS;\n\n case 416: // Range Not Satisfiable\n return Code.OUT_OF_RANGE;\n\n case 429: // Too Many Requests\n return Code.RESOURCE_EXHAUSTED;\n\n case 499: // Client Closed Request\n return Code.CANCELLED;\n\n case 500: // Internal Server Error\n return Code.UNKNOWN;\n // Other possibilities:\n // return Code.INTERNAL;\n // return Code.DATA_LOSS;\n\n case 501: // Unimplemented\n return Code.UNIMPLEMENTED;\n\n case 503: // Service Unavailable\n return Code.UNAVAILABLE;\n\n case 504: // Gateway Timeout\n return Code.DEADLINE_EXCEEDED;\n\n default:\n if (status >= 200 && status < 300) {\n return Code.OK;\n }\n if (status >= 400 && status < 500) {\n return Code.FAILED_PRECONDITION;\n }\n if (status >= 500 && status < 600) {\n return Code.INTERNAL;\n }\n return Code.UNKNOWN;\n }\n}\n\n/**\n * Converts an HTTP response's error status to the equivalent error code.\n *\n * @param status - An HTTP error response status (\"FAILED_PRECONDITION\",\n * \"UNKNOWN\", etc.)\n * @returns The equivalent Code. Non-matching responses are mapped to\n * Code.UNKNOWN.\n */\nexport function mapCodeFromHttpResponseErrorStatus(status: string): Code {\n const serverError = status.toLowerCase().replace(/_/g, '-');\n return Object.values(Code).indexOf(serverError as Code) >= 0\n ? (serverError as Code)\n : Code.UNKNOWN;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Token } from '../../api/credentials';\nimport { Stream } from '../../remote/connection';\nimport { RestConnection } from '../../remote/rest_connection';\nimport { mapCodeFromHttpStatus } from '../../remote/rpc_error';\nimport { FirestoreError } from '../../util/error';\nimport { StringMap } from '../../util/types';\n\n/**\n * A Rest-based connection that relies on the native HTTP stack\n * (e.g. `fetch` or a polyfill).\n */\nexport class FetchConnection extends RestConnection {\n openStream(\n rpcName: string,\n token: Token | null\n ): Stream {\n throw new Error('Not supported by FetchConnection');\n }\n\n protected async performRPCRequest(\n rpcName: string,\n url: string,\n headers: StringMap,\n body: Req,\n forwardCredentials: boolean\n ): Promise {\n const requestJson = JSON.stringify(body);\n let response: Response;\n\n try {\n const fetchArgs: RequestInit = {\n method: 'POST',\n headers,\n body: requestJson\n };\n if (forwardCredentials) {\n fetchArgs.credentials = 'include';\n }\n response = await fetch(url, fetchArgs);\n } catch (e) {\n const err = e as { status: number | undefined; statusText: string };\n throw new FirestoreError(\n mapCodeFromHttpStatus(err.status),\n 'Request failed with error: ' + err.statusText\n );\n }\n\n if (!response.ok) {\n let errorResponse = await response.json();\n if (Array.isArray(errorResponse)) {\n errorResponse = errorResponse[0];\n }\n const errorMessage = errorResponse?.error?.message;\n throw new FirestoreError(\n mapCodeFromHttpStatus(response.status),\n `Request failed with error: ${errorMessage ?? response.statusText}`\n );\n }\n\n return response.json();\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DatabaseInfo } from '../../core/database_info';\nimport { Connection } from '../../remote/connection';\nimport { FetchConnection } from '../browser_lite/fetch_connection';\n\nexport { newConnectivityMonitor } from '../browser/connection';\n\n/** Initializes the HTTP connection for the REST API. */\nexport function newConnection(databaseInfo: DatabaseInfo): Connection {\n return new FetchConnection(databaseInfo);\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { debugAssert } from './assert';\n\nexport interface Dict {\n [stringKey: string]: V;\n}\n\nexport function objectSize(obj: object): number {\n let count = 0;\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n count++;\n }\n }\n return count;\n}\n\nexport function forEach(\n obj: Dict | undefined,\n fn: (key: string, val: V) => void\n): void {\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n fn(key, obj[key]);\n }\n }\n}\n\nexport function mapToArray(\n obj: Dict,\n fn: (element: V, key: string, obj: Dict) => R\n): R[] {\n const result: R[] = [];\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n result.push(fn(obj[key], key, obj));\n }\n }\n return result;\n}\n\nexport function isEmpty(obj: Dict): boolean {\n debugAssert(\n obj != null && typeof obj === 'object',\n 'isEmpty() expects object parameter.'\n );\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n return false;\n }\n }\n return true;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** Sentinel value that sorts before any Mutation Batch ID. */\nexport const BATCHID_UNKNOWN = -1;\n\n// An Object whose keys and values are strings.\nexport interface StringMap {\n [key: string]: string;\n}\n\n/**\n * Returns whether a variable is either undefined or null.\n */\nexport function isNullOrUndefined(value: unknown): value is null | undefined {\n return value === null || value === undefined;\n}\n\n/** Returns whether the value represents -0. */\nexport function isNegativeZero(value: number): boolean {\n // Detect if the value is -0.0. Based on polyfill from\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is\n return value === 0 && 1 / value === 1 / -0;\n}\n\n/**\n * Returns whether a value is an integer and in the safe integer range\n * @param value - The value to test for being an integer and in the safe range\n */\nexport function isSafeInteger(value: unknown): boolean {\n return (\n typeof value === 'number' &&\n Number.isInteger(value) &&\n !isNegativeZero(value) &&\n value <= Number.MAX_SAFE_INTEGER &&\n value >= Number.MIN_SAFE_INTEGER\n );\n}\n\n/** The subset of the browser's Window interface used by the SDK. */\nexport interface WindowLike {\n readonly localStorage: Storage;\n readonly indexedDB: IDBFactory | null;\n addEventListener(type: string, listener: EventListener): void;\n removeEventListener(type: string, listener: EventListener): void;\n}\n\n/** The subset of the browser's Document interface used by the SDK. */\nexport interface DocumentLike {\n readonly visibilityState: DocumentVisibilityState;\n addEventListener(type: string, listener: EventListener): void;\n removeEventListener(type: string, listener: EventListener): void;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** Converts a Base64 encoded string to a binary string. */\n\nexport function decodeBase64(encoded: string): string {\n // Note: We used to validate the base64 string here via a regular expression.\n // This was removed to improve the performance of indexing.\n return Buffer.from(encoded, 'base64').toString('binary');\n}\n\n/** Converts a binary string to a Base64 encoded string. */\nexport function encodeBase64(raw: string): string {\n return Buffer.from(raw, 'binary').toString('base64');\n}\n\n/** True if and only if the Base64 conversion functions are available. */\nexport function isBase64Available(): boolean {\n return true;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { decodeBase64, encodeBase64 } from '../platform/base64';\n\nimport { primitiveComparator } from './misc';\n\n/**\n * Immutable class that represents a \"proto\" byte string.\n *\n * Proto byte strings can either be Base64-encoded strings or Uint8Arrays when\n * sent on the wire. This class abstracts away this differentiation by holding\n * the proto byte string in a common class that must be converted into a string\n * before being sent as a proto.\n * @internal\n */\nexport class ByteString {\n static readonly EMPTY_BYTE_STRING = new ByteString('');\n\n private constructor(private readonly binaryString: string) {}\n\n static fromBase64String(base64: string): ByteString {\n const binaryString = decodeBase64(base64);\n return new ByteString(binaryString);\n }\n\n static fromUint8Array(array: Uint8Array): ByteString {\n // TODO(indexing); Remove the copy of the byte string here as this method\n // is frequently called during indexing.\n const binaryString = binaryStringFromUint8Array(array);\n return new ByteString(binaryString);\n }\n\n [Symbol.iterator](): Iterator {\n let i = 0;\n return {\n next: () => {\n if (i < this.binaryString.length) {\n return { value: this.binaryString.charCodeAt(i++), done: false };\n } else {\n return { value: undefined, done: true };\n }\n }\n };\n }\n\n toBase64(): string {\n return encodeBase64(this.binaryString);\n }\n\n toUint8Array(): Uint8Array {\n return uint8ArrayFromBinaryString(this.binaryString);\n }\n\n approximateByteSize(): number {\n return this.binaryString.length * 2;\n }\n\n compareTo(other: ByteString): number {\n return primitiveComparator(this.binaryString, other.binaryString);\n }\n\n isEqual(other: ByteString): boolean {\n return this.binaryString === other.binaryString;\n }\n}\n\n/**\n * Helper function to convert an Uint8array to a binary string.\n */\nexport function binaryStringFromUint8Array(array: Uint8Array): string {\n let binaryString = '';\n for (let i = 0; i < array.length; ++i) {\n binaryString += String.fromCharCode(array[i]);\n }\n return binaryString;\n}\n\n/**\n * Helper function to convert a binary string to an Uint8Array.\n */\nexport function uint8ArrayFromBinaryString(binaryString: string): Uint8Array {\n const buffer = new Uint8Array(binaryString.length);\n for (let i = 0; i < binaryString.length; i++) {\n buffer[i] = binaryString.charCodeAt(i);\n }\n return buffer;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Timestamp } from '../protos/firestore_proto_api';\nimport { hardAssert } from '../util/assert';\nimport { ByteString } from '../util/byte_string';\n\n// A RegExp matching ISO 8601 UTC timestamps with optional fraction.\nconst ISO_TIMESTAMP_REG_EXP = new RegExp(\n /^\\d{4}-\\d\\d-\\d\\dT\\d\\d:\\d\\d:\\d\\d(?:\\.(\\d+))?Z$/\n);\n\n/**\n * Converts the possible Proto values for a timestamp value into a \"seconds and\n * nanos\" representation.\n */\nexport function normalizeTimestamp(date: Timestamp): {\n seconds: number;\n nanos: number;\n} {\n hardAssert(!!date, 0x986a, 'Cannot normalize null or undefined timestamp.');\n\n // The json interface (for the browser) will return an iso timestamp string,\n // while the proto js library (for node) will return a\n // google.protobuf.Timestamp instance.\n if (typeof date === 'string') {\n // The date string can have higher precision (nanos) than the Date class\n // (millis), so we do some custom parsing here.\n\n // Parse the nanos right out of the string.\n let nanos = 0;\n const fraction = ISO_TIMESTAMP_REG_EXP.exec(date);\n hardAssert(!!fraction, 0xb5de, 'invalid timestamp', {\n timestamp: date\n });\n if (fraction[1]) {\n // Pad the fraction out to 9 digits (nanos).\n let nanoStr = fraction[1];\n nanoStr = (nanoStr + '000000000').substr(0, 9);\n nanos = Number(nanoStr);\n }\n\n // Parse the date to get the seconds.\n const parsedDate = new Date(date);\n const seconds = Math.floor(parsedDate.getTime() / 1000);\n\n return { seconds, nanos };\n } else {\n // TODO(b/37282237): Use strings for Proto3 timestamps\n // assert(!this.options.useProto3Json,\n // 'The timestamp instance format requires Proto JS.');\n const seconds = normalizeNumber(date.seconds);\n const nanos = normalizeNumber(date.nanos);\n return { seconds, nanos };\n }\n}\n\n/**\n * Converts the possible Proto types for numbers into a JavaScript number.\n * Returns 0 if the value is not numeric.\n */\nexport function normalizeNumber(value: number | string | undefined): number {\n // TODO(bjornick): Handle int64 greater than 53 bits.\n if (typeof value === 'number') {\n return value;\n } else if (typeof value === 'string') {\n return Number(value);\n } else {\n return 0;\n }\n}\n\n/** Converts the possible Proto types for Blobs into a ByteString. */\nexport function normalizeByteString(blob: string | Uint8Array): ByteString {\n if (typeof blob === 'string') {\n return ByteString.fromBase64String(blob);\n } else {\n return ByteString.fromUint8Array(blob);\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isPlainObject } from '../util/input_validation';\n\nimport { Code, FirestoreError } from './error';\n\n/**\n * A list of data types Firestore objects may serialize in their toJSON implemenetations.\n * @private\n * @internal\n */\nexport type JsonTypeDesc =\n | 'object'\n | 'string'\n | 'number'\n | 'boolean'\n | 'null'\n | 'undefined';\n\n/**\n * An association of JsonTypeDesc values to their native types.\n * @private\n * @internal\n */\nexport type TSType = T extends 'object'\n ? object\n : T extends 'string'\n ? string\n : T extends 'number'\n ? number\n : T extends 'boolean'\n ? boolean\n : T extends 'null'\n ? null\n : T extends 'undefined'\n ? undefined\n : never;\n\n/**\n * The representation of a JSON object property name and its type value.\n * @private\n * @internal\n */\nexport interface Property {\n value?: TSType;\n typeString: JsonTypeDesc;\n}\n\n/**\n * A type Firestore data types may use to define the fields used in their JSON serialization.\n * @private\n * @internal\n */\nexport interface JsonSchema {\n [key: string]: Property;\n}\n\n/**\n * Associates the JSON property type to the native type and sets them to be Required.\n * @private\n * @internal\n */\nexport type Json = {\n [K in keyof T]: Required['value'];\n};\n\n/**\n * Helper function to define a JSON schema {@link Property}.\n * @private\n * @internal\n */\nexport function property(\n typeString: T,\n optionalValue?: TSType\n): Property {\n const result: Property = {\n typeString\n };\n if (optionalValue) {\n result.value = optionalValue;\n }\n return result;\n}\n\n/**\n * Validates the JSON object based on the provided schema, and narrows the type to the provided\n * JSON schema.\n * @private\n * @internal\n *\n * @param json A JSON object to validate.\n * @param scheme a {@link JsonSchema} that defines the properties to validate.\n * @returns true if the JSON schema exists within the object. Throws a FirestoreError otherwise.\n */\nexport function validateJSON(\n json: object,\n schema: S\n): json is Json {\n if (!isPlainObject(json)) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'JSON must be an object');\n }\n let error: string | undefined = undefined;\n for (const key in schema) {\n if (schema[key]) {\n const typeString = schema[key].typeString;\n const value: { value: unknown } | undefined =\n 'value' in schema[key] ? { value: schema[key].value } : undefined;\n if (!(key in json)) {\n error = `JSON missing required field: '${key}'`;\n break;\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const fieldValue = (json as any)[key];\n if (typeString && typeof fieldValue !== typeString) {\n error = `JSON field '${key}' must be a ${typeString}.`;\n break;\n } else if (value !== undefined && fieldValue !== value.value) {\n error = `Expected '${key}' field to equal '${value.value}'`;\n break;\n }\n }\n }\n if (error) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, error);\n }\n return true;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Code, FirestoreError } from '../util/error';\n// API extractor fails importing 'property' unless we also explicitly import 'Property'.\n// eslint-disable-next-line @typescript-eslint/no-unused-vars, unused-imports/no-unused-imports-ts\nimport { Property, property, validateJSON } from '../util/json_validation';\nimport { primitiveComparator } from '../util/misc';\n\n// The earliest date supported by Firestore timestamps (0001-01-01T00:00:00Z).\nconst MIN_SECONDS = -62135596800;\n\n// Number of nanoseconds in a millisecond.\nconst MS_TO_NANOS = 1e6;\n\n/**\n * A `Timestamp` represents a point in time independent of any time zone or\n * calendar, represented as seconds and fractions of seconds at nanosecond\n * resolution in UTC Epoch time.\n *\n * It is encoded using the Proleptic Gregorian Calendar which extends the\n * Gregorian calendar backwards to year one. It is encoded assuming all minutes\n * are 60 seconds long, i.e. leap seconds are \"smeared\" so that no leap second\n * table is needed for interpretation. Range is from 0001-01-01T00:00:00Z to\n * 9999-12-31T23:59:59.999999999Z.\n *\n * For examples and further specifications, refer to the\n * {@link https://github.com/google/protobuf/blob/master/src/google/protobuf/timestamp.proto | Timestamp definition}.\n */\nexport class Timestamp {\n /**\n * Creates a new timestamp with the current date, with millisecond precision.\n *\n * @returns a new timestamp representing the current date.\n */\n static now(): Timestamp {\n return Timestamp.fromMillis(Date.now());\n }\n\n /**\n * Creates a new timestamp from the given date.\n *\n * @param date - The date to initialize the `Timestamp` from.\n * @returns A new `Timestamp` representing the same point in time as the given\n * date.\n */\n static fromDate(date: Date): Timestamp {\n return Timestamp.fromMillis(date.getTime());\n }\n\n /**\n * Creates a new timestamp from the given number of milliseconds.\n *\n * @param milliseconds - Number of milliseconds since Unix epoch\n * 1970-01-01T00:00:00Z.\n * @returns A new `Timestamp` representing the same point in time as the given\n * number of milliseconds.\n */\n static fromMillis(milliseconds: number): Timestamp {\n const seconds = Math.floor(milliseconds / 1000);\n const nanos = Math.floor((milliseconds - seconds * 1000) * MS_TO_NANOS);\n return new Timestamp(seconds, nanos);\n }\n\n /**\n * Creates a new timestamp.\n *\n * @param seconds - The number of seconds of UTC time since Unix epoch\n * 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to\n * 9999-12-31T23:59:59Z inclusive.\n * @param nanoseconds - The non-negative fractions of a second at nanosecond\n * resolution. Negative second values with fractions must still have\n * non-negative nanoseconds values that count forward in time. Must be\n * from 0 to 999,999,999 inclusive.\n */\n constructor(\n /**\n * The number of seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z.\n */\n readonly seconds: number,\n /**\n * The fractions of a second at nanosecond resolution.*\n */\n readonly nanoseconds: number\n ) {\n if (nanoseconds < 0) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Timestamp nanoseconds out of range: ' + nanoseconds\n );\n }\n if (nanoseconds >= 1e9) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Timestamp nanoseconds out of range: ' + nanoseconds\n );\n }\n if (seconds < MIN_SECONDS) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Timestamp seconds out of range: ' + seconds\n );\n }\n // This will break in the year 10,000.\n if (seconds >= 253402300800) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Timestamp seconds out of range: ' + seconds\n );\n }\n }\n\n /**\n * Converts a `Timestamp` to a JavaScript `Date` object. This conversion\n * causes a loss of precision since `Date` objects only support millisecond\n * precision.\n *\n * @returns JavaScript `Date` object representing the same point in time as\n * this `Timestamp`, with millisecond precision.\n */\n toDate(): Date {\n return new Date(this.toMillis());\n }\n\n /**\n * Converts a `Timestamp` to a numeric timestamp (in milliseconds since\n * epoch). This operation causes a loss of precision.\n *\n * @returns The point in time corresponding to this timestamp, represented as\n * the number of milliseconds since Unix epoch 1970-01-01T00:00:00Z.\n */\n toMillis(): number {\n return this.seconds * 1000 + this.nanoseconds / MS_TO_NANOS;\n }\n\n _compareTo(other: Timestamp): number {\n if (this.seconds === other.seconds) {\n return primitiveComparator(this.nanoseconds, other.nanoseconds);\n }\n return primitiveComparator(this.seconds, other.seconds);\n }\n\n /**\n * Returns true if this `Timestamp` is equal to the provided one.\n *\n * @param other - The `Timestamp` to compare against.\n * @returns true if this `Timestamp` is equal to the provided one.\n */\n isEqual(other: Timestamp): boolean {\n return (\n other.seconds === this.seconds && other.nanoseconds === this.nanoseconds\n );\n }\n\n /** Returns a textual representation of this `Timestamp`. */\n toString(): string {\n return (\n 'Timestamp(seconds=' +\n this.seconds +\n ', nanoseconds=' +\n this.nanoseconds +\n ')'\n );\n }\n\n static _jsonSchemaVersion: string = 'firestore/timestamp/1.0';\n static _jsonSchema = {\n type: property('string', Timestamp._jsonSchemaVersion),\n seconds: property('number'),\n nanoseconds: property('number')\n };\n\n /**\n * Returns a JSON-serializable representation of this `Timestamp`.\n */\n toJSON(): { seconds: number; nanoseconds: number; type: string } {\n return {\n type: Timestamp._jsonSchemaVersion,\n seconds: this.seconds,\n nanoseconds: this.nanoseconds\n };\n }\n\n /**\n * Builds a `Timestamp` instance from a JSON object created by {@link Timestamp.toJSON}.\n */\n static fromJSON(json: object): Timestamp {\n if (validateJSON(json, Timestamp._jsonSchema)) {\n return new Timestamp(json.seconds, json.nanoseconds);\n }\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Unexpected error creating Timestamp from JSON.'\n );\n }\n\n /**\n * Converts this object to a primitive string, which allows `Timestamp` objects\n * to be compared using the `>`, `<=`, `>=` and `>` operators.\n */\n valueOf(): string {\n // This method returns a string of the form . where\n // is translated to have a non-negative value and both \n // and are left-padded with zeroes to be a consistent length.\n // Strings with this format then have a lexicographical ordering that matches\n // the expected ordering. The translation is done to avoid having\n // a leading negative sign (i.e. a leading '-' character) in its string\n // representation, which would affect its lexicographical ordering.\n const adjustedSeconds = this.seconds - MIN_SECONDS;\n // Note: Up to 12 decimal digits are required to represent all valid\n // 'seconds' values.\n const formattedSeconds = String(adjustedSeconds).padStart(12, '0');\n const formattedNanoseconds = String(this.nanoseconds).padStart(9, '0');\n return formattedSeconds + '.' + formattedNanoseconds;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Timestamp } from '../lite-api/timestamp';\nimport {\n Value as ProtoValue,\n MapValue as ProtoMapValue\n} from '../protos/firestore_proto_api';\n\nimport { normalizeTimestamp } from './normalize';\n\n/**\n * Represents a locally-applied ServerTimestamp.\n *\n * Server Timestamps are backed by MapValues that contain an internal field\n * `__type__` with a value of `server_timestamp`. The previous value and local\n * write time are stored in its `__previous_value__` and `__local_write_time__`\n * fields respectively.\n *\n * Notes:\n * - ServerTimestampValue instances are created as the result of applying a\n * transform. They can only exist in the local view of a document. Therefore\n * they do not need to be parsed or serialized.\n * - When evaluated locally (e.g. for snapshot.data()), they by default\n * evaluate to `null`. This behavior can be configured by passing custom\n * FieldValueOptions to value().\n * - With respect to other ServerTimestampValues, they sort by their\n * localWriteTime.\n */\n\nconst SERVER_TIMESTAMP_SENTINEL = 'server_timestamp';\nconst TYPE_KEY = '__type__';\nconst PREVIOUS_VALUE_KEY = '__previous_value__';\nconst LOCAL_WRITE_TIME_KEY = '__local_write_time__';\n\nexport function isServerTimestamp(value: ProtoValue | null): boolean {\n const type = (value?.mapValue?.fields || {})[TYPE_KEY]?.stringValue;\n return type === SERVER_TIMESTAMP_SENTINEL;\n}\n\n/**\n * Creates a new ServerTimestamp proto value (using the internal format).\n */\nexport function serverTimestamp(\n localWriteTime: Timestamp,\n previousValue: ProtoValue | null\n): ProtoValue {\n const mapValue: ProtoMapValue = {\n fields: {\n [TYPE_KEY]: {\n stringValue: SERVER_TIMESTAMP_SENTINEL\n },\n [LOCAL_WRITE_TIME_KEY]: {\n timestampValue: {\n seconds: localWriteTime.seconds,\n nanos: localWriteTime.nanoseconds\n }\n }\n }\n };\n\n // We should avoid storing deeply nested server timestamp map values\n // because we never use the intermediate \"previous values\".\n // For example:\n // previous: 42L, add: t1, result: t1 -> 42L\n // previous: t1, add: t2, result: t2 -> 42L (NOT t2 -> t1 -> 42L)\n // previous: t2, add: t3, result: t3 -> 42L (NOT t3 -> t2 -> t1 -> 42L)\n // `getPreviousValue` recursively traverses server timestamps to find the\n // least recent Value.\n if (previousValue && isServerTimestamp(previousValue)) {\n previousValue = getPreviousValue(previousValue);\n }\n if (previousValue) {\n mapValue.fields![PREVIOUS_VALUE_KEY] = previousValue;\n }\n\n return { mapValue };\n}\n\n/**\n * Returns the value of the field before this ServerTimestamp was set.\n *\n * Preserving the previous values allows the user to display the last resoled\n * value until the backend responds with the timestamp.\n */\nexport function getPreviousValue(value: ProtoValue): ProtoValue | null {\n const previousValue = value.mapValue!.fields![PREVIOUS_VALUE_KEY];\n\n if (isServerTimestamp(previousValue)) {\n return getPreviousValue(previousValue);\n }\n return previousValue;\n}\n\n/**\n * Returns the local time at which this timestamp was first set.\n */\nexport function getLocalWriteTime(value: ProtoValue): Timestamp {\n const localWriteTime = normalizeTimestamp(\n value.mapValue!.fields![LOCAL_WRITE_TIME_KEY].timestampValue!\n );\n return new Timestamp(localWriteTime.seconds, localWriteTime.nanos);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DatabaseId } from '../core/database_info';\nimport {\n ArrayValue,\n LatLng,\n MapValue,\n Timestamp,\n Value as ProtoValue,\n Value\n} from '../protos/firestore_proto_api';\nimport { fail } from '../util/assert';\nimport {\n arrayEquals,\n compareUtf8Strings,\n primitiveComparator\n} from '../util/misc';\nimport { forEach, objectSize } from '../util/obj';\nimport { isNegativeZero } from '../util/types';\n\nimport { DocumentKey } from './document_key';\nimport {\n normalizeByteString,\n normalizeNumber,\n normalizeTimestamp\n} from './normalize';\nimport {\n getLocalWriteTime,\n getPreviousValue,\n isServerTimestamp\n} from './server_timestamps';\nimport { TypeOrder } from './type_order';\n\nexport const TYPE_KEY = '__type__';\nconst MAX_VALUE_TYPE = '__max__';\nexport const MAX_VALUE: Value = {\n mapValue: {\n fields: {\n '__type__': { stringValue: MAX_VALUE_TYPE }\n }\n }\n};\n\nexport const VECTOR_VALUE_SENTINEL = '__vector__';\nexport const VECTOR_MAP_VECTORS_KEY = 'value';\n\nexport const MIN_VALUE: Value = {\n nullValue: 'NULL_VALUE'\n};\n\n/** Extracts the backend's type order for the provided value. */\nexport function typeOrder(value: Value): TypeOrder {\n if ('nullValue' in value) {\n return TypeOrder.NullValue;\n } else if ('booleanValue' in value) {\n return TypeOrder.BooleanValue;\n } else if ('integerValue' in value || 'doubleValue' in value) {\n return TypeOrder.NumberValue;\n } else if ('timestampValue' in value) {\n return TypeOrder.TimestampValue;\n } else if ('stringValue' in value) {\n return TypeOrder.StringValue;\n } else if ('bytesValue' in value) {\n return TypeOrder.BlobValue;\n } else if ('referenceValue' in value) {\n return TypeOrder.RefValue;\n } else if ('geoPointValue' in value) {\n return TypeOrder.GeoPointValue;\n } else if ('arrayValue' in value) {\n return TypeOrder.ArrayValue;\n } else if ('mapValue' in value) {\n if (isServerTimestamp(value)) {\n return TypeOrder.ServerTimestampValue;\n } else if (isMaxValue(value)) {\n return TypeOrder.MaxValue;\n } else if (isVectorValue(value)) {\n return TypeOrder.VectorValue;\n }\n return TypeOrder.ObjectValue;\n } else {\n return fail(0x6e87, 'Invalid value type', { value });\n }\n}\n\n/** Tests `left` and `right` for equality based on the backend semantics. */\nexport function valueEquals(left: Value, right: Value): boolean {\n if (left === right) {\n return true;\n }\n\n const leftType = typeOrder(left);\n const rightType = typeOrder(right);\n if (leftType !== rightType) {\n return false;\n }\n\n switch (leftType) {\n case TypeOrder.NullValue:\n return true;\n case TypeOrder.BooleanValue:\n return left.booleanValue === right.booleanValue;\n case TypeOrder.ServerTimestampValue:\n return getLocalWriteTime(left).isEqual(getLocalWriteTime(right));\n case TypeOrder.TimestampValue:\n return timestampEquals(left, right);\n case TypeOrder.StringValue:\n return left.stringValue === right.stringValue;\n case TypeOrder.BlobValue:\n return blobEquals(left, right);\n case TypeOrder.RefValue:\n return left.referenceValue === right.referenceValue;\n case TypeOrder.GeoPointValue:\n return geoPointEquals(left, right);\n case TypeOrder.NumberValue:\n return numberEquals(left, right);\n case TypeOrder.ArrayValue:\n return arrayEquals(\n left.arrayValue!.values || [],\n right.arrayValue!.values || [],\n valueEquals\n );\n case TypeOrder.VectorValue:\n case TypeOrder.ObjectValue:\n return objectEquals(left, right);\n case TypeOrder.MaxValue:\n return true;\n default:\n return fail(0xcbf8, 'Unexpected value type', { left });\n }\n}\n\nfunction timestampEquals(left: Value, right: Value): boolean {\n if (\n typeof left.timestampValue === 'string' &&\n typeof right.timestampValue === 'string' &&\n left.timestampValue.length === right.timestampValue.length\n ) {\n // Use string equality for ISO 8601 timestamps\n return left.timestampValue === right.timestampValue;\n }\n\n const leftTimestamp = normalizeTimestamp(left.timestampValue!);\n const rightTimestamp = normalizeTimestamp(right.timestampValue!);\n return (\n leftTimestamp.seconds === rightTimestamp.seconds &&\n leftTimestamp.nanos === rightTimestamp.nanos\n );\n}\n\nfunction geoPointEquals(left: Value, right: Value): boolean {\n return (\n normalizeNumber(left.geoPointValue!.latitude) ===\n normalizeNumber(right.geoPointValue!.latitude) &&\n normalizeNumber(left.geoPointValue!.longitude) ===\n normalizeNumber(right.geoPointValue!.longitude)\n );\n}\n\nfunction blobEquals(left: Value, right: Value): boolean {\n return normalizeByteString(left.bytesValue!).isEqual(\n normalizeByteString(right.bytesValue!)\n );\n}\n\nexport function numberEquals(left: Value, right: Value): boolean {\n if ('integerValue' in left && 'integerValue' in right) {\n return (\n normalizeNumber(left.integerValue) === normalizeNumber(right.integerValue)\n );\n } else if ('doubleValue' in left && 'doubleValue' in right) {\n const n1 = normalizeNumber(left.doubleValue!);\n const n2 = normalizeNumber(right.doubleValue!);\n\n if (n1 === n2) {\n return isNegativeZero(n1) === isNegativeZero(n2);\n } else {\n return isNaN(n1) && isNaN(n2);\n }\n }\n\n return false;\n}\n\nfunction objectEquals(left: Value, right: Value): boolean {\n const leftMap = left.mapValue!.fields || {};\n const rightMap = right.mapValue!.fields || {};\n\n if (objectSize(leftMap) !== objectSize(rightMap)) {\n return false;\n }\n\n for (const key in leftMap) {\n if (leftMap.hasOwnProperty(key)) {\n if (\n rightMap[key] === undefined ||\n !valueEquals(leftMap[key], rightMap[key])\n ) {\n return false;\n }\n }\n }\n return true;\n}\n\n/** Returns true if the ArrayValue contains the specified element. */\nexport function arrayValueContains(\n haystack: ArrayValue,\n needle: Value\n): boolean {\n return (\n (haystack.values || []).find(v => valueEquals(v, needle)) !== undefined\n );\n}\n\nexport function valueCompare(left: Value, right: Value): number {\n if (left === right) {\n return 0;\n }\n\n const leftType = typeOrder(left);\n const rightType = typeOrder(right);\n\n if (leftType !== rightType) {\n return primitiveComparator(leftType, rightType);\n }\n\n switch (leftType) {\n case TypeOrder.NullValue:\n case TypeOrder.MaxValue:\n return 0;\n case TypeOrder.BooleanValue:\n return primitiveComparator(left.booleanValue!, right.booleanValue!);\n case TypeOrder.NumberValue:\n return compareNumbers(left, right);\n case TypeOrder.TimestampValue:\n return compareTimestamps(left.timestampValue!, right.timestampValue!);\n case TypeOrder.ServerTimestampValue:\n return compareTimestamps(\n getLocalWriteTime(left),\n getLocalWriteTime(right)\n );\n case TypeOrder.StringValue:\n return compareUtf8Strings(left.stringValue!, right.stringValue!);\n case TypeOrder.BlobValue:\n return compareBlobs(left.bytesValue!, right.bytesValue!);\n case TypeOrder.RefValue:\n return compareReferences(left.referenceValue!, right.referenceValue!);\n case TypeOrder.GeoPointValue:\n return compareGeoPoints(left.geoPointValue!, right.geoPointValue!);\n case TypeOrder.ArrayValue:\n return compareArrays(left.arrayValue!, right.arrayValue!);\n case TypeOrder.VectorValue:\n return compareVectors(left.mapValue!, right.mapValue!);\n case TypeOrder.ObjectValue:\n return compareMaps(left.mapValue!, right.mapValue!);\n default:\n throw fail(0x5ae0, 'Invalid value type', { leftType });\n }\n}\n\nfunction compareNumbers(left: Value, right: Value): number {\n const leftNumber = normalizeNumber(left.integerValue || left.doubleValue);\n const rightNumber = normalizeNumber(right.integerValue || right.doubleValue);\n\n if (leftNumber < rightNumber) {\n return -1;\n } else if (leftNumber > rightNumber) {\n return 1;\n } else if (leftNumber === rightNumber) {\n return 0;\n } else {\n // one or both are NaN.\n if (isNaN(leftNumber)) {\n return isNaN(rightNumber) ? 0 : -1;\n } else {\n return 1;\n }\n }\n}\n\nfunction compareTimestamps(left: Timestamp, right: Timestamp): number {\n if (\n typeof left === 'string' &&\n typeof right === 'string' &&\n left.length === right.length\n ) {\n return primitiveComparator(left, right);\n }\n\n const leftTimestamp = normalizeTimestamp(left);\n const rightTimestamp = normalizeTimestamp(right);\n\n const comparison = primitiveComparator(\n leftTimestamp.seconds,\n rightTimestamp.seconds\n );\n if (comparison !== 0) {\n return comparison;\n }\n return primitiveComparator(leftTimestamp.nanos, rightTimestamp.nanos);\n}\n\nfunction compareReferences(leftPath: string, rightPath: string): number {\n const leftSegments = leftPath.split('/');\n const rightSegments = rightPath.split('/');\n for (let i = 0; i < leftSegments.length && i < rightSegments.length; i++) {\n const comparison = primitiveComparator(leftSegments[i], rightSegments[i]);\n if (comparison !== 0) {\n return comparison;\n }\n }\n return primitiveComparator(leftSegments.length, rightSegments.length);\n}\n\nfunction compareGeoPoints(left: LatLng, right: LatLng): number {\n const comparison = primitiveComparator(\n normalizeNumber(left.latitude),\n normalizeNumber(right.latitude)\n );\n if (comparison !== 0) {\n return comparison;\n }\n return primitiveComparator(\n normalizeNumber(left.longitude),\n normalizeNumber(right.longitude)\n );\n}\n\nfunction compareBlobs(\n left: string | Uint8Array,\n right: string | Uint8Array\n): number {\n const leftBytes = normalizeByteString(left);\n const rightBytes = normalizeByteString(right);\n return leftBytes.compareTo(rightBytes);\n}\n\nfunction compareArrays(left: ArrayValue, right: ArrayValue): number {\n const leftArray = left.values || [];\n const rightArray = right.values || [];\n\n for (let i = 0; i < leftArray.length && i < rightArray.length; ++i) {\n const compare = valueCompare(leftArray[i], rightArray[i]);\n if (compare) {\n return compare;\n }\n }\n return primitiveComparator(leftArray.length, rightArray.length);\n}\n\nfunction compareVectors(left: MapValue, right: MapValue): number {\n const leftMap = left.fields || {};\n const rightMap = right.fields || {};\n\n // The vector is a map, but only vector value is compared.\n const leftArrayValue = leftMap[VECTOR_MAP_VECTORS_KEY]?.arrayValue;\n const rightArrayValue = rightMap[VECTOR_MAP_VECTORS_KEY]?.arrayValue;\n\n const lengthCompare = primitiveComparator(\n leftArrayValue?.values?.length || 0,\n rightArrayValue?.values?.length || 0\n );\n if (lengthCompare !== 0) {\n return lengthCompare;\n }\n\n return compareArrays(leftArrayValue!, rightArrayValue!);\n}\n\nfunction compareMaps(left: MapValue, right: MapValue): number {\n if (left === MAX_VALUE.mapValue && right === MAX_VALUE.mapValue) {\n return 0;\n } else if (left === MAX_VALUE.mapValue) {\n return 1;\n } else if (right === MAX_VALUE.mapValue) {\n return -1;\n }\n\n const leftMap = left.fields || {};\n const leftKeys = Object.keys(leftMap);\n const rightMap = right.fields || {};\n const rightKeys = Object.keys(rightMap);\n\n // Even though MapValues are likely sorted correctly based on their insertion\n // order (e.g. when received from the backend), local modifications can bring\n // elements out of order. We need to re-sort the elements to ensure that\n // canonical IDs are independent of insertion order.\n leftKeys.sort();\n rightKeys.sort();\n\n for (let i = 0; i < leftKeys.length && i < rightKeys.length; ++i) {\n const keyCompare = compareUtf8Strings(leftKeys[i], rightKeys[i]);\n if (keyCompare !== 0) {\n return keyCompare;\n }\n const compare = valueCompare(leftMap[leftKeys[i]], rightMap[rightKeys[i]]);\n if (compare !== 0) {\n return compare;\n }\n }\n\n return primitiveComparator(leftKeys.length, rightKeys.length);\n}\n\n/**\n * Generates the canonical ID for the provided field value (as used in Target\n * serialization).\n */\nexport function canonicalId(value: Value): string {\n return canonifyValue(value);\n}\n\nfunction canonifyValue(value: Value): string {\n if ('nullValue' in value) {\n return 'null';\n } else if ('booleanValue' in value) {\n return '' + value.booleanValue!;\n } else if ('integerValue' in value) {\n return '' + value.integerValue!;\n } else if ('doubleValue' in value) {\n return '' + value.doubleValue!;\n } else if ('timestampValue' in value) {\n return canonifyTimestamp(value.timestampValue!);\n } else if ('stringValue' in value) {\n return value.stringValue!;\n } else if ('bytesValue' in value) {\n return canonifyByteString(value.bytesValue!);\n } else if ('referenceValue' in value) {\n return canonifyReference(value.referenceValue!);\n } else if ('geoPointValue' in value) {\n return canonifyGeoPoint(value.geoPointValue!);\n } else if ('arrayValue' in value) {\n return canonifyArray(value.arrayValue!);\n } else if ('mapValue' in value) {\n return canonifyMap(value.mapValue!);\n } else {\n return fail(0xee4d, 'Invalid value type', { value });\n }\n}\n\nfunction canonifyByteString(byteString: string | Uint8Array): string {\n return normalizeByteString(byteString).toBase64();\n}\n\nfunction canonifyTimestamp(timestamp: Timestamp): string {\n const normalizedTimestamp = normalizeTimestamp(timestamp);\n return `time(${normalizedTimestamp.seconds},${normalizedTimestamp.nanos})`;\n}\n\nfunction canonifyGeoPoint(geoPoint: LatLng): string {\n return `geo(${geoPoint.latitude},${geoPoint.longitude})`;\n}\n\nfunction canonifyReference(referenceValue: string): string {\n return DocumentKey.fromName(referenceValue).toString();\n}\n\nfunction canonifyMap(mapValue: MapValue): string {\n // Iteration order in JavaScript is not guaranteed. To ensure that we generate\n // matching canonical IDs for identical maps, we need to sort the keys.\n const sortedKeys = Object.keys(mapValue.fields || {}).sort();\n\n let result = '{';\n let first = true;\n for (const key of sortedKeys) {\n if (!first) {\n result += ',';\n } else {\n first = false;\n }\n result += `${key}:${canonifyValue(mapValue.fields![key])}`;\n }\n return result + '}';\n}\n\nfunction canonifyArray(arrayValue: ArrayValue): string {\n let result = '[';\n let first = true;\n for (const value of arrayValue.values || []) {\n if (!first) {\n result += ',';\n } else {\n first = false;\n }\n result += canonifyValue(value);\n }\n return result + ']';\n}\n\n/**\n * Returns an approximate (and wildly inaccurate) in-memory size for the field\n * value.\n *\n * The memory size takes into account only the actual user data as it resides\n * in memory and ignores object overhead.\n */\nexport function estimateByteSize(value: Value): number {\n switch (typeOrder(value)) {\n case TypeOrder.NullValue:\n return 4;\n case TypeOrder.BooleanValue:\n return 4;\n case TypeOrder.NumberValue:\n return 8;\n case TypeOrder.TimestampValue:\n // Timestamps are made up of two distinct numbers (seconds + nanoseconds)\n return 16;\n case TypeOrder.ServerTimestampValue:\n const previousValue = getPreviousValue(value);\n return previousValue ? 16 + estimateByteSize(previousValue) : 16;\n case TypeOrder.StringValue:\n // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures:\n // \"JavaScript's String type is [...] a set of elements of 16-bit unsigned\n // integer values\"\n return value.stringValue!.length * 2;\n case TypeOrder.BlobValue:\n return normalizeByteString(value.bytesValue!).approximateByteSize();\n case TypeOrder.RefValue:\n return value.referenceValue!.length;\n case TypeOrder.GeoPointValue:\n // GeoPoints are made up of two distinct numbers (latitude + longitude)\n return 16;\n case TypeOrder.ArrayValue:\n return estimateArrayByteSize(value.arrayValue!);\n case TypeOrder.VectorValue:\n case TypeOrder.ObjectValue:\n return estimateMapByteSize(value.mapValue!);\n default:\n throw fail(0x34ae, 'Invalid value type', { value });\n }\n}\n\nfunction estimateMapByteSize(mapValue: MapValue): number {\n let size = 0;\n forEach(mapValue.fields, (key, val) => {\n size += key.length + estimateByteSize(val);\n });\n return size;\n}\n\nfunction estimateArrayByteSize(arrayValue: ArrayValue): number {\n return (arrayValue.values || []).reduce(\n (previousSize, value) => previousSize + estimateByteSize(value),\n 0\n );\n}\n\n/** Returns a reference value for the provided database and key. */\nexport function refValue(databaseId: DatabaseId, key: DocumentKey): Value {\n return {\n referenceValue: `projects/${databaseId.projectId}/databases/${\n databaseId.database\n }/documents/${key.path.canonicalString()}`\n };\n}\n\n/** Returns true if `value` is an IntegerValue . */\nexport function isInteger(\n value?: Value | null\n): value is { integerValue: string | number } {\n return !!value && 'integerValue' in value;\n}\n\n/** Returns true if `value` is a DoubleValue. */\nexport function isDouble(\n value?: Value | null\n): value is { doubleValue: string | number } {\n return !!value && 'doubleValue' in value;\n}\n\n/** Returns true if `value` is either an IntegerValue or a DoubleValue. */\nexport function isNumber(value?: Value | null): boolean {\n return isInteger(value) || isDouble(value);\n}\n\n/** Returns true if `value` is an ArrayValue. */\nexport function isArray(\n value?: Value | null\n): value is { arrayValue: ArrayValue } {\n return !!value && 'arrayValue' in value;\n}\n\n/** Returns true if `value` is a ReferenceValue. */\nexport function isReferenceValue(\n value?: Value | null\n): value is { referenceValue: string } {\n return !!value && 'referenceValue' in value;\n}\n\n/** Returns true if `value` is a NullValue. */\nexport function isNullValue(\n value?: Value | null\n): value is { nullValue: 'NULL_VALUE' } {\n return !!value && 'nullValue' in value;\n}\n\n/** Returns true if `value` is NaN. */\nexport function isNanValue(\n value?: Value | null\n): value is { doubleValue: 'NaN' | number } {\n return !!value && 'doubleValue' in value && isNaN(Number(value.doubleValue));\n}\n\n/** Returns true if `value` is a MapValue. */\nexport function isMapValue(\n value?: Value | null\n): value is { mapValue: MapValue } {\n return !!value && 'mapValue' in value;\n}\n\n/** Returns true if `value` is a VetorValue. */\nexport function isVectorValue(value: ProtoValue | null): boolean {\n const type = (value?.mapValue?.fields || {})[TYPE_KEY]?.stringValue;\n return type === VECTOR_VALUE_SENTINEL;\n}\n\n/** Creates a deep copy of `source`. */\nexport function deepClone(source: Value): Value {\n if (source.geoPointValue) {\n return { geoPointValue: { ...source.geoPointValue } };\n } else if (\n source.timestampValue &&\n typeof source.timestampValue === 'object'\n ) {\n return { timestampValue: { ...source.timestampValue } };\n } else if (source.mapValue) {\n const target: Value = { mapValue: { fields: {} } };\n forEach(\n source.mapValue.fields,\n (key, val) => (target.mapValue!.fields![key] = deepClone(val))\n );\n return target;\n } else if (source.arrayValue) {\n const target: Value = { arrayValue: { values: [] } };\n for (let i = 0; i < (source.arrayValue.values || []).length; ++i) {\n target.arrayValue!.values![i] = deepClone(source.arrayValue.values![i]);\n }\n return target;\n } else {\n return { ...source };\n }\n}\n\n/** Returns true if the Value represents the canonical {@link #MAX_VALUE} . */\nexport function isMaxValue(value: Value): boolean {\n return (\n (((value.mapValue || {}).fields || {})['__type__'] || {}).stringValue ===\n MAX_VALUE_TYPE\n );\n}\n\nexport const MIN_VECTOR_VALUE = {\n mapValue: {\n fields: {\n [TYPE_KEY]: { stringValue: VECTOR_VALUE_SENTINEL },\n [VECTOR_MAP_VECTORS_KEY]: {\n arrayValue: {}\n }\n }\n }\n};\n\n/** Returns the lowest value for the given value type (inclusive). */\nexport function valuesGetLowerBound(value: Value): Value {\n if ('nullValue' in value) {\n return MIN_VALUE;\n } else if ('booleanValue' in value) {\n return { booleanValue: false };\n } else if ('integerValue' in value || 'doubleValue' in value) {\n return { doubleValue: NaN };\n } else if ('timestampValue' in value) {\n return { timestampValue: { seconds: Number.MIN_SAFE_INTEGER } };\n } else if ('stringValue' in value) {\n return { stringValue: '' };\n } else if ('bytesValue' in value) {\n return { bytesValue: '' };\n } else if ('referenceValue' in value) {\n return refValue(DatabaseId.empty(), DocumentKey.empty());\n } else if ('geoPointValue' in value) {\n return { geoPointValue: { latitude: -90, longitude: -180 } };\n } else if ('arrayValue' in value) {\n return { arrayValue: {} };\n } else if ('mapValue' in value) {\n if (isVectorValue(value)) {\n return MIN_VECTOR_VALUE;\n }\n return { mapValue: {} };\n } else {\n return fail(0x8c66, 'Invalid value type', { value });\n }\n}\n\n/** Returns the largest value for the given value type (exclusive). */\nexport function valuesGetUpperBound(value: Value): Value {\n if ('nullValue' in value) {\n return { booleanValue: false };\n } else if ('booleanValue' in value) {\n return { doubleValue: NaN };\n } else if ('integerValue' in value || 'doubleValue' in value) {\n return { timestampValue: { seconds: Number.MIN_SAFE_INTEGER } };\n } else if ('timestampValue' in value) {\n return { stringValue: '' };\n } else if ('stringValue' in value) {\n return { bytesValue: '' };\n } else if ('bytesValue' in value) {\n return refValue(DatabaseId.empty(), DocumentKey.empty());\n } else if ('referenceValue' in value) {\n return { geoPointValue: { latitude: -90, longitude: -180 } };\n } else if ('geoPointValue' in value) {\n return { arrayValue: {} };\n } else if ('arrayValue' in value) {\n return MIN_VECTOR_VALUE;\n } else if ('mapValue' in value) {\n if (isVectorValue(value)) {\n return { mapValue: {} };\n }\n return MAX_VALUE;\n } else {\n return fail(0xf207, 'Invalid value type', { value });\n }\n}\n\nexport function lowerBoundCompare(\n left: { value: Value; inclusive: boolean },\n right: { value: Value; inclusive: boolean }\n): number {\n const cmp = valueCompare(left.value, right.value);\n if (cmp !== 0) {\n return cmp;\n }\n\n if (left.inclusive && !right.inclusive) {\n return -1;\n } else if (!left.inclusive && right.inclusive) {\n return 1;\n }\n\n return 0;\n}\n\nexport function upperBoundCompare(\n left: { value: Value; inclusive: boolean },\n right: { value: Value; inclusive: boolean }\n): number {\n const cmp = valueCompare(left.value, right.value);\n if (cmp !== 0) {\n return cmp;\n }\n\n if (left.inclusive && !right.inclusive) {\n return 1;\n } else if (!left.inclusive && right.inclusive) {\n return -1;\n }\n\n return 0;\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { isReferenceValue, valueCompare, valueEquals } from '../model/values';\nimport { Value as ProtoValue } from '../protos/firestore_proto_api';\nimport { debugAssert } from '../util/assert';\n\nimport { Direction, OrderBy } from './order_by';\n\n/**\n * Represents a bound of a query.\n *\n * The bound is specified with the given components representing a position and\n * whether it's just before or just after the position (relative to whatever the\n * query order is).\n *\n * The position represents a logical index position for a query. It's a prefix\n * of values for the (potentially implicit) order by clauses of a query.\n *\n * Bound provides a function to determine whether a document comes before or\n * after a bound. This is influenced by whether the position is just before or\n * just after the provided values.\n */\nexport class Bound {\n constructor(readonly position: ProtoValue[], readonly inclusive: boolean) {}\n}\n\nfunction boundCompareToDocument(\n bound: Bound,\n orderBy: OrderBy[],\n doc: Document\n): number {\n debugAssert(\n bound.position.length <= orderBy.length,\n \"Bound has more components than query's orderBy\"\n );\n let comparison = 0;\n for (let i = 0; i < bound.position.length; i++) {\n const orderByComponent = orderBy[i];\n const component = bound.position[i];\n if (orderByComponent.field.isKeyField()) {\n debugAssert(\n isReferenceValue(component),\n 'Bound has a non-key value where the key path is being used.'\n );\n comparison = DocumentKey.comparator(\n DocumentKey.fromName(component.referenceValue),\n doc.key\n );\n } else {\n const docValue = doc.data.field(orderByComponent.field);\n debugAssert(\n docValue !== null,\n 'Field should exist since document matched the orderBy already.'\n );\n comparison = valueCompare(component, docValue);\n }\n if (orderByComponent.dir === Direction.DESCENDING) {\n comparison = comparison * -1;\n }\n if (comparison !== 0) {\n break;\n }\n }\n return comparison;\n}\n\n/**\n * Returns true if a document sorts after a bound using the provided sort\n * order.\n */\nexport function boundSortsAfterDocument(\n bound: Bound,\n orderBy: OrderBy[],\n doc: Document\n): boolean {\n const comparison = boundCompareToDocument(bound, orderBy, doc);\n return bound.inclusive ? comparison >= 0 : comparison > 0;\n}\n\n/**\n * Returns true if a document sorts before a bound using the provided sort\n * order.\n */\nexport function boundSortsBeforeDocument(\n bound: Bound,\n orderBy: OrderBy[],\n doc: Document\n): boolean {\n const comparison = boundCompareToDocument(bound, orderBy, doc);\n return bound.inclusive ? comparison <= 0 : comparison < 0;\n}\n\nexport function boundEquals(left: Bound | null, right: Bound | null): boolean {\n if (left === null) {\n return right === null;\n } else if (right === null) {\n return false;\n }\n\n if (\n left.inclusive !== right.inclusive ||\n left.position.length !== right.position.length\n ) {\n return false;\n }\n for (let i = 0; i < left.position.length; i++) {\n const leftPosition = left.position[i];\n const rightPosition = right.position[i];\n if (!valueEquals(leftPosition, rightPosition)) {\n return false;\n }\n }\n return true;\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { FieldPath } from '../model/path';\nimport {\n arrayValueContains,\n canonicalId,\n isArray,\n isReferenceValue,\n typeOrder,\n valueCompare,\n valueEquals\n} from '../model/values';\nimport { Value as ProtoValue } from '../protos/firestore_proto_api';\nimport { debugAssert, fail } from '../util/assert';\n\n// The operator of a FieldFilter\nexport const enum Operator {\n LESS_THAN = '<',\n LESS_THAN_OR_EQUAL = '<=',\n EQUAL = '==',\n NOT_EQUAL = '!=',\n GREATER_THAN = '>',\n GREATER_THAN_OR_EQUAL = '>=',\n ARRAY_CONTAINS = 'array-contains',\n IN = 'in',\n NOT_IN = 'not-in',\n ARRAY_CONTAINS_ANY = 'array-contains-any'\n}\n\n// The operator of a CompositeFilter\nexport const enum CompositeOperator {\n OR = 'or',\n AND = 'and'\n}\n\nexport abstract class Filter {\n abstract matches(doc: Document): boolean;\n\n abstract getFlattenedFilters(): readonly FieldFilter[];\n\n abstract getFilters(): Filter[];\n}\n\nexport class FieldFilter extends Filter {\n protected constructor(\n public readonly field: FieldPath,\n public readonly op: Operator,\n public readonly value: ProtoValue\n ) {\n super();\n }\n\n /**\n * Creates a filter based on the provided arguments.\n */\n static create(\n field: FieldPath,\n op: Operator,\n value: ProtoValue\n ): FieldFilter {\n if (field.isKeyField()) {\n if (op === Operator.IN || op === Operator.NOT_IN) {\n return this.createKeyFieldInFilter(field, op, value);\n } else {\n debugAssert(\n isReferenceValue(value),\n 'Comparing on key, but filter value not a RefValue'\n );\n debugAssert(\n op !== Operator.ARRAY_CONTAINS && op !== Operator.ARRAY_CONTAINS_ANY,\n `'${op.toString()}' queries don't make sense on document keys.`\n );\n return new KeyFieldFilter(field, op, value);\n }\n } else if (op === Operator.ARRAY_CONTAINS) {\n return new ArrayContainsFilter(field, value);\n } else if (op === Operator.IN) {\n debugAssert(\n isArray(value),\n 'IN filter has invalid value: ' + value.toString()\n );\n return new InFilter(field, value);\n } else if (op === Operator.NOT_IN) {\n debugAssert(\n isArray(value),\n 'NOT_IN filter has invalid value: ' + value.toString()\n );\n return new NotInFilter(field, value);\n } else if (op === Operator.ARRAY_CONTAINS_ANY) {\n debugAssert(\n isArray(value),\n 'ARRAY_CONTAINS_ANY filter has invalid value: ' + value.toString()\n );\n return new ArrayContainsAnyFilter(field, value);\n } else {\n return new FieldFilter(field, op, value);\n }\n }\n\n private static createKeyFieldInFilter(\n field: FieldPath,\n op: Operator.IN | Operator.NOT_IN,\n value: ProtoValue\n ): FieldFilter {\n debugAssert(\n isArray(value),\n `Comparing on key with ${op.toString()}` +\n ', but filter value not an ArrayValue'\n );\n debugAssert(\n (value.arrayValue.values || []).every(elem => isReferenceValue(elem)),\n `Comparing on key with ${op.toString()}` +\n ', but an array value was not a RefValue'\n );\n\n return op === Operator.IN\n ? new KeyFieldInFilter(field, value)\n : new KeyFieldNotInFilter(field, value);\n }\n\n matches(doc: Document): boolean {\n const other = doc.data.field(this.field);\n // Types do not have to match in NOT_EQUAL filters.\n if (this.op === Operator.NOT_EQUAL) {\n return (\n other !== null &&\n other.nullValue === undefined &&\n this.matchesComparison(valueCompare(other!, this.value))\n );\n }\n\n // Only compare types with matching backend order (such as double and int).\n return (\n other !== null &&\n typeOrder(this.value) === typeOrder(other) &&\n this.matchesComparison(valueCompare(other, this.value))\n );\n }\n\n protected matchesComparison(comparison: number): boolean {\n switch (this.op) {\n case Operator.LESS_THAN:\n return comparison < 0;\n case Operator.LESS_THAN_OR_EQUAL:\n return comparison <= 0;\n case Operator.EQUAL:\n return comparison === 0;\n case Operator.NOT_EQUAL:\n return comparison !== 0;\n case Operator.GREATER_THAN:\n return comparison > 0;\n case Operator.GREATER_THAN_OR_EQUAL:\n return comparison >= 0;\n default:\n return fail(0xb8a2, 'Unknown FieldFilter operator', {\n operator: this.op\n });\n }\n }\n\n isInequality(): boolean {\n return (\n [\n Operator.LESS_THAN,\n Operator.LESS_THAN_OR_EQUAL,\n Operator.GREATER_THAN,\n Operator.GREATER_THAN_OR_EQUAL,\n Operator.NOT_EQUAL,\n Operator.NOT_IN\n ].indexOf(this.op) >= 0\n );\n }\n\n getFlattenedFilters(): readonly FieldFilter[] {\n return [this];\n }\n\n getFilters(): Filter[] {\n return [this];\n }\n}\n\nexport class CompositeFilter extends Filter {\n private memoizedFlattenedFilters: FieldFilter[] | null = null;\n\n protected constructor(\n public readonly filters: readonly Filter[],\n public readonly op: CompositeOperator\n ) {\n super();\n }\n\n /**\n * Creates a filter based on the provided arguments.\n */\n static create(filters: Filter[], op: CompositeOperator): CompositeFilter {\n return new CompositeFilter(filters, op);\n }\n\n matches(doc: Document): boolean {\n if (compositeFilterIsConjunction(this)) {\n // For conjunctions, all filters must match, so return false if any filter doesn't match.\n return this.filters.find(filter => !filter.matches(doc)) === undefined;\n } else {\n // For disjunctions, at least one filter should match.\n return this.filters.find(filter => filter.matches(doc)) !== undefined;\n }\n }\n\n getFlattenedFilters(): readonly FieldFilter[] {\n if (this.memoizedFlattenedFilters !== null) {\n return this.memoizedFlattenedFilters;\n }\n\n this.memoizedFlattenedFilters = this.filters.reduce((result, subfilter) => {\n return result.concat(subfilter.getFlattenedFilters());\n }, [] as FieldFilter[]);\n\n return this.memoizedFlattenedFilters;\n }\n\n // Returns a mutable copy of `this.filters`\n getFilters(): Filter[] {\n return Object.assign([], this.filters);\n }\n}\n\nexport function compositeFilterIsConjunction(\n compositeFilter: CompositeFilter\n): boolean {\n return compositeFilter.op === CompositeOperator.AND;\n}\n\nexport function compositeFilterIsDisjunction(\n compositeFilter: CompositeFilter\n): boolean {\n return compositeFilter.op === CompositeOperator.OR;\n}\n\n/**\n * Returns true if this filter is a conjunction of field filters only. Returns false otherwise.\n */\nexport function compositeFilterIsFlatConjunction(\n compositeFilter: CompositeFilter\n): boolean {\n return (\n compositeFilterIsFlat(compositeFilter) &&\n compositeFilterIsConjunction(compositeFilter)\n );\n}\n\n/**\n * Returns true if this filter does not contain any composite filters. Returns false otherwise.\n */\nexport function compositeFilterIsFlat(\n compositeFilter: CompositeFilter\n): boolean {\n for (const filter of compositeFilter.filters) {\n if (filter instanceof CompositeFilter) {\n return false;\n }\n }\n return true;\n}\n\nexport function canonifyFilter(filter: Filter): string {\n debugAssert(\n filter instanceof FieldFilter || filter instanceof CompositeFilter,\n 'canonifyFilter() only supports FieldFilters and CompositeFilters'\n );\n\n if (filter instanceof FieldFilter) {\n // TODO(b/29183165): Technically, this won't be unique if two values have\n // the same description, such as the int 3 and the string \"3\". So we should\n // add the types in here somehow, too.\n return (\n filter.field.canonicalString() +\n filter.op.toString() +\n canonicalId(filter.value)\n );\n } else if (compositeFilterIsFlatConjunction(filter)) {\n // Older SDK versions use an implicit AND operation between their filters.\n // In the new SDK versions, the developer may use an explicit AND filter.\n // To stay consistent with the old usages, we add a special case to ensure\n // the canonical ID for these two are the same. For example:\n // `col.whereEquals(\"a\", 1).whereEquals(\"b\", 2)` should have the same\n // canonical ID as `col.where(and(equals(\"a\",1), equals(\"b\",2)))`.\n return filter.filters.map(filter => canonifyFilter(filter)).join(',');\n } else {\n // filter instanceof CompositeFilter\n const canonicalIdsString = filter.filters\n .map(filter => canonifyFilter(filter))\n .join(',');\n return `${filter.op}(${canonicalIdsString})`;\n }\n}\n\nexport function filterEquals(f1: Filter, f2: Filter): boolean {\n if (f1 instanceof FieldFilter) {\n return fieldFilterEquals(f1, f2);\n } else if (f1 instanceof CompositeFilter) {\n return compositeFilterEquals(f1, f2);\n } else {\n fail(0x4bef, 'Only FieldFilters and CompositeFilters can be compared');\n }\n}\n\nexport function fieldFilterEquals(f1: FieldFilter, f2: Filter): boolean {\n return (\n f2 instanceof FieldFilter &&\n f1.op === f2.op &&\n f1.field.isEqual(f2.field) &&\n valueEquals(f1.value, f2.value)\n );\n}\n\nexport function compositeFilterEquals(\n f1: CompositeFilter,\n f2: Filter\n): boolean {\n if (\n f2 instanceof CompositeFilter &&\n f1.op === f2.op &&\n f1.filters.length === f2.filters.length\n ) {\n const subFiltersMatch: boolean = f1.filters.reduce(\n (result: boolean, f1Filter: Filter, index: number): boolean =>\n result && filterEquals(f1Filter, f2.filters[index]),\n true\n );\n\n return subFiltersMatch;\n }\n\n return false;\n}\n\n/**\n * Returns a new composite filter that contains all filter from\n * `compositeFilter` plus all the given filters in `otherFilters`.\n */\nexport function compositeFilterWithAddedFilters(\n compositeFilter: CompositeFilter,\n otherFilters: Filter[]\n): CompositeFilter {\n const mergedFilters = compositeFilter.filters.concat(otherFilters);\n return CompositeFilter.create(mergedFilters, compositeFilter.op);\n}\n\n/** Returns a debug description for `filter`. */\nexport function stringifyFilter(filter: Filter): string {\n debugAssert(\n filter instanceof FieldFilter || filter instanceof CompositeFilter,\n 'stringifyFilter() only supports FieldFilters and CompositeFilters'\n );\n if (filter instanceof FieldFilter) {\n return stringifyFieldFilter(filter);\n } else if (filter instanceof CompositeFilter) {\n return stringifyCompositeFilter(filter);\n } else {\n return 'Filter';\n }\n}\n\nexport function stringifyCompositeFilter(filter: CompositeFilter): string {\n return (\n filter.op.toString() +\n ` {` +\n filter.getFilters().map(stringifyFilter).join(' ,') +\n '}'\n );\n}\n\nexport function stringifyFieldFilter(filter: FieldFilter): string {\n return `${filter.field.canonicalString()} ${filter.op} ${canonicalId(\n filter.value\n )}`;\n}\n\n/** Filter that matches on key fields (i.e. '__name__'). */\nexport class KeyFieldFilter extends FieldFilter {\n private readonly key: DocumentKey;\n\n constructor(field: FieldPath, op: Operator, value: ProtoValue) {\n super(field, op, value);\n debugAssert(\n isReferenceValue(value),\n 'KeyFieldFilter expects a ReferenceValue'\n );\n this.key = DocumentKey.fromName(value.referenceValue);\n }\n\n matches(doc: Document): boolean {\n const comparison = DocumentKey.comparator(doc.key, this.key);\n return this.matchesComparison(comparison);\n }\n}\n\n/** Filter that matches on key fields within an array. */\nexport class KeyFieldInFilter extends FieldFilter {\n private readonly keys: DocumentKey[];\n\n constructor(field: FieldPath, value: ProtoValue) {\n super(field, Operator.IN, value);\n this.keys = extractDocumentKeysFromArrayValue(Operator.IN, value);\n }\n\n matches(doc: Document): boolean {\n return this.keys.some(key => key.isEqual(doc.key));\n }\n}\n\n/** Filter that matches on key fields not present within an array. */\nexport class KeyFieldNotInFilter extends FieldFilter {\n private readonly keys: DocumentKey[];\n\n constructor(field: FieldPath, value: ProtoValue) {\n super(field, Operator.NOT_IN, value);\n this.keys = extractDocumentKeysFromArrayValue(Operator.NOT_IN, value);\n }\n\n matches(doc: Document): boolean {\n return !this.keys.some(key => key.isEqual(doc.key));\n }\n}\n\nfunction extractDocumentKeysFromArrayValue(\n op: Operator.IN | Operator.NOT_IN,\n value: ProtoValue\n): DocumentKey[] {\n debugAssert(\n isArray(value),\n 'KeyFieldInFilter/KeyFieldNotInFilter expects an ArrayValue'\n );\n return (value.arrayValue?.values || []).map(v => {\n debugAssert(\n isReferenceValue(v),\n `Comparing on key with ${op.toString()}, but an array value was not ` +\n `a ReferenceValue`\n );\n return DocumentKey.fromName(v.referenceValue);\n });\n}\n\n/** A Filter that implements the array-contains operator. */\nexport class ArrayContainsFilter extends FieldFilter {\n constructor(field: FieldPath, value: ProtoValue) {\n super(field, Operator.ARRAY_CONTAINS, value);\n }\n\n matches(doc: Document): boolean {\n const other = doc.data.field(this.field);\n return isArray(other) && arrayValueContains(other.arrayValue, this.value);\n }\n}\n\n/** A Filter that implements the IN operator. */\nexport class InFilter extends FieldFilter {\n constructor(field: FieldPath, value: ProtoValue) {\n super(field, Operator.IN, value);\n debugAssert(isArray(value), 'InFilter expects an ArrayValue');\n }\n\n matches(doc: Document): boolean {\n const other = doc.data.field(this.field);\n return other !== null && arrayValueContains(this.value.arrayValue!, other);\n }\n}\n\n/** A Filter that implements the not-in operator. */\nexport class NotInFilter extends FieldFilter {\n constructor(field: FieldPath, value: ProtoValue) {\n super(field, Operator.NOT_IN, value);\n debugAssert(isArray(value), 'NotInFilter expects an ArrayValue');\n }\n\n matches(doc: Document): boolean {\n if (\n arrayValueContains(this.value.arrayValue!, { nullValue: 'NULL_VALUE' })\n ) {\n return false;\n }\n const other = doc.data.field(this.field);\n return (\n other !== null &&\n other.nullValue === undefined &&\n !arrayValueContains(this.value.arrayValue!, other)\n );\n }\n}\n\n/** A Filter that implements the array-contains-any operator. */\nexport class ArrayContainsAnyFilter extends FieldFilter {\n constructor(field: FieldPath, value: ProtoValue) {\n super(field, Operator.ARRAY_CONTAINS_ANY, value);\n debugAssert(isArray(value), 'ArrayContainsAnyFilter expects an ArrayValue');\n }\n\n matches(doc: Document): boolean {\n const other = doc.data.field(this.field);\n if (!isArray(other) || !other.arrayValue.values) {\n return false;\n }\n return other.arrayValue.values.some(val =>\n arrayValueContains(this.value.arrayValue!, val)\n );\n }\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FieldPath } from '../model/path';\n\n/**\n * The direction of sorting in an order by.\n */\nexport const enum Direction {\n ASCENDING = 'asc',\n DESCENDING = 'desc'\n}\n\n/**\n * An ordering on a field, in some Direction. Direction defaults to ASCENDING.\n */\nexport class OrderBy {\n constructor(\n readonly field: FieldPath,\n readonly dir: Direction = Direction.ASCENDING\n ) {}\n}\n\nexport function canonifyOrderBy(orderBy: OrderBy): string {\n // TODO(b/29183165): Make this collision robust.\n return orderBy.field.canonicalString() + orderBy.dir;\n}\n\nexport function stringifyOrderBy(orderBy: OrderBy): string {\n return `${orderBy.field.canonicalString()} (${orderBy.dir})`;\n}\n\nexport function orderByEquals(left: OrderBy, right: OrderBy): boolean {\n return left.dir === right.dir && left.field.isEqual(right.field);\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Timestamp } from '../lite-api/timestamp';\n\n/**\n * A version of a document in Firestore. This corresponds to the version\n * timestamp, such as update_time or read_time.\n */\nexport class SnapshotVersion {\n static fromTimestamp(value: Timestamp): SnapshotVersion {\n return new SnapshotVersion(value);\n }\n\n static min(): SnapshotVersion {\n return new SnapshotVersion(new Timestamp(0, 0));\n }\n\n static max(): SnapshotVersion {\n return new SnapshotVersion(new Timestamp(253402300799, 1e9 - 1));\n }\n\n private constructor(private timestamp: Timestamp) {}\n\n compareTo(other: SnapshotVersion): number {\n return this.timestamp._compareTo(other.timestamp);\n }\n\n isEqual(other: SnapshotVersion): boolean {\n return this.timestamp.isEqual(other.timestamp);\n }\n\n /** Returns a number representation of the version for use in spec tests. */\n toMicroseconds(): number {\n // Convert to microseconds.\n return this.timestamp.seconds * 1e6 + this.timestamp.nanoseconds / 1000;\n }\n\n toString(): string {\n return 'SnapshotVersion(' + this.timestamp.toString() + ')';\n }\n\n toTimestamp(): Timestamp {\n return this.timestamp;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { debugAssert, fail } from './assert';\n\n/*\n * Implementation of an immutable SortedMap using a Left-leaning\n * Red-Black Tree, adapted from the implementation in Mugs\n * (http://mads379.github.com/mugs/) by Mads Hartmann Jensen\n * (mads379@gmail.com).\n *\n * Original paper on Left-leaning Red-Black Trees:\n * http://www.cs.princeton.edu/~rs/talks/LLRB/LLRB.pdf\n *\n * Invariant 1: No red node has a red child\n * Invariant 2: Every leaf path has the same number of black nodes\n * Invariant 3: Only the left child can be red (left leaning)\n */\n\nexport type Comparator = (key1: K, key2: K) => number;\n\nexport interface Entry {\n key: K;\n value: V;\n}\n\n// An immutable sorted map implementation, based on a Left-leaning Red-Black\n// tree.\nexport class SortedMap {\n // visible for testing\n root: LLRBNode | LLRBEmptyNode;\n\n constructor(\n public comparator: Comparator,\n root?: LLRBNode | LLRBEmptyNode\n ) {\n this.root = root ? root : LLRBNode.EMPTY;\n }\n\n // Returns a copy of the map, with the specified key/value added or replaced.\n insert(key: K, value: V): SortedMap {\n return new SortedMap(\n this.comparator,\n this.root\n .insert(key, value, this.comparator)\n .copy(null, null, LLRBNode.BLACK, null, null)\n );\n }\n\n // Returns a copy of the map, with the specified key removed.\n remove(key: K): SortedMap {\n return new SortedMap(\n this.comparator,\n this.root\n .remove(key, this.comparator)\n .copy(null, null, LLRBNode.BLACK, null, null)\n );\n }\n\n // Returns the value of the node with the given key, or null.\n get(key: K): V | null {\n let node = this.root;\n while (!node.isEmpty()) {\n const cmp = this.comparator(key, node.key);\n if (cmp === 0) {\n return node.value;\n } else if (cmp < 0) {\n node = node.left;\n } else if (cmp > 0) {\n node = node.right;\n }\n }\n return null;\n }\n\n // Returns the index of the element in this sorted map, or -1 if it doesn't\n // exist.\n indexOf(key: K): number {\n // Number of nodes that were pruned when descending right\n let prunedNodes = 0;\n let node = this.root;\n while (!node.isEmpty()) {\n const cmp = this.comparator(key, node.key);\n if (cmp === 0) {\n return prunedNodes + node.left.size;\n } else if (cmp < 0) {\n node = node.left;\n } else {\n // Count all nodes left of the node plus the node itself\n prunedNodes += node.left.size + 1;\n node = node.right;\n }\n }\n // Node not found\n return -1;\n }\n\n isEmpty(): boolean {\n return this.root.isEmpty();\n }\n\n // Returns the total number of nodes in the map.\n get size(): number {\n return this.root.size;\n }\n\n // Returns the minimum key in the map.\n minKey(): K | null {\n return this.root.minKey();\n }\n\n // Returns the maximum key in the map.\n maxKey(): K | null {\n return this.root.maxKey();\n }\n\n // Traverses the map in key order and calls the specified action function\n // for each key/value pair. If action returns true, traversal is aborted.\n // Returns the first truthy value returned by action, or the last falsey\n // value returned by action.\n inorderTraversal(action: (k: K, v: V) => T): T {\n return (this.root as LLRBNode).inorderTraversal(action);\n }\n\n forEach(fn: (k: K, v: V) => void): void {\n this.inorderTraversal((k, v) => {\n fn(k, v);\n return false;\n });\n }\n\n toString(): string {\n const descriptions: string[] = [];\n this.inorderTraversal((k, v) => {\n descriptions.push(`${k}:${v}`);\n return false;\n });\n return `{${descriptions.join(', ')}}`;\n }\n\n // Traverses the map in reverse key order and calls the specified action\n // function for each key/value pair. If action returns true, traversal is\n // aborted.\n // Returns the first truthy value returned by action, or the last falsey\n // value returned by action.\n reverseTraversal(action: (k: K, v: V) => T): T {\n return (this.root as LLRBNode).reverseTraversal(action);\n }\n\n // Returns an iterator over the SortedMap.\n getIterator(): SortedMapIterator {\n return new SortedMapIterator(this.root, null, this.comparator, false);\n }\n\n getIteratorFrom(key: K): SortedMapIterator {\n return new SortedMapIterator(this.root, key, this.comparator, false);\n }\n\n getReverseIterator(): SortedMapIterator {\n return new SortedMapIterator(this.root, null, this.comparator, true);\n }\n\n getReverseIteratorFrom(key: K): SortedMapIterator {\n return new SortedMapIterator(this.root, key, this.comparator, true);\n }\n} // end SortedMap\n\n// An iterator over an LLRBNode.\nexport class SortedMapIterator {\n private isReverse: boolean;\n private nodeStack: Array | LLRBEmptyNode>;\n\n constructor(\n node: LLRBNode | LLRBEmptyNode,\n startKey: K | null,\n comparator: Comparator,\n isReverse: boolean\n ) {\n this.isReverse = isReverse;\n this.nodeStack = [];\n\n let cmp = 1;\n while (!node.isEmpty()) {\n cmp = startKey ? comparator(node.key, startKey) : 1;\n // flip the comparison if we're going in reverse\n if (startKey && isReverse) {\n cmp *= -1;\n }\n\n if (cmp < 0) {\n // This node is less than our start key. ignore it\n if (this.isReverse) {\n node = node.left;\n } else {\n node = node.right;\n }\n } else if (cmp === 0) {\n // This node is exactly equal to our start key. Push it on the stack,\n // but stop iterating;\n this.nodeStack.push(node);\n break;\n } else {\n // This node is greater than our start key, add it to the stack and move\n // to the next one\n this.nodeStack.push(node);\n if (this.isReverse) {\n node = node.right;\n } else {\n node = node.left;\n }\n }\n }\n }\n\n getNext(): Entry {\n debugAssert(\n this.nodeStack.length > 0,\n 'getNext() called on iterator when hasNext() is false.'\n );\n\n let node = this.nodeStack.pop()!;\n const result = { key: node.key, value: node.value };\n\n if (this.isReverse) {\n node = node.left;\n while (!node.isEmpty()) {\n this.nodeStack.push(node);\n node = node.right;\n }\n } else {\n node = node.right;\n while (!node.isEmpty()) {\n this.nodeStack.push(node);\n node = node.left;\n }\n }\n\n return result;\n }\n\n hasNext(): boolean {\n return this.nodeStack.length > 0;\n }\n\n peek(): Entry | null {\n if (this.nodeStack.length === 0) {\n return null;\n }\n\n const node = this.nodeStack[this.nodeStack.length - 1];\n return { key: node.key, value: node.value };\n }\n} // end SortedMapIterator\n\n// Represents a node in a Left-leaning Red-Black tree.\nexport class LLRBNode {\n readonly color: boolean;\n readonly left: LLRBNode | LLRBEmptyNode;\n readonly right: LLRBNode | LLRBEmptyNode;\n readonly size: number;\n\n // Empty node is shared between all LLRB trees.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n static EMPTY: LLRBEmptyNode = null as any;\n\n static RED = true;\n static BLACK = false;\n\n constructor(\n public key: K,\n public value: V,\n color?: boolean,\n left?: LLRBNode | LLRBEmptyNode,\n right?: LLRBNode | LLRBEmptyNode\n ) {\n this.color = color != null ? color : LLRBNode.RED;\n this.left = left != null ? left : LLRBNode.EMPTY;\n this.right = right != null ? right : LLRBNode.EMPTY;\n this.size = this.left.size + 1 + this.right.size;\n }\n\n // Returns a copy of the current node, optionally replacing pieces of it.\n copy(\n key: K | null,\n value: V | null,\n color: boolean | null,\n left: LLRBNode | LLRBEmptyNode | null,\n right: LLRBNode | LLRBEmptyNode | null\n ): LLRBNode {\n return new LLRBNode(\n key != null ? key : this.key,\n value != null ? value : this.value,\n color != null ? color : this.color,\n left != null ? left : this.left,\n right != null ? right : this.right\n );\n }\n\n isEmpty(): boolean {\n return false;\n }\n\n // Traverses the tree in key order and calls the specified action function\n // for each node. If action returns true, traversal is aborted.\n // Returns the first truthy value returned by action, or the last falsey\n // value returned by action.\n inorderTraversal(action: (k: K, v: V) => T): T {\n return (\n (this.left as LLRBNode).inorderTraversal(action) ||\n action(this.key, this.value) ||\n (this.right as LLRBNode).inorderTraversal(action)\n );\n }\n\n // Traverses the tree in reverse key order and calls the specified action\n // function for each node. If action returns true, traversal is aborted.\n // Returns the first truthy value returned by action, or the last falsey\n // value returned by action.\n reverseTraversal(action: (k: K, v: V) => T): T {\n return (\n (this.right as LLRBNode).reverseTraversal(action) ||\n action(this.key, this.value) ||\n (this.left as LLRBNode).reverseTraversal(action)\n );\n }\n\n // Returns the minimum node in the tree.\n private min(): LLRBNode {\n if (this.left.isEmpty()) {\n return this;\n } else {\n return (this.left as LLRBNode).min();\n }\n }\n\n // Returns the maximum key in the tree.\n minKey(): K | null {\n return this.min().key;\n }\n\n // Returns the maximum key in the tree.\n maxKey(): K | null {\n if (this.right.isEmpty()) {\n return this.key;\n } else {\n return this.right.maxKey();\n }\n }\n\n // Returns new tree, with the key/value added.\n insert(key: K, value: V, comparator: Comparator): LLRBNode {\n let n: LLRBNode = this;\n const cmp = comparator(key, n.key);\n if (cmp < 0) {\n n = n.copy(null, null, null, n.left.insert(key, value, comparator), null);\n } else if (cmp === 0) {\n n = n.copy(null, value, null, null, null);\n } else {\n n = n.copy(\n null,\n null,\n null,\n null,\n n.right.insert(key, value, comparator)\n );\n }\n return n.fixUp();\n }\n\n private removeMin(): LLRBNode | LLRBEmptyNode {\n if (this.left.isEmpty()) {\n return LLRBNode.EMPTY;\n }\n let n: LLRBNode = this;\n if (!n.left.isRed() && !n.left.left.isRed()) {\n n = n.moveRedLeft();\n }\n n = n.copy(null, null, null, (n.left as LLRBNode).removeMin(), null);\n return n.fixUp();\n }\n\n // Returns new tree, with the specified item removed.\n remove(\n key: K,\n comparator: Comparator\n ): LLRBNode | LLRBEmptyNode {\n let smallest: LLRBNode;\n let n: LLRBNode = this;\n if (comparator(key, n.key) < 0) {\n if (!n.left.isEmpty() && !n.left.isRed() && !n.left.left.isRed()) {\n n = n.moveRedLeft();\n }\n n = n.copy(null, null, null, n.left.remove(key, comparator), null);\n } else {\n if (n.left.isRed()) {\n n = n.rotateRight();\n }\n if (!n.right.isEmpty() && !n.right.isRed() && !n.right.left.isRed()) {\n n = n.moveRedRight();\n }\n if (comparator(key, n.key) === 0) {\n if (n.right.isEmpty()) {\n return LLRBNode.EMPTY;\n } else {\n smallest = (n.right as LLRBNode).min();\n n = n.copy(\n smallest.key,\n smallest.value,\n null,\n null,\n (n.right as LLRBNode).removeMin()\n );\n }\n }\n n = n.copy(null, null, null, null, n.right.remove(key, comparator));\n }\n return n.fixUp();\n }\n\n isRed(): boolean {\n return this.color;\n }\n\n // Returns new tree after performing any needed rotations.\n private fixUp(): LLRBNode {\n let n: LLRBNode = this;\n if (n.right.isRed() && !n.left.isRed()) {\n n = n.rotateLeft();\n }\n if (n.left.isRed() && n.left.left.isRed()) {\n n = n.rotateRight();\n }\n if (n.left.isRed() && n.right.isRed()) {\n n = n.colorFlip();\n }\n return n;\n }\n\n private moveRedLeft(): LLRBNode {\n let n = this.colorFlip();\n if (n.right.left.isRed()) {\n n = n.copy(\n null,\n null,\n null,\n null,\n (n.right as LLRBNode).rotateRight()\n );\n n = n.rotateLeft();\n n = n.colorFlip();\n }\n return n;\n }\n\n private moveRedRight(): LLRBNode {\n let n = this.colorFlip();\n if (n.left.left.isRed()) {\n n = n.rotateRight();\n n = n.colorFlip();\n }\n return n;\n }\n\n private rotateLeft(): LLRBNode {\n const nl = this.copy(null, null, LLRBNode.RED, null, this.right.left);\n return (this.right as LLRBNode).copy(\n null,\n null,\n this.color,\n nl,\n null\n );\n }\n\n private rotateRight(): LLRBNode {\n const nr = this.copy(null, null, LLRBNode.RED, this.left.right, null);\n return (this.left as LLRBNode).copy(null, null, this.color, null, nr);\n }\n\n private colorFlip(): LLRBNode {\n const left = this.left.copy(null, null, !this.left.color, null, null);\n const right = this.right.copy(null, null, !this.right.color, null, null);\n return this.copy(null, null, !this.color, left, right);\n }\n\n // For testing.\n checkMaxDepth(): boolean {\n const blackDepth = this.check();\n if (Math.pow(2.0, blackDepth) <= this.size + 1) {\n return true;\n } else {\n return false;\n }\n }\n\n // In a balanced RB tree, the black-depth (number of black nodes) from root to\n // leaves is equal on both sides. This function verifies that or asserts.\n protected check(): number {\n if (this.isRed() && this.left.isRed()) {\n throw fail(0xaad2, 'Red node has red child', {\n key: this.key,\n value: this.value\n });\n }\n if (this.right.isRed()) {\n throw fail(0x3721, 'Right child of (`key`, `value`) is red', {\n key: this.key,\n value: this.value\n });\n }\n const blackDepth = (this.left as LLRBNode).check();\n if (blackDepth !== (this.right as LLRBNode).check()) {\n throw fail(0x6d2d, 'Black depths differ');\n } else {\n return blackDepth + (this.isRed() ? 0 : 1);\n }\n }\n} // end LLRBNode\n\n// Represents an empty node (a leaf node in the Red-Black Tree).\nexport class LLRBEmptyNode {\n get key(): never {\n throw fail(0xe1a6, 'LLRBEmptyNode has no key.');\n }\n get value(): never {\n throw fail(0x3f0d, 'LLRBEmptyNode has no value.');\n }\n get color(): never {\n throw fail(0x4157, 'LLRBEmptyNode has no color.');\n }\n get left(): never {\n throw fail(0x741e, 'LLRBEmptyNode has no left child.');\n }\n get right(): never {\n throw fail(0x901e, 'LLRBEmptyNode has no right child.');\n }\n size = 0;\n\n // Returns a copy of the current node.\n copy(\n key: K | null,\n value: V | null,\n color: boolean | null,\n left: LLRBNode | LLRBEmptyNode | null,\n right: LLRBNode | LLRBEmptyNode | null\n ): LLRBEmptyNode {\n return this;\n }\n\n // Returns a copy of the tree, with the specified key/value added.\n insert(key: K, value: V, comparator: Comparator): LLRBNode {\n return new LLRBNode(key, value);\n }\n\n // Returns a copy of the tree, with the specified key removed.\n remove(key: K, comparator: Comparator): LLRBEmptyNode {\n return this;\n }\n\n isEmpty(): boolean {\n return true;\n }\n\n inorderTraversal(action: (k: K, v: V) => boolean): boolean {\n return false;\n }\n\n reverseTraversal(action: (k: K, v: V) => boolean): boolean {\n return false;\n }\n\n minKey(): K | null {\n return null;\n }\n\n maxKey(): K | null {\n return null;\n }\n\n isRed(): boolean {\n return false;\n }\n\n // For testing.\n checkMaxDepth(): boolean {\n return true;\n }\n\n protected check(): 0 {\n return 0;\n }\n} // end LLRBEmptyNode\n\nLLRBNode.EMPTY = new LLRBEmptyNode();\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SortedMap, SortedMapIterator } from './sorted_map';\n\n/**\n * SortedSet is an immutable (copy-on-write) collection that holds elements\n * in order specified by the provided comparator.\n *\n * NOTE: if provided comparator returns 0 for two elements, we consider them to\n * be equal!\n */\nexport class SortedSet {\n private data: SortedMap;\n\n constructor(private comparator: (left: T, right: T) => number) {\n this.data = new SortedMap(this.comparator);\n }\n\n has(elem: T): boolean {\n return this.data.get(elem) !== null;\n }\n\n first(): T | null {\n return this.data.minKey();\n }\n\n last(): T | null {\n return this.data.maxKey();\n }\n\n get size(): number {\n return this.data.size;\n }\n\n indexOf(elem: T): number {\n return this.data.indexOf(elem);\n }\n\n /** Iterates elements in order defined by \"comparator\" */\n forEach(cb: (elem: T) => void): void {\n this.data.inorderTraversal((k: T, v: boolean) => {\n cb(k);\n return false;\n });\n }\n\n /** Iterates over `elem`s such that: range[0] <= elem < range[1]. */\n forEachInRange(range: [T, T], cb: (elem: T) => void): void {\n const iter = this.data.getIteratorFrom(range[0]);\n while (iter.hasNext()) {\n const elem = iter.getNext();\n if (this.comparator(elem.key, range[1]) >= 0) {\n return;\n }\n cb(elem.key);\n }\n }\n\n /**\n * Iterates over `elem`s such that: start <= elem until false is returned.\n */\n forEachWhile(cb: (elem: T) => boolean, start?: T): void {\n let iter: SortedMapIterator;\n if (start !== undefined) {\n iter = this.data.getIteratorFrom(start);\n } else {\n iter = this.data.getIterator();\n }\n while (iter.hasNext()) {\n const elem = iter.getNext();\n const result = cb(elem.key);\n if (!result) {\n return;\n }\n }\n }\n\n /** Finds the least element greater than or equal to `elem`. */\n firstAfterOrEqual(elem: T): T | null {\n const iter = this.data.getIteratorFrom(elem);\n return iter.hasNext() ? iter.getNext().key : null;\n }\n\n getIterator(): SortedSetIterator {\n return new SortedSetIterator(this.data.getIterator());\n }\n\n getIteratorFrom(key: T): SortedSetIterator {\n return new SortedSetIterator(this.data.getIteratorFrom(key));\n }\n\n /** Inserts or updates an element */\n add(elem: T): SortedSet {\n return this.copy(this.data.remove(elem).insert(elem, true));\n }\n\n /** Deletes an element */\n delete(elem: T): SortedSet {\n if (!this.has(elem)) {\n return this;\n }\n return this.copy(this.data.remove(elem));\n }\n\n isEmpty(): boolean {\n return this.data.isEmpty();\n }\n\n unionWith(other: SortedSet): SortedSet {\n let result: SortedSet = this;\n\n // Make sure `result` always refers to the larger one of the two sets.\n if (result.size < other.size) {\n result = other;\n other = this;\n }\n\n other.forEach(elem => {\n result = result.add(elem);\n });\n return result;\n }\n\n isEqual(other: SortedSet): boolean {\n if (!(other instanceof SortedSet)) {\n return false;\n }\n if (this.size !== other.size) {\n return false;\n }\n\n const thisIt = this.data.getIterator();\n const otherIt = other.data.getIterator();\n while (thisIt.hasNext()) {\n const thisElem = thisIt.getNext().key;\n const otherElem = otherIt.getNext().key;\n if (this.comparator(thisElem, otherElem) !== 0) {\n return false;\n }\n }\n return true;\n }\n\n toArray(): T[] {\n const res: T[] = [];\n this.forEach(targetId => {\n res.push(targetId);\n });\n return res;\n }\n\n toString(): string {\n const result: T[] = [];\n this.forEach(elem => result.push(elem));\n return 'SortedSet(' + result.toString() + ')';\n }\n\n private copy(data: SortedMap): SortedSet {\n const result = new SortedSet(this.comparator);\n result.data = data;\n return result;\n }\n}\n\nexport class SortedSetIterator {\n constructor(private iter: SortedMapIterator) {}\n\n getNext(): T {\n return this.iter.getNext().key;\n }\n\n hasNext(): boolean {\n return this.iter.hasNext();\n }\n}\n\n/**\n * Compares two sorted sets for equality using their natural ordering. The\n * method computes the intersection and invokes `onAdd` for every element that\n * is in `after` but not `before`. `onRemove` is invoked for every element in\n * `before` but missing from `after`.\n *\n * The method creates a copy of both `before` and `after` and runs in O(n log\n * n), where n is the size of the two lists.\n *\n * @param before - The elements that exist in the original set.\n * @param after - The elements to diff against the original set.\n * @param comparator - The comparator for the elements in before and after.\n * @param onAdd - A function to invoke for every element that is part of `\n * after` but not `before`.\n * @param onRemove - A function to invoke for every element that is part of\n * `before` but not `after`.\n */\nexport function diffSortedSets(\n before: SortedSet,\n after: SortedSet,\n comparator: (l: T, r: T) => number,\n onAdd: (entry: T) => void,\n onRemove: (entry: T) => void\n): void {\n const beforeIt = before.getIterator();\n const afterIt = after.getIterator();\n\n let beforeValue = advanceIterator(beforeIt);\n let afterValue = advanceIterator(afterIt);\n\n // Walk through the two sets at the same time, using the ordering defined by\n // `comparator`.\n while (beforeValue || afterValue) {\n let added = false;\n let removed = false;\n\n if (beforeValue && afterValue) {\n const cmp = comparator(beforeValue, afterValue);\n if (cmp < 0) {\n // The element was removed if the next element in our ordered\n // walkthrough is only in `before`.\n removed = true;\n } else if (cmp > 0) {\n // The element was added if the next element in our ordered walkthrough\n // is only in `after`.\n added = true;\n }\n } else if (beforeValue != null) {\n removed = true;\n } else {\n added = true;\n }\n\n if (added) {\n onAdd(afterValue!);\n afterValue = advanceIterator(afterIt);\n } else if (removed) {\n onRemove(beforeValue!);\n beforeValue = advanceIterator(beforeIt);\n } else {\n beforeValue = advanceIterator(beforeIt);\n afterValue = advanceIterator(afterIt);\n }\n }\n}\n\n/**\n * Returns the next element from the iterator or `undefined` if none available.\n */\nfunction advanceIterator(it: SortedSetIterator): T | undefined {\n return it.hasNext() ? it.getNext() : undefined;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { debugAssert } from '../util/assert';\nimport { arrayEquals } from '../util/misc';\nimport { SortedSet } from '../util/sorted_set';\n\nimport { FieldPath } from './path';\n\n/**\n * Provides a set of fields that can be used to partially patch a document.\n * FieldMask is used in conjunction with ObjectValue.\n * Examples:\n * foo - Overwrites foo entirely with the provided value. If foo is not\n * present in the companion ObjectValue, the field is deleted.\n * foo.bar - Overwrites only the field bar of the object foo.\n * If foo is not an object, foo is replaced with an object\n * containing foo\n */\nexport class FieldMask {\n constructor(readonly fields: FieldPath[]) {\n // TODO(dimond): validation of FieldMask\n // Sort the field mask to support `FieldMask.isEqual()` and assert below.\n fields.sort(FieldPath.comparator);\n debugAssert(\n !fields.some((v, i) => i !== 0 && v.isEqual(fields[i - 1])),\n 'FieldMask contains field that is not unique: ' +\n fields.find((v, i) => i !== 0 && v.isEqual(fields[i - 1]))!\n );\n }\n\n static empty(): FieldMask {\n return new FieldMask([]);\n }\n\n /**\n * Returns a new FieldMask object that is the result of adding all the given\n * fields paths to this field mask.\n */\n unionWith(extraFields: FieldPath[]): FieldMask {\n let mergedMaskSet = new SortedSet(FieldPath.comparator);\n for (const fieldPath of this.fields) {\n mergedMaskSet = mergedMaskSet.add(fieldPath);\n }\n for (const fieldPath of extraFields) {\n mergedMaskSet = mergedMaskSet.add(fieldPath);\n }\n return new FieldMask(mergedMaskSet.toArray());\n }\n\n /**\n * Verifies that `fieldPath` is included by at least one field in this field\n * mask.\n *\n * This is an O(n) operation, where `n` is the size of the field mask.\n */\n covers(fieldPath: FieldPath): boolean {\n for (const fieldMaskPath of this.fields) {\n if (fieldMaskPath.isPrefixOf(fieldPath)) {\n return true;\n }\n }\n return false;\n }\n\n isEqual(other: FieldMask): boolean {\n return arrayEquals(this.fields, other.fields, (l, r) => l.isEqual(r));\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n MapValue as ProtoMapValue,\n Value as ProtoValue\n} from '../protos/firestore_proto_api';\nimport { debugAssert } from '../util/assert';\nimport { forEach } from '../util/obj';\n\nimport { FieldMask } from './field_mask';\nimport { FieldPath } from './path';\nimport { isServerTimestamp } from './server_timestamps';\nimport { deepClone, isMapValue, valueEquals } from './values';\n\nexport interface JsonObject {\n [name: string]: T;\n}\n/**\n * An ObjectValue represents a MapValue in the Firestore Proto and offers the\n * ability to add and remove fields (via the ObjectValueBuilder).\n */\nexport class ObjectValue {\n constructor(readonly value: { mapValue: ProtoMapValue }) {\n debugAssert(\n !isServerTimestamp(value),\n 'ServerTimestamps should be converted to ServerTimestampValue'\n );\n }\n\n static empty(): ObjectValue {\n return new ObjectValue({ mapValue: {} });\n }\n\n /**\n * Returns the value at the given path or null.\n *\n * @param path - the path to search\n * @returns The value at the path or null if the path is not set.\n */\n field(path: FieldPath): ProtoValue | null {\n if (path.isEmpty()) {\n return this.value;\n } else {\n let currentLevel: ProtoValue = this.value;\n for (let i = 0; i < path.length - 1; ++i) {\n currentLevel = (currentLevel.mapValue!.fields || {})[path.get(i)];\n if (!isMapValue(currentLevel)) {\n return null;\n }\n }\n currentLevel = (currentLevel.mapValue!.fields! || {})[path.lastSegment()];\n return currentLevel || null;\n }\n }\n\n /**\n * Sets the field to the provided value.\n *\n * @param path - The field path to set.\n * @param value - The value to set.\n */\n set(path: FieldPath, value: ProtoValue): void {\n debugAssert(\n !path.isEmpty(),\n 'Cannot set field for empty path on ObjectValue'\n );\n const fieldsMap = this.getFieldsMap(path.popLast());\n fieldsMap[path.lastSegment()] = deepClone(value);\n }\n\n /**\n * Sets the provided fields to the provided values.\n *\n * @param data - A map of fields to values (or null for deletes).\n */\n setAll(data: Map): void {\n let parent = FieldPath.emptyPath();\n\n let upserts: { [key: string]: ProtoValue } = {};\n let deletes: string[] = [];\n\n data.forEach((value, path) => {\n if (!parent.isImmediateParentOf(path)) {\n // Insert the accumulated changes at this parent location\n const fieldsMap = this.getFieldsMap(parent);\n this.applyChanges(fieldsMap, upserts, deletes);\n upserts = {};\n deletes = [];\n parent = path.popLast();\n }\n\n if (value) {\n upserts[path.lastSegment()] = deepClone(value);\n } else {\n deletes.push(path.lastSegment());\n }\n });\n\n const fieldsMap = this.getFieldsMap(parent);\n this.applyChanges(fieldsMap, upserts, deletes);\n }\n\n /**\n * Removes the field at the specified path. If there is no field at the\n * specified path, nothing is changed.\n *\n * @param path - The field path to remove.\n */\n delete(path: FieldPath): void {\n debugAssert(\n !path.isEmpty(),\n 'Cannot delete field for empty path on ObjectValue'\n );\n const nestedValue = this.field(path.popLast());\n if (isMapValue(nestedValue) && nestedValue.mapValue.fields) {\n delete nestedValue.mapValue.fields[path.lastSegment()];\n }\n }\n\n isEqual(other: ObjectValue): boolean {\n return valueEquals(this.value, other.value);\n }\n\n /**\n * Returns the map that contains the leaf element of `path`. If the parent\n * entry does not yet exist, or if it is not a map, a new map will be created.\n */\n private getFieldsMap(path: FieldPath): Record {\n let current = this.value;\n\n if (!current.mapValue!.fields) {\n current.mapValue = { fields: {} };\n }\n\n for (let i = 0; i < path.length; ++i) {\n let next = current.mapValue!.fields![path.get(i)];\n if (!isMapValue(next) || !next.mapValue.fields) {\n next = { mapValue: { fields: {} } };\n current.mapValue!.fields![path.get(i)] = next;\n }\n current = next as { mapValue: ProtoMapValue };\n }\n\n return current.mapValue!.fields!;\n }\n\n /**\n * Modifies `fieldsMap` by adding, replacing or deleting the specified\n * entries.\n */\n private applyChanges(\n fieldsMap: Record,\n inserts: { [key: string]: ProtoValue },\n deletes: string[]\n ): void {\n forEach(inserts, (key, val) => (fieldsMap[key] = val));\n for (const field of deletes) {\n delete fieldsMap[field];\n }\n }\n\n clone(): ObjectValue {\n return new ObjectValue(\n deepClone(this.value) as { mapValue: ProtoMapValue }\n );\n }\n}\n\n/**\n * Returns a FieldMask built from all fields in a MapValue.\n */\nexport function extractFieldMask(value: ProtoMapValue): FieldMask {\n const fields: FieldPath[] = [];\n forEach(value!.fields, (key, value) => {\n const currentPath = new FieldPath([key]);\n if (isMapValue(value)) {\n const nestedMask = extractFieldMask(value.mapValue!);\n const nestedFields = nestedMask.fields;\n if (nestedFields.length === 0) {\n // Preserve the empty map by adding it to the FieldMask.\n fields.push(currentPath);\n } else {\n // For nested and non-empty ObjectValues, add the FieldPath of the\n // leaf nodes.\n for (const nestedPath of nestedFields) {\n fields.push(currentPath.child(nestedPath));\n }\n }\n } else {\n // For nested and non-empty ObjectValues, add the FieldPath of the leaf\n // nodes.\n fields.push(currentPath);\n }\n });\n return new FieldMask(fields);\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { debugAssert, fail } from '../util/assert';\n\nimport { DocumentKey } from './document_key';\nimport { ObjectValue } from './object_value';\nimport { FieldPath } from './path';\nimport { valueCompare } from './values';\n\n/**\n * Whether the document represents an existing document, a document that is\n * known to exist or a document whose state or existence is unknown.\n */\nconst enum DocumentType {\n /**\n * Represents the initial state of a MutableDocument when only the document\n * key is known. Invalid documents transition to other states as mutations are\n * applied. If a document remains invalid after applying mutations, it should\n * be discarded.\n *\n * Invalid documents can have neither local nor committed mutations.\n */\n INVALID,\n /**\n * Represents a document in Firestore with a key, version, data and whether\n * the data has local mutations applied to it.\n *\n * Found documents can be synced or have or committed mutations applied.\n */\n FOUND_DOCUMENT,\n /**\n * Represents that no documents exists for the key at the given version.\n *\n * Documents that are deleted based on a local mutation do not raise snapshots\n * with `hasPendingWrites`. As such, deleted documents never have\n * `HAS_LOCAL_MUTATIONS` set. Once a delete is committed, we store them with\n * `HAS_COMMITTED_MUTATIONS` until we received the delete from the Watch\n * stream.\n */\n NO_DOCUMENT,\n /**\n * Represents an existing document whose data is unknown (e.g. a document that\n * was updated without a known base document).\n *\n * An unknown document always has `HAS_COMMITTED_MUTATIONS` set, since unknown\n * documents can only be generated by applying a patch mutation from a write\n * acknowledgement.\n */\n UNKNOWN_DOCUMENT\n}\n\n/** Describes whether a document has latency-compensated edits applied. */\nconst enum DocumentState {\n /** No mutations applied. Document was sent to us by Watch. */\n SYNCED,\n /**\n * Local mutations applied via the mutation queue. Document is potentially\n * inconsistent.\n */\n HAS_LOCAL_MUTATIONS,\n /**\n * Mutations applied based on a write acknowledgment. Document is potentially\n * inconsistent.\n */\n HAS_COMMITTED_MUTATIONS\n}\n\n/**\n * Represents a document in Firestore with a key, version, data and whether the\n * data has local mutations applied to it.\n */\nexport interface Document {\n /** The key for this document */\n readonly key: DocumentKey;\n\n /**\n * The version of this document if it exists or a version at which this\n * document was guaranteed to not exist.\n */\n readonly version: SnapshotVersion;\n\n /**\n * The timestamp at which this document was read from the remote server. Uses\n * `SnapshotVersion.min()` for documents created by the user.\n */\n readonly readTime: SnapshotVersion;\n\n /**\n * The timestamp at which the document was created. This value increases\n * monotonically when a document is deleted then recreated. It can also be\n * compared to `createTime` of other documents and the `readTime` of a query.\n */\n readonly createTime: SnapshotVersion;\n\n /** The underlying data of this document or an empty value if no data exists. */\n readonly data: ObjectValue;\n\n /** Returns whether local mutations were applied via the mutation queue. */\n readonly hasLocalMutations: boolean;\n\n /** Returns whether mutations were applied based on a write acknowledgment. */\n readonly hasCommittedMutations: boolean;\n\n /**\n * Whether this document had a local mutation applied that has not yet been\n * acknowledged by Watch.\n */\n readonly hasPendingWrites: boolean;\n\n /**\n * Returns whether this document is valid (i.e. it is an entry in the\n * RemoteDocumentCache, was created by a mutation or read from the backend).\n */\n isValidDocument(): boolean;\n\n /**\n * Returns whether the document exists and its data is known at the current\n * version.\n */\n isFoundDocument(): boolean;\n\n /**\n * Returns whether the document is known to not exist at the current version.\n */\n isNoDocument(): boolean;\n\n /**\n * Returns whether the document exists and its data is unknown at the current\n * version.\n */\n isUnknownDocument(): boolean;\n\n isEqual(other: Document | null | undefined): boolean;\n\n /** Creates a mutable copy of this document. */\n mutableCopy(): MutableDocument;\n\n toString(): string;\n}\n\n/**\n * Represents a document in Firestore with a key, version, data and whether it\n * has local mutations applied to it.\n *\n * Documents can transition between states via `convertToFoundDocument()`,\n * `convertToNoDocument()` and `convertToUnknownDocument()`. If a document does\n * not transition to one of these states even after all mutations have been\n * applied, `isValidDocument()` returns false and the document should be removed\n * from all views.\n */\nexport class MutableDocument implements Document {\n private constructor(\n readonly key: DocumentKey,\n private documentType: DocumentType,\n public version: SnapshotVersion,\n public readTime: SnapshotVersion,\n public createTime: SnapshotVersion,\n public data: ObjectValue,\n private documentState: DocumentState\n ) {}\n\n /**\n * Creates a document with no known version or data, but which can serve as\n * base document for mutations.\n */\n static newInvalidDocument(documentKey: DocumentKey): MutableDocument {\n return new MutableDocument(\n documentKey,\n DocumentType.INVALID,\n /* version */ SnapshotVersion.min(),\n /* readTime */ SnapshotVersion.min(),\n /* createTime */ SnapshotVersion.min(),\n ObjectValue.empty(),\n DocumentState.SYNCED\n );\n }\n\n /**\n * Creates a new document that is known to exist with the given data at the\n * given version.\n */\n static newFoundDocument(\n documentKey: DocumentKey,\n version: SnapshotVersion,\n createTime: SnapshotVersion,\n value: ObjectValue\n ): MutableDocument {\n return new MutableDocument(\n documentKey,\n DocumentType.FOUND_DOCUMENT,\n /* version */ version,\n /* readTime */ SnapshotVersion.min(),\n /* createTime */ createTime,\n value,\n DocumentState.SYNCED\n );\n }\n\n /** Creates a new document that is known to not exist at the given version. */\n static newNoDocument(\n documentKey: DocumentKey,\n version: SnapshotVersion\n ): MutableDocument {\n return new MutableDocument(\n documentKey,\n DocumentType.NO_DOCUMENT,\n /* version */ version,\n /* readTime */ SnapshotVersion.min(),\n /* createTime */ SnapshotVersion.min(),\n ObjectValue.empty(),\n DocumentState.SYNCED\n );\n }\n\n /**\n * Creates a new document that is known to exist at the given version but\n * whose data is not known (e.g. a document that was updated without a known\n * base document).\n */\n static newUnknownDocument(\n documentKey: DocumentKey,\n version: SnapshotVersion\n ): MutableDocument {\n return new MutableDocument(\n documentKey,\n DocumentType.UNKNOWN_DOCUMENT,\n /* version */ version,\n /* readTime */ SnapshotVersion.min(),\n /* createTime */ SnapshotVersion.min(),\n ObjectValue.empty(),\n DocumentState.HAS_COMMITTED_MUTATIONS\n );\n }\n\n /**\n * Changes the document type to indicate that it exists and that its version\n * and data are known.\n */\n convertToFoundDocument(\n version: SnapshotVersion,\n value: ObjectValue\n ): MutableDocument {\n // If a document is switching state from being an invalid or deleted\n // document to a valid (FOUND_DOCUMENT) document, either due to receiving an\n // update from Watch or due to applying a local set mutation on top\n // of a deleted document, our best guess about its createTime would be the\n // version at which the document transitioned to a FOUND_DOCUMENT.\n if (\n this.createTime.isEqual(SnapshotVersion.min()) &&\n (this.documentType === DocumentType.NO_DOCUMENT ||\n this.documentType === DocumentType.INVALID)\n ) {\n this.createTime = version;\n }\n this.version = version;\n this.documentType = DocumentType.FOUND_DOCUMENT;\n this.data = value;\n this.documentState = DocumentState.SYNCED;\n return this;\n }\n\n /**\n * Changes the document type to indicate that it doesn't exist at the given\n * version.\n */\n convertToNoDocument(version: SnapshotVersion): MutableDocument {\n this.version = version;\n this.documentType = DocumentType.NO_DOCUMENT;\n this.data = ObjectValue.empty();\n this.documentState = DocumentState.SYNCED;\n return this;\n }\n\n /**\n * Changes the document type to indicate that it exists at a given version but\n * that its data is not known (e.g. a document that was updated without a known\n * base document).\n */\n convertToUnknownDocument(version: SnapshotVersion): MutableDocument {\n this.version = version;\n this.documentType = DocumentType.UNKNOWN_DOCUMENT;\n this.data = ObjectValue.empty();\n this.documentState = DocumentState.HAS_COMMITTED_MUTATIONS;\n return this;\n }\n\n setHasCommittedMutations(): MutableDocument {\n debugAssert(\n this.isValidDocument(),\n 'Invalid documents cannot have committed mutations'\n );\n this.documentState = DocumentState.HAS_COMMITTED_MUTATIONS;\n return this;\n }\n\n setHasLocalMutations(): MutableDocument {\n this.documentState = DocumentState.HAS_LOCAL_MUTATIONS;\n this.version = SnapshotVersion.min();\n return this;\n }\n\n setReadTime(readTime: SnapshotVersion): MutableDocument {\n this.readTime = readTime;\n return this;\n }\n\n get hasLocalMutations(): boolean {\n return this.documentState === DocumentState.HAS_LOCAL_MUTATIONS;\n }\n\n get hasCommittedMutations(): boolean {\n return this.documentState === DocumentState.HAS_COMMITTED_MUTATIONS;\n }\n\n get hasPendingWrites(): boolean {\n return this.hasLocalMutations || this.hasCommittedMutations;\n }\n\n isValidDocument(): boolean {\n return this.documentType !== DocumentType.INVALID;\n }\n\n isFoundDocument(): boolean {\n return this.documentType === DocumentType.FOUND_DOCUMENT;\n }\n\n isNoDocument(): boolean {\n return this.documentType === DocumentType.NO_DOCUMENT;\n }\n\n isUnknownDocument(): boolean {\n return this.documentType === DocumentType.UNKNOWN_DOCUMENT;\n }\n\n isEqual(other: Document | null | undefined): boolean {\n return (\n other instanceof MutableDocument &&\n this.key.isEqual(other.key) &&\n this.version.isEqual(other.version) &&\n this.documentType === other.documentType &&\n this.documentState === other.documentState &&\n this.data.isEqual(other.data)\n );\n }\n\n mutableCopy(): MutableDocument {\n return new MutableDocument(\n this.key,\n this.documentType,\n this.version,\n this.readTime,\n this.createTime,\n this.data.clone(),\n this.documentState\n );\n }\n\n toString(): string {\n return (\n `Document(${this.key}, ${this.version}, ${JSON.stringify(\n this.data.value\n )}, ` +\n `{createTime: ${this.createTime}}), ` +\n `{documentType: ${this.documentType}}), ` +\n `{documentState: ${this.documentState}})`\n );\n }\n}\n\n/**\n * Compares the value for field `field` in the provided documents. Throws if\n * the field does not exist in both documents.\n */\nexport function compareDocumentsByField(\n field: FieldPath,\n d1: Document,\n d2: Document\n): number {\n const v1 = d1.data.field(field);\n const v2 = d2.data.field(field);\n if (v1 !== null && v2 !== null) {\n return valueCompare(v1, v2);\n } else {\n return fail(\n 0xa786,\n \"Trying to compare documents on fields that don't exist\"\n );\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DocumentKey } from '../model/document_key';\nimport {\n FieldIndex,\n fieldIndexGetArraySegment,\n fieldIndexGetDirectionalSegments,\n IndexKind\n} from '../model/field_index';\nimport { FieldPath, ResourcePath } from '../model/path';\nimport {\n canonicalId,\n MAX_VALUE,\n MIN_VALUE,\n lowerBoundCompare,\n upperBoundCompare,\n valuesGetLowerBound,\n valuesGetUpperBound\n} from '../model/values';\nimport { Value as ProtoValue } from '../protos/firestore_proto_api';\nimport { debugCast } from '../util/assert';\nimport { SortedSet } from '../util/sorted_set';\nimport { isNullOrUndefined } from '../util/types';\n\nimport { Bound, boundEquals } from './bound';\nimport {\n Filter,\n FieldFilter,\n canonifyFilter,\n stringifyFilter,\n filterEquals,\n Operator\n} from './filter';\nimport {\n canonifyOrderBy,\n OrderBy,\n orderByEquals,\n stringifyOrderBy\n} from './order_by';\n\n/**\n * A Target represents the WatchTarget representation of a Query, which is used\n * by the LocalStore and the RemoteStore to keep track of and to execute\n * backend queries. While a Query can represent multiple Targets, each Targets\n * maps to a single WatchTarget in RemoteStore and a single TargetData entry\n * in persistence.\n */\nexport interface Target {\n readonly path: ResourcePath;\n readonly collectionGroup: string | null;\n readonly orderBy: OrderBy[];\n readonly filters: Filter[];\n readonly limit: number | null;\n readonly startAt: Bound | null;\n readonly endAt: Bound | null;\n}\n\n// Visible for testing\nexport class TargetImpl implements Target {\n memoizedCanonicalId: string | null = null;\n constructor(\n readonly path: ResourcePath,\n readonly collectionGroup: string | null = null,\n readonly orderBy: OrderBy[] = [],\n readonly filters: Filter[] = [],\n readonly limit: number | null = null,\n readonly startAt: Bound | null = null,\n readonly endAt: Bound | null = null\n ) {}\n}\n\n/**\n * Initializes a Target with a path and optional additional query constraints.\n * Path must currently be empty if this is a collection group query.\n *\n * NOTE: you should always construct `Target` from `Query.toTarget` instead of\n * using this factory method, because `Query` provides an implicit `orderBy`\n * property.\n */\nexport function newTarget(\n path: ResourcePath,\n collectionGroup: string | null = null,\n orderBy: OrderBy[] = [],\n filters: Filter[] = [],\n limit: number | null = null,\n startAt: Bound | null = null,\n endAt: Bound | null = null\n): Target {\n return new TargetImpl(\n path,\n collectionGroup,\n orderBy,\n filters,\n limit,\n startAt,\n endAt\n );\n}\n\nexport function canonifyTarget(target: Target): string {\n const targetImpl = debugCast(target, TargetImpl);\n\n if (targetImpl.memoizedCanonicalId === null) {\n let str = targetImpl.path.canonicalString();\n if (targetImpl.collectionGroup !== null) {\n str += '|cg:' + targetImpl.collectionGroup;\n }\n str += '|f:';\n str += targetImpl.filters.map(f => canonifyFilter(f)).join(',');\n str += '|ob:';\n str += targetImpl.orderBy.map(o => canonifyOrderBy(o)).join(',');\n\n if (!isNullOrUndefined(targetImpl.limit)) {\n str += '|l:';\n str += targetImpl.limit!;\n }\n if (targetImpl.startAt) {\n str += '|lb:';\n str += targetImpl.startAt.inclusive ? 'b:' : 'a:';\n str += targetImpl.startAt.position.map(p => canonicalId(p)).join(',');\n }\n if (targetImpl.endAt) {\n str += '|ub:';\n str += targetImpl.endAt.inclusive ? 'a:' : 'b:';\n str += targetImpl.endAt.position.map(p => canonicalId(p)).join(',');\n }\n targetImpl.memoizedCanonicalId = str;\n }\n return targetImpl.memoizedCanonicalId;\n}\n\nexport function stringifyTarget(target: Target): string {\n let str = target.path.canonicalString();\n if (target.collectionGroup !== null) {\n str += ' collectionGroup=' + target.collectionGroup;\n }\n if (target.filters.length > 0) {\n str += `, filters: [${target.filters\n .map(f => stringifyFilter(f))\n .join(', ')}]`;\n }\n if (!isNullOrUndefined(target.limit)) {\n str += ', limit: ' + target.limit;\n }\n if (target.orderBy.length > 0) {\n str += `, orderBy: [${target.orderBy\n .map(o => stringifyOrderBy(o))\n .join(', ')}]`;\n }\n if (target.startAt) {\n str += ', startAt: ';\n str += target.startAt.inclusive ? 'b:' : 'a:';\n str += target.startAt.position.map(p => canonicalId(p)).join(',');\n }\n if (target.endAt) {\n str += ', endAt: ';\n str += target.endAt.inclusive ? 'a:' : 'b:';\n str += target.endAt.position.map(p => canonicalId(p)).join(',');\n }\n return `Target(${str})`;\n}\n\nexport function targetEquals(left: Target, right: Target): boolean {\n if (left.limit !== right.limit) {\n return false;\n }\n\n if (left.orderBy.length !== right.orderBy.length) {\n return false;\n }\n\n for (let i = 0; i < left.orderBy.length; i++) {\n if (!orderByEquals(left.orderBy[i], right.orderBy[i])) {\n return false;\n }\n }\n\n if (left.filters.length !== right.filters.length) {\n return false;\n }\n\n for (let i = 0; i < left.filters.length; i++) {\n if (!filterEquals(left.filters[i], right.filters[i])) {\n return false;\n }\n }\n\n if (left.collectionGroup !== right.collectionGroup) {\n return false;\n }\n\n if (!left.path.isEqual(right.path)) {\n return false;\n }\n\n if (!boundEquals(left.startAt, right.startAt)) {\n return false;\n }\n\n return boundEquals(left.endAt, right.endAt);\n}\n\nexport function targetIsDocumentTarget(target: Target): boolean {\n return (\n DocumentKey.isDocumentKey(target.path) &&\n target.collectionGroup === null &&\n target.filters.length === 0\n );\n}\n\n/** Returns the field filters that target the given field path. */\nexport function targetGetFieldFiltersForPath(\n target: Target,\n path: FieldPath\n): FieldFilter[] {\n return target.filters.filter(\n f => f instanceof FieldFilter && f.field.isEqual(path)\n ) as FieldFilter[];\n}\n\n/**\n * Returns the values that are used in ARRAY_CONTAINS or ARRAY_CONTAINS_ANY\n * filters. Returns `null` if there are no such filters.\n */\nexport function targetGetArrayValues(\n target: Target,\n fieldIndex: FieldIndex\n): ProtoValue[] | null {\n const segment = fieldIndexGetArraySegment(fieldIndex);\n if (segment === undefined) {\n return null;\n }\n\n for (const fieldFilter of targetGetFieldFiltersForPath(\n target,\n segment.fieldPath\n )) {\n switch (fieldFilter.op) {\n case Operator.ARRAY_CONTAINS_ANY:\n return fieldFilter.value.arrayValue!.values || [];\n case Operator.ARRAY_CONTAINS:\n return [fieldFilter.value];\n default:\n // Remaining filters are not array filters.\n }\n }\n return null;\n}\n\n/**\n * Returns the list of values that are used in != or NOT_IN filters. Returns\n * `null` if there are no such filters.\n */\nexport function targetGetNotInValues(\n target: Target,\n fieldIndex: FieldIndex\n): ProtoValue[] | null {\n const values = new Map();\n\n for (const segment of fieldIndexGetDirectionalSegments(fieldIndex)) {\n for (const fieldFilter of targetGetFieldFiltersForPath(\n target,\n segment.fieldPath\n )) {\n switch (fieldFilter.op) {\n case Operator.EQUAL:\n case Operator.IN:\n // Encode equality prefix, which is encoded in the index value before\n // the inequality (e.g. `a == 'a' && b != 'b'` is encoded to\n // `value != 'ab'`).\n values.set(segment.fieldPath.canonicalString(), fieldFilter.value);\n break;\n case Operator.NOT_IN:\n case Operator.NOT_EQUAL:\n // NotIn/NotEqual is always a suffix. There cannot be any remaining\n // segments and hence we can return early here.\n values.set(segment.fieldPath.canonicalString(), fieldFilter.value);\n return Array.from(values.values());\n default:\n // Remaining filters cannot be used as notIn bounds.\n }\n }\n }\n\n return null;\n}\n\n/**\n * Returns a lower bound of field values that can be used as a starting point to\n * scan the index defined by `fieldIndex`. Returns `MIN_VALUE` if no lower bound\n * exists.\n */\nexport function targetGetLowerBound(\n target: Target,\n fieldIndex: FieldIndex\n): Bound {\n const values: ProtoValue[] = [];\n let inclusive = true;\n\n // For each segment, retrieve a lower bound if there is a suitable filter or\n // startAt.\n for (const segment of fieldIndexGetDirectionalSegments(fieldIndex)) {\n const segmentBound =\n segment.kind === IndexKind.ASCENDING\n ? targetGetAscendingBound(target, segment.fieldPath, target.startAt)\n : targetGetDescendingBound(target, segment.fieldPath, target.startAt);\n\n values.push(segmentBound.value);\n inclusive &&= segmentBound.inclusive;\n }\n return new Bound(values, inclusive);\n}\n\n/**\n * Returns an upper bound of field values that can be used as an ending point\n * when scanning the index defined by `fieldIndex`. Returns `MAX_VALUE` if no\n * upper bound exists.\n */\nexport function targetGetUpperBound(\n target: Target,\n fieldIndex: FieldIndex\n): Bound {\n const values: ProtoValue[] = [];\n let inclusive = true;\n\n // For each segment, retrieve an upper bound if there is a suitable filter or\n // endAt.\n for (const segment of fieldIndexGetDirectionalSegments(fieldIndex)) {\n const segmentBound =\n segment.kind === IndexKind.ASCENDING\n ? targetGetDescendingBound(target, segment.fieldPath, target.endAt)\n : targetGetAscendingBound(target, segment.fieldPath, target.endAt);\n\n values.push(segmentBound.value);\n inclusive &&= segmentBound.inclusive;\n }\n\n return new Bound(values, inclusive);\n}\n\n/**\n * Returns the value to use as the lower bound for ascending index segment at\n * the provided `fieldPath` (or the upper bound for an descending segment).\n */\nfunction targetGetAscendingBound(\n target: Target,\n fieldPath: FieldPath,\n bound: Bound | null\n): { value: ProtoValue; inclusive: boolean } {\n let value: ProtoValue = MIN_VALUE;\n\n let inclusive = true;\n\n // Process all filters to find a value for the current field segment\n for (const fieldFilter of targetGetFieldFiltersForPath(target, fieldPath)) {\n let filterValue: ProtoValue = MIN_VALUE;\n let filterInclusive = true;\n\n switch (fieldFilter.op) {\n case Operator.LESS_THAN:\n case Operator.LESS_THAN_OR_EQUAL:\n filterValue = valuesGetLowerBound(fieldFilter.value);\n break;\n case Operator.EQUAL:\n case Operator.IN:\n case Operator.GREATER_THAN_OR_EQUAL:\n filterValue = fieldFilter.value;\n break;\n case Operator.GREATER_THAN:\n filterValue = fieldFilter.value;\n filterInclusive = false;\n break;\n case Operator.NOT_EQUAL:\n case Operator.NOT_IN:\n filterValue = MIN_VALUE;\n break;\n default:\n // Remaining filters cannot be used as lower bounds.\n }\n\n if (\n lowerBoundCompare(\n { value, inclusive },\n { value: filterValue, inclusive: filterInclusive }\n ) < 0\n ) {\n value = filterValue;\n inclusive = filterInclusive;\n }\n }\n\n // If there is an additional bound, compare the values against the existing\n // range to see if we can narrow the scope.\n if (bound !== null) {\n for (let i = 0; i < target.orderBy.length; ++i) {\n const orderBy = target.orderBy[i];\n if (orderBy.field.isEqual(fieldPath)) {\n const cursorValue = bound.position[i];\n if (\n lowerBoundCompare(\n { value, inclusive },\n { value: cursorValue, inclusive: bound.inclusive }\n ) < 0\n ) {\n value = cursorValue;\n inclusive = bound.inclusive;\n }\n break;\n }\n }\n }\n\n return { value, inclusive };\n}\n\n/**\n * Returns the value to use as the upper bound for ascending index segment at\n * the provided `fieldPath` (or the lower bound for a descending segment).\n */\nfunction targetGetDescendingBound(\n target: Target,\n fieldPath: FieldPath,\n bound: Bound | null\n): { value: ProtoValue; inclusive: boolean } {\n let value: ProtoValue = MAX_VALUE;\n let inclusive = true;\n\n // Process all filters to find a value for the current field segment\n for (const fieldFilter of targetGetFieldFiltersForPath(target, fieldPath)) {\n let filterValue: ProtoValue = MAX_VALUE;\n let filterInclusive = true;\n\n switch (fieldFilter.op) {\n case Operator.GREATER_THAN_OR_EQUAL:\n case Operator.GREATER_THAN:\n filterValue = valuesGetUpperBound(fieldFilter.value);\n filterInclusive = false;\n break;\n case Operator.EQUAL:\n case Operator.IN:\n case Operator.LESS_THAN_OR_EQUAL:\n filterValue = fieldFilter.value;\n break;\n case Operator.LESS_THAN:\n filterValue = fieldFilter.value;\n filterInclusive = false;\n break;\n case Operator.NOT_EQUAL:\n case Operator.NOT_IN:\n filterValue = MAX_VALUE;\n break;\n default:\n // Remaining filters cannot be used as upper bounds.\n }\n\n if (\n upperBoundCompare(\n { value, inclusive },\n { value: filterValue, inclusive: filterInclusive }\n ) > 0\n ) {\n value = filterValue;\n inclusive = filterInclusive;\n }\n }\n\n // If there is an additional bound, compare the values against the existing\n // range to see if we can narrow the scope.\n if (bound !== null) {\n for (let i = 0; i < target.orderBy.length; ++i) {\n const orderBy = target.orderBy[i];\n if (orderBy.field.isEqual(fieldPath)) {\n const cursorValue = bound.position[i];\n if (\n upperBoundCompare(\n { value, inclusive },\n { value: cursorValue, inclusive: bound.inclusive }\n ) > 0\n ) {\n value = cursorValue;\n inclusive = bound.inclusive;\n }\n break;\n }\n }\n }\n\n return { value, inclusive };\n}\n\n/** Returns the number of segments of a perfect index for this target. */\nexport function targetGetSegmentCount(target: Target): number {\n let fields = new SortedSet(FieldPath.comparator);\n let hasArraySegment = false;\n\n for (const filter of target.filters) {\n for (const subFilter of filter.getFlattenedFilters()) {\n // __name__ is not an explicit segment of any index, so we don't need to\n // count it.\n if (subFilter.field.isKeyField()) {\n continue;\n }\n\n // ARRAY_CONTAINS or ARRAY_CONTAINS_ANY filters must be counted separately.\n // For instance, it is possible to have an index for \"a ARRAY a ASC\". Even\n // though these are on the same field, they should be counted as two\n // separate segments in an index.\n if (\n subFilter.op === Operator.ARRAY_CONTAINS ||\n subFilter.op === Operator.ARRAY_CONTAINS_ANY\n ) {\n hasArraySegment = true;\n } else {\n fields = fields.add(subFilter.field);\n }\n }\n }\n\n for (const orderBy of target.orderBy) {\n // __name__ is not an explicit segment of any index, so we don't need to\n // count it.\n if (!orderBy.field.isKeyField()) {\n fields = fields.add(orderBy.field);\n }\n }\n\n return fields.size + (hasArraySegment ? 1 : 0);\n}\n\nexport function targetHasLimit(target: Target): boolean {\n return target.limit !== null;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { compareDocumentsByField, Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { FieldPath, ResourcePath } from '../model/path';\nimport { debugAssert, debugCast, fail } from '../util/assert';\nimport { SortedSet } from '../util/sorted_set';\n\nimport {\n Bound,\n boundSortsAfterDocument,\n boundSortsBeforeDocument\n} from './bound';\nimport { FieldFilter, Filter } from './filter';\nimport { Direction, OrderBy } from './order_by';\nimport {\n canonifyTarget,\n newTarget,\n stringifyTarget,\n Target,\n targetEquals\n} from './target';\n\nexport const enum LimitType {\n First = 'F',\n Last = 'L'\n}\n\n/**\n * The Query interface defines all external properties of a query.\n *\n * QueryImpl implements this interface to provide memoization for `queryNormalizedOrderBy`\n * and `queryToTarget`.\n */\nexport interface Query {\n readonly path: ResourcePath;\n readonly collectionGroup: string | null;\n readonly explicitOrderBy: OrderBy[];\n readonly filters: Filter[];\n readonly limit: number | null;\n readonly limitType: LimitType;\n readonly startAt: Bound | null;\n readonly endAt: Bound | null;\n}\n\n/**\n * Query encapsulates all the query attributes we support in the SDK. It can\n * be run against the LocalStore, as well as be converted to a `Target` to\n * query the RemoteStore results.\n *\n * Visible for testing.\n */\nexport class QueryImpl implements Query {\n memoizedNormalizedOrderBy: OrderBy[] | null = null;\n\n // The corresponding `Target` of this `Query` instance, for use with\n // non-aggregate queries.\n memoizedTarget: Target | null = null;\n\n // The corresponding `Target` of this `Query` instance, for use with\n // aggregate queries. Unlike targets for non-aggregate queries,\n // aggregate query targets do not contain normalized order-bys, they only\n // contain explicit order-bys.\n memoizedAggregateTarget: Target | null = null;\n\n /**\n * Initializes a Query with a path and optional additional query constraints.\n * Path must currently be empty if this is a collection group query.\n */\n constructor(\n readonly path: ResourcePath,\n readonly collectionGroup: string | null = null,\n readonly explicitOrderBy: OrderBy[] = [],\n readonly filters: Filter[] = [],\n readonly limit: number | null = null,\n readonly limitType: LimitType = LimitType.First,\n readonly startAt: Bound | null = null,\n readonly endAt: Bound | null = null\n ) {\n if (this.startAt) {\n debugAssert(\n this.startAt.position.length <= queryNormalizedOrderBy(this).length,\n 'Bound is longer than orderBy'\n );\n }\n if (this.endAt) {\n debugAssert(\n this.endAt.position.length <= queryNormalizedOrderBy(this).length,\n 'Bound is longer than orderBy'\n );\n }\n }\n}\n\n/** Creates a new Query instance with the options provided. */\nexport function newQuery(\n path: ResourcePath,\n collectionGroup: string | null,\n explicitOrderBy: OrderBy[],\n filters: Filter[],\n limit: number | null,\n limitType: LimitType,\n startAt: Bound | null,\n endAt: Bound | null\n): Query {\n return new QueryImpl(\n path,\n collectionGroup,\n explicitOrderBy,\n filters,\n limit,\n limitType,\n startAt,\n endAt\n );\n}\n\n/** Creates a new Query for a query that matches all documents at `path` */\nexport function newQueryForPath(path: ResourcePath): Query {\n return new QueryImpl(path);\n}\n\n/**\n * Helper to convert a collection group query into a collection query at a\n * specific path. This is used when executing collection group queries, since\n * we have to split the query into a set of collection queries at multiple\n * paths.\n */\nexport function asCollectionQueryAtPath(\n query: Query,\n path: ResourcePath\n): Query {\n return new QueryImpl(\n path,\n /*collectionGroup=*/ null,\n query.explicitOrderBy.slice(),\n query.filters.slice(),\n query.limit,\n query.limitType,\n query.startAt,\n query.endAt\n );\n}\n\n/**\n * Returns true if this query does not specify any query constraints that\n * could remove results.\n */\nexport function queryMatchesAllDocuments(query: Query): boolean {\n return (\n query.filters.length === 0 &&\n query.limit === null &&\n query.startAt == null &&\n query.endAt == null &&\n (query.explicitOrderBy.length === 0 ||\n (query.explicitOrderBy.length === 1 &&\n query.explicitOrderBy[0].field.isKeyField()))\n );\n}\n\n// Returns the sorted set of inequality filter fields used in this query.\nexport function getInequalityFilterFields(query: Query): SortedSet {\n let result = new SortedSet(FieldPath.comparator);\n query.filters.forEach((filter: Filter) => {\n const subFilters = filter.getFlattenedFilters();\n subFilters.forEach((filter: FieldFilter) => {\n if (filter.isInequality()) {\n result = result.add(filter.field);\n }\n });\n });\n return result;\n}\n\n/**\n * Creates a new Query for a collection group query that matches all documents\n * within the provided collection group.\n */\nexport function newQueryForCollectionGroup(collectionId: string): Query {\n return new QueryImpl(ResourcePath.emptyPath(), collectionId);\n}\n\n/**\n * Returns whether the query matches a single document by path (rather than a\n * collection).\n */\nexport function isDocumentQuery(query: Query): boolean {\n return (\n DocumentKey.isDocumentKey(query.path) &&\n query.collectionGroup === null &&\n query.filters.length === 0\n );\n}\n\n/**\n * Returns whether the query matches a collection group rather than a specific\n * collection.\n */\nexport function isCollectionGroupQuery(query: Query): boolean {\n return query.collectionGroup !== null;\n}\n\n/**\n * Returns the normalized order-by constraint that is used to execute the Query,\n * which can be different from the order-by constraints the user provided (e.g.\n * the SDK and backend always orders by `__name__`). The normalized order-by\n * includes implicit order-bys in addition to the explicit user provided\n * order-bys.\n */\nexport function queryNormalizedOrderBy(query: Query): OrderBy[] {\n const queryImpl = debugCast(query, QueryImpl);\n if (queryImpl.memoizedNormalizedOrderBy === null) {\n queryImpl.memoizedNormalizedOrderBy = [];\n const fieldsNormalized = new Set();\n\n // Any explicit order by fields should be added as is.\n for (const orderBy of queryImpl.explicitOrderBy) {\n queryImpl.memoizedNormalizedOrderBy.push(orderBy);\n fieldsNormalized.add(orderBy.field.canonicalString());\n }\n\n // The order of the implicit ordering always matches the last explicit order by.\n const lastDirection =\n queryImpl.explicitOrderBy.length > 0\n ? queryImpl.explicitOrderBy[queryImpl.explicitOrderBy.length - 1].dir\n : Direction.ASCENDING;\n\n // Any inequality fields not explicitly ordered should be implicitly ordered in a lexicographical\n // order. When there are multiple inequality filters on the same field, the field should be added\n // only once.\n // Note: `SortedSet` sorts the key field before other fields. However, we want the key\n // field to be sorted last.\n const inequalityFields: SortedSet =\n getInequalityFilterFields(queryImpl);\n inequalityFields.forEach(field => {\n if (\n !fieldsNormalized.has(field.canonicalString()) &&\n !field.isKeyField()\n ) {\n queryImpl.memoizedNormalizedOrderBy!.push(\n new OrderBy(field, lastDirection)\n );\n }\n });\n\n // Add the document key field to the last if it is not explicitly ordered.\n if (!fieldsNormalized.has(FieldPath.keyField().canonicalString())) {\n queryImpl.memoizedNormalizedOrderBy.push(\n new OrderBy(FieldPath.keyField(), lastDirection)\n );\n }\n }\n return queryImpl.memoizedNormalizedOrderBy;\n}\n\n/**\n * Converts this `Query` instance to its corresponding `Target` representation.\n */\nexport function queryToTarget(query: Query): Target {\n const queryImpl = debugCast(query, QueryImpl);\n if (!queryImpl.memoizedTarget) {\n queryImpl.memoizedTarget = _queryToTarget(\n queryImpl,\n queryNormalizedOrderBy(query)\n );\n }\n\n return queryImpl.memoizedTarget;\n}\n\n/**\n * Converts this `Query` instance to its corresponding `Target` representation,\n * for use within an aggregate query. Unlike targets for non-aggregate queries,\n * aggregate query targets do not contain normalized order-bys, they only\n * contain explicit order-bys.\n */\nexport function queryToAggregateTarget(query: Query): Target {\n const queryImpl = debugCast(query, QueryImpl);\n\n if (!queryImpl.memoizedAggregateTarget) {\n // Do not include implicit order-bys for aggregate queries.\n queryImpl.memoizedAggregateTarget = _queryToTarget(\n queryImpl,\n query.explicitOrderBy\n );\n }\n\n return queryImpl.memoizedAggregateTarget;\n}\n\nfunction _queryToTarget(queryImpl: QueryImpl, orderBys: OrderBy[]): Target {\n if (queryImpl.limitType === LimitType.First) {\n return newTarget(\n queryImpl.path,\n queryImpl.collectionGroup,\n orderBys,\n queryImpl.filters,\n queryImpl.limit,\n queryImpl.startAt,\n queryImpl.endAt\n );\n } else {\n // Flip the orderBy directions since we want the last results\n orderBys = orderBys.map(orderBy => {\n const dir =\n orderBy.dir === Direction.DESCENDING\n ? Direction.ASCENDING\n : Direction.DESCENDING;\n return new OrderBy(orderBy.field, dir);\n });\n\n // We need to swap the cursors to match the now-flipped query ordering.\n const startAt = queryImpl.endAt\n ? new Bound(queryImpl.endAt.position, queryImpl.endAt.inclusive)\n : null;\n const endAt = queryImpl.startAt\n ? new Bound(queryImpl.startAt.position, queryImpl.startAt.inclusive)\n : null;\n\n // Now return as a LimitType.First query.\n return newTarget(\n queryImpl.path,\n queryImpl.collectionGroup,\n orderBys,\n queryImpl.filters,\n queryImpl.limit,\n startAt,\n endAt\n );\n }\n}\n\nexport function queryWithAddedFilter(query: Query, filter: Filter): Query {\n debugAssert(\n !isDocumentQuery(query),\n 'No filtering allowed for document query'\n );\n\n const newFilters = query.filters.concat([filter]);\n return new QueryImpl(\n query.path,\n query.collectionGroup,\n query.explicitOrderBy.slice(),\n newFilters,\n query.limit,\n query.limitType,\n query.startAt,\n query.endAt\n );\n}\n\nexport function queryWithAddedOrderBy(query: Query, orderBy: OrderBy): Query {\n debugAssert(\n !query.startAt && !query.endAt,\n 'Bounds must be set after orderBy'\n );\n // TODO(dimond): validate that orderBy does not list the same key twice.\n const newOrderBy = query.explicitOrderBy.concat([orderBy]);\n return new QueryImpl(\n query.path,\n query.collectionGroup,\n newOrderBy,\n query.filters.slice(),\n query.limit,\n query.limitType,\n query.startAt,\n query.endAt\n );\n}\n\nexport function queryWithLimit(\n query: Query,\n limit: number | null,\n limitType: LimitType\n): Query {\n return new QueryImpl(\n query.path,\n query.collectionGroup,\n query.explicitOrderBy.slice(),\n query.filters.slice(),\n limit,\n limitType,\n query.startAt,\n query.endAt\n );\n}\n\nexport function queryWithStartAt(query: Query, bound: Bound): Query {\n return new QueryImpl(\n query.path,\n query.collectionGroup,\n query.explicitOrderBy.slice(),\n query.filters.slice(),\n query.limit,\n query.limitType,\n bound,\n query.endAt\n );\n}\n\nexport function queryWithEndAt(query: Query, bound: Bound): Query {\n return new QueryImpl(\n query.path,\n query.collectionGroup,\n query.explicitOrderBy.slice(),\n query.filters.slice(),\n query.limit,\n query.limitType,\n query.startAt,\n bound\n );\n}\n\nexport function queryEquals(left: Query, right: Query): boolean {\n return (\n targetEquals(queryToTarget(left), queryToTarget(right)) &&\n left.limitType === right.limitType\n );\n}\n\n// TODO(b/29183165): This is used to get a unique string from a query to, for\n// example, use as a dictionary key, but the implementation is subject to\n// collisions. Make it collision-free.\nexport function canonifyQuery(query: Query): string {\n return `${canonifyTarget(queryToTarget(query))}|lt:${query.limitType}`;\n}\n\nexport function stringifyQuery(query: Query): string {\n return `Query(target=${stringifyTarget(queryToTarget(query))}; limitType=${\n query.limitType\n })`;\n}\n\n/** Returns whether `doc` matches the constraints of `query`. */\nexport function queryMatches(query: Query, doc: Document): boolean {\n return (\n doc.isFoundDocument() &&\n queryMatchesPathAndCollectionGroup(query, doc) &&\n queryMatchesOrderBy(query, doc) &&\n queryMatchesFilters(query, doc) &&\n queryMatchesBounds(query, doc)\n );\n}\n\nfunction queryMatchesPathAndCollectionGroup(\n query: Query,\n doc: Document\n): boolean {\n const docPath = doc.key.path;\n if (query.collectionGroup !== null) {\n // NOTE: this.path is currently always empty since we don't expose Collection\n // Group queries rooted at a document path yet.\n return (\n doc.key.hasCollectionId(query.collectionGroup) &&\n query.path.isPrefixOf(docPath)\n );\n } else if (DocumentKey.isDocumentKey(query.path)) {\n // exact match for document queries\n return query.path.isEqual(docPath);\n } else {\n // shallow ancestor queries by default\n return query.path.isImmediateParentOf(docPath);\n }\n}\n\n/**\n * A document must have a value for every ordering clause in order to show up\n * in the results.\n */\nfunction queryMatchesOrderBy(query: Query, doc: Document): boolean {\n // We must use `queryNormalizedOrderBy()` to get the list of all orderBys (both implicit and explicit).\n // Note that for OR queries, orderBy applies to all disjunction terms and implicit orderBys must\n // be taken into account. For example, the query \"a > 1 || b==1\" has an implicit \"orderBy a\" due\n // to the inequality, and is evaluated as \"a > 1 orderBy a || b==1 orderBy a\".\n // A document with content of {b:1} matches the filters, but does not match the orderBy because\n // it's missing the field 'a'.\n for (const orderBy of queryNormalizedOrderBy(query)) {\n // order-by key always matches\n if (!orderBy.field.isKeyField() && doc.data.field(orderBy.field) === null) {\n return false;\n }\n }\n return true;\n}\n\nfunction queryMatchesFilters(query: Query, doc: Document): boolean {\n for (const filter of query.filters) {\n if (!filter.matches(doc)) {\n return false;\n }\n }\n return true;\n}\n\n/** Makes sure a document is within the bounds, if provided. */\nfunction queryMatchesBounds(query: Query, doc: Document): boolean {\n if (\n query.startAt &&\n !boundSortsBeforeDocument(query.startAt, queryNormalizedOrderBy(query), doc)\n ) {\n return false;\n }\n if (\n query.endAt &&\n !boundSortsAfterDocument(query.endAt, queryNormalizedOrderBy(query), doc)\n ) {\n return false;\n }\n return true;\n}\n\n/**\n * Returns the collection group that this query targets.\n *\n * PORTING NOTE: This is only used in the Web SDK to facilitate multi-tab\n * synchronization for query results.\n */\nexport function queryCollectionGroup(query: Query): string {\n return (\n query.collectionGroup ||\n (query.path.length % 2 === 1\n ? query.path.lastSegment()\n : query.path.get(query.path.length - 2))\n );\n}\n\n/**\n * Returns a new comparator function that can be used to compare two documents\n * based on the Query's ordering constraint.\n */\nexport function newQueryComparator(\n query: Query\n): (d1: Document, d2: Document) => number {\n return (d1: Document, d2: Document): number => {\n let comparedOnKeyField = false;\n for (const orderBy of queryNormalizedOrderBy(query)) {\n const comp = compareDocs(orderBy, d1, d2);\n if (comp !== 0) {\n return comp;\n }\n comparedOnKeyField = comparedOnKeyField || orderBy.field.isKeyField();\n }\n // Assert that we actually compared by key\n debugAssert(\n comparedOnKeyField,\n \"orderBy used that doesn't compare on key field\"\n );\n return 0;\n };\n}\n\nexport function compareDocs(\n orderBy: OrderBy,\n d1: Document,\n d2: Document\n): number {\n const comparison = orderBy.field.isKeyField()\n ? DocumentKey.comparator(d1.key, d2.key)\n : compareDocumentsByField(orderBy.field, d1, d2);\n switch (orderBy.dir) {\n case Direction.ASCENDING:\n return comparison;\n case Direction.DESCENDING:\n return -1 * comparison;\n default:\n return fail(0x4d4e, 'Unknown direction', { direction: orderBy.dir });\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Value as ProtoValue } from '../protos/firestore_proto_api';\nimport { isNegativeZero, isSafeInteger } from '../util/types';\n\n/** Base interface for the Serializer implementation. */\nexport interface Serializer {\n readonly useProto3Json: boolean;\n}\n\n/**\n * Returns an DoubleValue for `value` that is encoded based the serializer's\n * `useProto3Json` setting.\n */\nexport function toDouble(serializer: Serializer, value: number): ProtoValue {\n if (serializer.useProto3Json) {\n if (isNaN(value)) {\n return { doubleValue: 'NaN' };\n } else if (value === Infinity) {\n return { doubleValue: 'Infinity' };\n } else if (value === -Infinity) {\n return { doubleValue: '-Infinity' };\n }\n }\n return { doubleValue: isNegativeZero(value) ? '-0' : value };\n}\n\n/**\n * Returns an IntegerValue for `value`.\n */\nexport function toInteger(value: number): ProtoValue {\n return { integerValue: '' + value };\n}\n\n/**\n * Returns a value for a number that's appropriate to put into a proto.\n * The return value is an IntegerValue if it can safely represent the value,\n * otherwise a DoubleValue is returned.\n */\nexport function toNumber(serializer: Serializer, value: number): ProtoValue {\n return isSafeInteger(value) ? toInteger(value) : toDouble(serializer, value);\n}\n","/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Timestamp } from '../lite-api/timestamp';\nimport { Value as ProtoValue } from '../protos/firestore_proto_api';\nimport { Serializer, toDouble, toInteger } from '../remote/number_serializer';\nimport { debugAssert } from '../util/assert';\nimport { arrayEquals } from '../util/misc';\n\nimport { normalizeNumber } from './normalize';\nimport { serverTimestamp } from './server_timestamps';\nimport { isArray, isInteger, isNumber, valueEquals } from './values';\n\n/** Used to represent a field transform on a mutation. */\nexport class TransformOperation {\n // Make sure that the structural type of `TransformOperation` is unique.\n // See https://github.com/microsoft/TypeScript/issues/5451\n private _ = undefined;\n}\n\n/**\n * Computes the local transform result against the provided `previousValue`,\n * optionally using the provided localWriteTime.\n */\nexport function applyTransformOperationToLocalView(\n transform: TransformOperation,\n previousValue: ProtoValue | null,\n localWriteTime: Timestamp\n): ProtoValue {\n if (transform instanceof ServerTimestampTransform) {\n return serverTimestamp(localWriteTime, previousValue);\n } else if (transform instanceof ArrayUnionTransformOperation) {\n return applyArrayUnionTransformOperation(transform, previousValue);\n } else if (transform instanceof ArrayRemoveTransformOperation) {\n return applyArrayRemoveTransformOperation(transform, previousValue);\n } else {\n debugAssert(\n transform instanceof NumericIncrementTransformOperation,\n 'Expected NumericIncrementTransformOperation but was: ' + transform\n );\n return applyNumericIncrementTransformOperationToLocalView(\n transform,\n previousValue\n );\n }\n}\n\n/**\n * Computes a final transform result after the transform has been acknowledged\n * by the server, potentially using the server-provided transformResult.\n */\nexport function applyTransformOperationToRemoteDocument(\n transform: TransformOperation,\n previousValue: ProtoValue | null,\n transformResult: ProtoValue | null\n): ProtoValue {\n // The server just sends null as the transform result for array operations,\n // so we have to calculate a result the same as we do for local\n // applications.\n if (transform instanceof ArrayUnionTransformOperation) {\n return applyArrayUnionTransformOperation(transform, previousValue);\n } else if (transform instanceof ArrayRemoveTransformOperation) {\n return applyArrayRemoveTransformOperation(transform, previousValue);\n }\n\n debugAssert(\n transformResult !== null,\n \"Didn't receive transformResult for non-array transform\"\n );\n return transformResult;\n}\n\n/**\n * If this transform operation is not idempotent, returns the base value to\n * persist for this transform. If a base value is returned, the transform\n * operation is always applied to this base value, even if document has\n * already been updated.\n *\n * Base values provide consistent behavior for non-idempotent transforms and\n * allow us to return the same latency-compensated value even if the backend\n * has already applied the transform operation. The base value is null for\n * idempotent transforms, as they can be re-played even if the backend has\n * already applied them.\n *\n * @returns a base value to store along with the mutation, or null for\n * idempotent transforms.\n */\nexport function computeTransformOperationBaseValue(\n transform: TransformOperation,\n previousValue: ProtoValue | null\n): ProtoValue | null {\n if (transform instanceof NumericIncrementTransformOperation) {\n return isNumber(previousValue) ? previousValue! : { integerValue: 0 };\n }\n return null;\n}\n\nexport function transformOperationEquals(\n left: TransformOperation,\n right: TransformOperation\n): boolean {\n if (\n left instanceof ArrayUnionTransformOperation &&\n right instanceof ArrayUnionTransformOperation\n ) {\n return arrayEquals(left.elements, right.elements, valueEquals);\n } else if (\n left instanceof ArrayRemoveTransformOperation &&\n right instanceof ArrayRemoveTransformOperation\n ) {\n return arrayEquals(left.elements, right.elements, valueEquals);\n } else if (\n left instanceof NumericIncrementTransformOperation &&\n right instanceof NumericIncrementTransformOperation\n ) {\n return valueEquals(left.operand, right.operand);\n }\n\n return (\n left instanceof ServerTimestampTransform &&\n right instanceof ServerTimestampTransform\n );\n}\n\n/** Transforms a value into a server-generated timestamp. */\nexport class ServerTimestampTransform extends TransformOperation {}\n\n/** Transforms an array value via a union operation. */\nexport class ArrayUnionTransformOperation extends TransformOperation {\n constructor(readonly elements: ProtoValue[]) {\n super();\n }\n}\n\nfunction applyArrayUnionTransformOperation(\n transform: ArrayUnionTransformOperation,\n previousValue: ProtoValue | null\n): ProtoValue {\n const values = coercedFieldValuesArray(previousValue);\n for (const toUnion of transform.elements) {\n if (!values.some(element => valueEquals(element, toUnion))) {\n values.push(toUnion);\n }\n }\n return { arrayValue: { values } };\n}\n\n/** Transforms an array value via a remove operation. */\nexport class ArrayRemoveTransformOperation extends TransformOperation {\n constructor(readonly elements: ProtoValue[]) {\n super();\n }\n}\n\nfunction applyArrayRemoveTransformOperation(\n transform: ArrayRemoveTransformOperation,\n previousValue: ProtoValue | null\n): ProtoValue {\n let values = coercedFieldValuesArray(previousValue);\n for (const toRemove of transform.elements) {\n values = values.filter(element => !valueEquals(element, toRemove));\n }\n return { arrayValue: { values } };\n}\n\n/**\n * Implements the backend semantics for locally computed NUMERIC_ADD (increment)\n * transforms. Converts all field values to integers or doubles, but unlike the\n * backend does not cap integer values at 2^63. Instead, JavaScript number\n * arithmetic is used and precision loss can occur for values greater than 2^53.\n */\nexport class NumericIncrementTransformOperation extends TransformOperation {\n constructor(readonly serializer: Serializer, readonly operand: ProtoValue) {\n super();\n debugAssert(\n isNumber(operand),\n 'NumericIncrementTransform transform requires a NumberValue'\n );\n }\n}\n\nexport function applyNumericIncrementTransformOperationToLocalView(\n transform: NumericIncrementTransformOperation,\n previousValue: ProtoValue | null\n): ProtoValue {\n // PORTING NOTE: Since JavaScript's integer arithmetic is limited to 53 bit\n // precision and resolves overflows by reducing precision, we do not\n // manually cap overflows at 2^63.\n const baseValue = computeTransformOperationBaseValue(\n transform,\n previousValue\n )!;\n const sum = asNumber(baseValue) + asNumber(transform.operand);\n if (isInteger(baseValue) && isInteger(transform.operand)) {\n return toInteger(sum);\n } else {\n return toDouble(transform.serializer, sum);\n }\n}\n\nfunction asNumber(value: ProtoValue): number {\n return normalizeNumber(value.integerValue || value.doubleValue);\n}\n\nfunction coercedFieldValuesArray(value: ProtoValue | null): ProtoValue[] {\n return isArray(value) && value.arrayValue.values\n ? value.arrayValue.values.slice()\n : [];\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { Timestamp } from '../lite-api/timestamp';\nimport { Value as ProtoValue } from '../protos/firestore_proto_api';\nimport { debugAssert, hardAssert } from '../util/assert';\nimport { arrayEquals } from '../util/misc';\nimport { SortedSet } from '../util/sorted_set';\n\nimport { Document, MutableDocument } from './document';\nimport { DocumentKey } from './document_key';\nimport { FieldMask } from './field_mask';\nimport { ObjectValue } from './object_value';\nimport { FieldPath } from './path';\nimport {\n applyTransformOperationToLocalView,\n applyTransformOperationToRemoteDocument,\n computeTransformOperationBaseValue,\n TransformOperation,\n transformOperationEquals\n} from './transform_operation';\n\n/** A field path and the TransformOperation to perform upon it. */\nexport class FieldTransform {\n constructor(\n readonly field: FieldPath,\n readonly transform: TransformOperation\n ) {}\n}\n\nexport function fieldTransformEquals(\n left: FieldTransform,\n right: FieldTransform\n): boolean {\n return (\n left.field.isEqual(right.field) &&\n transformOperationEquals(left.transform, right.transform)\n );\n}\n\nexport function fieldTransformsAreEqual(\n left?: FieldTransform[],\n right?: FieldTransform[]\n): boolean {\n if (left === undefined && right === undefined) {\n return true;\n }\n\n if (left && right) {\n return arrayEquals(left, right, (l, r) => fieldTransformEquals(l, r));\n }\n\n return false;\n}\n\n/** The result of successfully applying a mutation to the backend. */\nexport class MutationResult {\n constructor(\n /**\n * The version at which the mutation was committed:\n *\n * - For most operations, this is the updateTime in the WriteResult.\n * - For deletes, the commitTime of the WriteResponse (because deletes are\n * not stored and have no updateTime).\n *\n * Note that these versions can be different: No-op writes will not change\n * the updateTime even though the commitTime advances.\n */\n readonly version: SnapshotVersion,\n /**\n * The resulting fields returned from the backend after a mutation\n * containing field transforms has been committed. Contains one FieldValue\n * for each FieldTransform that was in the mutation.\n *\n * Will be empty if the mutation did not contain any field transforms.\n */\n readonly transformResults: Array\n ) {}\n}\n\nexport const enum MutationType {\n Set,\n Patch,\n Delete,\n Verify\n}\n\n/**\n * Encodes a precondition for a mutation. This follows the model that the\n * backend accepts with the special case of an explicit \"empty\" precondition\n * (meaning no precondition).\n */\nexport class Precondition {\n private constructor(\n readonly updateTime?: SnapshotVersion,\n readonly exists?: boolean\n ) {\n debugAssert(\n updateTime === undefined || exists === undefined,\n 'Precondition can specify \"exists\" or \"updateTime\" but not both'\n );\n }\n\n /** Creates a new empty Precondition. */\n static none(): Precondition {\n return new Precondition();\n }\n\n /** Creates a new Precondition with an exists flag. */\n static exists(exists: boolean): Precondition {\n return new Precondition(undefined, exists);\n }\n\n /** Creates a new Precondition based on a version a document exists at. */\n static updateTime(version: SnapshotVersion): Precondition {\n return new Precondition(version);\n }\n\n /** Returns whether this Precondition is empty. */\n get isNone(): boolean {\n return this.updateTime === undefined && this.exists === undefined;\n }\n\n isEqual(other: Precondition): boolean {\n return (\n this.exists === other.exists &&\n (this.updateTime\n ? !!other.updateTime && this.updateTime.isEqual(other.updateTime)\n : !other.updateTime)\n );\n }\n}\n\n/** Returns true if the preconditions is valid for the given document. */\nexport function preconditionIsValidForDocument(\n precondition: Precondition,\n document: MutableDocument\n): boolean {\n if (precondition.updateTime !== undefined) {\n return (\n document.isFoundDocument() &&\n document.version.isEqual(precondition.updateTime)\n );\n } else if (precondition.exists !== undefined) {\n return precondition.exists === document.isFoundDocument();\n } else {\n debugAssert(precondition.isNone, 'Precondition should be empty');\n return true;\n }\n}\n\n/**\n * A mutation describes a self-contained change to a document. Mutations can\n * create, replace, delete, and update subsets of documents.\n *\n * Mutations not only act on the value of the document but also its version.\n *\n * For local mutations (mutations that haven't been committed yet), we preserve\n * the existing version for Set and Patch mutations. For Delete mutations, we\n * reset the version to 0.\n *\n * Here's the expected transition table.\n *\n * MUTATION APPLIED TO RESULTS IN\n *\n * SetMutation Document(v3) Document(v3)\n * SetMutation NoDocument(v3) Document(v0)\n * SetMutation InvalidDocument(v0) Document(v0)\n * PatchMutation Document(v3) Document(v3)\n * PatchMutation NoDocument(v3) NoDocument(v3)\n * PatchMutation InvalidDocument(v0) UnknownDocument(v3)\n * DeleteMutation Document(v3) NoDocument(v0)\n * DeleteMutation NoDocument(v3) NoDocument(v0)\n * DeleteMutation InvalidDocument(v0) NoDocument(v0)\n *\n * For acknowledged mutations, we use the updateTime of the WriteResponse as\n * the resulting version for Set and Patch mutations. As deletes have no\n * explicit update time, we use the commitTime of the WriteResponse for\n * Delete mutations.\n *\n * If a mutation is acknowledged by the backend but fails the precondition check\n * locally, we transition to an `UnknownDocument` and rely on Watch to send us\n * the updated version.\n *\n * Field transforms are used only with Patch and Set Mutations. We use the\n * `updateTransforms` message to store transforms, rather than the `transforms`s\n * messages.\n *\n * ## Subclassing Notes\n *\n * Every type of mutation needs to implement its own applyToRemoteDocument() and\n * applyToLocalView() to implement the actual behavior of applying the mutation\n * to some source document (see `setMutationApplyToRemoteDocument()` for an\n * example).\n */\nexport abstract class Mutation {\n abstract readonly type: MutationType;\n abstract readonly key: DocumentKey;\n abstract readonly precondition: Precondition;\n abstract readonly fieldTransforms: FieldTransform[];\n /**\n * Returns a `FieldMask` representing the fields that will be changed by\n * applying this mutation. Returns `null` if the mutation will overwrite the\n * entire document.\n */\n abstract getFieldMask(): FieldMask | null;\n}\n\n/**\n * A utility method to calculate a `Mutation` representing the overlay from the\n * final state of the document, and a `FieldMask` representing the fields that\n * are mutated by the local mutations.\n */\nexport function calculateOverlayMutation(\n doc: MutableDocument,\n mask: FieldMask | null\n): Mutation | null {\n if (!doc.hasLocalMutations || (mask && mask!.fields.length === 0)) {\n return null;\n }\n\n // mask is null when sets or deletes are applied to the current document.\n if (mask === null) {\n if (doc.isNoDocument()) {\n return new DeleteMutation(doc.key, Precondition.none());\n } else {\n return new SetMutation(doc.key, doc.data, Precondition.none());\n }\n } else {\n const docValue = doc.data;\n const patchValue = ObjectValue.empty();\n let maskSet = new SortedSet(FieldPath.comparator);\n for (let path of mask.fields) {\n if (!maskSet.has(path)) {\n let value = docValue.field(path);\n // If we are deleting a nested field, we take the immediate parent as\n // the mask used to construct the resulting mutation.\n // Justification: Nested fields can create parent fields implicitly. If\n // only a leaf entry is deleted in later mutations, the parent field\n // should still remain, but we may have lost this information.\n // Consider mutation (foo.bar 1), then mutation (foo.bar delete()).\n // This leaves the final result (foo, {}). Despite the fact that `doc`\n // has the correct result, `foo` is not in `mask`, and the resulting\n // mutation would miss `foo`.\n if (value === null && path.length > 1) {\n path = path.popLast();\n value = docValue.field(path);\n }\n if (value === null) {\n patchValue.delete(path);\n } else {\n patchValue.set(path, value);\n }\n maskSet = maskSet.add(path);\n }\n }\n return new PatchMutation(\n doc.key,\n patchValue,\n new FieldMask(maskSet.toArray()),\n Precondition.none()\n );\n }\n}\n\n/**\n * Applies this mutation to the given document for the purposes of computing a\n * new remote document. If the input document doesn't match the expected state\n * (e.g. it is invalid or outdated), the document type may transition to\n * unknown.\n *\n * @param mutation - The mutation to apply.\n * @param document - The document to mutate. The input document can be an\n * invalid document if the client has no knowledge of the pre-mutation state\n * of the document.\n * @param mutationResult - The result of applying the mutation from the backend.\n */\nexport function mutationApplyToRemoteDocument(\n mutation: Mutation,\n document: MutableDocument,\n mutationResult: MutationResult\n): void {\n mutationVerifyKeyMatches(mutation, document);\n if (mutation instanceof SetMutation) {\n setMutationApplyToRemoteDocument(mutation, document, mutationResult);\n } else if (mutation instanceof PatchMutation) {\n patchMutationApplyToRemoteDocument(mutation, document, mutationResult);\n } else {\n debugAssert(\n mutation instanceof DeleteMutation,\n 'Unexpected mutation type: ' + mutation\n );\n deleteMutationApplyToRemoteDocument(mutation, document, mutationResult);\n }\n}\n\n/**\n * Applies this mutation to the given document for the purposes of computing\n * the new local view of a document. If the input document doesn't match the\n * expected state, the document is not modified.\n *\n * @param mutation - The mutation to apply.\n * @param document - The document to mutate. The input document can be an\n * invalid document if the client has no knowledge of the pre-mutation state\n * of the document.\n * @param previousMask - The fields that have been updated before applying this mutation.\n * @param localWriteTime - A timestamp indicating the local write time of the\n * batch this mutation is a part of.\n * @returns A `FieldMask` representing the fields that are changed by applying this mutation.\n */\nexport function mutationApplyToLocalView(\n mutation: Mutation,\n document: MutableDocument,\n previousMask: FieldMask | null,\n localWriteTime: Timestamp\n): FieldMask | null {\n mutationVerifyKeyMatches(mutation, document);\n\n if (mutation instanceof SetMutation) {\n return setMutationApplyToLocalView(\n mutation,\n document,\n previousMask,\n localWriteTime\n );\n } else if (mutation instanceof PatchMutation) {\n return patchMutationApplyToLocalView(\n mutation,\n document,\n previousMask,\n localWriteTime\n );\n } else {\n debugAssert(\n mutation instanceof DeleteMutation,\n 'Unexpected mutation type: ' + mutation\n );\n return deleteMutationApplyToLocalView(mutation, document, previousMask);\n }\n}\n\n/**\n * If this mutation is not idempotent, returns the base value to persist with\n * this mutation. If a base value is returned, the mutation is always applied\n * to this base value, even if document has already been updated.\n *\n * The base value is a sparse object that consists of only the document\n * fields for which this mutation contains a non-idempotent transformation\n * (e.g. a numeric increment). The provided value guarantees consistent\n * behavior for non-idempotent transforms and allow us to return the same\n * latency-compensated value even if the backend has already applied the\n * mutation. The base value is null for idempotent mutations, as they can be\n * re-played even if the backend has already applied them.\n *\n * @returns a base value to store along with the mutation, or null for\n * idempotent mutations.\n */\nexport function mutationExtractBaseValue(\n mutation: Mutation,\n document: Document\n): ObjectValue | null {\n let baseObject: ObjectValue | null = null;\n for (const fieldTransform of mutation.fieldTransforms) {\n const existingValue = document.data.field(fieldTransform.field);\n const coercedValue = computeTransformOperationBaseValue(\n fieldTransform.transform,\n existingValue || null\n );\n\n if (coercedValue != null) {\n if (baseObject === null) {\n baseObject = ObjectValue.empty();\n }\n baseObject.set(fieldTransform.field, coercedValue);\n }\n }\n return baseObject ? baseObject : null;\n}\n\nexport function mutationEquals(left: Mutation, right: Mutation): boolean {\n if (left.type !== right.type) {\n return false;\n }\n\n if (!left.key.isEqual(right.key)) {\n return false;\n }\n\n if (!left.precondition.isEqual(right.precondition)) {\n return false;\n }\n\n if (!fieldTransformsAreEqual(left.fieldTransforms, right.fieldTransforms)) {\n return false;\n }\n\n if (left.type === MutationType.Set) {\n return (left as SetMutation).value.isEqual((right as SetMutation).value);\n }\n\n if (left.type === MutationType.Patch) {\n return (\n (left as PatchMutation).data.isEqual((right as PatchMutation).data) &&\n (left as PatchMutation).fieldMask.isEqual(\n (right as PatchMutation).fieldMask\n )\n );\n }\n\n return true;\n}\n\nfunction mutationVerifyKeyMatches(\n mutation: Mutation,\n document: MutableDocument\n): void {\n debugAssert(\n document.key.isEqual(mutation.key),\n 'Can only apply a mutation to a document with the same key'\n );\n}\n\n/**\n * A mutation that creates or replaces the document at the given key with the\n * object value contents.\n */\nexport class SetMutation extends Mutation {\n constructor(\n readonly key: DocumentKey,\n readonly value: ObjectValue,\n readonly precondition: Precondition,\n readonly fieldTransforms: FieldTransform[] = []\n ) {\n super();\n }\n\n readonly type: MutationType = MutationType.Set;\n\n getFieldMask(): FieldMask | null {\n return null;\n }\n}\n\nfunction setMutationApplyToRemoteDocument(\n mutation: SetMutation,\n document: MutableDocument,\n mutationResult: MutationResult\n): void {\n // Unlike setMutationApplyToLocalView, if we're applying a mutation to a\n // remote document the server has accepted the mutation so the precondition\n // must have held.\n const newData = mutation.value.clone();\n const transformResults = serverTransformResults(\n mutation.fieldTransforms,\n document,\n mutationResult.transformResults\n );\n newData.setAll(transformResults);\n document\n .convertToFoundDocument(mutationResult.version, newData)\n .setHasCommittedMutations();\n}\n\nfunction setMutationApplyToLocalView(\n mutation: SetMutation,\n document: MutableDocument,\n previousMask: FieldMask | null,\n localWriteTime: Timestamp\n): FieldMask | null {\n if (!preconditionIsValidForDocument(mutation.precondition, document)) {\n // The mutation failed to apply (e.g. a document ID created with add()\n // caused a name collision).\n return previousMask;\n }\n\n const newData = mutation.value.clone();\n const transformResults = localTransformResults(\n mutation.fieldTransforms,\n localWriteTime,\n document\n );\n newData.setAll(transformResults);\n document\n .convertToFoundDocument(document.version, newData)\n .setHasLocalMutations();\n return null; // SetMutation overwrites all fields.\n}\n\n/**\n * A mutation that modifies fields of the document at the given key with the\n * given values. The values are applied through a field mask:\n *\n * * When a field is in both the mask and the values, the corresponding field\n * is updated.\n * * When a field is in neither the mask nor the values, the corresponding\n * field is unmodified.\n * * When a field is in the mask but not in the values, the corresponding field\n * is deleted.\n * * When a field is not in the mask but is in the values, the values map is\n * ignored.\n */\nexport class PatchMutation extends Mutation {\n constructor(\n readonly key: DocumentKey,\n readonly data: ObjectValue,\n readonly fieldMask: FieldMask,\n readonly precondition: Precondition,\n readonly fieldTransforms: FieldTransform[] = []\n ) {\n super();\n }\n\n readonly type: MutationType = MutationType.Patch;\n\n getFieldMask(): FieldMask | null {\n return this.fieldMask;\n }\n}\n\nfunction patchMutationApplyToRemoteDocument(\n mutation: PatchMutation,\n document: MutableDocument,\n mutationResult: MutationResult\n): void {\n if (!preconditionIsValidForDocument(mutation.precondition, document)) {\n // Since the mutation was not rejected, we know that the precondition\n // matched on the backend. We therefore must not have the expected version\n // of the document in our cache and convert to an UnknownDocument with a\n // known updateTime.\n document.convertToUnknownDocument(mutationResult.version);\n return;\n }\n\n const transformResults = serverTransformResults(\n mutation.fieldTransforms,\n document,\n mutationResult.transformResults\n );\n const newData = document.data;\n newData.setAll(getPatch(mutation));\n newData.setAll(transformResults);\n document\n .convertToFoundDocument(mutationResult.version, newData)\n .setHasCommittedMutations();\n}\n\nfunction patchMutationApplyToLocalView(\n mutation: PatchMutation,\n document: MutableDocument,\n previousMask: FieldMask | null,\n localWriteTime: Timestamp\n): FieldMask | null {\n if (!preconditionIsValidForDocument(mutation.precondition, document)) {\n return previousMask;\n }\n\n const transformResults = localTransformResults(\n mutation.fieldTransforms,\n localWriteTime,\n document\n );\n const newData = document.data;\n newData.setAll(getPatch(mutation));\n newData.setAll(transformResults);\n document\n .convertToFoundDocument(document.version, newData)\n .setHasLocalMutations();\n\n if (previousMask === null) {\n return null;\n }\n\n return previousMask\n .unionWith(mutation.fieldMask.fields)\n .unionWith(mutation.fieldTransforms.map(transform => transform.field));\n}\n\n/**\n * Returns a FieldPath/Value map with the content of the PatchMutation.\n */\nfunction getPatch(mutation: PatchMutation): Map {\n const result = new Map();\n mutation.fieldMask.fields.forEach(fieldPath => {\n if (!fieldPath.isEmpty()) {\n const newValue = mutation.data.field(fieldPath);\n result.set(fieldPath, newValue);\n }\n });\n return result;\n}\n\n/**\n * Creates a list of \"transform results\" (a transform result is a field value\n * representing the result of applying a transform) for use after a mutation\n * containing transforms has been acknowledged by the server.\n *\n * @param fieldTransforms - The field transforms to apply the result to.\n * @param mutableDocument - The current state of the document after applying all\n * previous mutations.\n * @param serverTransformResults - The transform results received by the server.\n * @returns The transform results list.\n */\nfunction serverTransformResults(\n fieldTransforms: FieldTransform[],\n mutableDocument: MutableDocument,\n serverTransformResults: Array\n): Map {\n const transformResults = new Map();\n hardAssert(\n fieldTransforms.length === serverTransformResults.length,\n 0x7f90,\n 'server transform result count should match field transform count',\n {\n serverTransformResultCount: serverTransformResults.length,\n fieldTransformCount: fieldTransforms.length\n }\n );\n\n for (let i = 0; i < serverTransformResults.length; i++) {\n const fieldTransform = fieldTransforms[i];\n const transform = fieldTransform.transform;\n const previousValue = mutableDocument.data.field(fieldTransform.field);\n transformResults.set(\n fieldTransform.field,\n applyTransformOperationToRemoteDocument(\n transform,\n previousValue,\n serverTransformResults[i]\n )\n );\n }\n return transformResults;\n}\n\n/**\n * Creates a list of \"transform results\" (a transform result is a field value\n * representing the result of applying a transform) for use when applying a\n * transform locally.\n *\n * @param fieldTransforms - The field transforms to apply the result to.\n * @param localWriteTime - The local time of the mutation (used to\n * generate ServerTimestampValues).\n * @param mutableDocument - The document to apply transforms on.\n * @returns The transform results list.\n */\nfunction localTransformResults(\n fieldTransforms: FieldTransform[],\n localWriteTime: Timestamp,\n mutableDocument: MutableDocument\n): Map {\n const transformResults = new Map();\n for (const fieldTransform of fieldTransforms) {\n const transform = fieldTransform.transform;\n\n const previousValue = mutableDocument.data.field(fieldTransform.field);\n transformResults.set(\n fieldTransform.field,\n applyTransformOperationToLocalView(\n transform,\n previousValue,\n localWriteTime\n )\n );\n }\n return transformResults;\n}\n\n/** A mutation that deletes the document at the given key. */\nexport class DeleteMutation extends Mutation {\n constructor(readonly key: DocumentKey, readonly precondition: Precondition) {\n super();\n }\n\n readonly type: MutationType = MutationType.Delete;\n readonly fieldTransforms: FieldTransform[] = [];\n\n getFieldMask(): FieldMask | null {\n return null;\n }\n}\n\nfunction deleteMutationApplyToRemoteDocument(\n mutation: DeleteMutation,\n document: MutableDocument,\n mutationResult: MutationResult\n): void {\n debugAssert(\n mutationResult.transformResults.length === 0,\n 'Transform results received by DeleteMutation.'\n );\n\n // Unlike applyToLocalView, if we're applying a mutation to a remote\n // document the server has accepted the mutation so the precondition must\n // have held.\n document\n .convertToNoDocument(mutationResult.version)\n .setHasCommittedMutations();\n}\n\nfunction deleteMutationApplyToLocalView(\n mutation: DeleteMutation,\n document: MutableDocument,\n previousMask: FieldMask | null\n): FieldMask | null {\n debugAssert(\n document.key.isEqual(mutation.key),\n 'Can only apply mutation to document with same key'\n );\n if (preconditionIsValidForDocument(mutation.precondition, document)) {\n document.convertToNoDocument(document.version).setHasLocalMutations();\n return null;\n }\n return previousMask;\n}\n\n/**\n * A mutation that verifies the existence of the document at the given key with\n * the provided precondition.\n *\n * The `verify` operation is only used in Transactions, and this class serves\n * primarily to facilitate serialization into protos.\n */\nexport class VerifyMutation extends Mutation {\n constructor(readonly key: DocumentKey, readonly precondition: Precondition) {\n super();\n }\n\n readonly type: MutationType = MutationType.Verify;\n readonly fieldTransforms: FieldTransform[] = [];\n\n getFieldMask(): FieldMask | null {\n return null;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Aggregate } from '../core/aggregate';\nimport { Bound } from '../core/bound';\nimport { DatabaseId } from '../core/database_info';\nimport {\n CompositeFilter,\n compositeFilterIsFlatConjunction,\n CompositeOperator,\n FieldFilter,\n Filter,\n Operator\n} from '../core/filter';\nimport { Direction, OrderBy } from '../core/order_by';\nimport {\n LimitType,\n newQuery,\n newQueryForPath,\n Query,\n queryToTarget\n} from '../core/query';\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { targetIsDocumentTarget, Target } from '../core/target';\nimport { TargetId } from '../core/types';\nimport { Timestamp } from '../lite-api/timestamp';\nimport { TargetData, TargetPurpose } from '../local/target_data';\nimport { MutableDocument } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { FieldMask } from '../model/field_mask';\nimport {\n DeleteMutation,\n FieldTransform,\n Mutation,\n MutationResult,\n PatchMutation,\n Precondition,\n SetMutation,\n VerifyMutation\n} from '../model/mutation';\nimport { normalizeTimestamp } from '../model/normalize';\nimport { ObjectValue } from '../model/object_value';\nimport { FieldPath, ResourcePath } from '../model/path';\nimport {\n ArrayRemoveTransformOperation,\n ArrayUnionTransformOperation,\n NumericIncrementTransformOperation,\n ServerTimestampTransform,\n TransformOperation\n} from '../model/transform_operation';\nimport { isNanValue, isNullValue } from '../model/values';\nimport {\n ApiClientObjectMap as ProtoApiClientObjectMap,\n BatchGetDocumentsResponse as ProtoBatchGetDocumentsResponse,\n CompositeFilterOp as ProtoCompositeFilterOp,\n Cursor as ProtoCursor,\n Document as ProtoDocument,\n DocumentMask as ProtoDocumentMask,\n DocumentsTarget as ProtoDocumentsTarget,\n FieldFilterOp as ProtoFieldFilterOp,\n FieldReference as ProtoFieldReference,\n FieldTransform as ProtoFieldTransform,\n Filter as ProtoFilter,\n ListenResponse as ProtoListenResponse,\n Order as ProtoOrder,\n OrderDirection as ProtoOrderDirection,\n Precondition as ProtoPrecondition,\n QueryTarget as ProtoQueryTarget,\n RunAggregationQueryRequest as ProtoRunAggregationQueryRequest,\n Aggregation as ProtoAggregation,\n Status as ProtoStatus,\n Target as ProtoTarget,\n TargetChangeTargetChangeType as ProtoTargetChangeTargetChangeType,\n Timestamp as ProtoTimestamp,\n Write as ProtoWrite,\n WriteResult as ProtoWriteResult\n} from '../protos/firestore_proto_api';\nimport { debugAssert, fail, hardAssert } from '../util/assert';\nimport { ByteString } from '../util/byte_string';\nimport { Code, FirestoreError } from '../util/error';\nimport { isNullOrUndefined } from '../util/types';\n\nimport { ExistenceFilter } from './existence_filter';\nimport { Serializer } from './number_serializer';\nimport { mapCodeFromRpcCode } from './rpc_error';\nimport {\n DocumentWatchChange,\n ExistenceFilterChange,\n WatchChange,\n WatchTargetChange,\n WatchTargetChangeState\n} from './watch_change';\n\nconst DIRECTIONS = (() => {\n const dirs: { [dir: string]: ProtoOrderDirection } = {};\n dirs[Direction.ASCENDING] = 'ASCENDING';\n dirs[Direction.DESCENDING] = 'DESCENDING';\n return dirs;\n})();\n\nconst OPERATORS = (() => {\n const ops: { [op: string]: ProtoFieldFilterOp } = {};\n ops[Operator.LESS_THAN] = 'LESS_THAN';\n ops[Operator.LESS_THAN_OR_EQUAL] = 'LESS_THAN_OR_EQUAL';\n ops[Operator.GREATER_THAN] = 'GREATER_THAN';\n ops[Operator.GREATER_THAN_OR_EQUAL] = 'GREATER_THAN_OR_EQUAL';\n ops[Operator.EQUAL] = 'EQUAL';\n ops[Operator.NOT_EQUAL] = 'NOT_EQUAL';\n ops[Operator.ARRAY_CONTAINS] = 'ARRAY_CONTAINS';\n ops[Operator.IN] = 'IN';\n ops[Operator.NOT_IN] = 'NOT_IN';\n ops[Operator.ARRAY_CONTAINS_ANY] = 'ARRAY_CONTAINS_ANY';\n return ops;\n})();\n\nconst COMPOSITE_OPERATORS = (() => {\n const ops: { [op: string]: ProtoCompositeFilterOp } = {};\n ops[CompositeOperator.AND] = 'AND';\n ops[CompositeOperator.OR] = 'OR';\n return ops;\n})();\n\nfunction assertPresent(value: unknown, description: string): asserts value {\n debugAssert(!isNullOrUndefined(value), description + ' is missing');\n}\n\n/**\n * This class generates JsonObject values for the Datastore API suitable for\n * sending to either GRPC stub methods or via the JSON/HTTP REST API.\n *\n * The serializer supports both Protobuf.js and Proto3 JSON formats. By\n * setting `useProto3Json` to true, the serializer will use the Proto3 JSON\n * format.\n *\n * For a description of the Proto3 JSON format check\n * https://developers.google.com/protocol-buffers/docs/proto3#json\n *\n * TODO(klimt): We can remove the databaseId argument if we keep the full\n * resource name in documents.\n */\nexport class JsonProtoSerializer implements Serializer {\n constructor(\n readonly databaseId: DatabaseId,\n readonly useProto3Json: boolean\n ) {}\n}\n\nfunction fromRpcStatus(status: ProtoStatus): FirestoreError {\n const code =\n status.code === undefined ? Code.UNKNOWN : mapCodeFromRpcCode(status.code);\n return new FirestoreError(code, status.message || '');\n}\n\n/**\n * Returns a value for a number (or null) that's appropriate to put into\n * a google.protobuf.Int32Value proto.\n * DO NOT USE THIS FOR ANYTHING ELSE.\n * This method cheats. It's typed as returning \"number\" because that's what\n * our generated proto interfaces say Int32Value must be. But GRPC actually\n * expects a { value: } struct.\n */\nfunction toInt32Proto(\n serializer: JsonProtoSerializer,\n val: number | null\n): number | { value: number } | null {\n if (serializer.useProto3Json || isNullOrUndefined(val)) {\n return val;\n } else {\n return { value: val };\n }\n}\n\n/**\n * Returns a number (or null) from a google.protobuf.Int32Value proto.\n */\nfunction fromInt32Proto(\n val: number | { value: number } | undefined\n): number | null {\n let result;\n if (typeof val === 'object') {\n result = val.value;\n } else {\n result = val;\n }\n return isNullOrUndefined(result) ? null : result;\n}\n\n/**\n * Returns a value for a Date that's appropriate to put into a proto.\n */\nexport function toTimestamp(\n serializer: JsonProtoSerializer,\n timestamp: Timestamp\n): ProtoTimestamp {\n if (serializer.useProto3Json) {\n // Serialize to ISO-8601 date format, but with full nano resolution.\n // Since JS Date has only millis, let's only use it for the seconds and\n // then manually add the fractions to the end.\n const jsDateStr = new Date(timestamp.seconds * 1000).toISOString();\n // Remove .xxx frac part and Z in the end.\n const strUntilSeconds = jsDateStr.replace(/\\.\\d*/, '').replace('Z', '');\n // Pad the fraction out to 9 digits (nanos).\n const nanoStr = ('000000000' + timestamp.nanoseconds).slice(-9);\n\n return `${strUntilSeconds}.${nanoStr}Z`;\n } else {\n return {\n seconds: '' + timestamp.seconds,\n nanos: timestamp.nanoseconds\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } as any;\n }\n}\n\n/**\n * Returns a Timestamp typed object given protobuf timestamp value.\n */\nexport function fromTimestamp(date: ProtoTimestamp): Timestamp {\n const timestamp = normalizeTimestamp(date);\n return new Timestamp(timestamp.seconds, timestamp.nanos);\n}\n\n/**\n * Returns a value for bytes that's appropriate to put in a proto.\n *\n * Visible for testing.\n */\nexport function toBytes(\n serializer: JsonProtoSerializer,\n bytes: ByteString\n): string | Uint8Array {\n if (serializer.useProto3Json) {\n return bytes.toBase64();\n } else {\n return bytes.toUint8Array();\n }\n}\n\n/**\n * Returns a ByteString based on the proto string value.\n */\nexport function fromBytes(\n serializer: JsonProtoSerializer,\n value: string | Uint8Array | undefined\n): ByteString {\n if (serializer.useProto3Json) {\n hardAssert(\n value === undefined || typeof value === 'string',\n 0xe30b,\n 'value must be undefined or a string when using proto3 Json'\n );\n return ByteString.fromBase64String(value ? value : '');\n } else {\n hardAssert(\n value === undefined ||\n // Check if the value is an instance of both Buffer and Uint8Array,\n // despite the fact that Buffer extends Uint8Array. In some\n // environments, such as jsdom, the prototype chain of Buffer\n // does not indicate that it extends Uint8Array.\n value instanceof Buffer ||\n value instanceof Uint8Array,\n 0x3f41,\n 'value must be undefined, Buffer, or Uint8Array'\n );\n return ByteString.fromUint8Array(value ? value : new Uint8Array());\n }\n}\n\nexport function toVersion(\n serializer: JsonProtoSerializer,\n version: SnapshotVersion\n): ProtoTimestamp {\n return toTimestamp(serializer, version.toTimestamp());\n}\n\nexport function fromVersion(version: ProtoTimestamp): SnapshotVersion {\n hardAssert(!!version, 0xc050, \"Trying to deserialize version that isn't set\");\n return SnapshotVersion.fromTimestamp(fromTimestamp(version));\n}\n\nexport function toResourceName(\n databaseId: DatabaseId,\n path: ResourcePath\n): string {\n return toResourcePath(databaseId, path).canonicalString();\n}\n\nexport function toResourcePath(\n databaseId: DatabaseId,\n path?: ResourcePath\n): ResourcePath {\n const resourcePath = fullyQualifiedPrefixPath(databaseId).child('documents');\n return path === undefined ? resourcePath : resourcePath.child(path);\n}\n\nfunction fromResourceName(name: string): ResourcePath {\n const resource = ResourcePath.fromString(name);\n hardAssert(\n isValidResourceName(resource),\n 0x27ce,\n 'Tried to deserialize invalid key',\n { key: resource.toString() }\n );\n return resource;\n}\n\nexport function toName(\n serializer: JsonProtoSerializer,\n key: DocumentKey\n): string {\n return toResourceName(serializer.databaseId, key.path);\n}\n\nexport function fromName(\n serializer: JsonProtoSerializer,\n name: string\n): DocumentKey {\n const resource = fromResourceName(name);\n\n if (resource.get(1) !== serializer.databaseId.projectId) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Tried to deserialize key from different project: ' +\n resource.get(1) +\n ' vs ' +\n serializer.databaseId.projectId\n );\n }\n\n if (resource.get(3) !== serializer.databaseId.database) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Tried to deserialize key from different database: ' +\n resource.get(3) +\n ' vs ' +\n serializer.databaseId.database\n );\n }\n return new DocumentKey(extractLocalPathFromResourceName(resource));\n}\n\nfunction toQueryPath(\n serializer: JsonProtoSerializer,\n path: ResourcePath\n): string {\n return toResourceName(serializer.databaseId, path);\n}\n\nfunction fromQueryPath(name: string): ResourcePath {\n const resourceName = fromResourceName(name);\n // In v1beta1 queries for collections at the root did not have a trailing\n // \"/documents\". In v1 all resource paths contain \"/documents\". Preserve the\n // ability to read the v1beta1 form for compatibility with queries persisted\n // in the local target cache.\n if (resourceName.length === 4) {\n return ResourcePath.emptyPath();\n }\n return extractLocalPathFromResourceName(resourceName);\n}\n\nexport function getEncodedDatabaseId(serializer: JsonProtoSerializer): string {\n const path = new ResourcePath([\n 'projects',\n serializer.databaseId.projectId,\n 'databases',\n serializer.databaseId.database\n ]);\n return path.canonicalString();\n}\n\nfunction fullyQualifiedPrefixPath(databaseId: DatabaseId): ResourcePath {\n return new ResourcePath([\n 'projects',\n databaseId.projectId,\n 'databases',\n databaseId.database\n ]);\n}\n\nfunction extractLocalPathFromResourceName(\n resourceName: ResourcePath\n): ResourcePath {\n hardAssert(\n resourceName.length > 4 && resourceName.get(4) === 'documents',\n 0x71a3,\n 'tried to deserialize invalid key',\n { key: resourceName.toString() }\n );\n return resourceName.popFirst(5);\n}\n\n/** Creates a Document proto from key and fields (but no create/update time) */\nexport function toMutationDocument(\n serializer: JsonProtoSerializer,\n key: DocumentKey,\n fields: ObjectValue\n): ProtoDocument {\n return {\n name: toName(serializer, key),\n fields: fields.value.mapValue.fields\n };\n}\n\nexport function toDocument(\n serializer: JsonProtoSerializer,\n document: MutableDocument\n): ProtoDocument {\n debugAssert(\n !document.hasLocalMutations,\n \"Can't serialize documents with mutations.\"\n );\n return {\n name: toName(serializer, document.key),\n fields: document.data.value.mapValue.fields,\n updateTime: toTimestamp(serializer, document.version.toTimestamp()),\n createTime: toTimestamp(serializer, document.createTime.toTimestamp())\n };\n}\n\nexport function fromDocument(\n serializer: JsonProtoSerializer,\n document: ProtoDocument,\n hasCommittedMutations?: boolean\n): MutableDocument {\n const key = fromName(serializer, document.name!);\n const version = fromVersion(document.updateTime!);\n // If we read a document from persistence that is missing createTime, it's due\n // to older SDK versions not storing this information. In such cases, we'll\n // set the createTime to zero. This can be removed in the long term.\n const createTime = document.createTime\n ? fromVersion(document.createTime)\n : SnapshotVersion.min();\n const data = new ObjectValue({ mapValue: { fields: document.fields } });\n const result = MutableDocument.newFoundDocument(\n key,\n version,\n createTime,\n data\n );\n if (hasCommittedMutations) {\n result.setHasCommittedMutations();\n }\n return hasCommittedMutations ? result.setHasCommittedMutations() : result;\n}\n\nfunction fromFound(\n serializer: JsonProtoSerializer,\n doc: ProtoBatchGetDocumentsResponse\n): MutableDocument {\n hardAssert(\n !!doc.found,\n 0xaa33,\n 'Tried to deserialize a found document from a missing document.'\n );\n assertPresent(doc.found.name, 'doc.found.name');\n assertPresent(doc.found.updateTime, 'doc.found.updateTime');\n const key = fromName(serializer, doc.found.name);\n const version = fromVersion(doc.found.updateTime);\n const createTime = doc.found.createTime\n ? fromVersion(doc.found.createTime)\n : SnapshotVersion.min();\n const data = new ObjectValue({ mapValue: { fields: doc.found.fields } });\n return MutableDocument.newFoundDocument(key, version, createTime, data);\n}\n\nfunction fromMissing(\n serializer: JsonProtoSerializer,\n result: ProtoBatchGetDocumentsResponse\n): MutableDocument {\n hardAssert(\n !!result.missing,\n 0x0f36,\n 'Tried to deserialize a missing document from a found document.'\n );\n hardAssert(\n !!result.readTime,\n 0x5995,\n 'Tried to deserialize a missing document without a read time.'\n );\n const key = fromName(serializer, result.missing);\n const version = fromVersion(result.readTime);\n return MutableDocument.newNoDocument(key, version);\n}\n\nexport function fromBatchGetDocumentsResponse(\n serializer: JsonProtoSerializer,\n result: ProtoBatchGetDocumentsResponse\n): MutableDocument {\n if ('found' in result) {\n return fromFound(serializer, result);\n } else if ('missing' in result) {\n return fromMissing(serializer, result);\n }\n return fail(0x1c42, 'invalid batch get response', { result });\n}\n\nexport function fromWatchChange(\n serializer: JsonProtoSerializer,\n change: ProtoListenResponse\n): WatchChange {\n let watchChange: WatchChange;\n if ('targetChange' in change) {\n assertPresent(change.targetChange, 'targetChange');\n // proto3 default value is unset in JSON (undefined), so use 'NO_CHANGE'\n // if unset\n const state = fromWatchTargetChangeState(\n change.targetChange.targetChangeType || 'NO_CHANGE'\n );\n const targetIds: TargetId[] = change.targetChange.targetIds || [];\n\n const resumeToken = fromBytes(serializer, change.targetChange.resumeToken);\n const causeProto = change.targetChange!.cause;\n const cause = causeProto && fromRpcStatus(causeProto);\n watchChange = new WatchTargetChange(\n state,\n targetIds,\n resumeToken,\n cause || null\n );\n } else if ('documentChange' in change) {\n assertPresent(change.documentChange, 'documentChange');\n const entityChange = change.documentChange;\n assertPresent(entityChange.document, 'documentChange.name');\n assertPresent(entityChange.document.name, 'documentChange.document.name');\n assertPresent(\n entityChange.document.updateTime,\n 'documentChange.document.updateTime'\n );\n const key = fromName(serializer, entityChange.document.name);\n const version = fromVersion(entityChange.document.updateTime);\n const createTime = entityChange.document.createTime\n ? fromVersion(entityChange.document.createTime)\n : SnapshotVersion.min();\n const data = new ObjectValue({\n mapValue: { fields: entityChange.document.fields }\n });\n const doc = MutableDocument.newFoundDocument(\n key,\n version,\n createTime,\n data\n );\n const updatedTargetIds = entityChange.targetIds || [];\n const removedTargetIds = entityChange.removedTargetIds || [];\n watchChange = new DocumentWatchChange(\n updatedTargetIds,\n removedTargetIds,\n doc.key,\n doc\n );\n } else if ('documentDelete' in change) {\n assertPresent(change.documentDelete, 'documentDelete');\n const docDelete = change.documentDelete;\n assertPresent(docDelete.document, 'documentDelete.document');\n const key = fromName(serializer, docDelete.document);\n const version = docDelete.readTime\n ? fromVersion(docDelete.readTime)\n : SnapshotVersion.min();\n const doc = MutableDocument.newNoDocument(key, version);\n const removedTargetIds = docDelete.removedTargetIds || [];\n watchChange = new DocumentWatchChange([], removedTargetIds, doc.key, doc);\n } else if ('documentRemove' in change) {\n assertPresent(change.documentRemove, 'documentRemove');\n const docRemove = change.documentRemove;\n assertPresent(docRemove.document, 'documentRemove');\n const key = fromName(serializer, docRemove.document);\n const removedTargetIds = docRemove.removedTargetIds || [];\n watchChange = new DocumentWatchChange([], removedTargetIds, key, null);\n } else if ('filter' in change) {\n // TODO(dimond): implement existence filter parsing with strategy.\n assertPresent(change.filter, 'filter');\n const filter = change.filter;\n assertPresent(filter.targetId, 'filter.targetId');\n const { count = 0, unchangedNames } = filter;\n const existenceFilter = new ExistenceFilter(count, unchangedNames);\n const targetId = filter.targetId;\n watchChange = new ExistenceFilterChange(targetId, existenceFilter);\n } else {\n return fail(0x2d51, 'Unknown change type', { change });\n }\n return watchChange;\n}\n\nfunction fromWatchTargetChangeState(\n state: ProtoTargetChangeTargetChangeType\n): WatchTargetChangeState {\n if (state === 'NO_CHANGE') {\n return WatchTargetChangeState.NoChange;\n } else if (state === 'ADD') {\n return WatchTargetChangeState.Added;\n } else if (state === 'REMOVE') {\n return WatchTargetChangeState.Removed;\n } else if (state === 'CURRENT') {\n return WatchTargetChangeState.Current;\n } else if (state === 'RESET') {\n return WatchTargetChangeState.Reset;\n } else {\n return fail(0x9991, 'Got unexpected TargetChange.state', { state });\n }\n}\n\nexport function versionFromListenResponse(\n change: ProtoListenResponse\n): SnapshotVersion {\n // We have only reached a consistent snapshot for the entire stream if there\n // is a read_time set and it applies to all targets (i.e. the list of\n // targets is empty). The backend is guaranteed to send such responses.\n if (!('targetChange' in change)) {\n return SnapshotVersion.min();\n }\n const targetChange = change.targetChange!;\n if (targetChange.targetIds && targetChange.targetIds.length) {\n return SnapshotVersion.min();\n }\n if (!targetChange.readTime) {\n return SnapshotVersion.min();\n }\n return fromVersion(targetChange.readTime);\n}\n\nexport function toMutation(\n serializer: JsonProtoSerializer,\n mutation: Mutation\n): ProtoWrite {\n let result: ProtoWrite;\n if (mutation instanceof SetMutation) {\n result = {\n update: toMutationDocument(serializer, mutation.key, mutation.value)\n };\n } else if (mutation instanceof DeleteMutation) {\n result = { delete: toName(serializer, mutation.key) };\n } else if (mutation instanceof PatchMutation) {\n result = {\n update: toMutationDocument(serializer, mutation.key, mutation.data),\n updateMask: toDocumentMask(mutation.fieldMask)\n };\n } else if (mutation instanceof VerifyMutation) {\n result = {\n verify: toName(serializer, mutation.key)\n };\n } else {\n return fail(0x40d7, 'Unknown mutation type', {\n mutationType: mutation.type\n });\n }\n\n if (mutation.fieldTransforms.length > 0) {\n result.updateTransforms = mutation.fieldTransforms.map(transform =>\n toFieldTransform(serializer, transform)\n );\n }\n\n if (!mutation.precondition.isNone) {\n result.currentDocument = toPrecondition(serializer, mutation.precondition);\n }\n\n return result;\n}\n\nexport function fromMutation(\n serializer: JsonProtoSerializer,\n proto: ProtoWrite\n): Mutation {\n const precondition = proto.currentDocument\n ? fromPrecondition(proto.currentDocument)\n : Precondition.none();\n\n const fieldTransforms = proto.updateTransforms\n ? proto.updateTransforms.map(transform =>\n fromFieldTransform(serializer, transform)\n )\n : [];\n\n if (proto.update) {\n assertPresent(proto.update.name, 'name');\n const key = fromName(serializer, proto.update.name);\n const value = new ObjectValue({\n mapValue: { fields: proto.update.fields }\n });\n\n if (proto.updateMask) {\n const fieldMask = fromDocumentMask(proto.updateMask);\n return new PatchMutation(\n key,\n value,\n fieldMask,\n precondition,\n fieldTransforms\n );\n } else {\n return new SetMutation(key, value, precondition, fieldTransforms);\n }\n } else if (proto.delete) {\n const key = fromName(serializer, proto.delete);\n return new DeleteMutation(key, precondition);\n } else if (proto.verify) {\n const key = fromName(serializer, proto.verify);\n return new VerifyMutation(key, precondition);\n } else {\n return fail(0x05b7, 'unknown mutation proto', { proto });\n }\n}\n\nfunction toPrecondition(\n serializer: JsonProtoSerializer,\n precondition: Precondition\n): ProtoPrecondition {\n debugAssert(!precondition.isNone, \"Can't serialize an empty precondition\");\n if (precondition.updateTime !== undefined) {\n return {\n updateTime: toVersion(serializer, precondition.updateTime)\n };\n } else if (precondition.exists !== undefined) {\n return { exists: precondition.exists };\n } else {\n return fail(0x6b69, 'Unknown precondition');\n }\n}\n\nfunction fromPrecondition(precondition: ProtoPrecondition): Precondition {\n if (precondition.updateTime !== undefined) {\n return Precondition.updateTime(fromVersion(precondition.updateTime));\n } else if (precondition.exists !== undefined) {\n return Precondition.exists(precondition.exists);\n } else {\n return Precondition.none();\n }\n}\n\nfunction fromWriteResult(\n proto: ProtoWriteResult,\n commitTime: ProtoTimestamp\n): MutationResult {\n // NOTE: Deletes don't have an updateTime.\n let version = proto.updateTime\n ? fromVersion(proto.updateTime)\n : fromVersion(commitTime);\n\n if (version.isEqual(SnapshotVersion.min())) {\n // The Firestore Emulator currently returns an update time of 0 for\n // deletes of non-existing documents (rather than null). This breaks the\n // test \"get deleted doc while offline with source=cache\" as NoDocuments\n // with version 0 are filtered by IndexedDb's RemoteDocumentCache.\n // TODO(#2149): Remove this when Emulator is fixed\n version = fromVersion(commitTime);\n }\n\n return new MutationResult(version, proto.transformResults || []);\n}\n\nexport function fromWriteResults(\n protos: ProtoWriteResult[] | undefined,\n commitTime?: ProtoTimestamp\n): MutationResult[] {\n if (protos && protos.length > 0) {\n hardAssert(\n commitTime !== undefined,\n 0x3811,\n 'Received a write result without a commit time'\n );\n return protos.map(proto => fromWriteResult(proto, commitTime));\n } else {\n return [];\n }\n}\n\nfunction toFieldTransform(\n serializer: JsonProtoSerializer,\n fieldTransform: FieldTransform\n): ProtoFieldTransform {\n const transform = fieldTransform.transform;\n if (transform instanceof ServerTimestampTransform) {\n return {\n fieldPath: fieldTransform.field.canonicalString(),\n setToServerValue: 'REQUEST_TIME'\n };\n } else if (transform instanceof ArrayUnionTransformOperation) {\n return {\n fieldPath: fieldTransform.field.canonicalString(),\n appendMissingElements: {\n values: transform.elements\n }\n };\n } else if (transform instanceof ArrayRemoveTransformOperation) {\n return {\n fieldPath: fieldTransform.field.canonicalString(),\n removeAllFromArray: {\n values: transform.elements\n }\n };\n } else if (transform instanceof NumericIncrementTransformOperation) {\n return {\n fieldPath: fieldTransform.field.canonicalString(),\n increment: transform.operand\n };\n } else {\n throw fail(0x51c2, 'Unknown transform', {\n transform: fieldTransform.transform\n });\n }\n}\n\nfunction fromFieldTransform(\n serializer: JsonProtoSerializer,\n proto: ProtoFieldTransform\n): FieldTransform {\n let transform: TransformOperation | null = null;\n if ('setToServerValue' in proto) {\n hardAssert(\n proto.setToServerValue === 'REQUEST_TIME',\n 0x40f6,\n 'Unknown server value transform proto',\n { proto }\n );\n transform = new ServerTimestampTransform();\n } else if ('appendMissingElements' in proto) {\n const values = proto.appendMissingElements!.values || [];\n transform = new ArrayUnionTransformOperation(values);\n } else if ('removeAllFromArray' in proto) {\n const values = proto.removeAllFromArray!.values || [];\n transform = new ArrayRemoveTransformOperation(values);\n } else if ('increment' in proto) {\n transform = new NumericIncrementTransformOperation(\n serializer,\n proto.increment!\n );\n } else {\n fail(0x40c8, 'Unknown transform proto', { proto });\n }\n const fieldPath = FieldPath.fromServerFormat(proto.fieldPath!);\n return new FieldTransform(fieldPath, transform!);\n}\n\nexport function toDocumentsTarget(\n serializer: JsonProtoSerializer,\n target: Target\n): ProtoDocumentsTarget {\n return { documents: [toQueryPath(serializer, target.path)] };\n}\n\nexport function fromDocumentsTarget(\n documentsTarget: ProtoDocumentsTarget\n): Target {\n const count = documentsTarget.documents!.length;\n hardAssert(\n count === 1,\n 0x07ae,\n 'DocumentsTarget contained other than 1 document',\n {\n count\n }\n );\n const name = documentsTarget.documents![0];\n return queryToTarget(newQueryForPath(fromQueryPath(name)));\n}\n\nexport function toQueryTarget(\n serializer: JsonProtoSerializer,\n target: Target\n): { queryTarget: ProtoQueryTarget; parent: ResourcePath } {\n // Dissect the path into parent, collectionId, and optional key filter.\n const queryTarget: ProtoQueryTarget = { structuredQuery: {} };\n const path = target.path;\n let parent: ResourcePath;\n if (target.collectionGroup !== null) {\n debugAssert(\n path.length % 2 === 0,\n 'Collection Group queries should be within a document path or root.'\n );\n parent = path;\n queryTarget.structuredQuery!.from = [\n {\n collectionId: target.collectionGroup,\n allDescendants: true\n }\n ];\n } else {\n debugAssert(\n path.length % 2 !== 0,\n 'Document queries with filters are not supported.'\n );\n parent = path.popLast();\n queryTarget.structuredQuery!.from = [{ collectionId: path.lastSegment() }];\n }\n queryTarget.parent = toQueryPath(serializer, parent);\n\n const where = toFilters(target.filters);\n if (where) {\n queryTarget.structuredQuery!.where = where;\n }\n\n const orderBy = toOrder(target.orderBy);\n if (orderBy) {\n queryTarget.structuredQuery!.orderBy = orderBy;\n }\n\n const limit = toInt32Proto(serializer, target.limit);\n if (limit !== null) {\n queryTarget.structuredQuery!.limit = limit;\n }\n\n if (target.startAt) {\n queryTarget.structuredQuery!.startAt = toStartAtCursor(target.startAt);\n }\n if (target.endAt) {\n queryTarget.structuredQuery!.endAt = toEndAtCursor(target.endAt);\n }\n\n return { queryTarget, parent };\n}\n\nexport function toRunAggregationQueryRequest(\n serializer: JsonProtoSerializer,\n target: Target,\n aggregates: Aggregate[],\n skipAliasing?: boolean\n): {\n request: ProtoRunAggregationQueryRequest;\n aliasMap: Record;\n parent: ResourcePath;\n} {\n const { queryTarget, parent } = toQueryTarget(serializer, target);\n const aliasMap: Record = {};\n\n const aggregations: ProtoAggregation[] = [];\n let aggregationNum = 0;\n\n aggregates.forEach(aggregate => {\n // Map all client-side aliases to a unique short-form\n // alias. This avoids issues with client-side aliases that\n // exceed the 1500-byte string size limit.\n const serverAlias = skipAliasing\n ? aggregate.alias\n : `aggregate_${aggregationNum++}`;\n aliasMap[serverAlias] = aggregate.alias;\n\n if (aggregate.aggregateType === 'count') {\n aggregations.push({\n alias: serverAlias,\n count: {}\n });\n } else if (aggregate.aggregateType === 'avg') {\n aggregations.push({\n alias: serverAlias,\n avg: {\n field: toFieldPathReference(aggregate.fieldPath!)\n }\n });\n } else if (aggregate.aggregateType === 'sum') {\n aggregations.push({\n alias: serverAlias,\n sum: {\n field: toFieldPathReference(aggregate.fieldPath!)\n }\n });\n }\n });\n\n return {\n request: {\n structuredAggregationQuery: {\n aggregations,\n structuredQuery: queryTarget.structuredQuery\n },\n parent: queryTarget.parent\n },\n aliasMap,\n parent\n };\n}\n\nexport function convertQueryTargetToQuery(target: ProtoQueryTarget): Query {\n let path = fromQueryPath(target.parent!);\n\n const query = target.structuredQuery!;\n const fromCount = query.from ? query.from.length : 0;\n let collectionGroup: string | null = null;\n if (fromCount > 0) {\n hardAssert(\n fromCount === 1,\n 0xfe26,\n 'StructuredQuery.from with more than one collection is not supported.'\n );\n const from = query.from![0];\n if (from.allDescendants) {\n collectionGroup = from.collectionId!;\n } else {\n path = path.child(from.collectionId!);\n }\n }\n\n let filterBy: Filter[] = [];\n if (query.where) {\n filterBy = fromFilters(query.where);\n }\n\n let orderBy: OrderBy[] = [];\n if (query.orderBy) {\n orderBy = fromOrder(query.orderBy);\n }\n\n let limit: number | null = null;\n if (query.limit) {\n limit = fromInt32Proto(query.limit);\n }\n\n let startAt: Bound | null = null;\n if (query.startAt) {\n startAt = fromStartAtCursor(query.startAt);\n }\n\n let endAt: Bound | null = null;\n if (query.endAt) {\n endAt = fromEndAtCursor(query.endAt);\n }\n\n return newQuery(\n path,\n collectionGroup,\n orderBy,\n filterBy,\n limit,\n LimitType.First,\n startAt,\n endAt\n );\n}\n\nexport function fromQueryTarget(target: ProtoQueryTarget): Target {\n return queryToTarget(convertQueryTargetToQuery(target));\n}\n\nexport function toListenRequestLabels(\n serializer: JsonProtoSerializer,\n targetData: TargetData\n): ProtoApiClientObjectMap | null {\n const value = toLabel(targetData.purpose);\n if (value == null) {\n return null;\n } else {\n return {\n 'goog-listen-tags': value\n };\n }\n}\n\nexport function toLabel(purpose: TargetPurpose): string | null {\n switch (purpose) {\n case TargetPurpose.Listen:\n return null;\n case TargetPurpose.ExistenceFilterMismatch:\n return 'existence-filter-mismatch';\n case TargetPurpose.ExistenceFilterMismatchBloom:\n return 'existence-filter-mismatch-bloom';\n case TargetPurpose.LimboResolution:\n return 'limbo-document';\n default:\n return fail(0x713b, 'Unrecognized query purpose', { purpose });\n }\n}\n\nexport function toTarget(\n serializer: JsonProtoSerializer,\n targetData: TargetData\n): ProtoTarget {\n let result: ProtoTarget;\n const target = targetData.target;\n\n if (targetIsDocumentTarget(target)) {\n result = { documents: toDocumentsTarget(serializer, target) };\n } else {\n result = { query: toQueryTarget(serializer, target).queryTarget };\n }\n\n result.targetId = targetData.targetId;\n\n if (targetData.resumeToken.approximateByteSize() > 0) {\n result.resumeToken = toBytes(serializer, targetData.resumeToken);\n const expectedCount = toInt32Proto(serializer, targetData.expectedCount);\n if (expectedCount !== null) {\n result.expectedCount = expectedCount;\n }\n } else if (targetData.snapshotVersion.compareTo(SnapshotVersion.min()) > 0) {\n // TODO(wuandy): Consider removing above check because it is most likely true.\n // Right now, many tests depend on this behaviour though (leaving min() out\n // of serialization).\n result.readTime = toTimestamp(\n serializer,\n targetData.snapshotVersion.toTimestamp()\n );\n const expectedCount = toInt32Proto(serializer, targetData.expectedCount);\n if (expectedCount !== null) {\n result.expectedCount = expectedCount;\n }\n }\n\n return result;\n}\n\nfunction toFilters(filters: Filter[]): ProtoFilter | undefined {\n if (filters.length === 0) {\n return;\n }\n\n return toFilter(CompositeFilter.create(filters, CompositeOperator.AND));\n}\n\nfunction fromFilters(filter: ProtoFilter): Filter[] {\n const result = fromFilter(filter);\n\n if (\n result instanceof CompositeFilter &&\n compositeFilterIsFlatConjunction(result)\n ) {\n return result.getFilters();\n }\n\n return [result];\n}\n\nfunction fromFilter(filter: ProtoFilter): Filter {\n if (filter.unaryFilter !== undefined) {\n return fromUnaryFilter(filter);\n } else if (filter.fieldFilter !== undefined) {\n return fromFieldFilter(filter);\n } else if (filter.compositeFilter !== undefined) {\n return fromCompositeFilter(filter);\n } else {\n return fail(0x7591, 'Unknown filter', { filter });\n }\n}\n\nfunction toOrder(orderBys: OrderBy[]): ProtoOrder[] | undefined {\n if (orderBys.length === 0) {\n return;\n }\n return orderBys.map(order => toPropertyOrder(order));\n}\n\nfunction fromOrder(orderBys: ProtoOrder[]): OrderBy[] {\n return orderBys.map(order => fromPropertyOrder(order));\n}\n\nfunction toStartAtCursor(cursor: Bound): ProtoCursor {\n return {\n before: cursor.inclusive,\n values: cursor.position\n };\n}\n\nfunction toEndAtCursor(cursor: Bound): ProtoCursor {\n return {\n before: !cursor.inclusive,\n values: cursor.position\n };\n}\n\nfunction fromStartAtCursor(cursor: ProtoCursor): Bound {\n const inclusive = !!cursor.before;\n const position = cursor.values || [];\n return new Bound(position, inclusive);\n}\n\nfunction fromEndAtCursor(cursor: ProtoCursor): Bound {\n const inclusive = !cursor.before;\n const position = cursor.values || [];\n return new Bound(position, inclusive);\n}\n\n// visible for testing\nexport function toDirection(dir: Direction): ProtoOrderDirection {\n return DIRECTIONS[dir];\n}\n\n// visible for testing\nexport function fromDirection(\n dir: ProtoOrderDirection | undefined\n): Direction | undefined {\n switch (dir) {\n case 'ASCENDING':\n return Direction.ASCENDING;\n case 'DESCENDING':\n return Direction.DESCENDING;\n default:\n return undefined;\n }\n}\n\n// visible for testing\nexport function toOperatorName(op: Operator): ProtoFieldFilterOp {\n return OPERATORS[op];\n}\n\nexport function toCompositeOperatorName(\n op: CompositeOperator\n): ProtoCompositeFilterOp {\n return COMPOSITE_OPERATORS[op];\n}\n\nexport function fromOperatorName(op: ProtoFieldFilterOp): Operator {\n switch (op) {\n case 'EQUAL':\n return Operator.EQUAL;\n case 'NOT_EQUAL':\n return Operator.NOT_EQUAL;\n case 'GREATER_THAN':\n return Operator.GREATER_THAN;\n case 'GREATER_THAN_OR_EQUAL':\n return Operator.GREATER_THAN_OR_EQUAL;\n case 'LESS_THAN':\n return Operator.LESS_THAN;\n case 'LESS_THAN_OR_EQUAL':\n return Operator.LESS_THAN_OR_EQUAL;\n case 'ARRAY_CONTAINS':\n return Operator.ARRAY_CONTAINS;\n case 'IN':\n return Operator.IN;\n case 'NOT_IN':\n return Operator.NOT_IN;\n case 'ARRAY_CONTAINS_ANY':\n return Operator.ARRAY_CONTAINS_ANY;\n case 'OPERATOR_UNSPECIFIED':\n return fail(0xe2fe, 'Unspecified operator');\n default:\n return fail(0xc54a, 'Unknown operator');\n }\n}\n\nexport function fromCompositeOperatorName(\n op: ProtoCompositeFilterOp\n): CompositeOperator {\n switch (op) {\n case 'AND':\n return CompositeOperator.AND;\n case 'OR':\n return CompositeOperator.OR;\n default:\n return fail(0x0402, 'Unknown operator');\n }\n}\n\nexport function toFieldPathReference(path: FieldPath): ProtoFieldReference {\n return { fieldPath: path.canonicalString() };\n}\n\nexport function fromFieldPathReference(\n fieldReference: ProtoFieldReference\n): FieldPath {\n return FieldPath.fromServerFormat(fieldReference.fieldPath!);\n}\n\n// visible for testing\nexport function toPropertyOrder(orderBy: OrderBy): ProtoOrder {\n return {\n field: toFieldPathReference(orderBy.field),\n direction: toDirection(orderBy.dir)\n };\n}\n\nexport function fromPropertyOrder(orderBy: ProtoOrder): OrderBy {\n return new OrderBy(\n fromFieldPathReference(orderBy.field!),\n fromDirection(orderBy.direction)\n );\n}\n\n// visible for testing\nexport function toFilter(filter: Filter): ProtoFilter {\n if (filter instanceof FieldFilter) {\n return toUnaryOrFieldFilter(filter);\n } else if (filter instanceof CompositeFilter) {\n return toCompositeFilter(filter);\n } else {\n return fail(0xd65d, 'Unrecognized filter type', { filter });\n }\n}\n\nexport function toCompositeFilter(filter: CompositeFilter): ProtoFilter {\n const protos = filter.getFilters().map(filter => toFilter(filter));\n\n if (protos.length === 1) {\n return protos[0];\n }\n\n return {\n compositeFilter: {\n op: toCompositeOperatorName(filter.op),\n filters: protos\n }\n };\n}\n\nexport function toUnaryOrFieldFilter(filter: FieldFilter): ProtoFilter {\n if (filter.op === Operator.EQUAL) {\n if (isNanValue(filter.value)) {\n return {\n unaryFilter: {\n field: toFieldPathReference(filter.field),\n op: 'IS_NAN'\n }\n };\n } else if (isNullValue(filter.value)) {\n return {\n unaryFilter: {\n field: toFieldPathReference(filter.field),\n op: 'IS_NULL'\n }\n };\n }\n } else if (filter.op === Operator.NOT_EQUAL) {\n if (isNanValue(filter.value)) {\n return {\n unaryFilter: {\n field: toFieldPathReference(filter.field),\n op: 'IS_NOT_NAN'\n }\n };\n } else if (isNullValue(filter.value)) {\n return {\n unaryFilter: {\n field: toFieldPathReference(filter.field),\n op: 'IS_NOT_NULL'\n }\n };\n }\n }\n return {\n fieldFilter: {\n field: toFieldPathReference(filter.field),\n op: toOperatorName(filter.op),\n value: filter.value\n }\n };\n}\n\nexport function fromUnaryFilter(filter: ProtoFilter): Filter {\n switch (filter.unaryFilter!.op!) {\n case 'IS_NAN':\n const nanField = fromFieldPathReference(filter.unaryFilter!.field!);\n return FieldFilter.create(nanField, Operator.EQUAL, {\n doubleValue: NaN\n });\n case 'IS_NULL':\n const nullField = fromFieldPathReference(filter.unaryFilter!.field!);\n return FieldFilter.create(nullField, Operator.EQUAL, {\n nullValue: 'NULL_VALUE'\n });\n case 'IS_NOT_NAN':\n const notNanField = fromFieldPathReference(filter.unaryFilter!.field!);\n return FieldFilter.create(notNanField, Operator.NOT_EQUAL, {\n doubleValue: NaN\n });\n case 'IS_NOT_NULL':\n const notNullField = fromFieldPathReference(filter.unaryFilter!.field!);\n return FieldFilter.create(notNullField, Operator.NOT_EQUAL, {\n nullValue: 'NULL_VALUE'\n });\n case 'OPERATOR_UNSPECIFIED':\n return fail(0xef81, 'Unspecified filter');\n default:\n return fail(0xed36, 'Unknown filter');\n }\n}\n\nexport function fromFieldFilter(filter: ProtoFilter): FieldFilter {\n return FieldFilter.create(\n fromFieldPathReference(filter.fieldFilter!.field!),\n fromOperatorName(filter.fieldFilter!.op!),\n filter.fieldFilter!.value!\n );\n}\n\nexport function fromCompositeFilter(filter: ProtoFilter): CompositeFilter {\n return CompositeFilter.create(\n filter.compositeFilter!.filters!.map(filter => fromFilter(filter)),\n fromCompositeOperatorName(filter.compositeFilter!.op!)\n );\n}\n\nexport function toDocumentMask(fieldMask: FieldMask): ProtoDocumentMask {\n const canonicalFields: string[] = [];\n fieldMask.fields.forEach(field =>\n canonicalFields.push(field.canonicalString())\n );\n return {\n fieldPaths: canonicalFields\n };\n}\n\nexport function fromDocumentMask(proto: ProtoDocumentMask): FieldMask {\n const paths = proto.fieldPaths || [];\n return new FieldMask(paths.map(path => FieldPath.fromServerFormat(path)));\n}\n\nexport function isValidResourceName(path: ResourcePath): boolean {\n // Resource names have at least 4 components (project ID, database ID)\n return (\n path.length >= 4 &&\n path.get(0) === 'projects' &&\n path.get(2) === 'databases'\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** Return the Platform-specific serializer monitor. */\nimport { DatabaseId } from '../../core/database_info';\nimport { JsonProtoSerializer } from '../../remote/serializer';\n\nexport function newSerializer(databaseId: DatabaseId): JsonProtoSerializer {\n return new JsonProtoSerializer(databaseId, /* useProto3Json= */ true);\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { AsyncQueue, DelayedOperation, TimerId } from '../util/async_queue';\nimport { logDebug } from '../util/log';\n\nconst LOG_TAG = 'ExponentialBackoff';\n\n/**\n * Initial backoff time in milliseconds after an error.\n * Set to 1s according to https://cloud.google.com/apis/design/errors.\n */\nconst DEFAULT_BACKOFF_INITIAL_DELAY_MS = 1000;\n\nconst DEFAULT_BACKOFF_FACTOR = 1.5;\n\n/** Maximum backoff time in milliseconds */\nconst DEFAULT_BACKOFF_MAX_DELAY_MS = 60 * 1000;\n\n/**\n * A helper for running delayed tasks following an exponential backoff curve\n * between attempts.\n *\n * Each delay is made up of a \"base\" delay which follows the exponential\n * backoff curve, and a +/- 50% \"jitter\" that is calculated and added to the\n * base delay. This prevents clients from accidentally synchronizing their\n * delays causing spikes of load to the backend.\n */\nexport class ExponentialBackoff {\n private currentBaseMs: number = 0;\n private timerPromise: DelayedOperation | null = null;\n /** The last backoff attempt, as epoch milliseconds. */\n private lastAttemptTime = Date.now();\n\n constructor(\n /**\n * The AsyncQueue to run backoff operations on.\n */\n private readonly queue: AsyncQueue,\n /**\n * The ID to use when scheduling backoff operations on the AsyncQueue.\n */\n private readonly timerId: TimerId,\n /**\n * The initial delay (used as the base delay on the first retry attempt).\n * Note that jitter will still be applied, so the actual delay could be as\n * little as 0.5*initialDelayMs.\n */\n private readonly initialDelayMs: number = DEFAULT_BACKOFF_INITIAL_DELAY_MS,\n /**\n * The multiplier to use to determine the extended base delay after each\n * attempt.\n */\n private readonly backoffFactor: number = DEFAULT_BACKOFF_FACTOR,\n /**\n * The maximum base delay after which no further backoff is performed.\n * Note that jitter will still be applied, so the actual delay could be as\n * much as 1.5*maxDelayMs.\n */\n private readonly maxDelayMs: number = DEFAULT_BACKOFF_MAX_DELAY_MS\n ) {\n this.reset();\n }\n\n /**\n * Resets the backoff delay.\n *\n * The very next backoffAndWait() will have no delay. If it is called again\n * (i.e. due to an error), initialDelayMs (plus jitter) will be used, and\n * subsequent ones will increase according to the backoffFactor.\n */\n reset(): void {\n this.currentBaseMs = 0;\n }\n\n /**\n * Resets the backoff delay to the maximum delay (e.g. for use after a\n * RESOURCE_EXHAUSTED error).\n */\n resetToMax(): void {\n this.currentBaseMs = this.maxDelayMs;\n }\n\n /**\n * Returns a promise that resolves after currentDelayMs, and increases the\n * delay for any subsequent attempts. If there was a pending backoff operation\n * already, it will be canceled.\n */\n backoffAndRun(op: () => Promise): void {\n // Cancel any pending backoff operation.\n this.cancel();\n\n // First schedule using the current base (which may be 0 and should be\n // honored as such).\n const desiredDelayWithJitterMs = Math.floor(\n this.currentBaseMs + this.jitterDelayMs()\n );\n\n // Guard against lastAttemptTime being in the future due to a clock change.\n const delaySoFarMs = Math.max(0, Date.now() - this.lastAttemptTime);\n\n // Guard against the backoff delay already being past.\n const remainingDelayMs = Math.max(\n 0,\n desiredDelayWithJitterMs - delaySoFarMs\n );\n\n if (remainingDelayMs > 0) {\n logDebug(\n LOG_TAG,\n `Backing off for ${remainingDelayMs} ms ` +\n `(base delay: ${this.currentBaseMs} ms, ` +\n `delay with jitter: ${desiredDelayWithJitterMs} ms, ` +\n `last attempt: ${delaySoFarMs} ms ago)`\n );\n }\n\n this.timerPromise = this.queue.enqueueAfterDelay(\n this.timerId,\n remainingDelayMs,\n () => {\n this.lastAttemptTime = Date.now();\n return op();\n }\n );\n\n // Apply backoff factor to determine next delay and ensure it is within\n // bounds.\n this.currentBaseMs *= this.backoffFactor;\n if (this.currentBaseMs < this.initialDelayMs) {\n this.currentBaseMs = this.initialDelayMs;\n }\n if (this.currentBaseMs > this.maxDelayMs) {\n this.currentBaseMs = this.maxDelayMs;\n }\n }\n\n skipBackoff(): void {\n if (this.timerPromise !== null) {\n this.timerPromise.skipDelay();\n this.timerPromise = null;\n }\n }\n\n cancel(): void {\n if (this.timerPromise !== null) {\n this.timerPromise.cancel();\n this.timerPromise = null;\n }\n }\n\n /** Returns a random value in the range [-currentBaseMs/2, currentBaseMs/2] */\n private jitterDelayMs(): number {\n return (Math.random() - 0.5) * this.currentBaseMs;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { CredentialsProvider } from '../api/credentials';\nimport { User } from '../auth/user';\nimport { Aggregate } from '../core/aggregate';\nimport { DatabaseId } from '../core/database_info';\nimport { queryToAggregateTarget, Query, queryToTarget } from '../core/query';\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { Mutation } from '../model/mutation';\nimport { ResourcePath } from '../model/path';\nimport {\n ApiClientObjectMap,\n BatchGetDocumentsRequest as ProtoBatchGetDocumentsRequest,\n BatchGetDocumentsResponse as ProtoBatchGetDocumentsResponse,\n RunAggregationQueryRequest as ProtoRunAggregationQueryRequest,\n RunAggregationQueryResponse as ProtoRunAggregationQueryResponse,\n RunQueryRequest as ProtoRunQueryRequest,\n RunQueryResponse as ProtoRunQueryResponse,\n Value\n} from '../protos/firestore_proto_api';\nimport { debugAssert, debugCast, hardAssert } from '../util/assert';\nimport { AsyncQueue } from '../util/async_queue';\nimport { Code, FirestoreError } from '../util/error';\nimport { isNullOrUndefined } from '../util/types';\n\nimport { Connection } from './connection';\nimport {\n PersistentListenStream,\n PersistentWriteStream,\n WatchStreamListener,\n WriteStreamListener\n} from './persistent_stream';\nimport {\n fromDocument,\n fromBatchGetDocumentsResponse,\n JsonProtoSerializer,\n toMutation,\n toName,\n toQueryTarget,\n toResourcePath,\n toRunAggregationQueryRequest\n} from './serializer';\n\n/**\n * Datastore and its related methods are a wrapper around the external Google\n * Cloud Datastore grpc API, which provides an interface that is more convenient\n * for the rest of the client SDK architecture to consume.\n */\nexport abstract class Datastore {\n abstract terminate(): void;\n abstract serializer: JsonProtoSerializer;\n}\n\n/**\n * An implementation of Datastore that exposes additional state for internal\n * consumption.\n */\nclass DatastoreImpl extends Datastore {\n terminated = false;\n\n constructor(\n readonly authCredentials: CredentialsProvider,\n readonly appCheckCredentials: CredentialsProvider,\n readonly connection: Connection,\n readonly serializer: JsonProtoSerializer\n ) {\n super();\n }\n\n verifyInitialized(): void {\n debugAssert(!!this.connection, 'Datastore.start() not called');\n if (this.terminated) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'The client has already been terminated.'\n );\n }\n }\n\n /** Invokes the provided RPC with auth and AppCheck tokens. */\n invokeRPC(\n rpcName: string,\n databaseId: DatabaseId,\n resourcePath: ResourcePath,\n request: Req\n ): Promise {\n this.verifyInitialized();\n return Promise.all([\n this.authCredentials.getToken(),\n this.appCheckCredentials.getToken()\n ])\n .then(([authToken, appCheckToken]) => {\n return this.connection.invokeRPC(\n rpcName,\n toResourcePath(databaseId, resourcePath),\n request,\n authToken,\n appCheckToken\n );\n })\n .catch((error: FirestoreError) => {\n if (error.name === 'FirebaseError') {\n if (error.code === Code.UNAUTHENTICATED) {\n this.authCredentials.invalidateToken();\n this.appCheckCredentials.invalidateToken();\n }\n throw error;\n } else {\n throw new FirestoreError(Code.UNKNOWN, error.toString());\n }\n });\n }\n\n /** Invokes the provided RPC with streamed results with auth and AppCheck tokens. */\n invokeStreamingRPC(\n rpcName: string,\n databaseId: DatabaseId,\n resourcePath: ResourcePath,\n request: Req,\n expectedResponseCount?: number\n ): Promise {\n this.verifyInitialized();\n return Promise.all([\n this.authCredentials.getToken(),\n this.appCheckCredentials.getToken()\n ])\n .then(([authToken, appCheckToken]) => {\n return this.connection.invokeStreamingRPC(\n rpcName,\n toResourcePath(databaseId, resourcePath),\n request,\n authToken,\n appCheckToken,\n expectedResponseCount\n );\n })\n .catch((error: FirestoreError) => {\n if (error.name === 'FirebaseError') {\n if (error.code === Code.UNAUTHENTICATED) {\n this.authCredentials.invalidateToken();\n this.appCheckCredentials.invalidateToken();\n }\n throw error;\n } else {\n throw new FirestoreError(Code.UNKNOWN, error.toString());\n }\n });\n }\n\n terminate(): void {\n this.terminated = true;\n this.connection.terminate();\n }\n}\n\n// TODO(firestorexp): Make sure there is only one Datastore instance per\n// firestore-exp client.\nexport function newDatastore(\n authCredentials: CredentialsProvider,\n appCheckCredentials: CredentialsProvider,\n connection: Connection,\n serializer: JsonProtoSerializer\n): Datastore {\n return new DatastoreImpl(\n authCredentials,\n appCheckCredentials,\n connection,\n serializer\n );\n}\n\nexport async function invokeCommitRpc(\n datastore: Datastore,\n mutations: Mutation[]\n): Promise {\n const datastoreImpl = debugCast(datastore, DatastoreImpl);\n const request = {\n writes: mutations.map(m => toMutation(datastoreImpl.serializer, m))\n };\n await datastoreImpl.invokeRPC(\n 'Commit',\n datastoreImpl.serializer.databaseId,\n ResourcePath.emptyPath(),\n request\n );\n}\n\nexport async function invokeBatchGetDocumentsRpc(\n datastore: Datastore,\n keys: DocumentKey[]\n): Promise {\n const datastoreImpl = debugCast(datastore, DatastoreImpl);\n const request = {\n documents: keys.map(k => toName(datastoreImpl.serializer, k))\n };\n const response = await datastoreImpl.invokeStreamingRPC<\n ProtoBatchGetDocumentsRequest,\n ProtoBatchGetDocumentsResponse\n >(\n 'BatchGetDocuments',\n datastoreImpl.serializer.databaseId,\n ResourcePath.emptyPath(),\n request,\n keys.length\n );\n\n const docs = new Map();\n response.forEach(proto => {\n const doc = fromBatchGetDocumentsResponse(datastoreImpl.serializer, proto);\n docs.set(doc.key.toString(), doc);\n });\n const result: Document[] = [];\n keys.forEach(key => {\n const doc = docs.get(key.toString());\n hardAssert(!!doc, 0xd7c2, 'Missing entity in write response for `key`', {\n key\n });\n result.push(doc);\n });\n return result;\n}\n\nexport async function invokeRunQueryRpc(\n datastore: Datastore,\n query: Query\n): Promise {\n const datastoreImpl = debugCast(datastore, DatastoreImpl);\n const { queryTarget, parent } = toQueryTarget(\n datastoreImpl.serializer,\n queryToTarget(query)\n );\n const response = await datastoreImpl.invokeStreamingRPC<\n ProtoRunQueryRequest,\n ProtoRunQueryResponse\n >('RunQuery', datastoreImpl.serializer.databaseId, parent, {\n structuredQuery: queryTarget.structuredQuery\n });\n return (\n response\n // Omit RunQueryResponses that only contain readTimes.\n .filter(proto => !!proto.document)\n .map(proto =>\n fromDocument(datastoreImpl.serializer, proto.document!, undefined)\n )\n );\n}\n\nexport async function invokeRunAggregationQueryRpc(\n datastore: Datastore,\n query: Query,\n aggregates: Aggregate[]\n): Promise> {\n const datastoreImpl = debugCast(datastore, DatastoreImpl);\n const { request, aliasMap, parent } = toRunAggregationQueryRequest(\n datastoreImpl.serializer,\n queryToAggregateTarget(query),\n aggregates\n );\n\n if (!datastoreImpl.connection.shouldResourcePathBeIncludedInRequest) {\n delete request.parent;\n }\n const response = await datastoreImpl.invokeStreamingRPC<\n ProtoRunAggregationQueryRequest,\n ProtoRunAggregationQueryResponse\n >(\n 'RunAggregationQuery',\n datastoreImpl.serializer.databaseId,\n parent,\n request,\n /*expectedResponseCount=*/ 1\n );\n\n // Omit RunAggregationQueryResponse that only contain readTimes.\n const filteredResult = response.filter(proto => !!proto.result);\n\n hardAssert(\n filteredResult.length === 1,\n 0xfcd7,\n 'Aggregation fields are missing from result.'\n );\n debugAssert(\n !isNullOrUndefined(filteredResult[0].result),\n 'aggregationQueryResponse.result'\n );\n debugAssert(\n !isNullOrUndefined(filteredResult[0].result.aggregateFields),\n 'aggregationQueryResponse.result.aggregateFields'\n );\n\n // Remap the short-form aliases that were sent to the server\n // to the client-side aliases. Users will access the results\n // using the client-side alias.\n const unmappedAggregateFields = filteredResult[0].result?.aggregateFields;\n const remappedFields = Object.keys(unmappedAggregateFields).reduce<\n ApiClientObjectMap\n >((accumulator, key) => {\n debugAssert(\n !isNullOrUndefined(aliasMap[key]),\n `'${key}' not present in aliasMap result`\n );\n accumulator[aliasMap[key]] = unmappedAggregateFields[key]!;\n return accumulator;\n }, {});\n\n return remappedFields;\n}\n\nexport function newPersistentWriteStream(\n datastore: Datastore,\n queue: AsyncQueue,\n listener: WriteStreamListener\n): PersistentWriteStream {\n const datastoreImpl = debugCast(datastore, DatastoreImpl);\n datastoreImpl.verifyInitialized();\n return new PersistentWriteStream(\n queue,\n datastoreImpl.connection,\n datastoreImpl.authCredentials,\n datastoreImpl.appCheckCredentials,\n datastoreImpl.serializer,\n listener\n );\n}\n\nexport function newPersistentWatchStream(\n datastore: Datastore,\n queue: AsyncQueue,\n listener: WatchStreamListener\n): PersistentListenStream {\n const datastoreImpl = debugCast(datastore, DatastoreImpl);\n datastoreImpl.verifyInitialized();\n return new PersistentListenStream(\n queue,\n datastoreImpl.connection,\n datastoreImpl.authCredentials,\n datastoreImpl.appCheckCredentials,\n datastoreImpl.serializer,\n listener\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport { _FirebaseService } from '@firebase/app';\n\nimport { CredentialsProvider } from '../api/credentials';\nimport { cloneLongPollingOptions } from '../api/long_polling_options';\nimport { User } from '../auth/user';\nimport { DatabaseId, DatabaseInfo } from '../core/database_info';\nimport { newConnection } from '../platform/connection';\nimport { newSerializer } from '../platform/serializer';\nimport { Datastore, newDatastore } from '../remote/datastore';\nimport { Code, FirestoreError } from '../util/error';\nimport { logDebug } from '../util/log';\n\nimport { FirestoreSettingsImpl } from './settings';\n\nexport const LOG_TAG = 'ComponentProvider';\n\n// The components module manages the lifetime of dependencies of the Firestore\n// client. Dependencies can be lazily constructed and only one exists per\n// Firestore instance.\n\n/**\n * An interface implemented by FirebaseFirestore that provides compatibility\n * with the usage in this file.\n *\n * This interface mainly exists to remove a cyclic dependency.\n */\nexport interface FirestoreService extends _FirebaseService {\n _authCredentials: CredentialsProvider;\n _appCheckCredentials: CredentialsProvider;\n _persistenceKey: string;\n _databaseId: DatabaseId;\n _terminated: boolean;\n\n _freezeSettings(): FirestoreSettingsImpl;\n}\n/**\n * An instance map that ensures only one Datastore exists per Firestore\n * instance.\n */\nconst datastoreInstances = new Map();\n\n/**\n * Returns an initialized and started Datastore for the given Firestore\n * instance. Callers must invoke removeComponents() when the Firestore\n * instance is terminated.\n */\nexport function getDatastore(firestore: FirestoreService): Datastore {\n if (firestore._terminated) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'The client has already been terminated.'\n );\n }\n if (!datastoreInstances.has(firestore)) {\n logDebug(LOG_TAG, 'Initializing Datastore');\n const databaseInfo = makeDatabaseInfo(\n firestore._databaseId,\n firestore.app.options.appId || '',\n firestore._persistenceKey,\n firestore._freezeSettings()\n );\n const connection = newConnection(databaseInfo);\n const serializer = newSerializer(firestore._databaseId);\n const datastore = newDatastore(\n firestore._authCredentials,\n firestore._appCheckCredentials,\n connection,\n serializer\n );\n\n datastoreInstances.set(firestore, datastore);\n }\n return datastoreInstances.get(firestore)!;\n}\n\n/**\n * Removes all components associated with the provided instance. Must be called\n * when the `Firestore` instance is terminated.\n */\nexport function removeComponents(firestore: FirestoreService): void {\n const datastore = datastoreInstances.get(firestore);\n if (datastore) {\n logDebug(LOG_TAG, 'Removing Datastore');\n datastoreInstances.delete(firestore);\n datastore.terminate();\n }\n}\n\nexport function makeDatabaseInfo(\n databaseId: DatabaseId,\n appId: string,\n persistenceKey: string,\n settings: FirestoreSettingsImpl\n): DatabaseInfo {\n return new DatabaseInfo(\n databaseId,\n appId,\n persistenceKey,\n settings.host,\n settings.ssl,\n settings.experimentalForceLongPolling,\n settings.experimentalAutoDetectLongPolling,\n cloneLongPollingOptions(settings.experimentalLongPollingOptions),\n settings.useFetchStreams,\n settings.isUsingEmulator\n );\n}\n","/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ListenSequenceNumber, TargetId } from '../core/types';\nimport { SortedMap } from '../util/sorted_map';\n\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { TargetData } from './target_data';\n\n/**\n * Describes a map whose keys are active target ids. We do not care about the type of the\n * values.\n */\nexport type ActiveTargets = SortedMap;\n\nexport const GC_DID_NOT_RUN: LruResults = {\n didRun: false,\n sequenceNumbersCollected: 0,\n targetsRemoved: 0,\n documentsRemoved: 0\n};\n\nexport const LRU_COLLECTION_DISABLED = -1;\nexport const LRU_DEFAULT_CACHE_SIZE_BYTES = 40 * 1024 * 1024;\n\nexport class LruParams {\n private static readonly DEFAULT_COLLECTION_PERCENTILE = 10;\n private static readonly DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT = 1000;\n\n static withCacheSize(cacheSize: number): LruParams {\n return new LruParams(\n cacheSize,\n LruParams.DEFAULT_COLLECTION_PERCENTILE,\n LruParams.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT\n );\n }\n\n static readonly DEFAULT: LruParams = new LruParams(\n LRU_DEFAULT_CACHE_SIZE_BYTES,\n LruParams.DEFAULT_COLLECTION_PERCENTILE,\n LruParams.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT\n );\n\n static readonly DISABLED: LruParams = new LruParams(\n LRU_COLLECTION_DISABLED,\n 0,\n 0\n );\n\n constructor(\n // When we attempt to collect, we will only do so if the cache size is greater than this\n // threshold. Passing `COLLECTION_DISABLED` here will cause collection to always be skipped.\n readonly cacheSizeCollectionThreshold: number,\n // The percentage of sequence numbers that we will attempt to collect\n readonly percentileToCollect: number,\n // A cap on the total number of sequence numbers that will be collected. This prevents\n // us from collecting a huge number of sequence numbers if the cache has grown very large.\n readonly maximumSequenceNumbersToCollect: number\n ) {}\n}\n\nexport interface LruGarbageCollector {\n readonly params: LruParams;\n\n collect(\n txn: PersistenceTransaction,\n activeTargetIds: ActiveTargets\n ): PersistencePromise;\n\n /** Given a percentile of target to collect, returns the number of targets to collect. */\n calculateTargetCount(\n txn: PersistenceTransaction,\n percentile: number\n ): PersistencePromise;\n\n /** Returns the nth sequence number, counting in order from the smallest. */\n nthSequenceNumber(\n txn: PersistenceTransaction,\n n: number\n ): PersistencePromise;\n\n /**\n * Removes documents that have a sequence number equal to or less than the\n * upper bound and are not otherwise pinned.\n */\n removeOrphanedDocuments(\n txn: PersistenceTransaction,\n upperBound: ListenSequenceNumber\n ): PersistencePromise;\n\n getCacheSize(txn: PersistenceTransaction): PersistencePromise;\n\n /**\n * Removes targets with a sequence number equal to or less than the given\n * upper bound, and removes document associations with those targets.\n */\n removeTargets(\n txn: PersistenceTransaction,\n upperBound: ListenSequenceNumber,\n activeTargetIds: ActiveTargets\n ): PersistencePromise;\n}\n\n/**\n * Describes the results of a garbage collection run. `didRun` will be set to\n * `false` if collection was skipped (either it is disabled or the cache size\n * has not hit the threshold). If collection ran, the other fields will be\n * filled in with the details of the results.\n */\nexport interface LruResults {\n readonly didRun: boolean;\n readonly sequenceNumbersCollected: number;\n readonly targetsRemoved: number;\n readonly documentsRemoved: number;\n}\n\n/**\n * Persistence layers intending to use LRU Garbage collection should have\n * reference delegates that implement this interface. This interface defines the\n * operations that the LRU garbage collector needs from the persistence layer.\n */\nexport interface LruDelegate {\n readonly garbageCollector: LruGarbageCollector;\n\n /** Enumerates all the targets in the TargetCache. */\n forEachTarget(\n txn: PersistenceTransaction,\n f: (target: TargetData) => void\n ): PersistencePromise;\n\n getSequenceNumberCount(\n txn: PersistenceTransaction\n ): PersistencePromise;\n\n /**\n * Enumerates sequence numbers for documents not associated with a target.\n * Note that this may include duplicate sequence numbers.\n */\n forEachOrphanedDocumentSequenceNumber(\n txn: PersistenceTransaction,\n f: (sequenceNumber: ListenSequenceNumber) => void\n ): PersistencePromise;\n\n /**\n * Removes all targets that have a sequence number less than or equal to\n * `upperBound`, and are not present in the `activeTargetIds` set.\n *\n * @returns the number of targets removed.\n */\n removeTargets(\n txn: PersistenceTransaction,\n upperBound: ListenSequenceNumber,\n activeTargetIds: ActiveTargets\n ): PersistencePromise;\n\n /**\n * Removes all unreferenced documents from the cache that have a sequence\n * number less than or equal to the given `upperBound`.\n *\n * @returns the number of documents removed.\n */\n removeOrphanedDocuments(\n txn: PersistenceTransaction,\n upperBound: ListenSequenceNumber\n ): PersistencePromise;\n\n getCacheSize(txn: PersistenceTransaction): PersistencePromise;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getGlobal, getUA, isIndexedDBAvailable } from '@firebase/util';\n\nimport { debugAssert } from '../util/assert';\nimport { Code, FirestoreError } from '../util/error';\nimport { logDebug, logError } from '../util/log';\nimport { Deferred } from '../util/promise';\n\nimport { PersistencePromise } from './persistence_promise';\n\n// References to `indexedDB` are guarded by SimpleDb.isAvailable() and getGlobal()\n/* eslint-disable no-restricted-globals */\n\nconst LOG_TAG = 'SimpleDb';\n\n/**\n * The maximum number of retry attempts for an IndexedDb transaction that fails\n * with a DOMException.\n */\nconst TRANSACTION_RETRY_COUNT = 3;\n\n// The different modes supported by `SimpleDb.runTransaction()`\ntype SimpleDbTransactionMode = 'readonly' | 'readwrite';\n\nexport interface SimpleDbSchemaConverter {\n createOrUpgrade(\n db: IDBDatabase,\n txn: IDBTransaction,\n fromVersion: number,\n toVersion: number\n ): PersistencePromise;\n}\n\n/**\n * Wraps an IDBTransaction and exposes a store() method to get a handle to a\n * specific object store.\n */\nexport class SimpleDbTransaction {\n private aborted = false;\n\n /**\n * A `Promise` that resolves with the result of the IndexedDb transaction.\n */\n private readonly completionDeferred = new Deferred();\n\n static open(\n db: IDBDatabase,\n action: string,\n mode: IDBTransactionMode,\n objectStoreNames: string[]\n ): SimpleDbTransaction {\n try {\n return new SimpleDbTransaction(\n action,\n db.transaction(objectStoreNames, mode)\n );\n } catch (e) {\n throw new IndexedDbTransactionError(action, e as Error);\n }\n }\n\n constructor(\n private readonly action: string,\n private readonly transaction: IDBTransaction\n ) {\n this.transaction.oncomplete = () => {\n this.completionDeferred.resolve();\n };\n this.transaction.onabort = () => {\n if (transaction.error) {\n this.completionDeferred.reject(\n new IndexedDbTransactionError(action, transaction.error)\n );\n } else {\n this.completionDeferred.resolve();\n }\n };\n this.transaction.onerror = (event: Event) => {\n const error = checkForAndReportiOSError(\n (event.target as IDBRequest).error!\n );\n this.completionDeferred.reject(\n new IndexedDbTransactionError(action, error)\n );\n };\n }\n\n get completionPromise(): Promise {\n return this.completionDeferred.promise;\n }\n\n abort(error?: Error): void {\n if (error) {\n this.completionDeferred.reject(error);\n }\n\n if (!this.aborted) {\n logDebug(\n LOG_TAG,\n 'Aborting transaction:',\n error ? error.message : 'Client-initiated abort'\n );\n this.aborted = true;\n this.transaction.abort();\n }\n }\n\n maybeCommit(): void {\n // If the browser supports V3 IndexedDB, we invoke commit() explicitly to\n // speed up index DB processing if the event loop remains blocks.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const maybeV3IndexedDb = this.transaction as any;\n if (!this.aborted && typeof maybeV3IndexedDb.commit === 'function') {\n maybeV3IndexedDb.commit();\n }\n }\n\n /**\n * Returns a SimpleDbStore for the specified store. All\n * operations performed on the SimpleDbStore happen within the context of this\n * transaction and it cannot be used anymore once the transaction is\n * completed.\n *\n * Note that we can't actually enforce that the KeyType and ValueType are\n * correct, but they allow type safety through the rest of the consuming code.\n */\n store(\n storeName: string\n ): SimpleDbStore {\n const store = this.transaction.objectStore(storeName);\n debugAssert(!!store, 'Object store not part of transaction: ' + storeName);\n return new SimpleDbStore(store);\n }\n}\n\n/**\n * Provides a wrapper around IndexedDb with a simplified interface that uses\n * Promise-like return values to chain operations. Real promises cannot be used\n * since .then() continuations are executed asynchronously (e.g. via\n * .setImmediate), which would cause IndexedDB to end the transaction.\n * See PersistencePromise for more details.\n */\nexport class SimpleDb {\n private db?: IDBDatabase;\n private lastClosedDbVersion: number | null = null;\n private versionchangelistener?: (event: IDBVersionChangeEvent) => void;\n\n /** Deletes the specified database. */\n static delete(name: string): Promise {\n logDebug(LOG_TAG, 'Removing database:', name);\n const globals = getGlobal();\n return wrapRequest(\n globals.indexedDB.deleteDatabase(name)\n ).toPromise();\n }\n\n /** Returns true if IndexedDB is available in the current environment. */\n static isAvailable(): boolean {\n if (!isIndexedDBAvailable()) {\n return false;\n }\n\n if (SimpleDb.isMockPersistence()) {\n return true;\n }\n\n // We extensively use indexed array values and compound keys,\n // which IE and Edge do not support. However, they still have indexedDB\n // defined on the window, so we need to check for them here and make sure\n // to return that persistence is not enabled for those browsers.\n // For tracking support of this feature, see here:\n // https://developer.microsoft.com/en-us/microsoft-edge/platform/status/indexeddbarraysandmultientrysupport/\n\n // Check the UA string to find out the browser.\n const ua = getUA();\n\n // IE 10\n // ua = 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)';\n\n // IE 11\n // ua = 'Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko';\n\n // Edge\n // ua = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML,\n // like Gecko) Chrome/39.0.2171.71 Safari/537.36 Edge/12.0';\n\n // iOS Safari: Disable for users running iOS version < 10.\n const iOSVersion = SimpleDb.getIOSVersion(ua);\n const isUnsupportedIOS = 0 < iOSVersion && iOSVersion < 10;\n\n // Android browser: Disable for users running version < 4.5.\n const androidVersion = getAndroidVersion(ua);\n const isUnsupportedAndroid = 0 < androidVersion && androidVersion < 4.5;\n\n if (\n ua.indexOf('MSIE ') > 0 ||\n ua.indexOf('Trident/') > 0 ||\n ua.indexOf('Edge/') > 0 ||\n isUnsupportedIOS ||\n isUnsupportedAndroid\n ) {\n return false;\n } else {\n return true;\n }\n }\n\n /**\n * Returns true if the backing IndexedDB store is the Node IndexedDBShim\n * (see https://github.com/axemclion/IndexedDBShim).\n */\n static isMockPersistence(): boolean {\n return (\n typeof process !== 'undefined' &&\n process.env?.USE_MOCK_PERSISTENCE === 'YES'\n );\n }\n\n /** Helper to get a typed SimpleDbStore from a transaction. */\n static getStore(\n txn: SimpleDbTransaction,\n store: string\n ): SimpleDbStore {\n return txn.store(store);\n }\n\n // visible for testing\n /** Parse User Agent to determine iOS version. Returns -1 if not found. */\n static getIOSVersion(ua: string): number {\n const iOSVersionRegex = ua.match(/i(?:phone|pad|pod) os ([\\d_]+)/i);\n const version = iOSVersionRegex\n ? iOSVersionRegex[1].split('_').slice(0, 2).join('.')\n : '-1';\n return Number(version);\n }\n\n /*\n * Creates a new SimpleDb wrapper for IndexedDb database `name`.\n *\n * Note that `version` must not be a downgrade. IndexedDB does not support\n * downgrading the schema version. We currently do not support any way to do\n * versioning outside of IndexedDB's versioning mechanism, as only\n * version-upgrade transactions are allowed to do things like create\n * objectstores.\n */\n constructor(\n private readonly name: string,\n private readonly version: number,\n private readonly schemaConverter: SimpleDbSchemaConverter\n ) {\n debugAssert(\n SimpleDb.isAvailable(),\n 'IndexedDB not supported in current environment.'\n );\n\n const iOSVersion = SimpleDb.getIOSVersion(getUA());\n // NOTE: According to https://bugs.webkit.org/show_bug.cgi?id=197050, the\n // bug we're checking for should exist in iOS >= 12.2 and < 13, but for\n // whatever reason it's much harder to hit after 12.2 so we only proactively\n // log on 12.2.\n if (iOSVersion === 12.2) {\n logError(\n 'Firestore persistence suffers from a bug in iOS 12.2 ' +\n 'Safari that may cause your app to stop working. See ' +\n 'https://stackoverflow.com/q/56496296/110915 for details ' +\n 'and a potential workaround.'\n );\n }\n }\n\n /**\n * Opens the specified database, creating or upgrading it if necessary.\n */\n async ensureDb(action: string): Promise {\n if (!this.db) {\n logDebug(LOG_TAG, 'Opening database:', this.name);\n this.db = await new Promise((resolve, reject) => {\n // TODO(mikelehen): Investigate browser compatibility.\n // https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API/Using_IndexedDB\n // suggests IE9 and older WebKit browsers handle upgrade\n // differently. They expect setVersion, as described here:\n // https://developer.mozilla.org/en-US/docs/Web/API/IDBVersionChangeRequest/setVersion\n const request = indexedDB.open(this.name, this.version);\n\n request.onsuccess = (event: Event) => {\n const db = (event.target as IDBOpenDBRequest).result;\n resolve(db);\n };\n\n request.onblocked = () => {\n reject(\n new IndexedDbTransactionError(\n action,\n 'Cannot upgrade IndexedDB schema while another tab is open. ' +\n 'Close all tabs that access Firestore and reload this page to proceed.'\n )\n );\n };\n\n request.onerror = (event: Event) => {\n const error: DOMException = (event.target as IDBOpenDBRequest).error!;\n if (error.name === 'VersionError') {\n reject(\n new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'A newer version of the Firestore SDK was previously used and so the persisted ' +\n 'data is not compatible with the version of the SDK you are now using. The SDK ' +\n 'will operate with persistence disabled. If you need persistence, please ' +\n 're-upgrade to a newer version of the SDK or else clear the persisted IndexedDB ' +\n 'data for your app to start fresh.'\n )\n );\n } else if (error.name === 'InvalidStateError') {\n reject(\n new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'Unable to open an IndexedDB connection. This could be due to running in a ' +\n 'private browsing session on a browser whose private browsing sessions do not ' +\n 'support IndexedDB: ' +\n error\n )\n );\n } else {\n reject(new IndexedDbTransactionError(action, error));\n }\n };\n\n request.onupgradeneeded = (event: IDBVersionChangeEvent) => {\n logDebug(\n LOG_TAG,\n 'Database \"' + this.name + '\" requires upgrade from version:',\n event.oldVersion\n );\n const db = (event.target as IDBOpenDBRequest).result;\n this.schemaConverter\n .createOrUpgrade(\n db,\n request.transaction!,\n event.oldVersion,\n this.version\n )\n .next(() => {\n logDebug(\n LOG_TAG,\n 'Database upgrade to version ' + this.version + ' complete'\n );\n });\n };\n });\n }\n\n if (this.versionchangelistener) {\n this.db.onversionchange = event => this.versionchangelistener!(event);\n }\n\n return this.db;\n }\n\n setVersionChangeListener(\n versionChangeListener: (event: IDBVersionChangeEvent) => void\n ): void {\n this.versionchangelistener = versionChangeListener;\n if (this.db) {\n this.db.onversionchange = (event: IDBVersionChangeEvent) => {\n return versionChangeListener(event);\n };\n }\n }\n\n async runTransaction(\n action: string,\n mode: SimpleDbTransactionMode,\n objectStores: string[],\n transactionFn: (transaction: SimpleDbTransaction) => PersistencePromise\n ): Promise {\n const readonly = mode === 'readonly';\n let attemptNumber = 0;\n\n while (true) {\n ++attemptNumber;\n\n try {\n this.db = await this.ensureDb(action);\n\n const transaction = SimpleDbTransaction.open(\n this.db,\n action,\n readonly ? 'readonly' : 'readwrite',\n objectStores\n );\n const transactionFnResult = transactionFn(transaction)\n .next(result => {\n transaction.maybeCommit();\n return result;\n })\n .catch(error => {\n // Abort the transaction if there was an error.\n transaction.abort(error);\n // We cannot actually recover, and calling `abort()` will cause the transaction's\n // completion promise to be rejected. This in turn means that we won't use\n // `transactionFnResult` below. We return a rejection here so that we don't add the\n // possibility of returning `void` to the type of `transactionFnResult`.\n return PersistencePromise.reject(error);\n })\n .toPromise();\n\n // As noted above, errors are propagated by aborting the transaction. So\n // we swallow any error here to avoid the browser logging it as unhandled.\n transactionFnResult.catch(() => {});\n\n // Wait for the transaction to complete (i.e. IndexedDb's onsuccess event to\n // fire), but still return the original transactionFnResult back to the\n // caller.\n await transaction.completionPromise;\n return transactionFnResult;\n } catch (e) {\n const error = e as Error;\n // TODO(schmidt-sebastian): We could probably be smarter about this and\n // not retry exceptions that are likely unrecoverable (such as quota\n // exceeded errors).\n\n // Note: We cannot use an instanceof check for FirestoreException, since the\n // exception is wrapped in a generic error by our async/await handling.\n const retryable =\n error.name !== 'FirebaseError' &&\n attemptNumber < TRANSACTION_RETRY_COUNT;\n logDebug(\n LOG_TAG,\n 'Transaction failed with error:',\n error.message,\n 'Retrying:',\n retryable\n );\n\n this.close();\n\n if (!retryable) {\n return Promise.reject(error);\n }\n }\n }\n }\n\n close(): void {\n if (this.db) {\n this.db.close();\n }\n this.db = undefined;\n }\n}\n\n/** Parse User Agent to determine Android version. Returns -1 if not found. */\nexport function getAndroidVersion(ua: string): number {\n const androidVersionRegex = ua.match(/Android ([\\d.]+)/i);\n const version = androidVersionRegex\n ? androidVersionRegex[1].split('.').slice(0, 2).join('.')\n : '-1';\n return Number(version);\n}\n\n/**\n * A controller for iterating over a key range or index. It allows an iterate\n * callback to delete the currently-referenced object, or jump to a new key\n * within the key range or index.\n */\nexport class IterationController {\n private shouldStop = false;\n private nextKey: IDBValidKey | null = null;\n\n constructor(private dbCursor: IDBCursorWithValue) {}\n\n get isDone(): boolean {\n return this.shouldStop;\n }\n\n get skipToKey(): IDBValidKey | null {\n return this.nextKey;\n }\n\n set cursor(value: IDBCursorWithValue) {\n this.dbCursor = value;\n }\n\n /**\n * This function can be called to stop iteration at any point.\n */\n done(): void {\n this.shouldStop = true;\n }\n\n /**\n * This function can be called to skip to that next key, which could be\n * an index or a primary key.\n */\n skip(key: IDBValidKey): void {\n this.nextKey = key;\n }\n\n /**\n * Delete the current cursor value from the object store.\n *\n * NOTE: You CANNOT do this with a keysOnly query.\n */\n delete(): PersistencePromise {\n return wrapRequest(this.dbCursor.delete());\n }\n}\n\n/**\n * Callback used with iterate() method.\n */\nexport type IterateCallback = (\n key: KeyType,\n value: ValueType,\n control: IterationController\n) => void | PersistencePromise;\n\n/** Options available to the iterate() method. */\nexport interface IterateOptions {\n /** Index to iterate over (else primary keys will be iterated) */\n index?: string;\n\n /** IndexedDB Range to iterate over (else entire store will be iterated) */\n range?: IDBKeyRange;\n\n /** If true, values aren't read while iterating. */\n keysOnly?: boolean;\n\n /** If true, iterate over the store in reverse. */\n reverse?: boolean;\n}\n\n/** An error that wraps exceptions that thrown during IndexedDB execution. */\nexport class IndexedDbTransactionError extends FirestoreError {\n name = 'IndexedDbTransactionError';\n\n constructor(actionName: string, cause: Error | string) {\n super(\n Code.UNAVAILABLE,\n `IndexedDB transaction '${actionName}' failed: ${cause}`\n );\n }\n}\n\n/** Verifies whether `e` is an IndexedDbTransactionError. */\nexport function isIndexedDbTransactionError(e: Error): boolean {\n // Use name equality, as instanceof checks on errors don't work with errors\n // that wrap other errors.\n return e.name === 'IndexedDbTransactionError';\n}\n\n/**\n * A wrapper around an IDBObjectStore providing an API that:\n *\n * 1) Has generic KeyType / ValueType parameters to provide strongly-typed\n * methods for acting against the object store.\n * 2) Deals with IndexedDB's onsuccess / onerror event callbacks, making every\n * method return a PersistencePromise instead.\n * 3) Provides a higher-level API to avoid needing to do excessive wrapping of\n * intermediate IndexedDB types (IDBCursorWithValue, etc.)\n */\nexport class SimpleDbStore<\n KeyType extends IDBValidKey,\n ValueType extends unknown\n> {\n constructor(private store: IDBObjectStore) {}\n\n /**\n * Writes a value into the Object Store.\n *\n * @param key - Optional explicit key to use when writing the object, else the\n * key will be auto-assigned (e.g. via the defined keyPath for the store).\n * @param value - The object to write.\n */\n put(value: ValueType): PersistencePromise;\n put(key: KeyType, value: ValueType): PersistencePromise;\n put(\n keyOrValue: KeyType | ValueType,\n value?: ValueType\n ): PersistencePromise {\n let request;\n if (value !== undefined) {\n logDebug(LOG_TAG, 'PUT', this.store.name, keyOrValue, value);\n request = this.store.put(value, keyOrValue as KeyType);\n } else {\n logDebug(LOG_TAG, 'PUT', this.store.name, '', keyOrValue);\n request = this.store.put(keyOrValue as ValueType);\n }\n return wrapRequest(request);\n }\n\n /**\n * Adds a new value into an Object Store and returns the new key. Similar to\n * IndexedDb's `add()`, this method will fail on primary key collisions.\n *\n * @param value - The object to write.\n * @returns The key of the value to add.\n */\n add(value: ValueType): PersistencePromise {\n logDebug(LOG_TAG, 'ADD', this.store.name, value, value);\n const request = this.store.add(value as ValueType);\n return wrapRequest(request);\n }\n\n /**\n * Gets the object with the specified key from the specified store, or null\n * if no object exists with the specified key.\n *\n * @key The key of the object to get.\n * @returns The object with the specified key or null if no object exists.\n */\n get(key: KeyType): PersistencePromise {\n const request = this.store.get(key);\n // We're doing an unsafe cast to ValueType.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return wrapRequest(request).next(result => {\n // Normalize nonexistence to null.\n if (result === undefined) {\n result = null;\n }\n logDebug(LOG_TAG, 'GET', this.store.name, key, result);\n return result;\n });\n }\n\n delete(key: KeyType | IDBKeyRange): PersistencePromise {\n logDebug(LOG_TAG, 'DELETE', this.store.name, key);\n const request = this.store.delete(key);\n return wrapRequest(request);\n }\n\n /**\n * If we ever need more of the count variants, we can add overloads. For now,\n * all we need is to count everything in a store.\n *\n * Returns the number of rows in the store.\n */\n count(): PersistencePromise {\n logDebug(LOG_TAG, 'COUNT', this.store.name);\n const request = this.store.count();\n return wrapRequest(request);\n }\n\n /** Loads all elements from the object store. */\n loadAll(): PersistencePromise;\n /** Loads all elements for the index range from the object store. */\n loadAll(range: IDBKeyRange): PersistencePromise;\n /** Loads all elements ordered by the given index. */\n loadAll(index: string): PersistencePromise;\n /**\n * Loads all elements from the object store that fall into the provided in the\n * index range for the given index.\n */\n loadAll(index: string, range: IDBKeyRange): PersistencePromise;\n loadAll(\n indexOrRange?: string | IDBKeyRange,\n range?: IDBKeyRange\n ): PersistencePromise {\n const iterateOptions = this.options(indexOrRange, range);\n // Use `getAll()` if the browser supports IndexedDB v3, as it is roughly\n // 20% faster.\n const store = iterateOptions.index\n ? this.store.index(iterateOptions.index)\n : this.store;\n if (typeof store.getAll === 'function') {\n const request = store.getAll(iterateOptions.range);\n return new PersistencePromise((resolve, reject) => {\n request.onerror = (event: Event) => {\n reject((event.target as IDBRequest).error!);\n };\n request.onsuccess = (event: Event) => {\n resolve((event.target as IDBRequest).result);\n };\n });\n } else {\n const cursor = this.cursor(iterateOptions);\n const results: ValueType[] = [];\n return this.iterateCursor(cursor, (key, value) => {\n results.push(value);\n }).next(() => {\n return results;\n });\n }\n }\n\n /**\n * Loads the first `count` elements from the provided index range. Loads all\n * elements if no limit is provided.\n */\n loadFirst(\n range: IDBKeyRange,\n count: number | null\n ): PersistencePromise {\n const request = this.store.getAll(\n range,\n count === null ? undefined : count\n );\n return new PersistencePromise((resolve, reject) => {\n request.onerror = (event: Event) => {\n reject((event.target as IDBRequest).error!);\n };\n request.onsuccess = (event: Event) => {\n resolve((event.target as IDBRequest).result);\n };\n });\n }\n\n deleteAll(): PersistencePromise;\n deleteAll(range: IDBKeyRange): PersistencePromise;\n deleteAll(index: string, range: IDBKeyRange): PersistencePromise;\n deleteAll(\n indexOrRange?: string | IDBKeyRange,\n range?: IDBKeyRange\n ): PersistencePromise {\n logDebug(LOG_TAG, 'DELETE ALL', this.store.name);\n const options = this.options(indexOrRange, range);\n options.keysOnly = false;\n const cursor = this.cursor(options);\n return this.iterateCursor(cursor, (key, value, control) => {\n // NOTE: Calling delete() on a cursor is documented as more efficient than\n // calling delete() on an object store with a single key\n // (https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/delete),\n // however, this requires us *not* to use a keysOnly cursor\n // (https://developer.mozilla.org/en-US/docs/Web/API/IDBCursor/delete). We\n // may want to compare the performance of each method.\n return control.delete();\n });\n }\n\n /**\n * Iterates over keys and values in an object store.\n *\n * @param options - Options specifying how to iterate the objects in the\n * store.\n * @param callback - will be called for each iterated object. Iteration can be\n * canceled at any point by calling the doneFn passed to the callback.\n * The callback can return a PersistencePromise if it performs async\n * operations but note that iteration will continue without waiting for them\n * to complete.\n * @returns A PersistencePromise that resolves once all PersistencePromises\n * returned by callbacks resolve.\n */\n iterate(\n callback: IterateCallback\n ): PersistencePromise;\n iterate(\n options: IterateOptions,\n callback: IterateCallback\n ): PersistencePromise;\n iterate(\n optionsOrCallback: IterateOptions | IterateCallback,\n callback?: IterateCallback\n ): PersistencePromise {\n let options;\n if (!callback) {\n options = {};\n callback = optionsOrCallback as IterateCallback;\n } else {\n options = optionsOrCallback as IterateOptions;\n }\n const cursor = this.cursor(options);\n return this.iterateCursor(cursor, callback);\n }\n\n /**\n * Iterates over a store, but waits for the given callback to complete for\n * each entry before iterating the next entry. This allows the callback to do\n * asynchronous work to determine if this iteration should continue.\n *\n * The provided callback should return `true` to continue iteration, and\n * `false` otherwise.\n */\n iterateSerial(\n callback: (k: KeyType, v: ValueType) => PersistencePromise\n ): PersistencePromise {\n const cursorRequest = this.cursor({});\n return new PersistencePromise((resolve, reject) => {\n cursorRequest.onerror = (event: Event) => {\n const error = checkForAndReportiOSError(\n (event.target as IDBRequest).error!\n );\n reject(error);\n };\n cursorRequest.onsuccess = (event: Event) => {\n const cursor: IDBCursorWithValue = (event.target as IDBRequest).result;\n if (!cursor) {\n resolve();\n return;\n }\n\n callback(cursor.primaryKey as KeyType, cursor.value).next(\n shouldContinue => {\n if (shouldContinue) {\n cursor.continue();\n } else {\n resolve();\n }\n }\n );\n };\n });\n }\n\n private iterateCursor(\n cursorRequest: IDBRequest,\n fn: IterateCallback\n ): PersistencePromise {\n const results: Array> = [];\n return new PersistencePromise((resolve, reject) => {\n cursorRequest.onerror = (event: Event) => {\n reject((event.target as IDBRequest).error!);\n };\n cursorRequest.onsuccess = (event: Event) => {\n const cursor: IDBCursorWithValue = (event.target as IDBRequest).result;\n if (!cursor) {\n resolve();\n return;\n }\n const controller = new IterationController(cursor);\n const userResult = fn(\n cursor.primaryKey as KeyType,\n cursor.value,\n controller\n );\n if (userResult instanceof PersistencePromise) {\n const userPromise: PersistencePromise = userResult.catch(\n err => {\n controller.done();\n return PersistencePromise.reject(err);\n }\n );\n results.push(userPromise);\n }\n if (controller.isDone) {\n resolve();\n } else if (controller.skipToKey === null) {\n cursor.continue();\n } else {\n cursor.continue(controller.skipToKey);\n }\n };\n }).next(() => PersistencePromise.waitFor(results));\n }\n\n private options(\n indexOrRange?: string | IDBKeyRange,\n range?: IDBKeyRange\n ): IterateOptions {\n let indexName: string | undefined = undefined;\n if (indexOrRange !== undefined) {\n if (typeof indexOrRange === 'string') {\n indexName = indexOrRange;\n } else {\n debugAssert(\n range === undefined,\n '3rd argument must not be defined if 2nd is a range.'\n );\n range = indexOrRange;\n }\n }\n return { index: indexName, range };\n }\n\n private cursor(options: IterateOptions): IDBRequest {\n let direction: IDBCursorDirection = 'next';\n if (options.reverse) {\n direction = 'prev';\n }\n if (options.index) {\n const index = this.store.index(options.index);\n if (options.keysOnly) {\n return index.openKeyCursor(options.range, direction);\n } else {\n return index.openCursor(options.range, direction);\n }\n } else {\n return this.store.openCursor(options.range, direction);\n }\n }\n}\n\n/**\n * Wraps an IDBRequest in a PersistencePromise, using the onsuccess / onerror\n * handlers to resolve / reject the PersistencePromise as appropriate.\n */\nfunction wrapRequest(request: IDBRequest): PersistencePromise {\n return new PersistencePromise((resolve, reject) => {\n request.onsuccess = (event: Event) => {\n const result = (event.target as IDBRequest).result;\n resolve(result);\n };\n\n request.onerror = (event: Event) => {\n const error = checkForAndReportiOSError(\n (event.target as IDBRequest).error!\n );\n reject(error);\n };\n });\n}\n\n// Guard so we only report the error once.\nlet reportedIOSError = false;\nfunction checkForAndReportiOSError(error: DOMException): Error {\n const iOSVersion = SimpleDb.getIOSVersion(getUA());\n if (iOSVersion >= 12.2 && iOSVersion < 13) {\n const IOS_ERROR =\n 'An internal error was encountered in the Indexed Database server';\n if (error.message.indexOf(IOS_ERROR) >= 0) {\n // Wrap error in a more descriptive one.\n const newError = new FirestoreError(\n 'internal',\n `IOS_INDEXEDDB_BUG1: IndexedDb has thrown '${IOS_ERROR}'. This is likely ` +\n `due to an unavoidable bug in iOS. See https://stackoverflow.com/q/56496296/110915 ` +\n `for details and a potential workaround.`\n );\n if (!reportedIOSError) {\n reportedIOSError = true;\n // Throw a global exception outside of this promise chain, for the user to\n // potentially catch.\n setTimeout(() => {\n throw newError;\n }, 0);\n }\n return newError;\n }\n }\n return error;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirestoreError } from '../api';\nimport { ListenSequence } from '../core/listen_sequence';\nimport { ListenSequenceNumber } from '../core/types';\nimport { debugAssert } from '../util/assert';\nimport { AsyncQueue, DelayedOperation, TimerId } from '../util/async_queue';\nimport { getLogLevel, logDebug, LogLevel } from '../util/log';\nimport { primitiveComparator } from '../util/misc';\nimport { SortedSet } from '../util/sorted_set';\n\nimport { ignoreIfPrimaryLeaseLoss, LocalStore } from './local_store';\nimport {\n ActiveTargets,\n GC_DID_NOT_RUN,\n LRU_COLLECTION_DISABLED,\n LruDelegate,\n LruGarbageCollector,\n LruParams,\n LruResults\n} from './lru_garbage_collector';\nimport { Scheduler } from './persistence';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { isIndexedDbTransactionError } from './simple_db';\n\nconst LOG_TAG = 'LruGarbageCollector';\n\nexport const LRU_MINIMUM_CACHE_SIZE_BYTES = 1 * 1024 * 1024;\n\n/** How long we wait to try running LRU GC after SDK initialization. */\nconst INITIAL_GC_DELAY_MS = 1 * 60 * 1000;\n/** Minimum amount of time between GC checks, after the first one. */\nconst REGULAR_GC_DELAY_MS = 5 * 60 * 1000;\n\n// The type and comparator for the items contained in the SortedSet used in\n// place of a priority queue for the RollingSequenceNumberBuffer.\ntype BufferEntry = [ListenSequenceNumber, number];\n\nfunction bufferEntryComparator(\n [aSequence, aIndex]: BufferEntry,\n [bSequence, bIndex]: BufferEntry\n): number {\n const seqCmp = primitiveComparator(aSequence, bSequence);\n if (seqCmp === 0) {\n // This order doesn't matter, but we can bias against churn by sorting\n // entries created earlier as less than newer entries.\n return primitiveComparator(aIndex, bIndex);\n } else {\n return seqCmp;\n }\n}\n\n/**\n * Used to calculate the nth sequence number. Keeps a rolling buffer of the\n * lowest n values passed to `addElement`, and finally reports the largest of\n * them in `maxValue`.\n */\nclass RollingSequenceNumberBuffer {\n private buffer: SortedSet = new SortedSet(\n bufferEntryComparator\n );\n\n private previousIndex = 0;\n\n constructor(private readonly maxElements: number) {}\n\n private nextIndex(): number {\n return ++this.previousIndex;\n }\n\n addElement(sequenceNumber: ListenSequenceNumber): void {\n const entry: BufferEntry = [sequenceNumber, this.nextIndex()];\n if (this.buffer.size < this.maxElements) {\n this.buffer = this.buffer.add(entry);\n } else {\n const highestValue = this.buffer.last()!;\n if (bufferEntryComparator(entry, highestValue) < 0) {\n this.buffer = this.buffer.delete(highestValue).add(entry);\n }\n }\n }\n\n get maxValue(): ListenSequenceNumber {\n // Guaranteed to be non-empty. If we decide we are not collecting any\n // sequence numbers, nthSequenceNumber below short-circuits. If we have\n // decided that we are collecting n sequence numbers, it's because n is some\n // percentage of the existing sequence numbers. That means we should never\n // be in a situation where we are collecting sequence numbers but don't\n // actually have any.\n return this.buffer.last()![0];\n }\n}\n\n/**\n * This class is responsible for the scheduling of LRU garbage collection. It handles checking\n * whether or not GC is enabled, as well as which delay to use before the next run.\n */\nexport class LruScheduler implements Scheduler {\n private gcTask: DelayedOperation | null;\n\n constructor(\n private readonly garbageCollector: LruGarbageCollector,\n private readonly asyncQueue: AsyncQueue,\n private readonly localStore: LocalStore\n ) {\n this.gcTask = null;\n }\n\n start(): void {\n debugAssert(\n this.gcTask === null,\n 'Cannot start an already started LruScheduler'\n );\n if (\n this.garbageCollector.params.cacheSizeCollectionThreshold !==\n LRU_COLLECTION_DISABLED\n ) {\n this.scheduleGC(INITIAL_GC_DELAY_MS);\n }\n }\n\n stop(): void {\n if (this.gcTask) {\n this.gcTask.cancel();\n this.gcTask = null;\n }\n }\n\n get started(): boolean {\n return this.gcTask !== null;\n }\n\n private scheduleGC(delay: number): void {\n debugAssert(\n this.gcTask === null,\n 'Cannot schedule GC while a task is pending'\n );\n logDebug(LOG_TAG, `Garbage collection scheduled in ${delay}ms`);\n this.gcTask = this.asyncQueue.enqueueAfterDelay(\n TimerId.LruGarbageCollection,\n delay,\n async () => {\n this.gcTask = null;\n try {\n await this.localStore.collectGarbage(this.garbageCollector);\n } catch (e) {\n if (isIndexedDbTransactionError(e as Error)) {\n logDebug(\n LOG_TAG,\n 'Ignoring IndexedDB error during garbage collection: ',\n e\n );\n } else {\n await ignoreIfPrimaryLeaseLoss(e as FirestoreError);\n }\n }\n await this.scheduleGC(REGULAR_GC_DELAY_MS);\n }\n );\n }\n}\n\n/**\n * Implements the steps for LRU garbage collection.\n */\nclass LruGarbageCollectorImpl implements LruGarbageCollector {\n constructor(\n private readonly delegate: LruDelegate,\n readonly params: LruParams\n ) {}\n\n calculateTargetCount(\n txn: PersistenceTransaction,\n percentile: number\n ): PersistencePromise {\n return this.delegate.getSequenceNumberCount(txn).next(targetCount => {\n return Math.floor((percentile / 100.0) * targetCount);\n });\n }\n\n nthSequenceNumber(\n txn: PersistenceTransaction,\n n: number\n ): PersistencePromise {\n if (n === 0) {\n return PersistencePromise.resolve(ListenSequence.INVALID);\n }\n\n const buffer = new RollingSequenceNumberBuffer(n);\n return this.delegate\n .forEachTarget(txn, target => buffer.addElement(target.sequenceNumber))\n .next(() => {\n return this.delegate.forEachOrphanedDocumentSequenceNumber(\n txn,\n sequenceNumber => buffer.addElement(sequenceNumber)\n );\n })\n .next(() => buffer.maxValue);\n }\n\n removeTargets(\n txn: PersistenceTransaction,\n upperBound: ListenSequenceNumber,\n activeTargetIds: ActiveTargets\n ): PersistencePromise {\n return this.delegate.removeTargets(txn, upperBound, activeTargetIds);\n }\n\n removeOrphanedDocuments(\n txn: PersistenceTransaction,\n upperBound: ListenSequenceNumber\n ): PersistencePromise {\n return this.delegate.removeOrphanedDocuments(txn, upperBound);\n }\n\n collect(\n txn: PersistenceTransaction,\n activeTargetIds: ActiveTargets\n ): PersistencePromise {\n if (this.params.cacheSizeCollectionThreshold === LRU_COLLECTION_DISABLED) {\n logDebug('LruGarbageCollector', 'Garbage collection skipped; disabled');\n return PersistencePromise.resolve(GC_DID_NOT_RUN);\n }\n\n return this.getCacheSize(txn).next(cacheSize => {\n if (cacheSize < this.params.cacheSizeCollectionThreshold) {\n logDebug(\n 'LruGarbageCollector',\n `Garbage collection skipped; Cache size ${cacheSize} ` +\n `is lower than threshold ${this.params.cacheSizeCollectionThreshold}`\n );\n return GC_DID_NOT_RUN;\n } else {\n return this.runGarbageCollection(txn, activeTargetIds);\n }\n });\n }\n\n getCacheSize(txn: PersistenceTransaction): PersistencePromise {\n return this.delegate.getCacheSize(txn);\n }\n\n private runGarbageCollection(\n txn: PersistenceTransaction,\n activeTargetIds: ActiveTargets\n ): PersistencePromise {\n let upperBoundSequenceNumber: number;\n let sequenceNumbersToCollect: number, targetsRemoved: number;\n // Timestamps for various pieces of the process\n let countedTargetsTs: number,\n foundUpperBoundTs: number,\n removedTargetsTs: number,\n removedDocumentsTs: number;\n const startTs = Date.now();\n return this.calculateTargetCount(txn, this.params.percentileToCollect)\n .next(sequenceNumbers => {\n // Cap at the configured max\n if (sequenceNumbers > this.params.maximumSequenceNumbersToCollect) {\n logDebug(\n 'LruGarbageCollector',\n 'Capping sequence numbers to collect down ' +\n `to the maximum of ${this.params.maximumSequenceNumbersToCollect} ` +\n `from ${sequenceNumbers}`\n );\n sequenceNumbersToCollect =\n this.params.maximumSequenceNumbersToCollect;\n } else {\n sequenceNumbersToCollect = sequenceNumbers;\n }\n countedTargetsTs = Date.now();\n\n return this.nthSequenceNumber(txn, sequenceNumbersToCollect);\n })\n .next(upperBound => {\n upperBoundSequenceNumber = upperBound;\n foundUpperBoundTs = Date.now();\n\n return this.removeTargets(\n txn,\n upperBoundSequenceNumber,\n activeTargetIds\n );\n })\n .next(numTargetsRemoved => {\n targetsRemoved = numTargetsRemoved;\n removedTargetsTs = Date.now();\n\n return this.removeOrphanedDocuments(txn, upperBoundSequenceNumber);\n })\n .next(documentsRemoved => {\n removedDocumentsTs = Date.now();\n\n if (getLogLevel() <= LogLevel.DEBUG) {\n const desc =\n 'LRU Garbage Collection\\n' +\n `\\tCounted targets in ${countedTargetsTs - startTs}ms\\n` +\n `\\tDetermined least recently used ${sequenceNumbersToCollect} in ` +\n `${foundUpperBoundTs - countedTargetsTs}ms\\n` +\n `\\tRemoved ${targetsRemoved} targets in ` +\n `${removedTargetsTs - foundUpperBoundTs}ms\\n` +\n `\\tRemoved ${documentsRemoved} documents in ` +\n `${removedDocumentsTs - removedTargetsTs}ms\\n` +\n `Total Duration: ${removedDocumentsTs - startTs}ms`;\n logDebug('LruGarbageCollector', desc);\n }\n\n return PersistencePromise.resolve({\n didRun: true,\n sequenceNumbersCollected: sequenceNumbersToCollect,\n targetsRemoved,\n documentsRemoved\n });\n });\n }\n}\n\nexport function newLruGarbageCollector(\n delegate: LruDelegate,\n params: LruParams\n): LruGarbageCollector {\n return new LruGarbageCollectorImpl(delegate, params);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { EmulatorMockTokenOptions } from '@firebase/util';\n\nimport { FirestoreLocalCache } from '../api/cache_config';\nimport { CredentialsSettings } from '../api/credentials';\nimport {\n ExperimentalLongPollingOptions,\n cloneLongPollingOptions,\n longPollingOptionsEqual\n} from '../api/long_polling_options';\nimport {\n LRU_COLLECTION_DISABLED,\n LRU_DEFAULT_CACHE_SIZE_BYTES\n} from '../local/lru_garbage_collector';\nimport { LRU_MINIMUM_CACHE_SIZE_BYTES } from '../local/lru_garbage_collector_impl';\nimport { Code, FirestoreError } from '../util/error';\nimport { validateIsNotUsedTogether } from '../util/input_validation';\n\n// settings() defaults:\nexport const DEFAULT_HOST = 'firestore.googleapis.com';\nexport const DEFAULT_SSL = true;\n\n// The minimum long-polling timeout is hardcoded on the server. The value here\n// should be kept in sync with the value used by the server, as the server will\n// silently ignore a value below the minimum and fall back to the default.\n// Googlers see b/266868871 for relevant discussion.\nconst MIN_LONG_POLLING_TIMEOUT_SECONDS = 5;\n\n// No maximum long-polling timeout is configured in the server, and defaults to\n// 30 seconds, which is what Watch appears to use.\n// Googlers see b/266868871 for relevant discussion.\nconst MAX_LONG_POLLING_TIMEOUT_SECONDS = 30;\n\n// Whether long-polling auto-detected is enabled by default.\nconst DEFAULT_AUTO_DETECT_LONG_POLLING = true;\n\n/**\n * Specifies custom configurations for your Cloud Firestore instance.\n * You must set these before invoking any other methods.\n */\nexport interface FirestoreSettings {\n /** The hostname to connect to. */\n host?: string;\n\n /** Whether to use SSL when connecting. */\n ssl?: boolean;\n\n /**\n * Whether to skip nested properties that are set to `undefined` during\n * object serialization. If set to `true`, these properties are skipped\n * and not written to Firestore. If set to `false` or omitted, the SDK\n * throws an exception when it encounters properties of type `undefined`.\n */\n ignoreUndefinedProperties?: boolean;\n}\n\n/**\n * @internal\n * Undocumented, private additional settings not exposed in our public API.\n */\nexport interface PrivateSettings extends FirestoreSettings {\n // Can be a google-auth-library or gapi client.\n credentials?: CredentialsSettings;\n cacheSizeBytes?: number;\n experimentalForceLongPolling?: boolean;\n experimentalAutoDetectLongPolling?: boolean;\n experimentalLongPollingOptions?: ExperimentalLongPollingOptions;\n useFetchStreams?: boolean;\n emulatorOptions?: { mockUserToken?: EmulatorMockTokenOptions | string };\n\n localCache?: FirestoreLocalCache;\n}\n\n/**\n * A concrete type describing all the values that can be applied via a\n * user-supplied `FirestoreSettings` object. This is a separate type so that\n * defaults can be supplied and the value can be checked for equality.\n */\nexport class FirestoreSettingsImpl {\n /** The hostname to connect to. */\n readonly host: string;\n\n /** Whether to use SSL when connecting. */\n readonly ssl: boolean;\n\n readonly cacheSizeBytes: number;\n\n readonly experimentalForceLongPolling: boolean;\n\n readonly experimentalAutoDetectLongPolling: boolean;\n\n readonly experimentalLongPollingOptions: ExperimentalLongPollingOptions;\n\n readonly ignoreUndefinedProperties: boolean;\n\n readonly useFetchStreams: boolean;\n readonly localCache?: FirestoreLocalCache;\n\n readonly isUsingEmulator: boolean;\n\n // Can be a google-auth-library or gapi client.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n credentials?: any;\n\n constructor(settings: PrivateSettings) {\n if (settings.host === undefined) {\n if (settings.ssl !== undefined) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n \"Can't provide ssl option if host option is not set\"\n );\n }\n this.host = DEFAULT_HOST;\n this.ssl = DEFAULT_SSL;\n } else {\n this.host = settings.host;\n this.ssl = settings.ssl ?? DEFAULT_SSL;\n }\n this.isUsingEmulator = settings.emulatorOptions !== undefined;\n\n this.credentials = settings.credentials;\n this.ignoreUndefinedProperties = !!settings.ignoreUndefinedProperties;\n this.localCache = settings.localCache;\n\n if (settings.cacheSizeBytes === undefined) {\n this.cacheSizeBytes = LRU_DEFAULT_CACHE_SIZE_BYTES;\n } else {\n if (\n settings.cacheSizeBytes !== LRU_COLLECTION_DISABLED &&\n settings.cacheSizeBytes < LRU_MINIMUM_CACHE_SIZE_BYTES\n ) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `cacheSizeBytes must be at least ${LRU_MINIMUM_CACHE_SIZE_BYTES}`\n );\n } else {\n this.cacheSizeBytes = settings.cacheSizeBytes;\n }\n }\n\n validateIsNotUsedTogether(\n 'experimentalForceLongPolling',\n settings.experimentalForceLongPolling,\n 'experimentalAutoDetectLongPolling',\n settings.experimentalAutoDetectLongPolling\n );\n\n this.experimentalForceLongPolling = !!settings.experimentalForceLongPolling;\n\n if (this.experimentalForceLongPolling) {\n this.experimentalAutoDetectLongPolling = false;\n } else if (settings.experimentalAutoDetectLongPolling === undefined) {\n this.experimentalAutoDetectLongPolling = DEFAULT_AUTO_DETECT_LONG_POLLING;\n } else {\n // For backwards compatibility, coerce the value to boolean even though\n // the TypeScript compiler has narrowed the type to boolean already.\n // noinspection PointlessBooleanExpressionJS\n this.experimentalAutoDetectLongPolling =\n !!settings.experimentalAutoDetectLongPolling;\n }\n\n this.experimentalLongPollingOptions = cloneLongPollingOptions(\n settings.experimentalLongPollingOptions ?? {}\n );\n validateLongPollingOptions(this.experimentalLongPollingOptions);\n\n this.useFetchStreams = !!settings.useFetchStreams;\n }\n\n isEqual(other: FirestoreSettingsImpl): boolean {\n return (\n this.host === other.host &&\n this.ssl === other.ssl &&\n this.credentials === other.credentials &&\n this.cacheSizeBytes === other.cacheSizeBytes &&\n this.experimentalForceLongPolling ===\n other.experimentalForceLongPolling &&\n this.experimentalAutoDetectLongPolling ===\n other.experimentalAutoDetectLongPolling &&\n longPollingOptionsEqual(\n this.experimentalLongPollingOptions,\n other.experimentalLongPollingOptions\n ) &&\n this.ignoreUndefinedProperties === other.ignoreUndefinedProperties &&\n this.useFetchStreams === other.useFetchStreams\n );\n }\n}\n\nfunction validateLongPollingOptions(\n options: ExperimentalLongPollingOptions\n): void {\n if (options.timeoutSeconds !== undefined) {\n if (isNaN(options.timeoutSeconds)) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `invalid long polling timeout: ` +\n `${options.timeoutSeconds} (must not be NaN)`\n );\n }\n if (options.timeoutSeconds < MIN_LONG_POLLING_TIMEOUT_SECONDS) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `invalid long polling timeout: ${options.timeoutSeconds} ` +\n `(minimum allowed value is ${MIN_LONG_POLLING_TIMEOUT_SECONDS})`\n );\n }\n if (options.timeoutSeconds > MAX_LONG_POLLING_TIMEOUT_SECONDS) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `invalid long polling timeout: ${options.timeoutSeconds} ` +\n `(maximum allowed value is ${MAX_LONG_POLLING_TIMEOUT_SECONDS})`\n );\n }\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport {\n _getProvider,\n _removeServiceInstance,\n FirebaseApp,\n getApp\n} from '@firebase/app';\nimport {\n createMockUserToken,\n deepEqual,\n EmulatorMockTokenOptions,\n getDefaultEmulatorHostnameAndPort,\n isCloudWorkstation,\n pingServer,\n updateEmulatorBanner\n} from '@firebase/util';\n\nimport {\n CredentialsProvider,\n EmulatorAuthCredentialsProvider,\n makeAuthCredentialsProvider,\n OAuthToken\n} from '../api/credentials';\nimport { User } from '../auth/user';\nimport { DatabaseId, DEFAULT_DATABASE_NAME } from '../core/database_info';\nimport { Code, FirestoreError } from '../util/error';\nimport { cast } from '../util/input_validation';\nimport { logWarn } from '../util/log';\n\nimport { FirestoreService, removeComponents } from './components';\nimport {\n DEFAULT_HOST,\n FirestoreSettingsImpl,\n PrivateSettings,\n FirestoreSettings\n} from './settings';\n\nexport { EmulatorMockTokenOptions } from '@firebase/util';\n\ndeclare module '@firebase/component' {\n interface NameServiceMapping {\n 'firestore/lite': Firestore;\n }\n}\n\n/**\n * The Cloud Firestore service interface.\n *\n * Do not call this constructor directly. Instead, use {@link (getFirestore:1)}.\n */\nexport class Firestore implements FirestoreService {\n /**\n * Whether it's a Firestore or Firestore Lite instance.\n */\n type: 'firestore-lite' | 'firestore' = 'firestore-lite';\n\n readonly _persistenceKey: string = '(lite)';\n\n private _settings = new FirestoreSettingsImpl({});\n private _settingsFrozen = false;\n private _emulatorOptions: {\n mockUserToken?: EmulatorMockTokenOptions | string;\n } = {};\n\n // A task that is assigned when the terminate() is invoked and resolved when\n // all components have shut down. Otherwise, Firestore is not terminated,\n // which can mean either the FirestoreClient is in the process of starting,\n // or restarting.\n private _terminateTask: Promise | 'notTerminated' = 'notTerminated';\n\n /** @hideconstructor */\n constructor(\n public _authCredentials: CredentialsProvider,\n public _appCheckCredentials: CredentialsProvider,\n readonly _databaseId: DatabaseId,\n readonly _app?: FirebaseApp\n ) {}\n\n /**\n * The {@link @firebase/app#FirebaseApp} associated with this `Firestore` service\n * instance.\n */\n get app(): FirebaseApp {\n if (!this._app) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n \"Firestore was not initialized using the Firebase SDK. 'app' is \" +\n 'not available'\n );\n }\n return this._app;\n }\n\n get _initialized(): boolean {\n return this._settingsFrozen;\n }\n\n get _terminated(): boolean {\n return this._terminateTask !== 'notTerminated';\n }\n\n _setSettings(settings: PrivateSettings): void {\n if (this._settingsFrozen) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'Firestore has already been started and its settings can no longer ' +\n 'be changed. You can only modify settings before calling any other ' +\n 'methods on a Firestore object.'\n );\n }\n this._settings = new FirestoreSettingsImpl(settings);\n this._emulatorOptions = settings.emulatorOptions || {};\n\n if (settings.credentials !== undefined) {\n this._authCredentials = makeAuthCredentialsProvider(settings.credentials);\n }\n }\n\n _getSettings(): FirestoreSettingsImpl {\n return this._settings;\n }\n\n _getEmulatorOptions(): { mockUserToken?: EmulatorMockTokenOptions | string } {\n return this._emulatorOptions;\n }\n\n _freezeSettings(): FirestoreSettingsImpl {\n this._settingsFrozen = true;\n return this._settings;\n }\n\n _delete(): Promise {\n // The `_terminateTask` must be assigned future that completes when\n // terminate is complete. The existence of this future puts SDK in state\n // that will not accept further API interaction.\n if (this._terminateTask === 'notTerminated') {\n this._terminateTask = this._terminate();\n }\n return this._terminateTask;\n }\n\n async _restart(): Promise {\n // The `_terminateTask` must equal 'notTerminated' after restart to\n // signal that client is in a state that accepts API calls.\n if (this._terminateTask === 'notTerminated') {\n await this._terminate();\n } else {\n this._terminateTask = 'notTerminated';\n }\n }\n\n /** Returns a JSON-serializable representation of this `Firestore` instance. */\n toJSON(): object {\n return {\n app: this._app,\n databaseId: this._databaseId,\n settings: this._settings\n };\n }\n\n /**\n * Terminates all components used by this client. Subclasses can override\n * this method to clean up their own dependencies, but must also call this\n * method.\n *\n * Only ever called once.\n */\n protected _terminate(): Promise {\n removeComponents(this);\n return Promise.resolve();\n }\n}\n\n/**\n * Initializes a new instance of Cloud Firestore with the provided settings.\n * Can only be called before any other functions, including\n * {@link (getFirestore:1)}. If the custom settings are empty, this function is\n * equivalent to calling {@link (getFirestore:1)}.\n *\n * @param app - The {@link @firebase/app#FirebaseApp} with which the `Firestore` instance will\n * be associated.\n * @param settings - A settings object to configure the `Firestore` instance.\n * @returns A newly initialized `Firestore` instance.\n */\nexport function initializeFirestore(\n app: FirebaseApp,\n settings: FirestoreSettings\n): Firestore;\n/**\n * Initializes a new instance of Cloud Firestore with the provided settings.\n * Can only be called before any other functions, including\n * {@link (getFirestore:1)}. If the custom settings are empty, this function is\n * equivalent to calling {@link (getFirestore:1)}.\n *\n * @param app - The {@link @firebase/app#FirebaseApp} with which the `Firestore` instance will\n * be associated.\n * @param settings - A settings object to configure the `Firestore` instance.\n * @param databaseId - The name of the database.\n * @returns A newly initialized `Firestore` instance.\n * @beta\n */\nexport function initializeFirestore(\n app: FirebaseApp,\n settings: FirestoreSettings,\n databaseId?: string\n): Firestore;\nexport function initializeFirestore(\n app: FirebaseApp,\n settings: FirestoreSettings,\n databaseId?: string\n): Firestore {\n if (!databaseId) {\n databaseId = DEFAULT_DATABASE_NAME;\n }\n const provider = _getProvider(app, 'firestore/lite');\n\n if (provider.isInitialized(databaseId)) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'Firestore can only be initialized once per app.'\n );\n }\n\n return provider.initialize({\n options: settings,\n instanceIdentifier: databaseId\n });\n}\n\n/**\n * Returns the existing default {@link Firestore} instance that is associated with the\n * default {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new\n * instance with default settings.\n *\n * @returns The {@link Firestore} instance of the provided app.\n */\nexport function getFirestore(): Firestore;\n/**\n * Returns the existing default {@link Firestore} instance that is associated with the\n * provided {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new\n * instance with default settings.\n *\n * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned {@link Firestore}\n * instance is associated with.\n * @returns The {@link Firestore} instance of the provided app.\n */\nexport function getFirestore(app: FirebaseApp): Firestore;\n/**\n * Returns the existing {@link Firestore} instance that is associated with the\n * default {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new\n * instance with default settings.\n *\n * @param databaseId - The name of the database.\n * @returns The {@link Firestore} instance of the provided app.\n * @beta\n */\nexport function getFirestore(databaseId: string): Firestore;\n/**\n * Returns the existing {@link Firestore} instance that is associated with the\n * provided {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new\n * instance with default settings.\n *\n * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned {@link Firestore}\n * instance is associated with.\n * @param databaseId - The name of the database.\n * @returns The {@link Firestore} instance of the provided app.\n * @beta\n */\nexport function getFirestore(app: FirebaseApp, databaseId: string): Firestore;\nexport function getFirestore(\n appOrDatabaseId?: FirebaseApp | string,\n optionalDatabaseId?: string\n): Firestore {\n const app: FirebaseApp =\n typeof appOrDatabaseId === 'object' ? appOrDatabaseId : getApp();\n const databaseId =\n typeof appOrDatabaseId === 'string'\n ? appOrDatabaseId\n : optionalDatabaseId || '(default)';\n const db = _getProvider(app, 'firestore/lite').getImmediate({\n identifier: databaseId\n }) as Firestore;\n if (!db._initialized) {\n const emulator = getDefaultEmulatorHostnameAndPort('firestore');\n if (emulator) {\n connectFirestoreEmulator(db, ...emulator);\n }\n }\n return db;\n}\n\n/**\n * Modify this instance to communicate with the Cloud Firestore emulator.\n *\n * Note: This must be called before this instance has been used to do any\n * operations.\n *\n * @param firestore - The `Firestore` instance to configure to connect to the\n * emulator.\n * @param host - the emulator host (ex: localhost).\n * @param port - the emulator port (ex: 9000).\n * @param options.mockUserToken - the mock auth token to use for unit testing\n * Security Rules.\n */\nexport function connectFirestoreEmulator(\n firestore: Firestore,\n host: string,\n port: number,\n options: {\n mockUserToken?: EmulatorMockTokenOptions | string;\n } = {}\n): void {\n firestore = cast(firestore, Firestore);\n const useSsl = isCloudWorkstation(host);\n const settings = firestore._getSettings();\n const existingConfig = {\n ...settings,\n emulatorOptions: firestore._getEmulatorOptions()\n };\n const newHostSetting = `${host}:${port}`;\n if (useSsl) {\n void pingServer(`https://${newHostSetting}`);\n updateEmulatorBanner('Firestore', true);\n }\n if (settings.host !== DEFAULT_HOST && settings.host !== newHostSetting) {\n logWarn(\n 'Host has been set in both settings() and connectFirestoreEmulator(), emulator host ' +\n 'will be used.'\n );\n }\n const newConfig = {\n ...settings,\n host: newHostSetting,\n ssl: useSsl,\n emulatorOptions: options\n };\n // No-op if the new configuration matches the current configuration. This supports SSR\n // enviornments which might call `connectFirestoreEmulator` multiple times as a standard practice.\n if (deepEqual(newConfig, existingConfig)) {\n return;\n }\n\n firestore._setSettings(newConfig);\n\n if (options.mockUserToken) {\n let token: string;\n let user: User;\n if (typeof options.mockUserToken === 'string') {\n token = options.mockUserToken;\n user = User.MOCK_USER;\n } else {\n // Let createMockUserToken validate first (catches common mistakes like\n // invalid field \"uid\" and missing field \"sub\" / \"user_id\".)\n token = createMockUserToken(\n options.mockUserToken,\n firestore._app?.options.projectId\n );\n const uid = options.mockUserToken.sub || options.mockUserToken.user_id;\n if (!uid) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n \"mockUserToken must contain 'sub' or 'user_id' field!\"\n );\n }\n user = new User(uid);\n }\n\n firestore._authCredentials = new EmulatorAuthCredentialsProvider(\n new OAuthToken(token, user)\n );\n }\n}\n\n/**\n * Terminates the provided `Firestore` instance.\n *\n * After calling `terminate()` only the `clearIndexedDbPersistence()` functions\n * may be used. Any other function will throw a `FirestoreError`. Termination\n * does not cancel any pending writes, and any promises that are awaiting a\n * response from the server will not be resolved.\n *\n * To restart after termination, create a new instance of `Firestore` with\n * {@link (getFirestore:1)}.\n *\n * Note: Under normal circumstances, calling `terminate()` is not required. This\n * function is useful only when you want to force this instance to release all of\n * its resources or in combination with {@link clearIndexedDbPersistence} to\n * ensure that all local state is destroyed between test runs.\n *\n * @param firestore - The `Firestore` instance to terminate.\n * @returns A `Promise` that is resolved when the instance has been successfully\n * terminated.\n */\nexport function terminate(firestore: Firestore): Promise {\n firestore = cast(firestore, Firestore);\n _removeServiceInstance(firestore.app, 'firestore/lite');\n return firestore._delete();\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n _registerComponent,\n registerVersion,\n SDK_VERSION\n} from '@firebase/app';\nimport { Component, ComponentType } from '@firebase/component';\n\nimport { version } from '../package.json';\nimport {\n LiteAppCheckTokenProvider,\n LiteAuthCredentialsProvider\n} from '../src/api/credentials';\nimport { databaseIdFromApp } from '../src/core/database_info';\nimport { setSDKVersion } from '../src/core/version';\nimport { Firestore } from '../src/lite-api/database';\n\ndeclare module '@firebase/component' {\n interface NameServiceMapping {\n 'firestore/lite': Firestore;\n }\n}\n\nexport function registerFirestore(): void {\n setSDKVersion(`${SDK_VERSION}_lite`);\n _registerComponent(\n new Component(\n 'firestore/lite',\n (container, { instanceIdentifier: databaseId, options: settings }) => {\n const app = container.getProvider('app').getImmediate()!;\n const firestoreInstance = new Firestore(\n new LiteAuthCredentialsProvider(\n container.getProvider('auth-internal')\n ),\n new LiteAppCheckTokenProvider(\n app,\n container.getProvider('app-check-internal')\n ),\n databaseIdFromApp(app, databaseId),\n app\n );\n if (settings) {\n firestoreInstance._setSettings(settings);\n }\n return firestoreInstance;\n },\n 'PUBLIC' as ComponentType.PUBLIC\n ).setMultipleInstances(true)\n );\n // RUNTIME_ENV and BUILD_TARGET are replaced by real values during the compilation\n registerVersion('firestore-lite', version, '__RUNTIME_ENV__');\n registerVersion('firestore-lite', version, '__BUILD_TARGET__');\n}\n","/**\n * @license\n * Copyright 2023 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FieldPath } from '../model/path';\n\n/**\n * Union type representing the aggregate type to be performed.\n */\nexport type AggregateType = 'count' | 'avg' | 'sum';\n\n/**\n * Represents an Aggregate to be performed over a query result set.\n */\nexport interface Aggregate {\n readonly fieldPath?: FieldPath;\n readonly alias: string;\n readonly aggregateType: AggregateType;\n}\n\n/**\n * Concrete implementation of the Aggregate type.\n */\nexport class AggregateImpl implements Aggregate {\n constructor(\n readonly alias: string,\n readonly aggregateType: AggregateType,\n readonly fieldPath?: FieldPath\n ) {}\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { AggregateType } from '../core/aggregate';\nimport { FieldPath as InternalFieldPath } from '../model/path';\nimport { ApiClientObjectMap, Value } from '../protos/firestore_proto_api';\n\nimport { average, count, sum } from './aggregate';\nimport { DocumentData, Query } from './reference';\nimport { AbstractUserDataWriter } from './user_data_writer';\n\nexport { AggregateType };\n\n/**\n * Represents an aggregation that can be performed by Firestore.\n */\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport class AggregateField {\n /** A type string to uniquely identify instances of this class. */\n readonly type = 'AggregateField';\n\n /** Indicates the aggregation operation of this AggregateField. */\n readonly aggregateType: AggregateType;\n\n /**\n * Create a new AggregateField\n * @param aggregateType Specifies the type of aggregation operation to perform.\n * @param _internalFieldPath Optionally specifies the field that is aggregated.\n * @internal\n */\n constructor(\n aggregateType: AggregateType = 'count',\n readonly _internalFieldPath?: InternalFieldPath\n ) {\n this.aggregateType = aggregateType;\n }\n}\n\n/**\n * The union of all `AggregateField` types that are supported by Firestore.\n */\nexport type AggregateFieldType =\n | ReturnType\n | ReturnType\n | ReturnType;\n\n/**\n * Specifies a set of aggregations and their aliases.\n */\nexport interface AggregateSpec {\n [field: string]: AggregateFieldType;\n}\n\n/**\n * A type whose keys are taken from an `AggregateSpec`, and whose values are the\n * result of the aggregation performed by the corresponding `AggregateField`\n * from the input `AggregateSpec`.\n */\nexport type AggregateSpecData = {\n [P in keyof T]: T[P] extends AggregateField ? U : never;\n};\n\n/**\n * The results of executing an aggregation query.\n */\nexport class AggregateQuerySnapshot<\n AggregateSpecType extends AggregateSpec,\n AppModelType = DocumentData,\n DbModelType extends DocumentData = DocumentData\n> {\n /** A type string to uniquely identify instances of this class. */\n readonly type = 'AggregateQuerySnapshot';\n\n /**\n * The underlying query over which the aggregations recorded in this\n * `AggregateQuerySnapshot` were performed.\n */\n readonly query: Query;\n\n /** @hideconstructor */\n constructor(\n query: Query,\n private readonly _userDataWriter: AbstractUserDataWriter,\n private readonly _data: ApiClientObjectMap\n ) {\n this.query = query;\n }\n\n /**\n * Returns the results of the aggregations performed over the underlying\n * query.\n *\n * The keys of the returned object will be the same as those of the\n * `AggregateSpec` object specified to the aggregation method, and the values\n * will be the corresponding aggregation result.\n *\n * @returns The results of the aggregations performed over the underlying\n * query.\n */\n data(): AggregateSpecData {\n return this._userDataWriter.convertObjectMap(\n this._data\n ) as AggregateSpecData;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getModularInstance } from '@firebase/util';\n\nimport {\n newQueryForCollectionGroup,\n newQueryForPath,\n Query as InternalQuery,\n queryEquals\n} from '../core/query';\nimport { DocumentKey } from '../model/document_key';\nimport { ResourcePath } from '../model/path';\nimport { Code, FirestoreError } from '../util/error';\nimport {\n cast,\n validateCollectionPath,\n validateDocumentPath,\n validateNonEmptyArgument\n} from '../util/input_validation';\n// API extractor fails importing property unless we also explicitly import Property.\n// eslint-disable-next-line @typescript-eslint/no-unused-vars, unused-imports/no-unused-imports-ts\nimport { Property, property, validateJSON } from '../util/json_validation';\nimport { AutoId } from '../util/misc';\n\nimport { Firestore } from './database';\nimport { FieldPath } from './field_path';\nimport { FieldValue } from './field_value';\nimport { FirestoreDataConverter } from './snapshot';\nimport { NestedUpdateFields, Primitive } from './types';\n\n/**\n * Document data (for use with {@link @firebase/firestore/lite#(setDoc:1)}) consists of fields mapped to\n * values.\n */\nexport interface DocumentData {\n /** A mapping between a field and its value. */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [field: string]: any;\n}\n\n/**\n * Similar to TypeScript's `Partial`, but allows nested fields to be\n * omitted and FieldValues to be passed in as property values.\n */\nexport type PartialWithFieldValue =\n | Partial\n | (T extends Primitive\n ? T\n : T extends {}\n ? { [K in keyof T]?: PartialWithFieldValue | FieldValue }\n : never);\n\n/**\n * Allows FieldValues to be passed in as a property value while maintaining\n * type safety.\n */\nexport type WithFieldValue =\n | T\n | (T extends Primitive\n ? T\n : T extends {}\n ? { [K in keyof T]: WithFieldValue | FieldValue }\n : never);\n\n/**\n * Update data (for use with {@link (updateDoc:1)}) that consists of field paths\n * (e.g. 'foo' or 'foo.baz') mapped to values. Fields that contain dots\n * reference nested fields within the document. FieldValues can be passed in\n * as property values.\n */\nexport type UpdateData = T extends Primitive\n ? T\n : T extends {}\n ? { [K in keyof T]?: UpdateData | FieldValue } & NestedUpdateFields\n : Partial;\n/**\n * An options object that configures the behavior of {@link @firebase/firestore/lite#(setDoc:1)}, {@link\n * @firebase/firestore/lite#(WriteBatch.set:1)} and {@link @firebase/firestore/lite#(Transaction.set:1)} calls. These calls can be\n * configured to perform granular merges instead of overwriting the target\n * documents in their entirety by providing a `SetOptions` with `merge: true`.\n *\n * @param merge - Changes the behavior of a `setDoc()` call to only replace the\n * values specified in its data argument. Fields omitted from the `setDoc()`\n * call remain untouched. If your input sets any field to an empty map, all\n * nested fields are overwritten.\n * @param mergeFields - Changes the behavior of `setDoc()` calls to only replace\n * the specified field paths. Any field path that is not specified is ignored\n * and remains untouched. If your input sets any field to an empty map, all\n * nested fields are overwritten.\n */\nexport type SetOptions =\n | {\n readonly merge?: boolean;\n }\n | {\n readonly mergeFields?: Array;\n };\n\n/**\n * A `Query` refers to a query which you can read or listen to. You can also\n * construct refined `Query` objects by adding filters and ordering.\n */\nexport class Query<\n AppModelType = DocumentData,\n DbModelType extends DocumentData = DocumentData\n> {\n /** The type of this Firestore reference. */\n readonly type: 'query' | 'collection' = 'query';\n\n /**\n * The `Firestore` instance for the Firestore database (useful for performing\n * transactions, etc.).\n */\n readonly firestore: Firestore;\n\n // This is the lite version of the Query class in the main SDK.\n\n /** @hideconstructor protected */\n constructor(\n firestore: Firestore,\n /**\n * If provided, the `FirestoreDataConverter` associated with this instance.\n */\n readonly converter: FirestoreDataConverter<\n AppModelType,\n DbModelType\n > | null,\n readonly _query: InternalQuery\n ) {\n this.firestore = firestore;\n }\n\n /**\n * Removes the current converter.\n *\n * @param converter - `null` removes the current converter.\n * @returns A `Query` that does not use a\n * converter.\n */\n withConverter(converter: null): Query;\n /**\n * Applies a custom data converter to this query, allowing you to use your own\n * custom model objects with Firestore. When you call {@link getDocs} with\n * the returned query, the provided converter will convert between Firestore\n * data of type `NewDbModelType` and your custom type `NewAppModelType`.\n *\n * @param converter - Converts objects to and from Firestore.\n * @returns A `Query` that uses the provided converter.\n */\n withConverter<\n NewAppModelType,\n NewDbModelType extends DocumentData = DocumentData\n >(\n converter: FirestoreDataConverter\n ): Query;\n withConverter<\n NewAppModelType,\n NewDbModelType extends DocumentData = DocumentData\n >(\n converter: FirestoreDataConverter | null\n ): Query {\n return new Query(\n this.firestore,\n converter,\n this._query\n );\n }\n}\n\n/**\n * A `DocumentReference` refers to a document location in a Firestore database\n * and can be used to write, read, or listen to the location. The document at\n * the referenced location may or may not exist.\n */\nexport class DocumentReference<\n AppModelType = DocumentData,\n DbModelType extends DocumentData = DocumentData\n> {\n /** The type of this Firestore reference. */\n readonly type = 'document';\n\n /**\n * The {@link Firestore} instance the document is in.\n * This is useful for performing transactions, for example.\n */\n readonly firestore: Firestore;\n\n /** @hideconstructor */\n constructor(\n firestore: Firestore,\n /**\n * If provided, the `FirestoreDataConverter` associated with this instance.\n */\n readonly converter: FirestoreDataConverter<\n AppModelType,\n DbModelType\n > | null,\n readonly _key: DocumentKey\n ) {\n this.firestore = firestore;\n }\n\n get _path(): ResourcePath {\n return this._key.path;\n }\n\n /**\n * The document's identifier within its collection.\n */\n get id(): string {\n return this._key.path.lastSegment();\n }\n\n /**\n * A string representing the path of the referenced document (relative\n * to the root of the database).\n */\n get path(): string {\n return this._key.path.canonicalString();\n }\n\n /**\n * The collection this `DocumentReference` belongs to.\n */\n get parent(): CollectionReference {\n return new CollectionReference(\n this.firestore,\n this.converter,\n this._key.path.popLast()\n );\n }\n\n /**\n * Applies a custom data converter to this `DocumentReference`, allowing you\n * to use your own custom model objects with Firestore. When you call {@link\n * @firebase/firestore/lite#(setDoc:1)}, {@link @firebase/firestore/lite#getDoc}, etc. with the returned `DocumentReference`\n * instance, the provided converter will convert between Firestore data of\n * type `NewDbModelType` and your custom type `NewAppModelType`.\n *\n * @param converter - Converts objects to and from Firestore.\n * @returns A `DocumentReference` that uses the provided converter.\n */\n withConverter<\n NewAppModelType,\n NewDbModelType extends DocumentData = DocumentData\n >(\n converter: FirestoreDataConverter\n ): DocumentReference;\n /**\n * Removes the current converter.\n *\n * @param converter - `null` removes the current converter.\n * @returns A `DocumentReference` that does not\n * use a converter.\n */\n withConverter(converter: null): DocumentReference;\n withConverter<\n NewAppModelType,\n NewDbModelType extends DocumentData = DocumentData\n >(\n converter: FirestoreDataConverter | null\n ): DocumentReference {\n return new DocumentReference(\n this.firestore,\n converter,\n this._key\n );\n }\n\n static _jsonSchemaVersion: string = 'firestore/documentReference/1.0';\n static _jsonSchema = {\n type: property('string', DocumentReference._jsonSchemaVersion),\n referencePath: property('string')\n };\n\n /**\n * Returns a JSON-serializable representation of this `DocumentReference` instance.\n *\n * @returns a JSON representation of this object.\n */\n toJSON(): object {\n return {\n type: DocumentReference._jsonSchemaVersion,\n referencePath: this._key.toString()\n };\n }\n\n /**\n * Builds a `DocumentReference` instance from a JSON object created by\n * {@link DocumentReference.toJSON}.\n *\n * @param firestore - The {@link Firestore} instance the snapshot should be loaded for.\n * @param json a JSON object represention of a `DocumentReference` instance\n * @returns an instance of {@link DocumentReference} if the JSON object could be parsed. Throws a\n * {@link FirestoreError} if an error occurs.\n */\n static fromJSON(firestore: Firestore, json: object): DocumentReference;\n /**\n * Builds a `DocumentReference` instance from a JSON object created by\n * {@link DocumentReference.toJSON}.\n *\n * @param firestore - The {@link Firestore} instance the snapshot should be loaded for.\n * @param json a JSON object represention of a `DocumentReference` instance\n * @param converter - Converts objects to and from Firestore.\n * @returns an instance of {@link DocumentReference} if the JSON object could be parsed. Throws a\n * {@link FirestoreError} if an error occurs.\n */\n static fromJSON<\n NewAppModelType = DocumentData,\n NewDbModelType extends DocumentData = DocumentData\n >(\n firestore: Firestore,\n json: object,\n converter: FirestoreDataConverter\n ): DocumentReference;\n static fromJSON<\n NewAppModelType = DocumentData,\n NewDbModelType extends DocumentData = DocumentData\n >(\n firestore: Firestore,\n json: object,\n converter?: FirestoreDataConverter\n ): DocumentReference {\n if (validateJSON(json, DocumentReference._jsonSchema)) {\n return new DocumentReference(\n firestore,\n converter ? converter : null,\n new DocumentKey(ResourcePath.fromString(json.referencePath))\n );\n }\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Unexpected error creating Bytes from JSON.'\n );\n }\n}\n\n/**\n * A `CollectionReference` object can be used for adding documents, getting\n * document references, and querying for documents (using {@link (query:1)}).\n */\nexport class CollectionReference<\n AppModelType = DocumentData,\n DbModelType extends DocumentData = DocumentData\n> extends Query {\n /** The type of this Firestore reference. */\n readonly type = 'collection';\n\n /** @hideconstructor */\n constructor(\n firestore: Firestore,\n converter: FirestoreDataConverter | null,\n readonly _path: ResourcePath\n ) {\n super(firestore, converter, newQueryForPath(_path));\n }\n\n /** The collection's identifier. */\n get id(): string {\n return this._query.path.lastSegment();\n }\n\n /**\n * A string representing the path of the referenced collection (relative\n * to the root of the database).\n */\n get path(): string {\n return this._query.path.canonicalString();\n }\n\n /**\n * A reference to the containing `DocumentReference` if this is a\n * subcollection. If this isn't a subcollection, the reference is null.\n */\n get parent(): DocumentReference | null {\n const parentPath = this._path.popLast();\n if (parentPath.isEmpty()) {\n return null;\n } else {\n return new DocumentReference(\n this.firestore,\n /* converter= */ null,\n new DocumentKey(parentPath)\n );\n }\n }\n\n /**\n * Applies a custom data converter to this `CollectionReference`, allowing you\n * to use your own custom model objects with Firestore. When you call {@link\n * addDoc} with the returned `CollectionReference` instance, the provided\n * converter will convert between Firestore data of type `NewDbModelType` and\n * your custom type `NewAppModelType`.\n *\n * @param converter - Converts objects to and from Firestore.\n * @returns A `CollectionReference` that uses the provided converter.\n */\n withConverter<\n NewAppModelType,\n NewDbModelType extends DocumentData = DocumentData\n >(\n converter: FirestoreDataConverter\n ): CollectionReference;\n /**\n * Removes the current converter.\n *\n * @param converter - `null` removes the current converter.\n * @returns A `CollectionReference` that does not\n * use a converter.\n */\n withConverter(\n converter: null\n ): CollectionReference;\n withConverter<\n NewAppModelType,\n NewDbModelType extends DocumentData = DocumentData\n >(\n converter: FirestoreDataConverter | null\n ): CollectionReference {\n return new CollectionReference(\n this.firestore,\n converter,\n this._path\n );\n }\n}\n\n/**\n * Gets a `CollectionReference` instance that refers to the collection at\n * the specified absolute path.\n *\n * @param firestore - A reference to the root `Firestore` instance.\n * @param path - A slash-separated path to a collection.\n * @param pathSegments - Additional path segments to apply relative to the first\n * argument.\n * @throws If the final path has an even number of segments and does not point\n * to a collection.\n * @returns The `CollectionReference` instance.\n */\nexport function collection(\n firestore: Firestore,\n path: string,\n ...pathSegments: string[]\n): CollectionReference;\n/**\n * Gets a `CollectionReference` instance that refers to a subcollection of\n * `reference` at the specified relative path.\n *\n * @param reference - A reference to a collection.\n * @param path - A slash-separated path to a collection.\n * @param pathSegments - Additional path segments to apply relative to the first\n * argument.\n * @throws If the final path has an even number of segments and does not point\n * to a collection.\n * @returns The `CollectionReference` instance.\n */\nexport function collection(\n reference: CollectionReference,\n path: string,\n ...pathSegments: string[]\n): CollectionReference;\n/**\n * Gets a `CollectionReference` instance that refers to a subcollection of\n * `reference` at the specified relative path.\n *\n * @param reference - A reference to a Firestore document.\n * @param path - A slash-separated path to a collection.\n * @param pathSegments - Additional path segments that will be applied relative\n * to the first argument.\n * @throws If the final path has an even number of segments and does not point\n * to a collection.\n * @returns The `CollectionReference` instance.\n */\nexport function collection(\n reference: DocumentReference,\n path: string,\n ...pathSegments: string[]\n): CollectionReference;\nexport function collection(\n parent:\n | Firestore\n | DocumentReference\n | CollectionReference,\n path: string,\n ...pathSegments: string[]\n): CollectionReference {\n parent = getModularInstance(parent);\n\n validateNonEmptyArgument('collection', 'path', path);\n if (parent instanceof Firestore) {\n const absolutePath = ResourcePath.fromString(path, ...pathSegments);\n validateCollectionPath(absolutePath);\n return new CollectionReference(parent, /* converter= */ null, absolutePath);\n } else {\n if (\n !(parent instanceof DocumentReference) &&\n !(parent instanceof CollectionReference)\n ) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Expected first argument to collection() to be a CollectionReference, ' +\n 'a DocumentReference or FirebaseFirestore'\n );\n }\n const absolutePath = parent._path.child(\n ResourcePath.fromString(path, ...pathSegments)\n );\n validateCollectionPath(absolutePath);\n return new CollectionReference(\n parent.firestore,\n /* converter= */ null,\n absolutePath\n );\n }\n}\n\n// TODO(firestorelite): Consider using ErrorFactory -\n// https://github.com/firebase/firebase-js-sdk/blob/0131e1f/packages/util/src/errors.ts#L106\n\n/**\n * Creates and returns a new `Query` instance that includes all documents in the\n * database that are contained in a collection or subcollection with the\n * given `collectionId`.\n *\n * @param firestore - A reference to the root `Firestore` instance.\n * @param collectionId - Identifies the collections to query over. Every\n * collection or subcollection with this ID as the last segment of its path\n * will be included. Cannot contain a slash.\n * @returns The created `Query`.\n */\nexport function collectionGroup(\n firestore: Firestore,\n collectionId: string\n): Query {\n firestore = cast(firestore, Firestore);\n\n validateNonEmptyArgument('collectionGroup', 'collection id', collectionId);\n if (collectionId.indexOf('/') >= 0) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid collection ID '${collectionId}' passed to function ` +\n `collectionGroup(). Collection IDs must not contain '/'.`\n );\n }\n\n return new Query(\n firestore,\n /* converter= */ null,\n newQueryForCollectionGroup(collectionId)\n );\n}\n\n/**\n * Gets a `DocumentReference` instance that refers to the document at the\n * specified absolute path.\n *\n * @param firestore - A reference to the root `Firestore` instance.\n * @param path - A slash-separated path to a document.\n * @param pathSegments - Additional path segments that will be applied relative\n * to the first argument.\n * @throws If the final path has an odd number of segments and does not point to\n * a document.\n * @returns The `DocumentReference` instance.\n */\nexport function doc(\n firestore: Firestore,\n path: string,\n ...pathSegments: string[]\n): DocumentReference;\n/**\n * Gets a `DocumentReference` instance that refers to a document within\n * `reference` at the specified relative path. If no path is specified, an\n * automatically-generated unique ID will be used for the returned\n * `DocumentReference`.\n *\n * @param reference - A reference to a collection.\n * @param path - A slash-separated path to a document. Has to be omitted to use\n * auto-generated IDs.\n * @param pathSegments - Additional path segments that will be applied relative\n * to the first argument.\n * @throws If the final path has an odd number of segments and does not point to\n * a document.\n * @returns The `DocumentReference` instance.\n */\nexport function doc(\n reference: CollectionReference,\n path?: string,\n ...pathSegments: string[]\n): DocumentReference;\n/**\n * Gets a `DocumentReference` instance that refers to a document within\n * `reference` at the specified relative path.\n *\n * @param reference - A reference to a Firestore document.\n * @param path - A slash-separated path to a document.\n * @param pathSegments - Additional path segments that will be applied relative\n * to the first argument.\n * @throws If the final path has an odd number of segments and does not point to\n * a document.\n * @returns The `DocumentReference` instance.\n */\nexport function doc(\n reference: DocumentReference,\n path: string,\n ...pathSegments: string[]\n): DocumentReference;\nexport function doc(\n parent:\n | Firestore\n | CollectionReference\n | DocumentReference,\n path?: string,\n ...pathSegments: string[]\n): DocumentReference {\n parent = getModularInstance(parent);\n\n // We allow omission of 'pathString' but explicitly prohibit passing in both\n // 'undefined' and 'null'.\n if (arguments.length === 1) {\n path = AutoId.newId();\n }\n validateNonEmptyArgument('doc', 'path', path);\n\n if (parent instanceof Firestore) {\n const absolutePath = ResourcePath.fromString(path, ...pathSegments);\n validateDocumentPath(absolutePath);\n return new DocumentReference(\n parent,\n /* converter= */ null,\n new DocumentKey(absolutePath)\n );\n } else {\n if (\n !(parent instanceof DocumentReference) &&\n !(parent instanceof CollectionReference)\n ) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Expected first argument to collection() to be a CollectionReference, ' +\n 'a DocumentReference or FirebaseFirestore'\n );\n }\n const absolutePath = parent._path.child(\n ResourcePath.fromString(path, ...pathSegments)\n );\n validateDocumentPath(absolutePath);\n return new DocumentReference(\n parent.firestore,\n parent instanceof CollectionReference ? parent.converter : null,\n new DocumentKey(absolutePath)\n );\n }\n}\n\n/**\n * Returns true if the provided references are equal.\n *\n * @param left - A reference to compare.\n * @param right - A reference to compare.\n * @returns true if the references point to the same location in the same\n * Firestore database.\n */\nexport function refEqual(\n left:\n | DocumentReference\n | CollectionReference,\n right:\n | DocumentReference\n | CollectionReference\n): boolean {\n left = getModularInstance(left);\n right = getModularInstance(right);\n\n if (\n (left instanceof DocumentReference ||\n left instanceof CollectionReference) &&\n (right instanceof DocumentReference || right instanceof CollectionReference)\n ) {\n return (\n left.firestore === right.firestore &&\n left.path === right.path &&\n left.converter === right.converter\n );\n }\n return false;\n}\n\n/**\n * Returns true if the provided queries point to the same collection and apply\n * the same constraints.\n *\n * @param left - A `Query` to compare.\n * @param right - A `Query` to compare.\n * @returns true if the references point to the same location in the same\n * Firestore database.\n */\nexport function queryEqual(\n left: Query,\n right: Query\n): boolean {\n left = getModularInstance(left);\n right = getModularInstance(right);\n\n if (left instanceof Query && right instanceof Query) {\n return (\n left.firestore === right.firestore &&\n queryEquals(left._query, right._query) &&\n left.converter === right.converter\n );\n }\n return false;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ByteString } from '../util/byte_string';\nimport { Code, FirestoreError } from '../util/error';\n// API extractor fails importing property unless we also explicitly import Property.\n// eslint-disable-next-line @typescript-eslint/no-unused-vars, unused-imports/no-unused-imports-ts\nimport { Property, property, validateJSON } from '../util/json_validation';\n\n/**\n * An immutable object representing an array of bytes.\n */\nexport class Bytes {\n _byteString: ByteString;\n\n /** @hideconstructor */\n constructor(byteString: ByteString) {\n this._byteString = byteString;\n }\n\n /**\n * Creates a new `Bytes` object from the given Base64 string, converting it to\n * bytes.\n *\n * @param base64 - The Base64 string used to create the `Bytes` object.\n */\n static fromBase64String(base64: string): Bytes {\n try {\n return new Bytes(ByteString.fromBase64String(base64));\n } catch (e) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Failed to construct data from Base64 string: ' + e\n );\n }\n }\n\n /**\n * Creates a new `Bytes` object from the given Uint8Array.\n *\n * @param array - The Uint8Array used to create the `Bytes` object.\n */\n static fromUint8Array(array: Uint8Array): Bytes {\n return new Bytes(ByteString.fromUint8Array(array));\n }\n\n /**\n * Returns the underlying bytes as a Base64-encoded string.\n *\n * @returns The Base64-encoded string created from the `Bytes` object.\n */\n toBase64(): string {\n return this._byteString.toBase64();\n }\n\n /**\n * Returns the underlying bytes in a new `Uint8Array`.\n *\n * @returns The Uint8Array created from the `Bytes` object.\n */\n toUint8Array(): Uint8Array {\n return this._byteString.toUint8Array();\n }\n\n /**\n * Returns a string representation of the `Bytes` object.\n *\n * @returns A string representation of the `Bytes` object.\n */\n toString(): string {\n return 'Bytes(base64: ' + this.toBase64() + ')';\n }\n\n /**\n * Returns true if this `Bytes` object is equal to the provided one.\n *\n * @param other - The `Bytes` object to compare against.\n * @returns true if this `Bytes` object is equal to the provided one.\n */\n isEqual(other: Bytes): boolean {\n return this._byteString.isEqual(other._byteString);\n }\n\n static _jsonSchemaVersion: string = 'firestore/bytes/1.0';\n static _jsonSchema = {\n type: property('string', Bytes._jsonSchemaVersion),\n bytes: property('string')\n };\n\n /**\n * Returns a JSON-serializable representation of this `Bytes` instance.\n *\n * @returns a JSON representation of this object.\n */\n toJSON(): object {\n return {\n type: Bytes._jsonSchemaVersion,\n bytes: this.toBase64()\n };\n }\n\n /**\n * Builds a `Bytes` instance from a JSON object created by {@link Bytes.toJSON}.\n *\n * @param json a JSON object represention of a `Bytes` instance\n * @returns an instance of {@link Bytes} if the JSON object could be parsed. Throws a\n * {@link FirestoreError} if an error occurs.\n */\n static fromJSON(json: object): Bytes {\n if (validateJSON(json, Bytes._jsonSchema)) {\n return Bytes.fromBase64String(json.bytes);\n }\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Unexpected error creating Bytes from JSON.'\n );\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n DOCUMENT_KEY_NAME,\n FieldPath as InternalFieldPath\n} from '../model/path';\nimport { Code, FirestoreError } from '../util/error';\n\n/**\n * A `FieldPath` refers to a field in a document. The path may consist of a\n * single field name (referring to a top-level field in the document), or a\n * list of field names (referring to a nested field in the document).\n *\n * Create a `FieldPath` by providing field names. If more than one field\n * name is provided, the path will point to a nested field in a document.\n */\nexport class FieldPath {\n /** Internal representation of a Firestore field path. */\n readonly _internalPath: InternalFieldPath;\n\n /**\n * Creates a `FieldPath` from the provided field names. If more than one field\n * name is provided, the path will point to a nested field in a document.\n *\n * @param fieldNames - A list of field names.\n */\n constructor(...fieldNames: string[]) {\n for (let i = 0; i < fieldNames.length; ++i) {\n if (fieldNames[i].length === 0) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid field name at argument $(i + 1). ` +\n 'Field names must not be empty.'\n );\n }\n }\n\n this._internalPath = new InternalFieldPath(fieldNames);\n }\n\n /**\n * Returns true if this `FieldPath` is equal to the provided one.\n *\n * @param other - The `FieldPath` to compare against.\n * @returns true if this `FieldPath` is equal to the provided one.\n */\n isEqual(other: FieldPath): boolean {\n return this._internalPath.isEqual(other._internalPath);\n }\n}\n\n/**\n * Returns a special sentinel `FieldPath` to refer to the ID of a document.\n * It can be used in queries to sort or filter by the document ID.\n */\nexport function documentId(): FieldPath {\n return new FieldPath(DOCUMENT_KEY_NAME);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ParseContext } from '../api/parse_context';\nimport { FieldTransform } from '../model/mutation';\n\n/**\n * Sentinel values that can be used when writing document fields with `set()`\n * or `update()`.\n */\nexport abstract class FieldValue {\n /**\n * @param _methodName - The public API endpoint that returns this class.\n * @hideconstructor\n */\n constructor(public _methodName: string) {}\n\n /** Compares `FieldValue`s for equality. */\n abstract isEqual(other: FieldValue): boolean;\n abstract _toFieldTransform(context: ParseContext): FieldTransform | null;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Code, FirestoreError } from '../util/error';\n// API extractor fails importing 'property' unless we also explicitly import 'Property'.\n// eslint-disable-next-line @typescript-eslint/no-unused-vars, unused-imports/no-unused-imports-ts\nimport { Property, property, validateJSON } from '../util/json_validation';\nimport { primitiveComparator } from '../util/misc';\n\n/**\n * An immutable object representing a geographic location in Firestore. The\n * location is represented as latitude/longitude pair.\n *\n * Latitude values are in the range of [-90, 90].\n * Longitude values are in the range of [-180, 180].\n */\nexport class GeoPoint {\n // Prefix with underscore to signal this is a private variable in JS and\n // prevent it showing up for autocompletion when typing latitude or longitude.\n private _lat: number;\n private _long: number;\n\n /**\n * Creates a new immutable `GeoPoint` object with the provided latitude and\n * longitude values.\n * @param latitude - The latitude as number between -90 and 90.\n * @param longitude - The longitude as number between -180 and 180.\n */\n constructor(latitude: number, longitude: number) {\n if (!isFinite(latitude) || latitude < -90 || latitude > 90) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Latitude must be a number between -90 and 90, but was: ' + latitude\n );\n }\n if (!isFinite(longitude) || longitude < -180 || longitude > 180) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Longitude must be a number between -180 and 180, but was: ' + longitude\n );\n }\n\n this._lat = latitude;\n this._long = longitude;\n }\n\n /**\n * The latitude of this `GeoPoint` instance.\n */\n get latitude(): number {\n return this._lat;\n }\n\n /**\n * The longitude of this `GeoPoint` instance.\n */\n get longitude(): number {\n return this._long;\n }\n\n /**\n * Returns true if this `GeoPoint` is equal to the provided one.\n *\n * @param other - The `GeoPoint` to compare against.\n * @returns true if this `GeoPoint` is equal to the provided one.\n */\n isEqual(other: GeoPoint): boolean {\n return this._lat === other._lat && this._long === other._long;\n }\n\n /**\n * Actually private to JS consumers of our API, so this function is prefixed\n * with an underscore.\n */\n _compareTo(other: GeoPoint): number {\n return (\n primitiveComparator(this._lat, other._lat) ||\n primitiveComparator(this._long, other._long)\n );\n }\n\n static _jsonSchemaVersion: string = 'firestore/geoPoint/1.0';\n static _jsonSchema = {\n type: property('string', GeoPoint._jsonSchemaVersion),\n latitude: property('number'),\n longitude: property('number')\n };\n\n /**\n * Returns a JSON-serializable representation of this `GeoPoint` instance.\n *\n * @returns a JSON representation of this object.\n */\n toJSON(): { latitude: number; longitude: number; type: string } {\n return {\n latitude: this._lat,\n longitude: this._long,\n type: GeoPoint._jsonSchemaVersion\n };\n }\n\n /**\n * Builds a `GeoPoint` instance from a JSON object created by {@link GeoPoint.toJSON}.\n *\n * @param json a JSON object represention of a `GeoPoint` instance\n * @returns an instance of {@link GeoPoint} if the JSON object could be parsed. Throws a\n * {@link FirestoreError} if an error occurs.\n */\n static fromJSON(json: object): GeoPoint {\n if (validateJSON(json, GeoPoint._jsonSchema)) {\n return new GeoPoint(json.latitude, json.longitude);\n }\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Unexpected error creating GeoPoint from JSON.'\n );\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Returns true iff the array contains the value using strong equality.\n */\nexport function includes(array: T[], value: T): boolean {\n for (let i = 0; i < array.length; i++) {\n if (array[i] === value) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * Returns true iff the array contains any value matching the predicate\n */\nexport function some(array: T[], predicate: (t: T) => boolean): boolean {\n for (let i = 0; i < array.length; i++) {\n if (predicate(array[i])) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * Calls predicate function for each item in the array until the predicate\n * returns true, at which point the index of that item is returned. If the\n * predicate does not return true for any item, null is returned.\n */\nexport function findIndex
(\n array: A[],\n predicate: (value: A) => boolean\n): number | null {\n for (let i = 0; i < array.length; i++) {\n if (predicate(array[i])) {\n return i;\n }\n }\n return null;\n}\n\n/**\n * Compares two array for equality using comparator. The method computes the\n * intersection and invokes `onAdd` for every element that is in `after` but not\n * `before`. `onRemove` is invoked for every element in `before` but missing\n * from `after`.\n *\n * The method creates a copy of both `before` and `after` and runs in O(n log\n * n), where n is the size of the two lists.\n *\n * @param before - The elements that exist in the original array.\n * @param after - The elements to diff against the original array.\n * @param comparator - The comparator for the elements in before and after.\n * @param onAdd - A function to invoke for every element that is part of `\n * after` but not `before`.\n * @param onRemove - A function to invoke for every element that is part of\n * `before` but not `after`.\n */\nexport function diffArrays(\n before: T[],\n after: T[],\n comparator: (l: T, r: T) => number,\n onAdd: (entry: T) => void,\n onRemove: (entry: T) => void\n): void {\n before = [...before];\n after = [...after];\n before.sort(comparator);\n after.sort(comparator);\n\n const bLen = before.length;\n const aLen = after.length;\n let a = 0;\n let b = 0;\n while (a < aLen && b < bLen) {\n const cmp = comparator(before[b], after[a]);\n if (cmp < 0) {\n // The element was removed if the next element in our ordered\n // walkthrough is only in `before`.\n onRemove(before[b++]);\n } else if (cmp > 0) {\n // The element was added if the next element in our ordered walkthrough\n // is only in `after`.\n onAdd(after[a++]);\n } else {\n a++;\n b++;\n }\n }\n while (a < aLen) {\n onAdd(after[a++]);\n }\n while (b < bLen) {\n onRemove(before[b++]);\n }\n}\n\n/**\n * Verifies equality for an array of objects using the `isEqual` interface.\n *\n * @private\n * @internal\n * @param left Array of objects supporting `isEqual`.\n * @param right Array of objects supporting `isEqual`.\n * @return True if arrays are equal.\n */\nexport function isArrayEqual boolean }>(\n left: T[],\n right: T[]\n): boolean {\n if (left.length !== right.length) {\n return false;\n }\n\n for (let i = 0; i < left.length; ++i) {\n if (!left[i].isEqual(right[i])) {\n return false;\n }\n }\n\n return true;\n}\n\n/**\n * Verifies equality for an array of primitives.\n *\n * @private\n * @internal\n * @param left Array of primitives.\n * @param right Array of primitives.\n * @return True if arrays are equal.\n */\nexport function isPrimitiveArrayEqual(\n left: T[],\n right: T[]\n): boolean {\n if (left.length !== right.length) {\n return false;\n }\n\n for (let i = 0; i < left.length; ++i) {\n if (left[i] !== right[i]) {\n return false;\n }\n }\n\n return true;\n}\n","/**\n * @license\n * Copyright 2024 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isPrimitiveArrayEqual } from '../util/array';\nimport { Code, FirestoreError } from '../util/error';\n// API extractor fails importing 'property' unless we also explicitly import 'Property'.\n// eslint-disable-next-line @typescript-eslint/no-unused-vars, unused-imports/no-unused-imports-ts\nimport { Property, property, validateJSON } from '../util/json_validation';\n\n/**\n * Represents a vector type in Firestore documents.\n * Create an instance with {@link vector}.\n *\n * @class VectorValue\n */\nexport class VectorValue {\n private readonly _values: number[];\n\n /**\n * @private\n * @internal\n */\n constructor(values: number[] | undefined) {\n // Making a copy of the parameter.\n this._values = (values || []).map(n => n);\n }\n\n /**\n * Returns a copy of the raw number array form of the vector.\n */\n toArray(): number[] {\n return this._values.map(n => n);\n }\n\n /**\n * Returns `true` if the two `VectorValue` values have the same raw number arrays, returns `false` otherwise.\n */\n isEqual(other: VectorValue): boolean {\n return isPrimitiveArrayEqual(this._values, other._values);\n }\n\n static _jsonSchemaVersion: string = 'firestore/vectorValue/1.0';\n static _jsonSchema = {\n type: property('string', VectorValue._jsonSchemaVersion),\n vectorValues: property('object')\n };\n\n /**\n * Returns a JSON-serializable representation of this `VectorValue` instance.\n *\n * @returns a JSON representation of this object.\n */\n toJSON(): object {\n return {\n type: VectorValue._jsonSchemaVersion,\n vectorValues: this._values\n };\n }\n\n /**\n * Builds a `VectorValue` instance from a JSON object created by {@link VectorValue.toJSON}.\n *\n * @param json a JSON object represention of a `VectorValue` instance.\n * @returns an instance of {@link VectorValue} if the JSON object could be parsed. Throws a\n * {@link FirestoreError} if an error occurs.\n */\n static fromJSON(json: object): VectorValue {\n if (validateJSON(json, VectorValue._jsonSchema)) {\n if (\n Array.isArray(json.vectorValues) &&\n json.vectorValues.every(element => typeof element === 'number')\n ) {\n return new VectorValue(json.vectorValues);\n }\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n \"Expected 'vectorValues' field to be a number array\"\n );\n }\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Unexpected error creating Timestamp from JSON.'\n );\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n DocumentData,\n FieldPath as PublicFieldPath,\n SetOptions\n} from '@firebase/firestore-types';\nimport { Compat, deepEqual, getModularInstance } from '@firebase/util';\n\nimport { ParseContext } from '../api/parse_context';\nimport { DatabaseId } from '../core/database_info';\nimport { DocumentKey } from '../model/document_key';\nimport { FieldMask } from '../model/field_mask';\nimport {\n FieldTransform,\n Mutation,\n PatchMutation,\n Precondition,\n SetMutation\n} from '../model/mutation';\nimport { ObjectValue } from '../model/object_value';\nimport { FieldPath as InternalFieldPath } from '../model/path';\nimport {\n ArrayRemoveTransformOperation,\n ArrayUnionTransformOperation,\n NumericIncrementTransformOperation,\n ServerTimestampTransform\n} from '../model/transform_operation';\nimport {\n TYPE_KEY,\n VECTOR_MAP_VECTORS_KEY,\n VECTOR_VALUE_SENTINEL\n} from '../model/values';\nimport { newSerializer } from '../platform/serializer';\nimport {\n MapValue as ProtoMapValue,\n Value as ProtoValue\n} from '../protos/firestore_proto_api';\nimport { toDouble, toNumber } from '../remote/number_serializer';\nimport {\n JsonProtoSerializer,\n toBytes,\n toResourceName,\n toTimestamp\n} from '../remote/serializer';\nimport { debugAssert, fail } from '../util/assert';\nimport { Code, FirestoreError } from '../util/error';\nimport { isPlainObject, valueDescription } from '../util/input_validation';\nimport { Dict, forEach, isEmpty } from '../util/obj';\n\nimport { Bytes } from './bytes';\nimport { Firestore } from './database';\nimport { FieldPath } from './field_path';\nimport { FieldValue } from './field_value';\nimport { GeoPoint } from './geo_point';\nimport {\n DocumentReference,\n PartialWithFieldValue,\n WithFieldValue\n} from './reference';\nimport { Timestamp } from './timestamp';\nimport { VectorValue } from './vector_value';\n\nconst RESERVED_FIELD_REGEX = /^__.*__$/;\n\n/**\n * An untyped Firestore Data Converter interface that is shared between the\n * lite, firestore-exp and classic SDK.\n */\nexport interface UntypedFirestoreDataConverter<\n AppModelType,\n DbModelType extends DocumentData = DocumentData\n> {\n toFirestore(\n modelObject: WithFieldValue\n ): WithFieldValue;\n toFirestore(\n modelObject: PartialWithFieldValue,\n options: SetOptions\n ): PartialWithFieldValue;\n fromFirestore(snapshot: unknown, options?: unknown): AppModelType;\n}\n\n/** The result of parsing document data (e.g. for a setData call). */\nexport class ParsedSetData {\n constructor(\n readonly data: ObjectValue,\n readonly fieldMask: FieldMask | null,\n readonly fieldTransforms: FieldTransform[]\n ) {}\n\n toMutation(key: DocumentKey, precondition: Precondition): Mutation {\n if (this.fieldMask !== null) {\n return new PatchMutation(\n key,\n this.data,\n this.fieldMask,\n precondition,\n this.fieldTransforms\n );\n } else {\n return new SetMutation(\n key,\n this.data,\n precondition,\n this.fieldTransforms\n );\n }\n }\n}\n\n/** The result of parsing \"update\" data (i.e. for an updateData call). */\nexport class ParsedUpdateData {\n constructor(\n readonly data: ObjectValue,\n // The fieldMask does not include document transforms.\n readonly fieldMask: FieldMask,\n readonly fieldTransforms: FieldTransform[]\n ) {}\n\n toMutation(key: DocumentKey, precondition: Precondition): Mutation {\n return new PatchMutation(\n key,\n this.data,\n this.fieldMask,\n precondition,\n this.fieldTransforms\n );\n }\n}\n\n/*\n * Represents what type of API method provided the data being parsed; useful\n * for determining which error conditions apply during parsing and providing\n * better error messages.\n */\nexport const enum UserDataSource {\n Set,\n Update,\n MergeSet,\n /**\n * Indicates the source is a where clause, cursor bound, arrayUnion()\n * element, etc. Of note, isWrite(source) will return false.\n */\n Argument,\n /**\n * Indicates that the source is an Argument that may directly contain nested\n * arrays (e.g. the operand of an `in` query).\n */\n ArrayArgument\n}\n\nfunction isWrite(dataSource: UserDataSource): boolean {\n switch (dataSource) {\n case UserDataSource.Set: // fall through\n case UserDataSource.MergeSet: // fall through\n case UserDataSource.Update:\n return true;\n case UserDataSource.Argument:\n case UserDataSource.ArrayArgument:\n return false;\n default:\n throw fail(0x9c4b, 'Unexpected case for UserDataSource', {\n dataSource\n });\n }\n}\n\n/** Contains the settings that are mutated as we parse user data. */\ninterface ContextSettings {\n /** Indicates what kind of API method this data came from. */\n readonly dataSource: UserDataSource;\n /** The name of the method the user called to create the ParseContext. */\n readonly methodName: string;\n /** The document the user is attempting to modify, if that applies. */\n readonly targetDoc?: DocumentKey;\n /**\n * A path within the object being parsed. This could be an empty path (in\n * which case the context represents the root of the data being parsed), or a\n * nonempty path (indicating the context represents a nested location within\n * the data).\n */\n readonly path?: InternalFieldPath;\n /**\n * Whether or not this context corresponds to an element of an array.\n * If not set, elements are treated as if they were outside of arrays.\n */\n readonly arrayElement?: boolean;\n /**\n * Whether or not a converter was specified in this context. If true, error\n * messages will reference the converter when invalid data is provided.\n */\n readonly hasConverter?: boolean;\n}\n\n/** A \"context\" object passed around while parsing user data. */\nclass ParseContextImpl implements ParseContext {\n readonly fieldTransforms: FieldTransform[];\n readonly fieldMask: InternalFieldPath[];\n /**\n * Initializes a ParseContext with the given source and path.\n *\n * @param settings - The settings for the parser.\n * @param databaseId - The database ID of the Firestore instance.\n * @param serializer - The serializer to use to generate the Value proto.\n * @param ignoreUndefinedProperties - Whether to ignore undefined properties\n * rather than throw.\n * @param fieldTransforms - A mutable list of field transforms encountered\n * while parsing the data.\n * @param fieldMask - A mutable list of field paths encountered while parsing\n * the data.\n *\n * TODO(b/34871131): We don't support array paths right now, so path can be\n * null to indicate the context represents any location within an array (in\n * which case certain features will not work and errors will be somewhat\n * compromised).\n */\n constructor(\n readonly settings: ContextSettings,\n readonly databaseId: DatabaseId,\n readonly serializer: JsonProtoSerializer,\n readonly ignoreUndefinedProperties: boolean,\n fieldTransforms?: FieldTransform[],\n fieldMask?: InternalFieldPath[]\n ) {\n // Minor hack: If fieldTransforms is undefined, we assume this is an\n // external call and we need to validate the entire path.\n if (fieldTransforms === undefined) {\n this.validatePath();\n }\n this.fieldTransforms = fieldTransforms || [];\n this.fieldMask = fieldMask || [];\n }\n\n get path(): InternalFieldPath | undefined {\n return this.settings.path;\n }\n\n get dataSource(): UserDataSource {\n return this.settings.dataSource;\n }\n\n /** Returns a new context with the specified settings overwritten. */\n contextWith(configuration: Partial): ParseContextImpl {\n return new ParseContextImpl(\n { ...this.settings, ...configuration },\n this.databaseId,\n this.serializer,\n this.ignoreUndefinedProperties,\n this.fieldTransforms,\n this.fieldMask\n );\n }\n\n childContextForField(field: string): ParseContextImpl {\n const childPath = this.path?.child(field);\n const context = this.contextWith({ path: childPath, arrayElement: false });\n context.validatePathSegment(field);\n return context;\n }\n\n childContextForFieldPath(field: InternalFieldPath): ParseContextImpl {\n const childPath = this.path?.child(field);\n const context = this.contextWith({ path: childPath, arrayElement: false });\n context.validatePath();\n return context;\n }\n\n childContextForArray(index: number): ParseContextImpl {\n // TODO(b/34871131): We don't support array paths right now; so make path\n // undefined.\n return this.contextWith({ path: undefined, arrayElement: true });\n }\n\n createError(reason: string): FirestoreError {\n return createError(\n reason,\n this.settings.methodName,\n this.settings.hasConverter || false,\n this.path,\n this.settings.targetDoc\n );\n }\n\n /** Returns 'true' if 'fieldPath' was traversed when creating this context. */\n contains(fieldPath: InternalFieldPath): boolean {\n return (\n this.fieldMask.find(field => fieldPath.isPrefixOf(field)) !== undefined ||\n this.fieldTransforms.find(transform =>\n fieldPath.isPrefixOf(transform.field)\n ) !== undefined\n );\n }\n\n private validatePath(): void {\n // TODO(b/34871131): Remove null check once we have proper paths for fields\n // within arrays.\n if (!this.path) {\n return;\n }\n for (let i = 0; i < this.path.length; i++) {\n this.validatePathSegment(this.path.get(i));\n }\n }\n\n private validatePathSegment(segment: string): void {\n if (segment.length === 0) {\n throw this.createError('Document fields must not be empty');\n }\n if (isWrite(this.dataSource) && RESERVED_FIELD_REGEX.test(segment)) {\n throw this.createError('Document fields cannot begin and end with \"__\"');\n }\n }\n}\n\n/**\n * Helper for parsing raw user input (provided via the API) into internal model\n * classes.\n */\nexport class UserDataReader {\n private readonly serializer: JsonProtoSerializer;\n\n constructor(\n private readonly databaseId: DatabaseId,\n private readonly ignoreUndefinedProperties: boolean,\n serializer?: JsonProtoSerializer\n ) {\n this.serializer = serializer || newSerializer(databaseId);\n }\n\n /** Creates a new top-level parse context. */\n createContext(\n dataSource: UserDataSource,\n methodName: string,\n targetDoc?: DocumentKey,\n hasConverter = false\n ): ParseContextImpl {\n return new ParseContextImpl(\n {\n dataSource,\n methodName,\n targetDoc,\n path: InternalFieldPath.emptyPath(),\n arrayElement: false,\n hasConverter\n },\n this.databaseId,\n this.serializer,\n this.ignoreUndefinedProperties\n );\n }\n}\n\nexport function newUserDataReader(firestore: Firestore): UserDataReader {\n const settings = firestore._freezeSettings();\n const serializer = newSerializer(firestore._databaseId);\n return new UserDataReader(\n firestore._databaseId,\n !!settings.ignoreUndefinedProperties,\n serializer\n );\n}\n\n/** Parse document data from a set() call. */\nexport function parseSetData(\n userDataReader: UserDataReader,\n methodName: string,\n targetDoc: DocumentKey,\n input: unknown,\n hasConverter: boolean,\n options: SetOptions = {}\n): ParsedSetData {\n const context = userDataReader.createContext(\n options.merge || options.mergeFields\n ? UserDataSource.MergeSet\n : UserDataSource.Set,\n methodName,\n targetDoc,\n hasConverter\n );\n validatePlainObject('Data must be an object, but it was:', context, input);\n const updateData = parseObject(input, context)!;\n\n let fieldMask: FieldMask | null;\n let fieldTransforms: FieldTransform[];\n\n if (options.merge) {\n fieldMask = new FieldMask(context.fieldMask);\n fieldTransforms = context.fieldTransforms;\n } else if (options.mergeFields) {\n const validatedFieldPaths: InternalFieldPath[] = [];\n\n for (const stringOrFieldPath of options.mergeFields) {\n const fieldPath = fieldPathFromArgument(\n methodName,\n stringOrFieldPath,\n targetDoc\n );\n if (!context.contains(fieldPath)) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Field '${fieldPath}' is specified in your field mask but missing from your input data.`\n );\n }\n\n if (!fieldMaskContains(validatedFieldPaths, fieldPath)) {\n validatedFieldPaths.push(fieldPath);\n }\n }\n\n fieldMask = new FieldMask(validatedFieldPaths);\n fieldTransforms = context.fieldTransforms.filter(transform =>\n fieldMask!.covers(transform.field)\n );\n } else {\n fieldMask = null;\n fieldTransforms = context.fieldTransforms;\n }\n\n return new ParsedSetData(\n new ObjectValue(updateData),\n fieldMask,\n fieldTransforms\n );\n}\n\nexport class DeleteFieldValueImpl extends FieldValue {\n _toFieldTransform(context: ParseContextImpl): null {\n if (context.dataSource === UserDataSource.MergeSet) {\n // No transform to add for a delete, but we need to add it to our\n // fieldMask so it gets deleted.\n context.fieldMask.push(context.path!);\n } else if (context.dataSource === UserDataSource.Update) {\n debugAssert(\n context.path!.length > 0,\n `${this._methodName}() at the top level should have already ` +\n 'been handled.'\n );\n throw context.createError(\n `${this._methodName}() can only appear at the top level ` +\n 'of your update data'\n );\n } else {\n // We shouldn't encounter delete sentinels for queries or non-merge set() calls.\n throw context.createError(\n `${this._methodName}() cannot be used with set() unless you pass ` +\n '{merge:true}'\n );\n }\n return null;\n }\n\n isEqual(other: FieldValue): boolean {\n return other instanceof DeleteFieldValueImpl;\n }\n}\n\n/**\n * Creates a child context for parsing SerializableFieldValues.\n *\n * This is different than calling `ParseContext.contextWith` because it keeps\n * the fieldTransforms and fieldMask separate.\n *\n * The created context has its `dataSource` set to `UserDataSource.Argument`.\n * Although these values are used with writes, any elements in these FieldValues\n * are not considered writes since they cannot contain any FieldValue sentinels,\n * etc.\n *\n * @param fieldValue - The sentinel FieldValue for which to create a child\n * context.\n * @param context - The parent context.\n * @param arrayElement - Whether or not the FieldValue has an array.\n */\nfunction createSentinelChildContext(\n fieldValue: FieldValue,\n context: ParseContextImpl,\n arrayElement: boolean\n): ParseContextImpl {\n return new ParseContextImpl(\n {\n dataSource: UserDataSource.Argument,\n targetDoc: context.settings.targetDoc,\n methodName: fieldValue._methodName,\n arrayElement\n },\n context.databaseId,\n context.serializer,\n context.ignoreUndefinedProperties\n );\n}\n\nexport class ServerTimestampFieldValueImpl extends FieldValue {\n _toFieldTransform(context: ParseContextImpl): FieldTransform {\n return new FieldTransform(context.path!, new ServerTimestampTransform());\n }\n\n isEqual(other: FieldValue): boolean {\n return other instanceof ServerTimestampFieldValueImpl;\n }\n}\n\nexport class ArrayUnionFieldValueImpl extends FieldValue {\n constructor(methodName: string, private readonly _elements: unknown[]) {\n super(methodName);\n }\n\n _toFieldTransform(context: ParseContextImpl): FieldTransform {\n const parseContext = createSentinelChildContext(\n this,\n context,\n /*array=*/ true\n );\n const parsedElements = this._elements.map(\n element => parseData(element, parseContext)!\n );\n const arrayUnion = new ArrayUnionTransformOperation(parsedElements);\n return new FieldTransform(context.path!, arrayUnion);\n }\n\n isEqual(other: FieldValue): boolean {\n return (\n other instanceof ArrayUnionFieldValueImpl &&\n deepEqual(this._elements, other._elements)\n );\n }\n}\n\nexport class ArrayRemoveFieldValueImpl extends FieldValue {\n constructor(methodName: string, private readonly _elements: unknown[]) {\n super(methodName);\n }\n\n _toFieldTransform(context: ParseContextImpl): FieldTransform {\n const parseContext = createSentinelChildContext(\n this,\n context,\n /*array=*/ true\n );\n const parsedElements = this._elements.map(\n element => parseData(element, parseContext)!\n );\n const arrayUnion = new ArrayRemoveTransformOperation(parsedElements);\n return new FieldTransform(context.path!, arrayUnion);\n }\n\n isEqual(other: FieldValue): boolean {\n return (\n other instanceof ArrayRemoveFieldValueImpl &&\n deepEqual(this._elements, other._elements)\n );\n }\n}\n\nexport class NumericIncrementFieldValueImpl extends FieldValue {\n constructor(methodName: string, private readonly _operand: number) {\n super(methodName);\n }\n\n _toFieldTransform(context: ParseContextImpl): FieldTransform {\n const numericIncrement = new NumericIncrementTransformOperation(\n context.serializer,\n toNumber(context.serializer, this._operand)\n );\n return new FieldTransform(context.path!, numericIncrement);\n }\n\n isEqual(other: FieldValue): boolean {\n return (\n other instanceof NumericIncrementFieldValueImpl &&\n this._operand === other._operand\n );\n }\n}\n\n/** Parse update data from an update() call. */\nexport function parseUpdateData(\n userDataReader: UserDataReader,\n methodName: string,\n targetDoc: DocumentKey,\n input: unknown\n): ParsedUpdateData {\n const context = userDataReader.createContext(\n UserDataSource.Update,\n methodName,\n targetDoc\n );\n validatePlainObject('Data must be an object, but it was:', context, input);\n\n const fieldMaskPaths: InternalFieldPath[] = [];\n const updateData = ObjectValue.empty();\n forEach(input as Dict, (key, value) => {\n const path = fieldPathFromDotSeparatedString(methodName, key, targetDoc);\n\n // For Compat types, we have to \"extract\" the underlying types before\n // performing validation.\n value = getModularInstance(value);\n\n const childContext = context.childContextForFieldPath(path);\n if (value instanceof DeleteFieldValueImpl) {\n // Add it to the field mask, but don't add anything to updateData.\n fieldMaskPaths.push(path);\n } else {\n const parsedValue = parseData(value, childContext);\n if (parsedValue != null) {\n fieldMaskPaths.push(path);\n updateData.set(path, parsedValue);\n }\n }\n });\n\n const mask = new FieldMask(fieldMaskPaths);\n return new ParsedUpdateData(updateData, mask, context.fieldTransforms);\n}\n\n/** Parse update data from a list of field/value arguments. */\nexport function parseUpdateVarargs(\n userDataReader: UserDataReader,\n methodName: string,\n targetDoc: DocumentKey,\n field: string | PublicFieldPath | Compat,\n value: unknown,\n moreFieldsAndValues: unknown[]\n): ParsedUpdateData {\n const context = userDataReader.createContext(\n UserDataSource.Update,\n methodName,\n targetDoc\n );\n const keys = [fieldPathFromArgument(methodName, field, targetDoc)];\n const values = [value];\n\n if (moreFieldsAndValues.length % 2 !== 0) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Function ${methodName}() needs to be called with an even number ` +\n 'of arguments that alternate between field names and values.'\n );\n }\n\n for (let i = 0; i < moreFieldsAndValues.length; i += 2) {\n keys.push(\n fieldPathFromArgument(\n methodName,\n moreFieldsAndValues[i] as string | PublicFieldPath\n )\n );\n values.push(moreFieldsAndValues[i + 1]);\n }\n\n const fieldMaskPaths: InternalFieldPath[] = [];\n const updateData = ObjectValue.empty();\n\n // We iterate in reverse order to pick the last value for a field if the\n // user specified the field multiple times.\n for (let i = keys.length - 1; i >= 0; --i) {\n if (!fieldMaskContains(fieldMaskPaths, keys[i])) {\n const path = keys[i];\n let value = values[i];\n\n // For Compat types, we have to \"extract\" the underlying types before\n // performing validation.\n value = getModularInstance(value);\n\n const childContext = context.childContextForFieldPath(path);\n if (value instanceof DeleteFieldValueImpl) {\n // Add it to the field mask, but don't add anything to updateData.\n fieldMaskPaths.push(path);\n } else {\n const parsedValue = parseData(value, childContext);\n if (parsedValue != null) {\n fieldMaskPaths.push(path);\n updateData.set(path, parsedValue);\n }\n }\n }\n }\n\n const mask = new FieldMask(fieldMaskPaths);\n return new ParsedUpdateData(updateData, mask, context.fieldTransforms);\n}\n\n/**\n * Parse a \"query value\" (e.g. value in a where filter or a value in a cursor\n * bound).\n *\n * @param allowArrays - Whether the query value is an array that may directly\n * contain additional arrays (e.g. the operand of an `in` query).\n */\nexport function parseQueryValue(\n userDataReader: UserDataReader,\n methodName: string,\n input: unknown,\n allowArrays = false\n): ProtoValue {\n const context = userDataReader.createContext(\n allowArrays ? UserDataSource.ArrayArgument : UserDataSource.Argument,\n methodName\n );\n const parsed = parseData(input, context);\n debugAssert(parsed != null, 'Parsed data should not be null.');\n debugAssert(\n context.fieldTransforms.length === 0,\n 'Field transforms should have been disallowed.'\n );\n return parsed;\n}\n\n/**\n * Parses user data to Protobuf Values.\n *\n * @param input - Data to be parsed.\n * @param context - A context object representing the current path being parsed,\n * the source of the data being parsed, etc.\n * @returns The parsed value, or null if the value was a FieldValue sentinel\n * that should not be included in the resulting parsed data.\n */\nexport function parseData(\n input: unknown,\n context: ParseContextImpl\n): ProtoValue | null {\n // Unwrap the API type from the Compat SDK. This will return the API type\n // from firestore-exp.\n input = getModularInstance(input);\n\n if (looksLikeJsonObject(input)) {\n validatePlainObject('Unsupported field value:', context, input);\n return parseObject(input, context);\n } else if (input instanceof FieldValue) {\n // FieldValues usually parse into transforms (except deleteField())\n // in which case we do not want to include this field in our parsed data\n // (as doing so will overwrite the field directly prior to the transform\n // trying to transform it). So we don't add this location to\n // context.fieldMask and we return null as our parsing result.\n parseSentinelFieldValue(input, context);\n return null;\n } else if (input === undefined && context.ignoreUndefinedProperties) {\n // If the input is undefined it can never participate in the fieldMask, so\n // don't handle this below. If `ignoreUndefinedProperties` is false,\n // `parseScalarValue` will reject an undefined value.\n return null;\n } else {\n // If context.path is null we are inside an array and we don't support\n // field mask paths more granular than the top-level array.\n if (context.path) {\n context.fieldMask.push(context.path);\n }\n\n if (input instanceof Array) {\n // TODO(b/34871131): Include the path containing the array in the error\n // message.\n // In the case of IN queries, the parsed data is an array (representing\n // the set of values to be included for the IN query) that may directly\n // contain additional arrays (each representing an individual field\n // value), so we disable this validation.\n if (\n context.settings.arrayElement &&\n context.dataSource !== UserDataSource.ArrayArgument\n ) {\n throw context.createError('Nested arrays are not supported');\n }\n return parseArray(input as unknown[], context);\n } else {\n return parseScalarValue(input, context);\n }\n }\n}\n\nexport function parseObject(\n obj: Dict,\n context: ParseContextImpl\n): { mapValue: ProtoMapValue } {\n const fields: Dict = {};\n\n if (isEmpty(obj)) {\n // If we encounter an empty object, we explicitly add it to the update\n // mask to ensure that the server creates a map entry.\n if (context.path && context.path.length > 0) {\n context.fieldMask.push(context.path);\n }\n } else {\n forEach(obj, (key: string, val: unknown) => {\n const parsedValue = parseData(val, context.childContextForField(key));\n if (parsedValue != null) {\n fields[key] = parsedValue;\n }\n });\n }\n\n return { mapValue: { fields } };\n}\n\nfunction parseArray(array: unknown[], context: ParseContextImpl): ProtoValue {\n const values: ProtoValue[] = [];\n let entryIndex = 0;\n for (const entry of array) {\n let parsedEntry = parseData(\n entry,\n context.childContextForArray(entryIndex)\n );\n if (parsedEntry == null) {\n // Just include nulls in the array for fields being replaced with a\n // sentinel.\n parsedEntry = { nullValue: 'NULL_VALUE' };\n }\n values.push(parsedEntry);\n entryIndex++;\n }\n return { arrayValue: { values } };\n}\n\n/**\n * \"Parses\" the provided FieldValueImpl, adding any necessary transforms to\n * context.fieldTransforms.\n */\nfunction parseSentinelFieldValue(\n value: FieldValue,\n context: ParseContextImpl\n): void {\n // Sentinels are only supported with writes, and not within arrays.\n if (!isWrite(context.dataSource)) {\n throw context.createError(\n `${value._methodName}() can only be used with update() and set()`\n );\n }\n if (!context.path) {\n throw context.createError(\n `${value._methodName}() is not currently supported inside arrays`\n );\n }\n\n const fieldTransform = value._toFieldTransform(context);\n if (fieldTransform) {\n context.fieldTransforms.push(fieldTransform);\n }\n}\n\n/**\n * Helper to parse a scalar value (i.e. not an Object, Array, or FieldValue)\n *\n * @returns The parsed value\n */\nfunction parseScalarValue(\n value: unknown,\n context: ParseContextImpl\n): ProtoValue | null {\n value = getModularInstance(value);\n\n if (value === null) {\n return { nullValue: 'NULL_VALUE' };\n } else if (typeof value === 'number') {\n return toNumber(context.serializer, value);\n } else if (typeof value === 'boolean') {\n return { booleanValue: value };\n } else if (typeof value === 'string') {\n return { stringValue: value };\n } else if (value instanceof Date) {\n const timestamp = Timestamp.fromDate(value);\n return {\n timestampValue: toTimestamp(context.serializer, timestamp)\n };\n } else if (value instanceof Timestamp) {\n // Firestore backend truncates precision down to microseconds. To ensure\n // offline mode works the same with regards to truncation, perform the\n // truncation immediately without waiting for the backend to do that.\n const timestamp = new Timestamp(\n value.seconds,\n Math.floor(value.nanoseconds / 1000) * 1000\n );\n return {\n timestampValue: toTimestamp(context.serializer, timestamp)\n };\n } else if (value instanceof GeoPoint) {\n return {\n geoPointValue: {\n latitude: value.latitude,\n longitude: value.longitude\n }\n };\n } else if (value instanceof Bytes) {\n return { bytesValue: toBytes(context.serializer, value._byteString) };\n } else if (value instanceof DocumentReference) {\n const thisDb = context.databaseId;\n const otherDb = value.firestore._databaseId;\n if (!otherDb.isEqual(thisDb)) {\n throw context.createError(\n 'Document reference is for database ' +\n `${otherDb.projectId}/${otherDb.database} but should be ` +\n `for database ${thisDb.projectId}/${thisDb.database}`\n );\n }\n return {\n referenceValue: toResourceName(\n value.firestore._databaseId || context.databaseId,\n value._key.path\n )\n };\n } else if (value instanceof VectorValue) {\n return parseVectorValue(value, context);\n } else {\n throw context.createError(\n `Unsupported field value: ${valueDescription(value)}`\n );\n }\n}\n\n/**\n * Creates a new VectorValue proto value (using the internal format).\n */\nexport function parseVectorValue(\n value: VectorValue,\n context: ParseContextImpl\n): ProtoValue {\n const mapValue: ProtoMapValue = {\n fields: {\n [TYPE_KEY]: {\n stringValue: VECTOR_VALUE_SENTINEL\n },\n [VECTOR_MAP_VECTORS_KEY]: {\n arrayValue: {\n values: value.toArray().map(value => {\n if (typeof value !== 'number') {\n throw context.createError(\n 'VectorValues must only contain numeric values.'\n );\n }\n\n return toDouble(context.serializer, value);\n })\n }\n }\n }\n };\n\n return { mapValue };\n}\n\n/**\n * Checks whether an object looks like a JSON object that should be converted\n * into a struct. Normal class/prototype instances are considered to look like\n * JSON objects since they should be converted to a struct value. Arrays, Dates,\n * GeoPoints, etc. are not considered to look like JSON objects since they map\n * to specific FieldValue types other than ObjectValue.\n */\nfunction looksLikeJsonObject(input: unknown): boolean {\n return (\n typeof input === 'object' &&\n input !== null &&\n !(input instanceof Array) &&\n !(input instanceof Date) &&\n !(input instanceof Timestamp) &&\n !(input instanceof GeoPoint) &&\n !(input instanceof Bytes) &&\n !(input instanceof DocumentReference) &&\n !(input instanceof FieldValue) &&\n !(input instanceof VectorValue)\n );\n}\n\nfunction validatePlainObject(\n message: string,\n context: ParseContextImpl,\n input: unknown\n): asserts input is Dict {\n if (!looksLikeJsonObject(input) || !isPlainObject(input)) {\n const description = valueDescription(input);\n if (description === 'an object') {\n // Massage the error if it was an object.\n throw context.createError(message + ' a custom object');\n } else {\n throw context.createError(message + ' ' + description);\n }\n }\n}\n\n/**\n * Helper that calls fromDotSeparatedString() but wraps any error thrown.\n */\nexport function fieldPathFromArgument(\n methodName: string,\n path: string | PublicFieldPath | Compat,\n targetDoc?: DocumentKey\n): InternalFieldPath {\n // If required, replace the FieldPath Compat class with the firestore-exp\n // FieldPath.\n path = getModularInstance(path);\n\n if (path instanceof FieldPath) {\n return path._internalPath;\n } else if (typeof path === 'string') {\n return fieldPathFromDotSeparatedString(methodName, path);\n } else {\n const message = 'Field path arguments must be of type string or ';\n throw createError(\n message,\n methodName,\n /* hasConverter= */ false,\n /* path= */ undefined,\n targetDoc\n );\n }\n}\n\n/**\n * Matches any characters in a field path string that are reserved.\n */\nconst FIELD_PATH_RESERVED = new RegExp('[~\\\\*/\\\\[\\\\]]');\n\n/**\n * Wraps fromDotSeparatedString with an error message about the method that\n * was thrown.\n * @param methodName - The publicly visible method name\n * @param path - The dot-separated string form of a field path which will be\n * split on dots.\n * @param targetDoc - The document against which the field path will be\n * evaluated.\n */\nexport function fieldPathFromDotSeparatedString(\n methodName: string,\n path: string,\n targetDoc?: DocumentKey\n): InternalFieldPath {\n const found = path.search(FIELD_PATH_RESERVED);\n if (found >= 0) {\n throw createError(\n `Invalid field path (${path}). Paths must not contain ` +\n `'~', '*', '/', '[', or ']'`,\n methodName,\n /* hasConverter= */ false,\n /* path= */ undefined,\n targetDoc\n );\n }\n\n try {\n return new FieldPath(...path.split('.'))._internalPath;\n } catch (e) {\n throw createError(\n `Invalid field path (${path}). Paths must not be empty, ` +\n `begin with '.', end with '.', or contain '..'`,\n methodName,\n /* hasConverter= */ false,\n /* path= */ undefined,\n targetDoc\n );\n }\n}\n\nfunction createError(\n reason: string,\n methodName: string,\n hasConverter: boolean,\n path?: InternalFieldPath,\n targetDoc?: DocumentKey\n): FirestoreError {\n const hasPath = path && !path.isEmpty();\n const hasDocument = targetDoc !== undefined;\n let message = `Function ${methodName}() called with invalid data`;\n if (hasConverter) {\n message += ' (via `toFirestore()`)';\n }\n message += '. ';\n\n let description = '';\n if (hasPath || hasDocument) {\n description += ' (found';\n\n if (hasPath) {\n description += ` in field ${path}`;\n }\n if (hasDocument) {\n description += ` in document ${targetDoc}`;\n }\n description += ')';\n }\n\n return new FirestoreError(\n Code.INVALID_ARGUMENT,\n message + reason + description\n );\n}\n\n/** Checks `haystack` if FieldPath `needle` is present. Runs in O(n). */\nfunction fieldMaskContains(\n haystack: InternalFieldPath[],\n needle: InternalFieldPath\n): boolean {\n return haystack.some(v => v.isEqual(needle));\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Compat, getModularInstance } from '@firebase/util';\n\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { FieldPath as InternalFieldPath } from '../model/path';\nimport { arrayEquals } from '../util/misc';\n\nimport { Firestore } from './database';\nimport { FieldPath } from './field_path';\nimport {\n DocumentData,\n DocumentReference,\n PartialWithFieldValue,\n Query,\n queryEqual,\n SetOptions,\n WithFieldValue\n} from './reference';\nimport {\n fieldPathFromDotSeparatedString,\n UntypedFirestoreDataConverter\n} from './user_data_reader';\nimport { AbstractUserDataWriter } from './user_data_writer';\n\n/**\n * Converter used by `withConverter()` to transform user objects of type\n * `AppModelType` into Firestore data of type `DbModelType`.\n *\n * Using the converter allows you to specify generic type arguments when\n * storing and retrieving objects from Firestore.\n *\n * In this context, an \"AppModel\" is a class that is used in an application to\n * package together related information and functionality. Such a class could,\n * for example, have properties with complex, nested data types, properties used\n * for memoization, properties of types not supported by Firestore (such as\n * `symbol` and `bigint`), and helper functions that perform compound\n * operations. Such classes are not suitable and/or possible to store into a\n * Firestore database. Instead, instances of such classes need to be converted\n * to \"plain old JavaScript objects\" (POJOs) with exclusively primitive\n * properties, potentially nested inside other POJOs or arrays of POJOs. In this\n * context, this type is referred to as the \"DbModel\" and would be an object\n * suitable for persisting into Firestore. For convenience, applications can\n * implement `FirestoreDataConverter` and register the converter with Firestore\n * objects, such as `DocumentReference` or `Query`, to automatically convert\n * `AppModel` to `DbModel` when storing into Firestore, and convert `DbModel`\n * to `AppModel` when retrieving from Firestore.\n *\n * @example\n *\n * Simple Example\n *\n * ```typescript\n * const numberConverter = {\n * toFirestore(value: WithFieldValue) {\n * return { value };\n * },\n * fromFirestore(snapshot: QueryDocumentSnapshot, options: SnapshotOptions) {\n * return snapshot.data(options).value as number;\n * }\n * };\n *\n * async function simpleDemo(db: Firestore): Promise {\n * const documentRef = doc(db, 'values/value123').withConverter(numberConverter);\n *\n * // converters are used with `setDoc`, `addDoc`, and `getDoc`\n * await setDoc(documentRef, 42);\n * const snapshot1 = await getDoc(documentRef);\n * assertEqual(snapshot1.data(), 42);\n *\n * // converters are not used when writing data with `updateDoc`\n * await updateDoc(documentRef, { value: 999 });\n * const snapshot2 = await getDoc(documentRef);\n * assertEqual(snapshot2.data(), 999);\n * }\n * ```\n *\n * Advanced Example\n *\n * ```typescript\n * // The Post class is a model that is used by our application.\n * // This class may have properties and methods that are specific\n * // to our application execution, which do not need to be persisted\n * // to Firestore.\n * class Post {\n * constructor(\n * readonly title: string,\n * readonly author: string,\n * readonly lastUpdatedMillis: number\n * ) {}\n * toString(): string {\n * return `${this.title} by ${this.author}`;\n * }\n * }\n *\n * // The PostDbModel represents how we want our posts to be stored\n * // in Firestore. This DbModel has different properties (`ttl`,\n * // `aut`, and `lut`) from the Post class we use in our application.\n * interface PostDbModel {\n * ttl: string;\n * aut: { firstName: string; lastName: string };\n * lut: Timestamp;\n * }\n *\n * // The `PostConverter` implements `FirestoreDataConverter` and specifies\n * // how the Firestore SDK can convert `Post` objects to `PostDbModel`\n * // objects and vice versa.\n * class PostConverter implements FirestoreDataConverter {\n * toFirestore(post: WithFieldValue): WithFieldValue {\n * return {\n * ttl: post.title,\n * aut: this._autFromAuthor(post.author),\n * lut: this._lutFromLastUpdatedMillis(post.lastUpdatedMillis)\n * };\n * }\n *\n * fromFirestore(snapshot: QueryDocumentSnapshot, options: SnapshotOptions): Post {\n * const data = snapshot.data(options) as PostDbModel;\n * const author = `${data.aut.firstName} ${data.aut.lastName}`;\n * return new Post(data.ttl, author, data.lut.toMillis());\n * }\n *\n * _autFromAuthor(\n * author: string | FieldValue\n * ): { firstName: string; lastName: string } | FieldValue {\n * if (typeof author !== 'string') {\n * // `author` is a FieldValue, so just return it.\n * return author;\n * }\n * const [firstName, lastName] = author.split(' ');\n * return {firstName, lastName};\n * }\n *\n * _lutFromLastUpdatedMillis(\n * lastUpdatedMillis: number | FieldValue\n * ): Timestamp | FieldValue {\n * if (typeof lastUpdatedMillis !== 'number') {\n * // `lastUpdatedMillis` must be a FieldValue, so just return it.\n * return lastUpdatedMillis;\n * }\n * return Timestamp.fromMillis(lastUpdatedMillis);\n * }\n * }\n *\n * async function advancedDemo(db: Firestore): Promise {\n * // Create a `DocumentReference` with a `FirestoreDataConverter`.\n * const documentRef = doc(db, 'posts/post123').withConverter(new PostConverter());\n *\n * // The `data` argument specified to `setDoc()` is type checked by the\n * // TypeScript compiler to be compatible with `Post`. Since the `data`\n * // argument is typed as `WithFieldValue` rather than just `Post`,\n * // this allows properties of the `data` argument to also be special\n * // Firestore values that perform server-side mutations, such as\n * // `arrayRemove()`, `deleteField()`, and `serverTimestamp()`.\n * await setDoc(documentRef, {\n * title: 'My Life',\n * author: 'Foo Bar',\n * lastUpdatedMillis: serverTimestamp()\n * });\n *\n * // The TypeScript compiler will fail to compile if the `data` argument to\n * // `setDoc()` is _not_ compatible with `WithFieldValue`. This\n * // type checking prevents the caller from specifying objects with incorrect\n * // properties or property values.\n * // @ts-expect-error \"Argument of type { ttl: string; } is not assignable\n * // to parameter of type WithFieldValue\"\n * await setDoc(documentRef, { ttl: 'The Title' });\n *\n * // When retrieving a document with `getDoc()` the `DocumentSnapshot`\n * // object's `data()` method returns a `Post`, rather than a generic object,\n * // which would have been returned if the `DocumentReference` did _not_ have a\n * // `FirestoreDataConverter` attached to it.\n * const snapshot1: DocumentSnapshot = await getDoc(documentRef);\n * const post1: Post = snapshot1.data()!;\n * if (post1) {\n * assertEqual(post1.title, 'My Life');\n * assertEqual(post1.author, 'Foo Bar');\n * }\n *\n * // The `data` argument specified to `updateDoc()` is type checked by the\n * // TypeScript compiler to be compatible with `PostDbModel`. Note that\n * // unlike `setDoc()`, whose `data` argument must be compatible with `Post`,\n * // the `data` argument to `updateDoc()` must be compatible with\n * // `PostDbModel`. Similar to `setDoc()`, since the `data` argument is typed\n * // as `WithFieldValue` rather than just `PostDbModel`, this\n * // allows properties of the `data` argument to also be those special\n * // Firestore values, like `arrayRemove()`, `deleteField()`, and\n * // `serverTimestamp()`.\n * await updateDoc(documentRef, {\n * 'aut.firstName': 'NewFirstName',\n * lut: serverTimestamp()\n * });\n *\n * // The TypeScript compiler will fail to compile if the `data` argument to\n * // `updateDoc()` is _not_ compatible with `WithFieldValue`.\n * // This type checking prevents the caller from specifying objects with\n * // incorrect properties or property values.\n * // @ts-expect-error \"Argument of type { title: string; } is not assignable\n * // to parameter of type WithFieldValue\"\n * await updateDoc(documentRef, { title: 'New Title' });\n * const snapshot2: DocumentSnapshot = await getDoc(documentRef);\n * const post2: Post = snapshot2.data()!;\n * if (post2) {\n * assertEqual(post2.title, 'My Life');\n * assertEqual(post2.author, 'NewFirstName Bar');\n * }\n * }\n * ```\n */\nexport interface FirestoreDataConverter<\n AppModelType,\n DbModelType extends DocumentData = DocumentData\n> {\n /**\n * Called by the Firestore SDK to convert a custom model object of type\n * `AppModelType` into a plain JavaScript object (suitable for writing\n * directly to the Firestore database) of type `DbModelType`. Used with\n * {@link @firebase/firestore/lite#(setDoc:1)},\n * {@link @firebase/firestore/lite#(WriteBatch.set:1)} and\n * {@link @firebase/firestore/lite#(Transaction.set:1)}.\n *\n * The `WithFieldValue` type extends `T` to also allow FieldValues such as\n * {@link (deleteField:1)} to be used as property values.\n */\n toFirestore(\n modelObject: WithFieldValue\n ): WithFieldValue;\n\n /**\n * Called by the Firestore SDK to convert a custom model object of type\n * `AppModelType` into a plain JavaScript object (suitable for writing\n * directly to the Firestore database) of type `DbModelType`. Used with\n * {@link @firebase/firestore/lite#(setDoc:1)},\n * {@link @firebase/firestore/lite#(WriteBatch.set:1)} and\n * {@link @firebase/firestore/lite#(Transaction.set:1)} with `merge:true`\n * or `mergeFields`.\n *\n * The `PartialWithFieldValue` type extends `Partial` to allow\n * FieldValues such as {@link (arrayUnion:1)} to be used as property values.\n * It also supports nested `Partial` by allowing nested fields to be\n * omitted.\n */\n toFirestore(\n modelObject: PartialWithFieldValue,\n options: SetOptions\n ): PartialWithFieldValue;\n\n /**\n * Called by the Firestore SDK to convert Firestore data into an object of\n * type `AppModelType`. You can access your data by calling:\n * `snapshot.data()`.\n *\n *\n * Generally, the data returned from `snapshot.data()` can be cast to\n * `DbModelType`; however, this is not guaranteed because Firestore does not\n * enforce a schema on the database. For example, writes from a previous\n * version of the application or writes from another client that did not use a\n * type converter could have written data with different properties and/or\n * property types. The implementation will need to choose whether to\n * gracefully recover from non-conforming data or throw an error.\n *\n * @param snapshot - A `QueryDocumentSnapshot` containing your data and\n * metadata.\n */\n fromFirestore(\n snapshot: QueryDocumentSnapshot\n ): AppModelType;\n}\n\n/**\n * A `DocumentSnapshot` contains data read from a document in your Firestore\n * database. The data can be extracted with `.data()` or `.get()` to\n * get a specific field.\n *\n * For a `DocumentSnapshot` that points to a non-existing document, any data\n * access will return 'undefined'. You can use the `exists()` method to\n * explicitly verify a document's existence.\n */\nexport class DocumentSnapshot<\n AppModelType = DocumentData,\n DbModelType extends DocumentData = DocumentData\n> {\n // Note: This class is stripped down version of the DocumentSnapshot in\n // the legacy SDK. The changes are:\n // - No support for SnapshotMetadata.\n // - No support for SnapshotOptions.\n\n /** @hideconstructor protected */\n constructor(\n public _firestore: Firestore,\n public _userDataWriter: AbstractUserDataWriter,\n public _key: DocumentKey,\n public _document: Document | null,\n public _converter: UntypedFirestoreDataConverter<\n AppModelType,\n DbModelType\n > | null\n ) {}\n\n /** Property of the `DocumentSnapshot` that provides the document's ID. */\n get id(): string {\n return this._key.path.lastSegment();\n }\n\n /**\n * The `DocumentReference` for the document included in the `DocumentSnapshot`.\n */\n get ref(): DocumentReference {\n return new DocumentReference(\n this._firestore,\n this._converter,\n this._key\n );\n }\n\n /**\n * Signals whether or not the document at the snapshot's location exists.\n *\n * @returns true if the document exists.\n */\n exists(): this is QueryDocumentSnapshot {\n return this._document !== null;\n }\n\n /**\n * Retrieves all fields in the document as an `Object`. Returns `undefined` if\n * the document doesn't exist.\n *\n * @returns An `Object` containing all fields in the document or `undefined`\n * if the document doesn't exist.\n */\n data(): AppModelType | undefined {\n if (!this._document) {\n return undefined;\n } else if (this._converter) {\n // We only want to use the converter and create a new DocumentSnapshot\n // if a converter has been provided.\n const snapshot = new QueryDocumentSnapshot(\n this._firestore,\n this._userDataWriter,\n this._key,\n this._document,\n /* converter= */ null\n );\n return this._converter.fromFirestore(snapshot);\n } else {\n return this._userDataWriter.convertValue(\n this._document.data.value\n ) as AppModelType;\n }\n }\n\n /**\n * Retrieves the field specified by `fieldPath`. Returns `undefined` if the\n * document or field doesn't exist.\n *\n * @param fieldPath - The path (for example 'foo' or 'foo.bar') to a specific\n * field.\n * @returns The data at the specified field location or undefined if no such\n * field exists in the document.\n */\n // We are using `any` here to avoid an explicit cast by our users.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n get(fieldPath: string | FieldPath): any {\n if (this._document) {\n const value = this._document.data.field(\n fieldPathFromArgument('DocumentSnapshot.get', fieldPath)\n );\n if (value !== null) {\n return this._userDataWriter.convertValue(value);\n }\n }\n return undefined;\n }\n}\n\n/**\n * A `QueryDocumentSnapshot` contains data read from a document in your\n * Firestore database as part of a query. The document is guaranteed to exist\n * and its data can be extracted with `.data()` or `.get()` to get a\n * specific field.\n *\n * A `QueryDocumentSnapshot` offers the same API surface as a\n * `DocumentSnapshot`. Since query results contain only existing documents, the\n * `exists` property will always be true and `data()` will never return\n * 'undefined'.\n */\nexport class QueryDocumentSnapshot<\n AppModelType = DocumentData,\n DbModelType extends DocumentData = DocumentData\n> extends DocumentSnapshot {\n /**\n * Retrieves all fields in the document as an `Object`.\n *\n * @override\n * @returns An `Object` containing all fields in the document.\n */\n data(): AppModelType {\n return super.data() as AppModelType;\n }\n}\n\n/**\n * A `QuerySnapshot` contains zero or more `DocumentSnapshot` objects\n * representing the results of a query. The documents can be accessed as an\n * array via the `docs` property or enumerated using the `forEach` method. The\n * number of documents can be determined via the `empty` and `size`\n * properties.\n */\nexport class QuerySnapshot<\n AppModelType = DocumentData,\n DbModelType extends DocumentData = DocumentData\n> {\n /**\n * The query on which you called {@link getDocs} in order to get this\n * `QuerySnapshot`.\n */\n readonly query: Query;\n\n /** @hideconstructor */\n constructor(\n _query: Query,\n readonly _docs: Array>\n ) {\n this.query = _query;\n }\n\n /** An array of all the documents in the `QuerySnapshot`. */\n get docs(): Array> {\n return [...this._docs];\n }\n\n /** The number of documents in the `QuerySnapshot`. */\n get size(): number {\n return this.docs.length;\n }\n\n /** True if there are no documents in the `QuerySnapshot`. */\n get empty(): boolean {\n return this.docs.length === 0;\n }\n\n /**\n * Enumerates all of the documents in the `QuerySnapshot`.\n *\n * @param callback - A callback to be called with a `QueryDocumentSnapshot` for\n * each document in the snapshot.\n * @param thisArg - The `this` binding for the callback.\n */\n forEach(\n callback: (\n result: QueryDocumentSnapshot\n ) => void,\n thisArg?: unknown\n ): void {\n this._docs.forEach(callback, thisArg);\n }\n}\n\n/**\n * Returns true if the provided snapshots are equal.\n *\n * @param left - A snapshot to compare.\n * @param right - A snapshot to compare.\n * @returns true if the snapshots are equal.\n */\nexport function snapshotEqual(\n left:\n | DocumentSnapshot\n | QuerySnapshot,\n right:\n | DocumentSnapshot\n | QuerySnapshot\n): boolean {\n left = getModularInstance(left);\n right = getModularInstance(right);\n\n if (left instanceof DocumentSnapshot && right instanceof DocumentSnapshot) {\n return (\n left._firestore === right._firestore &&\n left._key.isEqual(right._key) &&\n (left._document === null\n ? right._document === null\n : left._document.isEqual(right._document)) &&\n left._converter === right._converter\n );\n } else if (left instanceof QuerySnapshot && right instanceof QuerySnapshot) {\n return (\n queryEqual(left.query, right.query) &&\n arrayEquals(left.docs, right.docs, snapshotEqual)\n );\n }\n\n return false;\n}\n\n/**\n * Helper that calls `fromDotSeparatedString()` but wraps any error thrown.\n */\nexport function fieldPathFromArgument(\n methodName: string,\n arg: string | FieldPath | Compat\n): InternalFieldPath {\n if (typeof arg === 'string') {\n return fieldPathFromDotSeparatedString(methodName, arg);\n } else if (arg instanceof FieldPath) {\n return arg._internalPath;\n } else {\n return arg._delegate._internalPath;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getModularInstance } from '@firebase/util';\n\nimport { Bound } from '../core/bound';\nimport { DatabaseId } from '../core/database_info';\nimport {\n CompositeFilter,\n CompositeOperator,\n FieldFilter,\n Filter,\n Operator\n} from '../core/filter';\nimport { Direction, OrderBy } from '../core/order_by';\nimport {\n isCollectionGroupQuery,\n LimitType,\n Query as InternalQuery,\n queryNormalizedOrderBy,\n queryWithAddedFilter,\n queryWithAddedOrderBy,\n queryWithEndAt,\n queryWithLimit,\n queryWithStartAt\n} from '../core/query';\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { FieldPath as InternalFieldPath, ResourcePath } from '../model/path';\nimport { isServerTimestamp } from '../model/server_timestamps';\nimport { refValue } from '../model/values';\nimport { Value as ProtoValue } from '../protos/firestore_proto_api';\nimport { Code, FirestoreError } from '../util/error';\nimport {\n validatePositiveNumber,\n valueDescription\n} from '../util/input_validation';\n\nimport { FieldPath } from './field_path';\nimport { DocumentData, DocumentReference, Query } from './reference';\nimport { DocumentSnapshot, fieldPathFromArgument } from './snapshot';\nimport {\n newUserDataReader,\n parseQueryValue,\n UserDataReader\n} from './user_data_reader';\n\nexport function validateHasExplicitOrderByForLimitToLast(\n query: InternalQuery\n): void {\n if (\n query.limitType === LimitType.Last &&\n query.explicitOrderBy.length === 0\n ) {\n throw new FirestoreError(\n Code.UNIMPLEMENTED,\n 'limitToLast() queries require specifying at least one orderBy() clause'\n );\n }\n}\n\n/** Describes the different query constraints available in this SDK. */\nexport type QueryConstraintType =\n | 'where'\n | 'orderBy'\n | 'limit'\n | 'limitToLast'\n | 'startAt'\n | 'startAfter'\n | 'endAt'\n | 'endBefore';\n\n/**\n * An `AppliableConstraint` is an abstraction of a constraint that can be applied\n * to a Firestore query.\n */\nexport abstract class AppliableConstraint {\n /**\n * Takes the provided {@link Query} and returns a copy of the {@link Query} with this\n * {@link AppliableConstraint} applied.\n */\n abstract _apply(\n query: Query\n ): Query;\n}\n\n/**\n * A `QueryConstraint` is used to narrow the set of documents returned by a\n * Firestore query. `QueryConstraint`s are created by invoking {@link where},\n * {@link orderBy}, {@link (startAt:1)}, {@link (startAfter:1)}, {@link\n * (endBefore:1)}, {@link (endAt:1)}, {@link limit}, {@link limitToLast} and\n * can then be passed to {@link (query:1)} to create a new query instance that\n * also contains this `QueryConstraint`.\n */\nexport abstract class QueryConstraint extends AppliableConstraint {\n /** The type of this query constraint */\n abstract readonly type: QueryConstraintType;\n\n /**\n * Takes the provided {@link Query} and returns a copy of the {@link Query} with this\n * {@link AppliableConstraint} applied.\n */\n abstract _apply(\n query: Query\n ): Query;\n}\n\n/**\n * Creates a new immutable instance of {@link Query} that is extended to also\n * include additional query constraints.\n *\n * @param query - The {@link Query} instance to use as a base for the new\n * constraints.\n * @param compositeFilter - The {@link QueryCompositeFilterConstraint} to\n * apply. Create {@link QueryCompositeFilterConstraint} using {@link and} or\n * {@link or}.\n * @param queryConstraints - Additional {@link QueryNonFilterConstraint}s to\n * apply (e.g. {@link orderBy}, {@link limit}).\n * @throws if any of the provided query constraints cannot be combined with the\n * existing or new constraints.\n */\nexport function query(\n query: Query,\n compositeFilter: QueryCompositeFilterConstraint,\n ...queryConstraints: QueryNonFilterConstraint[]\n): Query;\n\n/**\n * Creates a new immutable instance of {@link Query} that is extended to also\n * include additional query constraints.\n *\n * @param query - The {@link Query} instance to use as a base for the new\n * constraints.\n * @param queryConstraints - The list of {@link QueryConstraint}s to apply.\n * @throws if any of the provided query constraints cannot be combined with the\n * existing or new constraints.\n */\nexport function query(\n query: Query,\n ...queryConstraints: QueryConstraint[]\n): Query;\n\nexport function query(\n query: Query,\n queryConstraint: QueryCompositeFilterConstraint | QueryConstraint | undefined,\n ...additionalQueryConstraints: Array<\n QueryConstraint | QueryNonFilterConstraint\n >\n): Query {\n let queryConstraints: AppliableConstraint[] = [];\n\n if (queryConstraint instanceof AppliableConstraint) {\n queryConstraints.push(queryConstraint);\n }\n\n queryConstraints = queryConstraints.concat(additionalQueryConstraints);\n\n validateQueryConstraintArray(queryConstraints);\n\n for (const constraint of queryConstraints) {\n query = constraint._apply(query);\n }\n return query;\n}\n\n/**\n * A `QueryFieldFilterConstraint` is used to narrow the set of documents returned by\n * a Firestore query by filtering on one or more document fields.\n * `QueryFieldFilterConstraint`s are created by invoking {@link where} and can then\n * be passed to {@link (query:1)} to create a new query instance that also contains\n * this `QueryFieldFilterConstraint`.\n */\nexport class QueryFieldFilterConstraint extends QueryConstraint {\n /** The type of this query constraint */\n readonly type = 'where';\n\n /**\n * @internal\n */\n protected constructor(\n private readonly _field: InternalFieldPath,\n private _op: Operator,\n private _value: unknown\n ) {\n super();\n }\n\n static _create(\n _field: InternalFieldPath,\n _op: Operator,\n _value: unknown\n ): QueryFieldFilterConstraint {\n return new QueryFieldFilterConstraint(_field, _op, _value);\n }\n\n _apply(\n query: Query\n ): Query {\n const filter = this._parse(query);\n validateNewFieldFilter(query._query, filter);\n return new Query(\n query.firestore,\n query.converter,\n queryWithAddedFilter(query._query, filter)\n );\n }\n\n _parse(\n query: Query\n ): FieldFilter {\n const reader = newUserDataReader(query.firestore);\n const filter = newQueryFilter(\n query._query,\n 'where',\n reader,\n query.firestore._databaseId,\n this._field,\n this._op,\n this._value\n );\n return filter;\n }\n}\n\n/**\n * Filter conditions in a {@link where} clause are specified using the\n * strings '<', '<=', '==', '!=', '>=', '>', 'array-contains', 'in',\n * 'array-contains-any', and 'not-in'.\n */\nexport type WhereFilterOp =\n | '<'\n | '<='\n | '=='\n | '!='\n | '>='\n | '>'\n | 'array-contains'\n | 'in'\n | 'array-contains-any'\n | 'not-in';\n\n/**\n * Creates a {@link QueryFieldFilterConstraint} that enforces that documents\n * must contain the specified field and that the value should satisfy the\n * relation constraint provided.\n *\n * @param fieldPath - The path to compare\n * @param opStr - The operation string (e.g \"<\", \"<=\", \"==\", \"<\",\n * \"<=\", \"!=\").\n * @param value - The value for comparison\n * @returns The created {@link QueryFieldFilterConstraint}.\n */\nexport function where(\n fieldPath: string | FieldPath,\n opStr: WhereFilterOp,\n value: unknown\n): QueryFieldFilterConstraint {\n const op = opStr as Operator;\n const field = fieldPathFromArgument('where', fieldPath);\n return QueryFieldFilterConstraint._create(field, op, value);\n}\n\n/**\n * A `QueryCompositeFilterConstraint` is used to narrow the set of documents\n * returned by a Firestore query by performing the logical OR or AND of multiple\n * {@link QueryFieldFilterConstraint}s or {@link QueryCompositeFilterConstraint}s.\n * `QueryCompositeFilterConstraint`s are created by invoking {@link or} or\n * {@link and} and can then be passed to {@link (query:1)} to create a new query\n * instance that also contains the `QueryCompositeFilterConstraint`.\n */\nexport class QueryCompositeFilterConstraint extends AppliableConstraint {\n /**\n * @internal\n */\n protected constructor(\n /** The type of this query constraint */\n readonly type: 'or' | 'and',\n private readonly _queryConstraints: QueryFilterConstraint[]\n ) {\n super();\n }\n\n static _create(\n type: 'or' | 'and',\n _queryConstraints: QueryFilterConstraint[]\n ): QueryCompositeFilterConstraint {\n return new QueryCompositeFilterConstraint(type, _queryConstraints);\n }\n\n _parse(\n query: Query\n ): Filter {\n const parsedFilters = this._queryConstraints\n .map(queryConstraint => {\n return queryConstraint._parse(query);\n })\n .filter(parsedFilter => parsedFilter.getFilters().length > 0);\n\n if (parsedFilters.length === 1) {\n return parsedFilters[0];\n }\n\n return CompositeFilter.create(parsedFilters, this._getOperator());\n }\n\n _apply(\n query: Query\n ): Query {\n const parsedFilter = this._parse(query);\n if (parsedFilter.getFilters().length === 0) {\n // Return the existing query if not adding any more filters (e.g. an empty\n // composite filter).\n return query;\n }\n validateNewFilter(query._query, parsedFilter);\n\n return new Query(\n query.firestore,\n query.converter,\n queryWithAddedFilter(query._query, parsedFilter)\n );\n }\n\n _getQueryConstraints(): readonly AppliableConstraint[] {\n return this._queryConstraints;\n }\n\n _getOperator(): CompositeOperator {\n return this.type === 'and' ? CompositeOperator.AND : CompositeOperator.OR;\n }\n}\n\n/**\n * `QueryNonFilterConstraint` is a helper union type that represents\n * QueryConstraints which are used to narrow or order the set of documents,\n * but that do not explicitly filter on a document field.\n * `QueryNonFilterConstraint`s are created by invoking {@link orderBy},\n * {@link (startAt:1)}, {@link (startAfter:1)}, {@link (endBefore:1)}, {@link (endAt:1)},\n * {@link limit} or {@link limitToLast} and can then be passed to {@link (query:1)}\n * to create a new query instance that also contains the `QueryConstraint`.\n */\nexport type QueryNonFilterConstraint =\n | QueryOrderByConstraint\n | QueryLimitConstraint\n | QueryStartAtConstraint\n | QueryEndAtConstraint;\n\n/**\n * `QueryFilterConstraint` is a helper union type that represents\n * {@link QueryFieldFilterConstraint} and {@link QueryCompositeFilterConstraint}.\n */\nexport type QueryFilterConstraint =\n | QueryFieldFilterConstraint\n | QueryCompositeFilterConstraint;\n\n/**\n * Creates a new {@link QueryCompositeFilterConstraint} that is a disjunction of\n * the given filter constraints. A disjunction filter includes a document if it\n * satisfies any of the given filters.\n *\n * @param queryConstraints - Optional. The list of\n * {@link QueryFilterConstraint}s to perform a disjunction for. These must be\n * created with calls to {@link where}, {@link or}, or {@link and}.\n * @returns The newly created {@link QueryCompositeFilterConstraint}.\n */\nexport function or(\n ...queryConstraints: QueryFilterConstraint[]\n): QueryCompositeFilterConstraint {\n // Only support QueryFilterConstraints\n queryConstraints.forEach(queryConstraint =>\n validateQueryFilterConstraint('or', queryConstraint)\n );\n\n return QueryCompositeFilterConstraint._create(\n CompositeOperator.OR,\n queryConstraints as QueryFilterConstraint[]\n );\n}\n\n/**\n * Creates a new {@link QueryCompositeFilterConstraint} that is a conjunction of\n * the given filter constraints. A conjunction filter includes a document if it\n * satisfies all of the given filters.\n *\n * @param queryConstraints - Optional. The list of\n * {@link QueryFilterConstraint}s to perform a conjunction for. These must be\n * created with calls to {@link where}, {@link or}, or {@link and}.\n * @returns The newly created {@link QueryCompositeFilterConstraint}.\n */\nexport function and(\n ...queryConstraints: QueryFilterConstraint[]\n): QueryCompositeFilterConstraint {\n // Only support QueryFilterConstraints\n queryConstraints.forEach(queryConstraint =>\n validateQueryFilterConstraint('and', queryConstraint)\n );\n\n return QueryCompositeFilterConstraint._create(\n CompositeOperator.AND,\n queryConstraints as QueryFilterConstraint[]\n );\n}\n\n/**\n * A `QueryOrderByConstraint` is used to sort the set of documents returned by a\n * Firestore query. `QueryOrderByConstraint`s are created by invoking\n * {@link orderBy} and can then be passed to {@link (query:1)} to create a new query\n * instance that also contains this `QueryOrderByConstraint`.\n *\n * Note: Documents that do not contain the orderBy field will not be present in\n * the query result.\n */\nexport class QueryOrderByConstraint extends QueryConstraint {\n /** The type of this query constraint */\n readonly type = 'orderBy';\n\n /**\n * @internal\n */\n protected constructor(\n private readonly _field: InternalFieldPath,\n private _direction: Direction\n ) {\n super();\n }\n\n static _create(\n _field: InternalFieldPath,\n _direction: Direction\n ): QueryOrderByConstraint {\n return new QueryOrderByConstraint(_field, _direction);\n }\n\n _apply(\n query: Query\n ): Query {\n const orderBy = newQueryOrderBy(query._query, this._field, this._direction);\n return new Query(\n query.firestore,\n query.converter,\n queryWithAddedOrderBy(query._query, orderBy)\n );\n }\n}\n\n/**\n * The direction of a {@link orderBy} clause is specified as 'desc' or 'asc'\n * (descending or ascending).\n */\nexport type OrderByDirection = 'desc' | 'asc';\n\n/**\n * Creates a {@link QueryOrderByConstraint} that sorts the query result by the\n * specified field, optionally in descending order instead of ascending.\n *\n * Note: Documents that do not contain the specified field will not be present\n * in the query result.\n *\n * @param fieldPath - The field to sort by.\n * @param directionStr - Optional direction to sort by ('asc' or 'desc'). If\n * not specified, order will be ascending.\n * @returns The created {@link QueryOrderByConstraint}.\n */\nexport function orderBy(\n fieldPath: string | FieldPath,\n directionStr: OrderByDirection = 'asc'\n): QueryOrderByConstraint {\n const direction = directionStr as Direction;\n const path = fieldPathFromArgument('orderBy', fieldPath);\n return QueryOrderByConstraint._create(path, direction);\n}\n\n/**\n * A `QueryLimitConstraint` is used to limit the number of documents returned by\n * a Firestore query.\n * `QueryLimitConstraint`s are created by invoking {@link limit} or\n * {@link limitToLast} and can then be passed to {@link (query:1)} to create a new\n * query instance that also contains this `QueryLimitConstraint`.\n */\nexport class QueryLimitConstraint extends QueryConstraint {\n /**\n * @internal\n */\n protected constructor(\n /** The type of this query constraint */\n readonly type: 'limit' | 'limitToLast',\n private readonly _limit: number,\n private readonly _limitType: LimitType\n ) {\n super();\n }\n\n static _create(\n type: 'limit' | 'limitToLast',\n _limit: number,\n _limitType: LimitType\n ): QueryLimitConstraint {\n return new QueryLimitConstraint(type, _limit, _limitType);\n }\n\n _apply(\n query: Query\n ): Query {\n return new Query(\n query.firestore,\n query.converter,\n queryWithLimit(query._query, this._limit, this._limitType)\n );\n }\n}\n\n/**\n * Creates a {@link QueryLimitConstraint} that only returns the first matching\n * documents.\n *\n * @param limit - The maximum number of items to return.\n * @returns The created {@link QueryLimitConstraint}.\n */\nexport function limit(limit: number): QueryLimitConstraint {\n validatePositiveNumber('limit', limit);\n return QueryLimitConstraint._create('limit', limit, LimitType.First);\n}\n\n/**\n * Creates a {@link QueryLimitConstraint} that only returns the last matching\n * documents.\n *\n * You must specify at least one `orderBy` clause for `limitToLast` queries,\n * otherwise an exception will be thrown during execution.\n *\n * @param limit - The maximum number of items to return.\n * @returns The created {@link QueryLimitConstraint}.\n */\nexport function limitToLast(limit: number): QueryLimitConstraint {\n validatePositiveNumber('limitToLast', limit);\n return QueryLimitConstraint._create('limitToLast', limit, LimitType.Last);\n}\n\n/**\n * A `QueryStartAtConstraint` is used to exclude documents from the start of a\n * result set returned by a Firestore query.\n * `QueryStartAtConstraint`s are created by invoking {@link (startAt:1)} or\n * {@link (startAfter:1)} and can then be passed to {@link (query:1)} to create a\n * new query instance that also contains this `QueryStartAtConstraint`.\n */\nexport class QueryStartAtConstraint extends QueryConstraint {\n /**\n * @internal\n */\n protected constructor(\n /** The type of this query constraint */\n readonly type: 'startAt' | 'startAfter',\n private readonly _docOrFields: Array>,\n private readonly _inclusive: boolean\n ) {\n super();\n }\n\n static _create(\n type: 'startAt' | 'startAfter',\n _docOrFields: Array>,\n _inclusive: boolean\n ): QueryStartAtConstraint {\n return new QueryStartAtConstraint(type, _docOrFields, _inclusive);\n }\n\n _apply(\n query: Query\n ): Query {\n const bound = newQueryBoundFromDocOrFields(\n query,\n this.type,\n this._docOrFields,\n this._inclusive\n );\n return new Query(\n query.firestore,\n query.converter,\n queryWithStartAt(query._query, bound)\n );\n }\n}\n\n/**\n * Creates a {@link QueryStartAtConstraint} that modifies the result set to\n * start at the provided document (inclusive). The starting position is relative\n * to the order of the query. The document must contain all of the fields\n * provided in the `orderBy` of this query.\n *\n * @param snapshot - The snapshot of the document to start at.\n * @returns A {@link QueryStartAtConstraint} to pass to `query()`.\n */\nexport function startAt(\n snapshot: DocumentSnapshot\n): QueryStartAtConstraint;\n/**\n * Creates a {@link QueryStartAtConstraint} that modifies the result set to\n * start at the provided fields relative to the order of the query. The order of\n * the field values must match the order of the order by clauses of the query.\n *\n * @param fieldValues - The field values to start this query at, in order\n * of the query's order by.\n * @returns A {@link QueryStartAtConstraint} to pass to `query()`.\n */\nexport function startAt(...fieldValues: unknown[]): QueryStartAtConstraint;\nexport function startAt(\n ...docOrFields: Array>\n): QueryStartAtConstraint {\n return QueryStartAtConstraint._create(\n 'startAt',\n docOrFields,\n /*inclusive=*/ true\n );\n}\n\n/**\n * Creates a {@link QueryStartAtConstraint} that modifies the result set to\n * start after the provided document (exclusive). The starting position is\n * relative to the order of the query. The document must contain all of the\n * fields provided in the orderBy of the query.\n *\n * @param snapshot - The snapshot of the document to start after.\n * @returns A {@link QueryStartAtConstraint} to pass to `query()`\n */\nexport function startAfter(\n snapshot: DocumentSnapshot\n): QueryStartAtConstraint;\n/**\n * Creates a {@link QueryStartAtConstraint} that modifies the result set to\n * start after the provided fields relative to the order of the query. The order\n * of the field values must match the order of the order by clauses of the query.\n *\n * @param fieldValues - The field values to start this query after, in order\n * of the query's order by.\n * @returns A {@link QueryStartAtConstraint} to pass to `query()`\n */\nexport function startAfter(...fieldValues: unknown[]): QueryStartAtConstraint;\nexport function startAfter(\n ...docOrFields: Array>\n): QueryStartAtConstraint {\n return QueryStartAtConstraint._create(\n 'startAfter',\n docOrFields,\n /*inclusive=*/ false\n );\n}\n\n/**\n * A `QueryEndAtConstraint` is used to exclude documents from the end of a\n * result set returned by a Firestore query.\n * `QueryEndAtConstraint`s are created by invoking {@link (endAt:1)} or\n * {@link (endBefore:1)} and can then be passed to {@link (query:1)} to create a new\n * query instance that also contains this `QueryEndAtConstraint`.\n */\nexport class QueryEndAtConstraint extends QueryConstraint {\n /**\n * @internal\n */\n protected constructor(\n /** The type of this query constraint */\n readonly type: 'endBefore' | 'endAt',\n private readonly _docOrFields: Array>,\n private readonly _inclusive: boolean\n ) {\n super();\n }\n\n static _create(\n type: 'endBefore' | 'endAt',\n _docOrFields: Array>,\n _inclusive: boolean\n ): QueryEndAtConstraint {\n return new QueryEndAtConstraint(type, _docOrFields, _inclusive);\n }\n\n _apply(\n query: Query\n ): Query {\n const bound = newQueryBoundFromDocOrFields(\n query,\n this.type,\n this._docOrFields,\n this._inclusive\n );\n return new Query(\n query.firestore,\n query.converter,\n queryWithEndAt(query._query, bound)\n );\n }\n}\n\n/**\n * Creates a {@link QueryEndAtConstraint} that modifies the result set to end\n * before the provided document (exclusive). The end position is relative to the\n * order of the query. The document must contain all of the fields provided in\n * the orderBy of the query.\n *\n * @param snapshot - The snapshot of the document to end before.\n * @returns A {@link QueryEndAtConstraint} to pass to `query()`\n */\nexport function endBefore(\n snapshot: DocumentSnapshot\n): QueryEndAtConstraint;\n/**\n * Creates a {@link QueryEndAtConstraint} that modifies the result set to end\n * before the provided fields relative to the order of the query. The order of\n * the field values must match the order of the order by clauses of the query.\n *\n * @param fieldValues - The field values to end this query before, in order\n * of the query's order by.\n * @returns A {@link QueryEndAtConstraint} to pass to `query()`\n */\nexport function endBefore(...fieldValues: unknown[]): QueryEndAtConstraint;\nexport function endBefore(\n ...docOrFields: Array>\n): QueryEndAtConstraint {\n return QueryEndAtConstraint._create(\n 'endBefore',\n docOrFields,\n /*inclusive=*/ false\n );\n}\n\n/**\n * Creates a {@link QueryEndAtConstraint} that modifies the result set to end at\n * the provided document (inclusive). The end position is relative to the order\n * of the query. The document must contain all of the fields provided in the\n * orderBy of the query.\n *\n * @param snapshot - The snapshot of the document to end at.\n * @returns A {@link QueryEndAtConstraint} to pass to `query()`\n */\nexport function endAt(\n snapshot: DocumentSnapshot\n): QueryEndAtConstraint;\n/**\n * Creates a {@link QueryEndAtConstraint} that modifies the result set to end at\n * the provided fields relative to the order of the query. The order of the field\n * values must match the order of the order by clauses of the query.\n *\n * @param fieldValues - The field values to end this query at, in order\n * of the query's order by.\n * @returns A {@link QueryEndAtConstraint} to pass to `query()`\n */\nexport function endAt(...fieldValues: unknown[]): QueryEndAtConstraint;\nexport function endAt(\n ...docOrFields: Array>\n): QueryEndAtConstraint {\n return QueryEndAtConstraint._create(\n 'endAt',\n docOrFields,\n /*inclusive=*/ true\n );\n}\n\n/** Helper function to create a bound from a document or fields */\nfunction newQueryBoundFromDocOrFields<\n AppModelType,\n DbModelType extends DocumentData\n>(\n query: Query,\n methodName: string,\n docOrFields: Array>,\n inclusive: boolean\n): Bound {\n docOrFields[0] = getModularInstance(docOrFields[0]);\n\n if (docOrFields[0] instanceof DocumentSnapshot) {\n return newQueryBoundFromDocument(\n query._query,\n query.firestore._databaseId,\n methodName,\n docOrFields[0]._document,\n inclusive\n );\n } else {\n const reader = newUserDataReader(query.firestore);\n return newQueryBoundFromFields(\n query._query,\n query.firestore._databaseId,\n reader,\n methodName,\n docOrFields,\n inclusive\n );\n }\n}\n\nexport function newQueryFilter(\n query: InternalQuery,\n methodName: string,\n dataReader: UserDataReader,\n databaseId: DatabaseId,\n fieldPath: InternalFieldPath,\n op: Operator,\n value: unknown\n): FieldFilter {\n let fieldValue: ProtoValue;\n if (fieldPath.isKeyField()) {\n if (op === Operator.ARRAY_CONTAINS || op === Operator.ARRAY_CONTAINS_ANY) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid Query. You can't perform '${op}' queries on documentId().`\n );\n } else if (op === Operator.IN || op === Operator.NOT_IN) {\n validateDisjunctiveFilterElements(value, op);\n const referenceList: ProtoValue[] = [];\n for (const arrayValue of value as ProtoValue[]) {\n referenceList.push(parseDocumentIdValue(databaseId, query, arrayValue));\n }\n fieldValue = { arrayValue: { values: referenceList } };\n } else {\n fieldValue = parseDocumentIdValue(databaseId, query, value);\n }\n } else {\n if (\n op === Operator.IN ||\n op === Operator.NOT_IN ||\n op === Operator.ARRAY_CONTAINS_ANY\n ) {\n validateDisjunctiveFilterElements(value, op);\n }\n fieldValue = parseQueryValue(\n dataReader,\n methodName,\n value,\n /* allowArrays= */ op === Operator.IN || op === Operator.NOT_IN\n );\n }\n const filter = FieldFilter.create(fieldPath, op, fieldValue);\n return filter;\n}\n\nexport function newQueryOrderBy(\n query: InternalQuery,\n fieldPath: InternalFieldPath,\n direction: Direction\n): OrderBy {\n if (query.startAt !== null) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Invalid query. You must not call startAt() or startAfter() before ' +\n 'calling orderBy().'\n );\n }\n if (query.endAt !== null) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Invalid query. You must not call endAt() or endBefore() before ' +\n 'calling orderBy().'\n );\n }\n const orderBy = new OrderBy(fieldPath, direction);\n return orderBy;\n}\n\n/**\n * Create a `Bound` from a query and a document.\n *\n * Note that the `Bound` will always include the key of the document\n * and so only the provided document will compare equal to the returned\n * position.\n *\n * Will throw if the document does not contain all fields of the order by\n * of the query or if any of the fields in the order by are an uncommitted\n * server timestamp.\n */\nexport function newQueryBoundFromDocument(\n query: InternalQuery,\n databaseId: DatabaseId,\n methodName: string,\n doc: Document | null,\n inclusive: boolean\n): Bound {\n if (!doc) {\n throw new FirestoreError(\n Code.NOT_FOUND,\n `Can't use a DocumentSnapshot that doesn't exist for ` +\n `${methodName}().`\n );\n }\n\n const components: ProtoValue[] = [];\n\n // Because people expect to continue/end a query at the exact document\n // provided, we need to use the implicit sort order rather than the explicit\n // sort order, because it's guaranteed to contain the document key. That way\n // the position becomes unambiguous and the query continues/ends exactly at\n // the provided document. Without the key (by using the explicit sort\n // orders), multiple documents could match the position, yielding duplicate\n // results.\n for (const orderBy of queryNormalizedOrderBy(query)) {\n if (orderBy.field.isKeyField()) {\n components.push(refValue(databaseId, doc.key));\n } else {\n const value = doc.data.field(orderBy.field);\n if (isServerTimestamp(value)) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Invalid query. You are trying to start or end a query using a ' +\n 'document for which the field \"' +\n orderBy.field +\n '\" is an uncommitted server timestamp. (Since the value of ' +\n 'this field is unknown, you cannot start/end a query with it.)'\n );\n } else if (value !== null) {\n components.push(value);\n } else {\n const field = orderBy.field.canonicalString();\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid query. You are trying to start or end a query using a ` +\n `document for which the field '${field}' (used as the ` +\n `orderBy) does not exist.`\n );\n }\n }\n }\n return new Bound(components, inclusive);\n}\n\n/**\n * Converts a list of field values to a `Bound` for the given query.\n */\nexport function newQueryBoundFromFields(\n query: InternalQuery,\n databaseId: DatabaseId,\n dataReader: UserDataReader,\n methodName: string,\n values: unknown[],\n inclusive: boolean\n): Bound {\n // Use explicit order by's because it has to match the query the user made\n const orderBy = query.explicitOrderBy;\n if (values.length > orderBy.length) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Too many arguments provided to ${methodName}(). ` +\n `The number of arguments must be less than or equal to the ` +\n `number of orderBy() clauses`\n );\n }\n\n const components: ProtoValue[] = [];\n for (let i = 0; i < values.length; i++) {\n const rawValue = values[i];\n const orderByComponent = orderBy[i];\n if (orderByComponent.field.isKeyField()) {\n if (typeof rawValue !== 'string') {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid query. Expected a string for document ID in ` +\n `${methodName}(), but got a ${typeof rawValue}`\n );\n }\n if (!isCollectionGroupQuery(query) && rawValue.indexOf('/') !== -1) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid query. When querying a collection and ordering by documentId(), ` +\n `the value passed to ${methodName}() must be a plain document ID, but ` +\n `'${rawValue}' contains a slash.`\n );\n }\n const path = query.path.child(ResourcePath.fromString(rawValue));\n if (!DocumentKey.isDocumentKey(path)) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid query. When querying a collection group and ordering by ` +\n `documentId(), the value passed to ${methodName}() must result in a ` +\n `valid document path, but '${path}' is not because it contains an odd number ` +\n `of segments.`\n );\n }\n const key = new DocumentKey(path);\n components.push(refValue(databaseId, key));\n } else {\n const wrapped = parseQueryValue(dataReader, methodName, rawValue);\n components.push(wrapped);\n }\n }\n\n return new Bound(components, inclusive);\n}\n\n/**\n * Parses the given `documentIdValue` into a `ReferenceValue`, throwing\n * appropriate errors if the value is anything other than a `DocumentReference`\n * or `string`, or if the string is malformed.\n */\nfunction parseDocumentIdValue(\n databaseId: DatabaseId,\n query: InternalQuery,\n documentIdValue: unknown\n): ProtoValue {\n documentIdValue = getModularInstance(documentIdValue);\n\n if (typeof documentIdValue === 'string') {\n if (documentIdValue === '') {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Invalid query. When querying with documentId(), you ' +\n 'must provide a valid document ID, but it was an empty string.'\n );\n }\n if (!isCollectionGroupQuery(query) && documentIdValue.indexOf('/') !== -1) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid query. When querying a collection by ` +\n `documentId(), you must provide a plain document ID, but ` +\n `'${documentIdValue}' contains a '/' character.`\n );\n }\n const path = query.path.child(ResourcePath.fromString(documentIdValue));\n if (!DocumentKey.isDocumentKey(path)) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid query. When querying a collection group by ` +\n `documentId(), the value provided must result in a valid document path, ` +\n `but '${path}' is not because it has an odd number of segments (${path.length}).`\n );\n }\n return refValue(databaseId, new DocumentKey(path));\n } else if (documentIdValue instanceof DocumentReference) {\n return refValue(databaseId, documentIdValue._key);\n } else {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid query. When querying with documentId(), you must provide a valid ` +\n `string or a DocumentReference, but it was: ` +\n `${valueDescription(documentIdValue)}.`\n );\n }\n}\n\n/**\n * Validates that the value passed into a disjunctive filter satisfies all\n * array requirements.\n */\nfunction validateDisjunctiveFilterElements(\n value: unknown,\n operator: Operator\n): void {\n if (!Array.isArray(value) || value.length === 0) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Invalid Query. A non-empty array is required for ' +\n `'${operator.toString()}' filters.`\n );\n }\n}\n\n/**\n * Given an operator, returns the set of operators that cannot be used with it.\n *\n * This is not a comprehensive check, and this function should be removed in the\n * long term. Validations should occur in the Firestore backend.\n *\n * Operators in a query must adhere to the following set of rules:\n * 1. Only one inequality per query.\n * 2. `NOT_IN` cannot be used with array, disjunctive, or `NOT_EQUAL` operators.\n */\nfunction conflictingOps(op: Operator): Operator[] {\n switch (op) {\n case Operator.NOT_EQUAL:\n return [Operator.NOT_EQUAL, Operator.NOT_IN];\n case Operator.ARRAY_CONTAINS_ANY:\n case Operator.IN:\n return [Operator.NOT_IN];\n case Operator.NOT_IN:\n return [\n Operator.ARRAY_CONTAINS_ANY,\n Operator.IN,\n Operator.NOT_IN,\n Operator.NOT_EQUAL\n ];\n default:\n return [];\n }\n}\n\nfunction validateNewFieldFilter(\n query: InternalQuery,\n fieldFilter: FieldFilter\n): void {\n const conflictingOp = findOpInsideFilters(\n query.filters,\n conflictingOps(fieldFilter.op)\n );\n if (conflictingOp !== null) {\n // Special case when it's a duplicate op to give a slightly clearer error message.\n if (conflictingOp === fieldFilter.op) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Invalid query. You cannot use more than one ' +\n `'${fieldFilter.op.toString()}' filter.`\n );\n } else {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid query. You cannot use '${fieldFilter.op.toString()}' filters ` +\n `with '${conflictingOp.toString()}' filters.`\n );\n }\n }\n}\n\nfunction validateNewFilter(query: InternalQuery, filter: Filter): void {\n let testQuery = query;\n const subFilters = filter.getFlattenedFilters();\n for (const subFilter of subFilters) {\n validateNewFieldFilter(testQuery, subFilter);\n testQuery = queryWithAddedFilter(testQuery, subFilter);\n }\n}\n\n// Checks if any of the provided filter operators are included in the given list of filters and\n// returns the first one that is, or null if none are.\nfunction findOpInsideFilters(\n filters: Filter[],\n operators: Operator[]\n): Operator | null {\n for (const filter of filters) {\n for (const fieldFilter of filter.getFlattenedFilters()) {\n if (operators.indexOf(fieldFilter.op) >= 0) {\n return fieldFilter.op;\n }\n }\n }\n return null;\n}\n\nexport function validateQueryFilterConstraint(\n functionName: string,\n queryConstraint: AppliableConstraint\n): void {\n if (\n !(queryConstraint instanceof QueryFieldFilterConstraint) &&\n !(queryConstraint instanceof QueryCompositeFilterConstraint)\n ) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Function ${functionName}() requires AppliableConstraints created with a call to 'where(...)', 'or(...)', or 'and(...)'.`\n );\n }\n}\n\nfunction validateQueryConstraintArray(\n queryConstraint: AppliableConstraint[]\n): void {\n const compositeFilterCount = queryConstraint.filter(\n filter => filter instanceof QueryCompositeFilterConstraint\n ).length;\n const fieldFilterCount = queryConstraint.filter(\n filter => filter instanceof QueryFieldFilterConstraint\n ).length;\n\n if (\n compositeFilterCount > 1 ||\n (compositeFilterCount > 0 && fieldFilterCount > 0)\n ) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'InvalidQuery. When using composite filters, you cannot use ' +\n 'more than one filter at the top level. Consider nesting the multiple ' +\n 'filters within an `and(...)` statement. For example: ' +\n 'change `query(query, where(...), or(...))` to ' +\n '`query(query, and(where(...), or(...)))`.'\n );\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DocumentData } from '@firebase/firestore-types';\n\nimport { DatabaseId } from '../core/database_info';\nimport { DocumentKey } from '../model/document_key';\nimport {\n normalizeByteString,\n normalizeNumber,\n normalizeTimestamp\n} from '../model/normalize';\nimport { ResourcePath } from '../model/path';\nimport {\n getLocalWriteTime,\n getPreviousValue\n} from '../model/server_timestamps';\nimport { TypeOrder } from '../model/type_order';\nimport { VECTOR_MAP_VECTORS_KEY, typeOrder } from '../model/values';\nimport {\n ApiClientObjectMap,\n ArrayValue as ProtoArrayValue,\n LatLng as ProtoLatLng,\n MapValue as ProtoMapValue,\n Timestamp as ProtoTimestamp,\n Value,\n Value as ProtoValue\n} from '../protos/firestore_proto_api';\nimport { isValidResourceName } from '../remote/serializer';\nimport { fail, hardAssert } from '../util/assert';\nimport { ByteString } from '../util/byte_string';\nimport { logError } from '../util/log';\nimport { forEach } from '../util/obj';\n\nimport { GeoPoint } from './geo_point';\nimport { Timestamp } from './timestamp';\nimport { VectorValue } from './vector_value';\n\nexport type ServerTimestampBehavior = 'estimate' | 'previous' | 'none';\n\n/**\n * Converts Firestore's internal types to the JavaScript types that we expose\n * to the user.\n *\n * @internal\n */\nexport abstract class AbstractUserDataWriter {\n convertValue(\n value: ProtoValue,\n serverTimestampBehavior: ServerTimestampBehavior = 'none'\n ): unknown {\n switch (typeOrder(value)) {\n case TypeOrder.NullValue:\n return null;\n case TypeOrder.BooleanValue:\n return value.booleanValue!;\n case TypeOrder.NumberValue:\n return normalizeNumber(value.integerValue || value.doubleValue);\n case TypeOrder.TimestampValue:\n return this.convertTimestamp(value.timestampValue!);\n case TypeOrder.ServerTimestampValue:\n return this.convertServerTimestamp(value, serverTimestampBehavior);\n case TypeOrder.StringValue:\n return value.stringValue!;\n case TypeOrder.BlobValue:\n return this.convertBytes(normalizeByteString(value.bytesValue!));\n case TypeOrder.RefValue:\n return this.convertReference(value.referenceValue!);\n case TypeOrder.GeoPointValue:\n return this.convertGeoPoint(value.geoPointValue!);\n case TypeOrder.ArrayValue:\n return this.convertArray(value.arrayValue!, serverTimestampBehavior);\n case TypeOrder.ObjectValue:\n return this.convertObject(value.mapValue!, serverTimestampBehavior);\n case TypeOrder.VectorValue:\n return this.convertVectorValue(value.mapValue!);\n default:\n throw fail(0xf2a2, 'Invalid value type', {\n value\n });\n }\n }\n\n private convertObject(\n mapValue: ProtoMapValue,\n serverTimestampBehavior: ServerTimestampBehavior\n ): DocumentData {\n return this.convertObjectMap(mapValue.fields, serverTimestampBehavior);\n }\n\n /**\n * @internal\n */\n convertObjectMap(\n fields: ApiClientObjectMap | undefined,\n serverTimestampBehavior: ServerTimestampBehavior = 'none'\n ): DocumentData {\n const result: DocumentData = {};\n forEach(fields, (key, value) => {\n result[key] = this.convertValue(value, serverTimestampBehavior);\n });\n return result;\n }\n\n /**\n * @internal\n */\n convertVectorValue(mapValue: ProtoMapValue): VectorValue {\n const values = mapValue.fields?.[\n VECTOR_MAP_VECTORS_KEY\n ].arrayValue?.values?.map(value => {\n return normalizeNumber(value.doubleValue);\n });\n\n return new VectorValue(values);\n }\n\n private convertGeoPoint(value: ProtoLatLng): GeoPoint {\n return new GeoPoint(\n normalizeNumber(value.latitude),\n normalizeNumber(value.longitude)\n );\n }\n\n private convertArray(\n arrayValue: ProtoArrayValue,\n serverTimestampBehavior: ServerTimestampBehavior\n ): unknown[] {\n return (arrayValue.values || []).map(value =>\n this.convertValue(value, serverTimestampBehavior)\n );\n }\n\n private convertServerTimestamp(\n value: ProtoValue,\n serverTimestampBehavior: ServerTimestampBehavior\n ): unknown {\n switch (serverTimestampBehavior) {\n case 'previous':\n const previousValue = getPreviousValue(value);\n if (previousValue == null) {\n return null;\n }\n return this.convertValue(previousValue, serverTimestampBehavior);\n case 'estimate':\n return this.convertTimestamp(getLocalWriteTime(value));\n default:\n return null;\n }\n }\n\n private convertTimestamp(value: ProtoTimestamp): Timestamp {\n const normalizedValue = normalizeTimestamp(value);\n return new Timestamp(normalizedValue.seconds, normalizedValue.nanos);\n }\n\n protected convertDocumentKey(\n name: string,\n expectedDatabaseId: DatabaseId\n ): DocumentKey {\n const resourcePath = ResourcePath.fromString(name);\n hardAssert(\n isValidResourceName(resourcePath),\n 0x25d8,\n 'ReferenceValue is not valid',\n { name }\n );\n const databaseId = new DatabaseId(resourcePath.get(1), resourcePath.get(3));\n const key = new DocumentKey(resourcePath.popFirst(5));\n\n if (!databaseId.isEqual(expectedDatabaseId)) {\n // TODO(b/64130202): Somehow support foreign references.\n logError(\n `Document ${key} contains a document ` +\n `reference within a different database (` +\n `${databaseId.projectId}/${databaseId.database}) which is not ` +\n `supported. It will be treated as a reference in the current ` +\n `database (${expectedDatabaseId.projectId}/${expectedDatabaseId.database}) ` +\n `instead.`\n );\n }\n return key;\n }\n\n protected abstract convertReference(name: string): unknown;\n\n protected abstract convertBytes(bytes: ByteString): unknown;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n DocumentData as PublicDocumentData,\n SetOptions as PublicSetOptions\n} from '@firebase/firestore-types';\nimport { getModularInstance } from '@firebase/util';\n\nimport { LimitType } from '../core/query';\nimport { DeleteMutation, Precondition } from '../model/mutation';\nimport {\n invokeBatchGetDocumentsRpc,\n invokeCommitRpc,\n invokeRunQueryRpc\n} from '../remote/datastore';\nimport { hardAssert } from '../util/assert';\nimport { ByteString } from '../util/byte_string';\nimport { cast } from '../util/input_validation';\n\nimport { Bytes } from './bytes';\nimport { getDatastore } from './components';\nimport { Firestore } from './database';\nimport { FieldPath } from './field_path';\nimport { validateHasExplicitOrderByForLimitToLast } from './query';\nimport {\n CollectionReference,\n doc,\n DocumentData,\n DocumentReference,\n PartialWithFieldValue,\n Query,\n SetOptions,\n UpdateData,\n WithFieldValue\n} from './reference';\nimport {\n DocumentSnapshot,\n QueryDocumentSnapshot,\n QuerySnapshot\n} from './snapshot';\nimport {\n newUserDataReader,\n ParsedUpdateData,\n parseSetData,\n parseUpdateData,\n parseUpdateVarargs,\n UntypedFirestoreDataConverter\n} from './user_data_reader';\nimport { AbstractUserDataWriter } from './user_data_writer';\n\n/**\n * Converts custom model object of type T into `DocumentData` by applying the\n * converter if it exists.\n *\n * This function is used when converting user objects to `DocumentData`\n * because we want to provide the user with a more specific error message if\n * their `set()` or fails due to invalid data originating from a `toFirestore()`\n * call.\n */\nexport function applyFirestoreDataConverter(\n converter: UntypedFirestoreDataConverter | null,\n value: WithFieldValue | PartialWithFieldValue,\n options?: PublicSetOptions\n): PublicDocumentData {\n let convertedValue;\n if (converter) {\n if (options && (options.merge || options.mergeFields)) {\n // Cast to `any` in order to satisfy the union type constraint on\n // toFirestore().\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n convertedValue = (converter as any).toFirestore(value, options);\n } else {\n convertedValue = converter.toFirestore(value as WithFieldValue);\n }\n } else {\n convertedValue = value as PublicDocumentData;\n }\n return convertedValue;\n}\n\nexport class LiteUserDataWriter extends AbstractUserDataWriter {\n constructor(protected firestore: Firestore) {\n super();\n }\n\n protected convertBytes(bytes: ByteString): Bytes {\n return new Bytes(bytes);\n }\n\n protected convertReference(name: string): DocumentReference {\n const key = this.convertDocumentKey(name, this.firestore._databaseId);\n return new DocumentReference(this.firestore, /* converter= */ null, key);\n }\n}\n\n/**\n * Reads the document referred to by the specified document reference.\n *\n * All documents are directly fetched from the server, even if the document was\n * previously read or modified. Recent modifications are only reflected in the\n * retrieved `DocumentSnapshot` if they have already been applied by the\n * backend. If the client is offline, the read fails. If you like to use\n * caching or see local modifications, please use the full Firestore SDK.\n *\n * @param reference - The reference of the document to fetch.\n * @returns A Promise resolved with a `DocumentSnapshot` containing the current\n * document contents.\n */\nexport function getDoc(\n reference: DocumentReference\n): Promise> {\n reference = cast>(\n reference,\n DocumentReference\n );\n const datastore = getDatastore(reference.firestore);\n const userDataWriter = new LiteUserDataWriter(reference.firestore);\n\n return invokeBatchGetDocumentsRpc(datastore, [reference._key]).then(\n result => {\n hardAssert(\n result.length === 1,\n 0x3d02,\n 'Expected a single document result'\n );\n const document = result[0];\n return new DocumentSnapshot(\n reference.firestore,\n userDataWriter,\n reference._key,\n document.isFoundDocument() ? document : null,\n reference.converter\n );\n }\n );\n}\n\n/**\n * Executes the query and returns the results as a {@link QuerySnapshot}.\n *\n * All queries are executed directly by the server, even if the query was\n * previously executed. Recent modifications are only reflected in the retrieved\n * results if they have already been applied by the backend. If the client is\n * offline, the operation fails. To see previously cached result and local\n * modifications, use the full Firestore SDK.\n *\n * @param query - The `Query` to execute.\n * @returns A Promise that will be resolved with the results of the query.\n */\nexport function getDocs(\n query: Query\n): Promise> {\n query = cast>(query, Query);\n validateHasExplicitOrderByForLimitToLast(query._query);\n\n const datastore = getDatastore(query.firestore);\n const userDataWriter = new LiteUserDataWriter(query.firestore);\n return invokeRunQueryRpc(datastore, query._query).then(result => {\n const docs = result.map(\n doc =>\n new QueryDocumentSnapshot(\n query.firestore,\n userDataWriter,\n doc.key,\n doc,\n query.converter\n )\n );\n\n if (query._query.limitType === LimitType.Last) {\n // Limit to last queries reverse the orderBy constraint that was\n // specified by the user. As such, we need to reverse the order of the\n // results to return the documents in the expected order.\n docs.reverse();\n }\n\n return new QuerySnapshot(query, docs);\n });\n}\n\n/**\n * Writes to the document referred to by the specified `DocumentReference`. If\n * the document does not yet exist, it will be created.\n *\n * The result of this write will only be reflected in document reads that occur\n * after the returned promise resolves. If the client is offline, the\n * write fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the document to write.\n * @param data - A map of the fields and values for the document.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns A `Promise` resolved once the data has been successfully written\n * to the backend.\n */\nexport function setDoc(\n reference: DocumentReference,\n data: WithFieldValue\n): Promise;\n/**\n * Writes to the document referred to by the specified `DocumentReference`. If\n * the document does not yet exist, it will be created. If you provide `merge`\n * or `mergeFields`, the provided data can be merged into an existing document.\n *\n * The result of this write will only be reflected in document reads that occur\n * after the returned promise resolves. If the client is offline, the\n * write fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the document to write.\n * @param data - A map of the fields and values for the document.\n * @param options - An object to configure the set behavior.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns A `Promise` resolved once the data has been successfully written\n * to the backend.\n */\nexport function setDoc(\n reference: DocumentReference,\n data: PartialWithFieldValue,\n options: SetOptions\n): Promise;\nexport function setDoc(\n reference: DocumentReference,\n data: PartialWithFieldValue,\n options?: SetOptions\n): Promise {\n reference = cast>(\n reference,\n DocumentReference\n );\n const convertedValue = applyFirestoreDataConverter(\n reference.converter,\n data,\n options\n );\n const dataReader = newUserDataReader(reference.firestore);\n const parsed = parseSetData(\n dataReader,\n 'setDoc',\n reference._key,\n convertedValue,\n reference.converter !== null,\n options\n );\n\n const datastore = getDatastore(reference.firestore);\n return invokeCommitRpc(datastore, [\n parsed.toMutation(reference._key, Precondition.none())\n ]);\n}\n\n/**\n * Updates fields in the document referred to by the specified\n * `DocumentReference`. The update will fail if applied to a document that does\n * not exist.\n *\n * The result of this update will only be reflected in document reads that occur\n * after the returned promise resolves. If the client is offline, the\n * update fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the document to update.\n * @param data - An object containing the fields and values with which to\n * update the document. Fields can contain dots to reference nested fields\n * within the document.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns A `Promise` resolved once the data has been successfully written\n * to the backend.\n */\nexport function updateDoc(\n reference: DocumentReference,\n data: UpdateData\n): Promise;\n/**\n * Updates fields in the document referred to by the specified\n * `DocumentReference` The update will fail if applied to a document that does\n * not exist.\n *\n * Nested fields can be updated by providing dot-separated field path\n * strings or by providing `FieldPath` objects.\n *\n * The result of this update will only be reflected in document reads that occur\n * after the returned promise resolves. If the client is offline, the\n * update fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the document to update.\n * @param field - The first field to update.\n * @param value - The first value.\n * @param moreFieldsAndValues - Additional key value pairs.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns A `Promise` resolved once the data has been successfully written\n * to the backend.\n */\nexport function updateDoc(\n reference: DocumentReference,\n field: string | FieldPath,\n value: unknown,\n ...moreFieldsAndValues: unknown[]\n): Promise;\nexport function updateDoc(\n reference: DocumentReference,\n fieldOrUpdateData: string | FieldPath | UpdateData,\n value?: unknown,\n ...moreFieldsAndValues: unknown[]\n): Promise {\n reference = cast>(\n reference,\n DocumentReference\n );\n const dataReader = newUserDataReader(reference.firestore);\n\n // For Compat types, we have to \"extract\" the underlying types before\n // performing validation.\n fieldOrUpdateData = getModularInstance(fieldOrUpdateData);\n\n let parsed: ParsedUpdateData;\n if (\n typeof fieldOrUpdateData === 'string' ||\n fieldOrUpdateData instanceof FieldPath\n ) {\n parsed = parseUpdateVarargs(\n dataReader,\n 'updateDoc',\n reference._key,\n fieldOrUpdateData,\n value,\n moreFieldsAndValues\n );\n } else {\n parsed = parseUpdateData(\n dataReader,\n 'updateDoc',\n reference._key,\n fieldOrUpdateData\n );\n }\n\n const datastore = getDatastore(reference.firestore);\n return invokeCommitRpc(datastore, [\n parsed.toMutation(reference._key, Precondition.exists(true))\n ]);\n}\n\n/**\n * Deletes the document referred to by the specified `DocumentReference`.\n *\n * The deletion will only be reflected in document reads that occur after the\n * returned promise resolves. If the client is offline, the\n * delete fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the document to delete.\n * @returns A `Promise` resolved once the document has been successfully\n * deleted from the backend.\n */\nexport function deleteDoc(\n reference: DocumentReference\n): Promise {\n reference = cast>(\n reference,\n DocumentReference\n );\n const datastore = getDatastore(reference.firestore);\n return invokeCommitRpc(datastore, [\n new DeleteMutation(reference._key, Precondition.none())\n ]);\n}\n\n/**\n * Add a new document to specified `CollectionReference` with the given data,\n * assigning it a document ID automatically.\n *\n * The result of this write will only be reflected in document reads that occur\n * after the returned promise resolves. If the client is offline, the\n * write fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the collection to add this document to.\n * @param data - An Object containing the data for the new document.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns A `Promise` resolved with a `DocumentReference` pointing to the\n * newly created document after it has been written to the backend.\n */\nexport function addDoc(\n reference: CollectionReference,\n data: WithFieldValue\n): Promise> {\n reference = cast>(\n reference,\n CollectionReference\n );\n const docRef = doc(reference);\n\n const convertedValue = applyFirestoreDataConverter(\n reference.converter,\n data as PartialWithFieldValue\n );\n\n const dataReader = newUserDataReader(reference.firestore);\n const parsed = parseSetData(\n dataReader,\n 'addDoc',\n docRef._key,\n convertedValue,\n docRef.converter !== null,\n {}\n );\n\n const datastore = getDatastore(reference.firestore);\n return invokeCommitRpc(datastore, [\n parsed.toMutation(docRef._key, Precondition.exists(false))\n ]).then(() => docRef);\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { deepEqual } from '@firebase/util';\n\nimport { AggregateImpl } from '../core/aggregate';\nimport { ApiClientObjectMap, Value } from '../protos/firestore_proto_api';\nimport { invokeRunAggregationQueryRpc } from '../remote/datastore';\nimport { cast } from '../util/input_validation';\nimport { mapToArray } from '../util/obj';\n\nimport {\n AggregateField,\n AggregateQuerySnapshot,\n AggregateSpec\n} from './aggregate_types';\nimport { getDatastore } from './components';\nimport { Firestore } from './database';\nimport { FieldPath } from './field_path';\nimport { DocumentData, Query, queryEqual } from './reference';\nimport { LiteUserDataWriter } from './reference_impl';\nimport { fieldPathFromArgument } from './user_data_reader';\n\n/**\n * Calculates the number of documents in the result set of the given query\n * without actually downloading the documents.\n *\n * Using this function to count the documents is efficient because only the\n * final count, not the documents' data, is downloaded. This function can\n * count the documents in cases where the result set is prohibitively large to\n * download entirely (thousands of documents).\n *\n * @param query The query whose result set size is calculated.\n * @returns A Promise that will be resolved with the count; the count can be\n * retrieved from `snapshot.data().count`, where `snapshot` is the\n * `AggregateQuerySnapshot` to which the returned Promise resolves.\n */\nexport function getCount(\n query: Query\n): Promise<\n AggregateQuerySnapshot<\n { count: AggregateField },\n AppModelType,\n DbModelType\n >\n> {\n const countQuerySpec: { count: AggregateField } = {\n count: count()\n };\n\n return getAggregate(query, countQuerySpec);\n}\n\n/**\n * Calculates the specified aggregations over the documents in the result\n * set of the given query without actually downloading the documents.\n *\n * Using this function to perform aggregations is efficient because only the\n * final aggregation values, not the documents' data, are downloaded. This\n * function can perform aggregations of the documents in cases where the result\n * set is prohibitively large to download entirely (thousands of documents).\n *\n * @param query The query whose result set is aggregated over.\n * @param aggregateSpec An `AggregateSpec` object that specifies the aggregates\n * to perform over the result set. The AggregateSpec specifies aliases for each\n * aggregate, which can be used to retrieve the aggregate result.\n * @example\n * ```typescript\n * const aggregateSnapshot = await getAggregate(query, {\n * countOfDocs: count(),\n * totalHours: sum('hours'),\n * averageScore: average('score')\n * });\n *\n * const countOfDocs: number = aggregateSnapshot.data().countOfDocs;\n * const totalHours: number = aggregateSnapshot.data().totalHours;\n * const averageScore: number | null = aggregateSnapshot.data().averageScore;\n * ```\n */\nexport function getAggregate<\n AggregateSpecType extends AggregateSpec,\n AppModelType,\n DbModelType extends DocumentData\n>(\n query: Query,\n aggregateSpec: AggregateSpecType\n): Promise<\n AggregateQuerySnapshot\n> {\n const firestore = cast(query.firestore, Firestore);\n const datastore = getDatastore(firestore);\n\n const internalAggregates = mapToArray(aggregateSpec, (aggregate, alias) => {\n return new AggregateImpl(\n alias,\n aggregate.aggregateType,\n aggregate._internalFieldPath\n );\n });\n\n // Run the aggregation and convert the results\n return invokeRunAggregationQueryRpc(\n datastore,\n query._query,\n internalAggregates\n ).then(aggregateResult =>\n convertToAggregateQuerySnapshot(firestore, query, aggregateResult)\n );\n}\n\nfunction convertToAggregateQuerySnapshot<\n AggregateSpecType extends AggregateSpec,\n AppModelType,\n DbModelType extends DocumentData\n>(\n firestore: Firestore,\n query: Query,\n aggregateResult: ApiClientObjectMap\n): AggregateQuerySnapshot {\n const userDataWriter = new LiteUserDataWriter(firestore);\n const querySnapshot = new AggregateQuerySnapshot<\n AggregateSpecType,\n AppModelType,\n DbModelType\n >(query, userDataWriter, aggregateResult);\n return querySnapshot;\n}\n\n/**\n * Create an AggregateField object that can be used to compute the sum of\n * a specified field over a range of documents in the result set of a query.\n * @param field Specifies the field to sum across the result set.\n */\nexport function sum(field: string | FieldPath): AggregateField {\n return new AggregateField('sum', fieldPathFromArgument('sum', field));\n}\n\n/**\n * Create an AggregateField object that can be used to compute the average of\n * a specified field over a range of documents in the result set of a query.\n * @param field Specifies the field to average across the result set.\n */\nexport function average(\n field: string | FieldPath\n): AggregateField {\n return new AggregateField('avg', fieldPathFromArgument('average', field));\n}\n\n/**\n * Create an AggregateField object that can be used to compute the count of\n * documents in the result set of a query.\n */\nexport function count(): AggregateField {\n return new AggregateField('count');\n}\n\n/**\n * Compares two 'AggregateField` instances for equality.\n *\n * @param left Compare this AggregateField to the `right`.\n * @param right Compare this AggregateField to the `left`.\n */\nexport function aggregateFieldEqual(\n left: AggregateField,\n right: AggregateField\n): boolean {\n return (\n left instanceof AggregateField &&\n right instanceof AggregateField &&\n left.aggregateType === right.aggregateType &&\n left._internalFieldPath?.canonicalString() ===\n right._internalFieldPath?.canonicalString()\n );\n}\n\n/**\n * Compares two `AggregateQuerySnapshot` instances for equality.\n *\n * Two `AggregateQuerySnapshot` instances are considered \"equal\" if they have\n * underlying queries that compare equal, and the same data.\n *\n * @param left - The first `AggregateQuerySnapshot` to compare.\n * @param right - The second `AggregateQuerySnapshot` to compare.\n *\n * @returns `true` if the objects are \"equal\", as defined above, or `false`\n * otherwise.\n */\nexport function aggregateQuerySnapshotEqual<\n AggregateSpecType extends AggregateSpec,\n AppModelType,\n DbModelType extends DocumentData\n>(\n left: AggregateQuerySnapshot,\n right: AggregateQuerySnapshot\n): boolean {\n return (\n queryEqual(left.query, right.query) && deepEqual(left.data(), right.data())\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FieldValue } from './field_value';\nimport {\n ArrayRemoveFieldValueImpl,\n ArrayUnionFieldValueImpl,\n DeleteFieldValueImpl,\n NumericIncrementFieldValueImpl,\n ServerTimestampFieldValueImpl\n} from './user_data_reader';\nimport { VectorValue } from './vector_value';\n\n/**\n * Returns a sentinel for use with {@link @firebase/firestore/lite#(updateDoc:1)} or\n * {@link @firebase/firestore/lite#(setDoc:1)} with `{merge: true}` to mark a field for deletion.\n */\nexport function deleteField(): FieldValue {\n return new DeleteFieldValueImpl('deleteField');\n}\n\n/**\n * Returns a sentinel used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link @firebase/firestore/lite#(updateDoc:1)} to\n * include a server-generated timestamp in the written data.\n */\nexport function serverTimestamp(): FieldValue {\n return new ServerTimestampFieldValueImpl('serverTimestamp');\n}\n\n/**\n * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link\n * @firebase/firestore/lite#(updateDoc:1)} that tells the server to union the given elements with any array\n * value that already exists on the server. Each specified element that doesn't\n * already exist in the array will be added to the end. If the field being\n * modified is not already an array it will be overwritten with an array\n * containing exactly the specified elements.\n *\n * @param elements - The elements to union into the array.\n * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or\n * `updateDoc()`.\n */\nexport function arrayUnion(...elements: unknown[]): FieldValue {\n // NOTE: We don't actually parse the data until it's used in set() or\n // update() since we'd need the Firestore instance to do this.\n return new ArrayUnionFieldValueImpl('arrayUnion', elements);\n}\n\n/**\n * Returns a special value that can be used with {@link (setDoc:1)} or {@link\n * updateDoc:1} that tells the server to remove the given elements from any\n * array value that already exists on the server. All instances of each element\n * specified will be removed from the array. If the field being modified is not\n * already an array it will be overwritten with an empty array.\n *\n * @param elements - The elements to remove from the array.\n * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or\n * `updateDoc()`\n */\nexport function arrayRemove(...elements: unknown[]): FieldValue {\n // NOTE: We don't actually parse the data until it's used in set() or\n // update() since we'd need the Firestore instance to do this.\n return new ArrayRemoveFieldValueImpl('arrayRemove', elements);\n}\n\n/**\n * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link\n * @firebase/firestore/lite#(updateDoc:1)} that tells the server to increment the field's current value by\n * the given value.\n *\n * If either the operand or the current field value uses floating point\n * precision, all arithmetic follows IEEE 754 semantics. If both values are\n * integers, values outside of JavaScript's safe number range\n * (`Number.MIN_SAFE_INTEGER` to `Number.MAX_SAFE_INTEGER`) are also subject to\n * precision loss. Furthermore, once processed by the Firestore backend, all\n * integer operations are capped between -2^63 and 2^63-1.\n *\n * If the current field value is not of type `number`, or if the field does not\n * yet exist, the transformation sets the field to the given value.\n *\n * @param n - The value to increment by.\n * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or\n * `updateDoc()`\n */\nexport function increment(n: number): FieldValue {\n return new NumericIncrementFieldValueImpl('increment', n);\n}\n\n/**\n * Creates a new `VectorValue` constructed with a copy of the given array of numbers.\n *\n * @param values - Create a `VectorValue` instance with a copy of this array of numbers.\n *\n * @returns A new `VectorValue` constructed with a copy of the given array of numbers.\n */\nexport function vector(values?: number[]): VectorValue {\n return new VectorValue(values);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Compat, getModularInstance } from '@firebase/util';\n\nimport { DeleteMutation, Mutation, Precondition } from '../model/mutation';\nimport { invokeCommitRpc } from '../remote/datastore';\nimport { Code, FirestoreError } from '../util/error';\nimport { cast } from '../util/input_validation';\n\nimport { getDatastore } from './components';\nimport { Firestore } from './database';\nimport { FieldPath } from './field_path';\nimport {\n DocumentData,\n DocumentReference,\n PartialWithFieldValue,\n SetOptions,\n UpdateData,\n WithFieldValue\n} from './reference';\nimport { applyFirestoreDataConverter } from './reference_impl';\nimport {\n newUserDataReader,\n parseSetData,\n parseUpdateData,\n parseUpdateVarargs,\n UserDataReader\n} from './user_data_reader';\n\n/**\n * A write batch, used to perform multiple writes as a single atomic unit.\n *\n * A `WriteBatch` object can be acquired by calling {@link writeBatch}. It\n * provides methods for adding writes to the write batch. None of the writes\n * will be committed (or visible locally) until {@link WriteBatch.commit} is\n * called.\n */\nexport class WriteBatch {\n // This is the lite version of the WriteBatch API used in the legacy SDK. The\n // class is a close copy but takes different input types.\n\n private readonly _dataReader: UserDataReader;\n private _mutations = [] as Mutation[];\n private _committed = false;\n\n /** @hideconstructor */\n constructor(\n private readonly _firestore: Firestore,\n private readonly _commitHandler: (m: Mutation[]) => Promise\n ) {\n this._dataReader = newUserDataReader(_firestore);\n }\n\n /**\n * Writes to the document referred to by the provided {@link\n * DocumentReference}. If the document does not exist yet, it will be created.\n *\n * @param documentRef - A reference to the document to be set.\n * @param data - An object of the fields and values for the document.\n * @returns This `WriteBatch` instance. Used for chaining method calls.\n */\n set(\n documentRef: DocumentReference,\n data: WithFieldValue\n ): WriteBatch;\n /**\n * Writes to the document referred to by the provided {@link\n * DocumentReference}. If the document does not exist yet, it will be created.\n * If you provide `merge` or `mergeFields`, the provided data can be merged\n * into an existing document.\n *\n * @param documentRef - A reference to the document to be set.\n * @param data - An object of the fields and values for the document.\n * @param options - An object to configure the set behavior.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns This `WriteBatch` instance. Used for chaining method calls.\n */\n set(\n documentRef: DocumentReference,\n data: PartialWithFieldValue,\n options: SetOptions\n ): WriteBatch;\n set(\n documentRef: DocumentReference,\n data: WithFieldValue | PartialWithFieldValue,\n options?: SetOptions\n ): WriteBatch {\n this._verifyNotCommitted();\n const ref = validateReference(documentRef, this._firestore);\n\n const convertedValue = applyFirestoreDataConverter(\n ref.converter,\n data,\n options\n );\n const parsed = parseSetData(\n this._dataReader,\n 'WriteBatch.set',\n ref._key,\n convertedValue,\n ref.converter !== null,\n options\n );\n this._mutations.push(parsed.toMutation(ref._key, Precondition.none()));\n return this;\n }\n\n /**\n * Updates fields in the document referred to by the provided {@link\n * DocumentReference}. The update will fail if applied to a document that does\n * not exist.\n *\n * @param documentRef - A reference to the document to be updated.\n * @param data - An object containing the fields and values with which to\n * update the document. Fields can contain dots to reference nested fields\n * within the document.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns This `WriteBatch` instance. Used for chaining method calls.\n */\n update(\n documentRef: DocumentReference,\n data: UpdateData\n ): WriteBatch;\n /**\n * Updates fields in the document referred to by this {@link\n * DocumentReference}. The update will fail if applied to a document that does\n * not exist.\n *\n * Nested fields can be update by providing dot-separated field path strings\n * or by providing `FieldPath` objects.\n *\n * @param documentRef - A reference to the document to be updated.\n * @param field - The first field to update.\n * @param value - The first value.\n * @param moreFieldsAndValues - Additional key value pairs.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns This `WriteBatch` instance. Used for chaining method calls.\n */\n update(\n documentRef: DocumentReference,\n field: string | FieldPath,\n value: unknown,\n ...moreFieldsAndValues: unknown[]\n ): WriteBatch;\n update(\n documentRef: DocumentReference,\n fieldOrUpdateData: string | FieldPath | UpdateData,\n value?: unknown,\n ...moreFieldsAndValues: unknown[]\n ): WriteBatch {\n this._verifyNotCommitted();\n const ref = validateReference(documentRef, this._firestore);\n\n // For Compat types, we have to \"extract\" the underlying types before\n // performing validation.\n fieldOrUpdateData = getModularInstance(fieldOrUpdateData);\n\n let parsed;\n if (\n typeof fieldOrUpdateData === 'string' ||\n fieldOrUpdateData instanceof FieldPath\n ) {\n parsed = parseUpdateVarargs(\n this._dataReader,\n 'WriteBatch.update',\n ref._key,\n fieldOrUpdateData,\n value,\n moreFieldsAndValues\n );\n } else {\n parsed = parseUpdateData(\n this._dataReader,\n 'WriteBatch.update',\n ref._key,\n fieldOrUpdateData\n );\n }\n\n this._mutations.push(\n parsed.toMutation(ref._key, Precondition.exists(true))\n );\n return this;\n }\n\n /**\n * Deletes the document referred to by the provided {@link DocumentReference}.\n *\n * @param documentRef - A reference to the document to be deleted.\n * @returns This `WriteBatch` instance. Used for chaining method calls.\n */\n delete(\n documentRef: DocumentReference\n ): WriteBatch {\n this._verifyNotCommitted();\n const ref = validateReference(documentRef, this._firestore);\n this._mutations = this._mutations.concat(\n new DeleteMutation(ref._key, Precondition.none())\n );\n return this;\n }\n\n /**\n * Commits all of the writes in this write batch as a single atomic unit.\n *\n * The result of these writes will only be reflected in document reads that\n * occur after the returned promise resolves. If the client is offline, the\n * write fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @returns A `Promise` resolved once all of the writes in the batch have been\n * successfully written to the backend as an atomic unit (note that it won't\n * resolve while you're offline).\n */\n commit(): Promise {\n this._verifyNotCommitted();\n this._committed = true;\n if (this._mutations.length > 0) {\n return this._commitHandler(this._mutations);\n }\n\n return Promise.resolve();\n }\n\n private _verifyNotCommitted(): void {\n if (this._committed) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'A write batch can no longer be used after commit() ' +\n 'has been called.'\n );\n }\n }\n}\n\nexport function validateReference<\n AppModelType,\n DbModelType extends DocumentData\n>(\n documentRef:\n | DocumentReference\n | Compat>,\n firestore: Firestore\n): DocumentReference {\n documentRef = getModularInstance(documentRef);\n\n if (documentRef.firestore !== firestore) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Provided document reference is from a different Firestore instance.'\n );\n } else {\n return documentRef as DocumentReference;\n }\n}\n\n/**\n * Creates a write batch, used for performing multiple writes as a single\n * atomic operation. The maximum number of writes allowed in a single WriteBatch\n * is 500.\n *\n * The result of these writes will only be reflected in document reads that\n * occur after the returned promise resolves. If the client is offline, the\n * write fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @returns A `WriteBatch` that can be used to atomically execute multiple\n * writes.\n */\nexport function writeBatch(firestore: Firestore): WriteBatch {\n firestore = cast(firestore, Firestore);\n const datastore = getDatastore(firestore);\n return new WriteBatch(firestore, writes =>\n invokeCommitRpc(datastore, writes)\n );\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Code, FirestoreError } from '../util/error';\n\nexport const DEFAULT_TRANSACTION_OPTIONS: TransactionOptions = {\n maxAttempts: 5\n};\n\n/**\n * Options to customize transaction behavior.\n */\nexport declare interface TransactionOptions {\n /** Maximum number of attempts to commit, after which transaction fails. Default is 5. */\n readonly maxAttempts: number;\n}\n\nexport function validateTransactionOptions(options: TransactionOptions): void {\n if (options.maxAttempts < 1) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Max attempts must be at least 1'\n );\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ParsedSetData, ParsedUpdateData } from '../lite-api/user_data_reader';\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport {\n DeleteMutation,\n Mutation,\n Precondition,\n VerifyMutation\n} from '../model/mutation';\nimport {\n Datastore,\n invokeBatchGetDocumentsRpc,\n invokeCommitRpc\n} from '../remote/datastore';\nimport { fail, debugAssert } from '../util/assert';\nimport { Code, FirestoreError } from '../util/error';\n\nimport { SnapshotVersion } from './snapshot_version';\n\n/**\n * Internal transaction object responsible for accumulating the mutations to\n * perform and the base versions for any documents read.\n */\nexport class Transaction {\n // The version of each document that was read during this transaction.\n private readVersions = new Map();\n private mutations: Mutation[] = [];\n private committed = false;\n\n /**\n * A deferred usage error that occurred previously in this transaction that\n * will cause the transaction to fail once it actually commits.\n */\n private lastTransactionError: FirestoreError | null = null;\n\n /**\n * Set of documents that have been written in the transaction.\n *\n * When there's more than one write to the same key in a transaction, any\n * writes after the first are handled differently.\n */\n private writtenDocs: Set = new Set();\n\n constructor(private datastore: Datastore) {}\n\n async lookup(keys: DocumentKey[]): Promise {\n this.ensureCommitNotCalled();\n\n if (this.mutations.length > 0) {\n this.lastTransactionError = new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Firestore transactions require all reads to be executed before all writes.'\n );\n throw this.lastTransactionError;\n }\n const docs = await invokeBatchGetDocumentsRpc(this.datastore, keys);\n docs.forEach(doc => this.recordVersion(doc));\n return docs;\n }\n\n set(key: DocumentKey, data: ParsedSetData): void {\n this.write(data.toMutation(key, this.precondition(key)));\n this.writtenDocs.add(key.toString());\n }\n\n update(key: DocumentKey, data: ParsedUpdateData): void {\n try {\n this.write(data.toMutation(key, this.preconditionForUpdate(key)));\n } catch (e) {\n this.lastTransactionError = e as FirestoreError | null;\n }\n this.writtenDocs.add(key.toString());\n }\n\n delete(key: DocumentKey): void {\n this.write(new DeleteMutation(key, this.precondition(key)));\n this.writtenDocs.add(key.toString());\n }\n\n async commit(): Promise {\n this.ensureCommitNotCalled();\n\n if (this.lastTransactionError) {\n throw this.lastTransactionError;\n }\n const unwritten = this.readVersions;\n // For each mutation, note that the doc was written.\n this.mutations.forEach(mutation => {\n unwritten.delete(mutation.key.toString());\n });\n // For each document that was read but not written to, we want to perform\n // a `verify` operation.\n unwritten.forEach((_, path) => {\n const key = DocumentKey.fromPath(path);\n this.mutations.push(new VerifyMutation(key, this.precondition(key)));\n });\n await invokeCommitRpc(this.datastore, this.mutations);\n this.committed = true;\n }\n\n private recordVersion(doc: Document): void {\n let docVersion: SnapshotVersion;\n\n if (doc.isFoundDocument()) {\n docVersion = doc.version;\n } else if (doc.isNoDocument()) {\n // Represent a deleted doc using SnapshotVersion.min().\n docVersion = SnapshotVersion.min();\n } else {\n throw fail(0xc542, 'Document in a transaction was a ', {\n documentName: doc.constructor.name\n });\n }\n\n const existingVersion = this.readVersions.get(doc.key.toString());\n if (existingVersion) {\n if (!docVersion.isEqual(existingVersion)) {\n // This transaction will fail no matter what.\n throw new FirestoreError(\n Code.ABORTED,\n 'Document version changed between two reads.'\n );\n }\n } else {\n this.readVersions.set(doc.key.toString(), docVersion);\n }\n }\n\n /**\n * Returns the version of this document when it was read in this transaction,\n * as a precondition, or no precondition if it was not read.\n */\n private precondition(key: DocumentKey): Precondition {\n const version = this.readVersions.get(key.toString());\n if (!this.writtenDocs.has(key.toString()) && version) {\n if (version.isEqual(SnapshotVersion.min())) {\n return Precondition.exists(false);\n } else {\n return Precondition.updateTime(version);\n }\n } else {\n return Precondition.none();\n }\n }\n\n /**\n * Returns the precondition for a document if the operation is an update.\n */\n private preconditionForUpdate(key: DocumentKey): Precondition {\n const version = this.readVersions.get(key.toString());\n // The first time a document is written, we want to take into account the\n // read time and existence\n if (!this.writtenDocs.has(key.toString()) && version) {\n if (version.isEqual(SnapshotVersion.min())) {\n // The document doesn't exist, so fail the transaction.\n\n // This has to be validated locally because you can't send a\n // precondition that a document does not exist without changing the\n // semantics of the backend write to be an insert. This is the reverse\n // of what we want, since we want to assert that the document doesn't\n // exist but then send the update and have it fail. Since we can't\n // express that to the backend, we have to validate locally.\n\n // Note: this can change once we can send separate verify writes in the\n // transaction.\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n \"Can't update a document that doesn't exist.\"\n );\n }\n // Document exists, base precondition on document update time.\n return Precondition.updateTime(version);\n } else {\n // Document was not read, so we just use the preconditions for a blind\n // update.\n return Precondition.exists(true);\n }\n }\n\n private write(mutation: Mutation): void {\n this.ensureCommitNotCalled();\n this.mutations.push(mutation);\n }\n\n private ensureCommitNotCalled(): void {\n debugAssert(\n !this.committed,\n 'A transaction object cannot be used after its update callback has been invoked.'\n );\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ExponentialBackoff } from '../remote/backoff';\nimport { Datastore } from '../remote/datastore';\nimport { isPermanentError } from '../remote/rpc_error';\nimport { AsyncQueue, TimerId } from '../util/async_queue';\nimport { FirestoreError } from '../util/error';\nimport { Deferred } from '../util/promise';\nimport { isNullOrUndefined } from '../util/types';\n\nimport { Transaction } from './transaction';\nimport { TransactionOptions } from './transaction_options';\n\n/**\n * TransactionRunner encapsulates the logic needed to run and retry transactions\n * with backoff.\n */\nexport class TransactionRunner {\n private attemptsRemaining: number;\n private backoff: ExponentialBackoff;\n\n constructor(\n private readonly asyncQueue: AsyncQueue,\n private readonly datastore: Datastore,\n private readonly options: TransactionOptions,\n private readonly updateFunction: (transaction: Transaction) => Promise,\n private readonly deferred: Deferred\n ) {\n this.attemptsRemaining = options.maxAttempts;\n this.backoff = new ExponentialBackoff(\n this.asyncQueue,\n TimerId.TransactionRetry\n );\n }\n\n /** Runs the transaction and sets the result on deferred. */\n run(): void {\n this.attemptsRemaining -= 1;\n this.runWithBackOff();\n }\n\n private runWithBackOff(): void {\n this.backoff.backoffAndRun(async () => {\n const transaction = new Transaction(this.datastore);\n const userPromise = this.tryRunUpdateFunction(transaction);\n if (userPromise) {\n userPromise\n .then(result => {\n this.asyncQueue.enqueueAndForget(() => {\n return transaction\n .commit()\n .then(() => {\n this.deferred.resolve(result);\n })\n .catch(commitError => {\n this.handleTransactionError(commitError);\n });\n });\n })\n .catch(userPromiseError => {\n this.handleTransactionError(userPromiseError);\n });\n }\n });\n }\n\n private tryRunUpdateFunction(transaction: Transaction): Promise | null {\n try {\n const userPromise = this.updateFunction(transaction);\n if (\n isNullOrUndefined(userPromise) ||\n !userPromise.catch ||\n !userPromise.then\n ) {\n this.deferred.reject(\n Error('Transaction callback must return a Promise')\n );\n return null;\n }\n return userPromise;\n } catch (error) {\n // Do not retry errors thrown by user provided updateFunction.\n this.deferred.reject(error as Error);\n return null;\n }\n }\n\n private handleTransactionError(error: Error): void {\n if (this.attemptsRemaining > 0 && this.isRetryableTransactionError(error)) {\n this.attemptsRemaining -= 1;\n this.asyncQueue.enqueueAndForget(() => {\n this.runWithBackOff();\n return Promise.resolve();\n });\n } else {\n this.deferred.reject(error);\n }\n }\n\n private isRetryableTransactionError(error: Error | undefined): boolean {\n if (error?.name === 'FirebaseError') {\n // In transactions, the backend will fail outdated reads with FAILED_PRECONDITION and\n // non-matching document versions with ABORTED. These errors should be retried.\n const code = (error as FirestoreError).code;\n return (\n code === 'aborted' ||\n code === 'failed-precondition' ||\n code === 'already-exists' ||\n !isPermanentError(code)\n );\n }\n return false;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isIndexedDbTransactionError } from '../local/simple_db';\n\nimport { Code, FirestoreError } from './error';\nimport { logError } from './log';\nimport { Deferred } from './promise';\n\nconst LOG_TAG = 'AsyncQueue';\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype TimerHandle = any;\n\n/**\n * Wellknown \"timer\" IDs used when scheduling delayed operations on the\n * AsyncQueue. These IDs can then be used from tests to check for the presence\n * of operations or to run them early.\n *\n * The string values are used when encoding these timer IDs in JSON spec tests.\n */\nexport const enum TimerId {\n /** All can be used with runDelayedOperationsEarly() to run all timers. */\n All = 'all',\n\n /**\n * The following 5 timers are used in persistent_stream.ts for the listen and\n * write streams. The \"Idle\" timer is used to close the stream due to\n * inactivity. The \"ConnectionBackoff\" timer is used to restart a stream once\n * the appropriate backoff delay has elapsed. The health check is used to mark\n * a stream healthy if it has not received an error during its initial setup.\n */\n ListenStreamIdle = 'listen_stream_idle',\n ListenStreamConnectionBackoff = 'listen_stream_connection_backoff',\n WriteStreamIdle = 'write_stream_idle',\n WriteStreamConnectionBackoff = 'write_stream_connection_backoff',\n HealthCheckTimeout = 'health_check_timeout',\n\n /**\n * A timer used in online_state_tracker.ts to transition from\n * OnlineState.Unknown to Offline after a set timeout, rather than waiting\n * indefinitely for success or failure.\n */\n OnlineStateTimeout = 'online_state_timeout',\n\n /**\n * A timer used to update the client metadata in IndexedDb, which is used\n * to determine the primary leaseholder.\n */\n ClientMetadataRefresh = 'client_metadata_refresh',\n\n /** A timer used to periodically attempt LRU Garbage collection */\n LruGarbageCollection = 'lru_garbage_collection',\n\n /**\n * A timer used to retry transactions. Since there can be multiple concurrent\n * transactions, multiple of these may be in the queue at a given time.\n */\n TransactionRetry = 'transaction_retry',\n\n /**\n * A timer used to retry operations scheduled via retryable AsyncQueue\n * operations.\n */\n AsyncQueueRetry = 'async_queue_retry',\n\n /**\n * A timer used to periodically attempt index backfill.\n */\n IndexBackfill = 'index_backfill'\n}\n\n/**\n * Represents an operation scheduled to be run in the future on an AsyncQueue.\n *\n * It is created via DelayedOperation.createAndSchedule().\n *\n * Supports cancellation (via cancel()) and early execution (via skipDelay()).\n *\n * Note: We implement `PromiseLike` instead of `Promise`, as the `Promise` type\n * in newer versions of TypeScript defines `finally`, which is not available in\n * IE.\n */\nexport class DelayedOperation implements PromiseLike {\n // handle for use with clearTimeout(), or null if the operation has been\n // executed or canceled already.\n private timerHandle: TimerHandle | null;\n\n private readonly deferred = new Deferred();\n\n private constructor(\n private readonly asyncQueue: AsyncQueue,\n readonly timerId: TimerId,\n readonly targetTimeMs: number,\n private readonly op: () => Promise,\n private readonly removalCallback: (op: DelayedOperation) => void\n ) {\n // It's normal for the deferred promise to be canceled (due to cancellation)\n // and so we attach a dummy catch callback to avoid\n // 'UnhandledPromiseRejectionWarning' log spam.\n this.deferred.promise.catch(err => {});\n }\n\n get promise(): Promise {\n return this.deferred.promise;\n }\n\n /**\n * Creates and returns a DelayedOperation that has been scheduled to be\n * executed on the provided asyncQueue after the provided delayMs.\n *\n * @param asyncQueue - The queue to schedule the operation on.\n * @param id - A Timer ID identifying the type of operation this is.\n * @param delayMs - The delay (ms) before the operation should be scheduled.\n * @param op - The operation to run.\n * @param removalCallback - A callback to be called synchronously once the\n * operation is executed or canceled, notifying the AsyncQueue to remove it\n * from its delayedOperations list.\n * PORTING NOTE: This exists to prevent making removeDelayedOperation() and\n * the DelayedOperation class public.\n */\n static createAndSchedule(\n asyncQueue: AsyncQueue,\n timerId: TimerId,\n delayMs: number,\n op: () => Promise,\n removalCallback: (op: DelayedOperation) => void\n ): DelayedOperation {\n const targetTime = Date.now() + delayMs;\n const delayedOp = new DelayedOperation(\n asyncQueue,\n timerId,\n targetTime,\n op,\n removalCallback\n );\n delayedOp.start(delayMs);\n return delayedOp;\n }\n\n /**\n * Starts the timer. This is called immediately after construction by\n * createAndSchedule().\n */\n private start(delayMs: number): void {\n this.timerHandle = setTimeout(() => this.handleDelayElapsed(), delayMs);\n }\n\n /**\n * Queues the operation to run immediately (if it hasn't already been run or\n * canceled).\n */\n skipDelay(): void {\n return this.handleDelayElapsed();\n }\n\n /**\n * Cancels the operation if it hasn't already been executed or canceled. The\n * promise will be rejected.\n *\n * As long as the operation has not yet been run, calling cancel() provides a\n * guarantee that the operation will not be run.\n */\n cancel(reason?: string): void {\n if (this.timerHandle !== null) {\n this.clearTimeout();\n this.deferred.reject(\n new FirestoreError(\n Code.CANCELLED,\n 'Operation cancelled' + (reason ? ': ' + reason : '')\n )\n );\n }\n }\n\n then = this.deferred.promise.then.bind(this.deferred.promise);\n\n private handleDelayElapsed(): void {\n this.asyncQueue.enqueueAndForget(() => {\n if (this.timerHandle !== null) {\n this.clearTimeout();\n return this.op().then(result => {\n return this.deferred.resolve(result);\n });\n } else {\n return Promise.resolve();\n }\n });\n }\n\n private clearTimeout(): void {\n if (this.timerHandle !== null) {\n this.removalCallback(this);\n clearTimeout(this.timerHandle);\n this.timerHandle = null;\n }\n }\n}\n\nexport interface AsyncQueue {\n // Is this AsyncQueue being shut down? If true, this instance will not enqueue\n // any new operations, Promises from enqueue requests will not resolve.\n readonly isShuttingDown: boolean;\n\n /**\n * Adds a new operation to the queue without waiting for it to complete (i.e.\n * we ignore the Promise result).\n */\n enqueueAndForget(op: () => Promise): void;\n\n /**\n * Regardless if the queue has initialized shutdown, adds a new operation to the\n * queue without waiting for it to complete (i.e. we ignore the Promise result).\n */\n enqueueAndForgetEvenWhileRestricted(\n op: () => Promise\n ): void;\n\n /**\n * Initialize the shutdown of this queue. Once this method is called, the\n * only possible way to request running an operation is through\n * `enqueueEvenWhileRestricted()`.\n *\n * @param purgeExistingTasks Whether already enqueued tasked should be\n * rejected (unless enqueued with `enqueueEvenWhileRestricted()`). Defaults\n * to false.\n */\n enterRestrictedMode(purgeExistingTasks?: boolean): void;\n\n /**\n * Adds a new operation to the queue. Returns a promise that will be resolved\n * when the promise returned by the new operation is (with its value).\n */\n enqueue(op: () => Promise): Promise;\n\n /**\n * Enqueue a retryable operation.\n *\n * A retryable operation is rescheduled with backoff if it fails with a\n * IndexedDbTransactionError (the error type used by SimpleDb). All\n * retryable operations are executed in order and only run if all prior\n * operations were retried successfully.\n */\n enqueueRetryable(op: () => Promise): void;\n\n /**\n * Schedules an operation to be queued on the AsyncQueue once the specified\n * `delayMs` has elapsed. The returned DelayedOperation can be used to cancel\n * or fast-forward the operation prior to its running.\n */\n enqueueAfterDelay(\n timerId: TimerId,\n delayMs: number,\n op: () => Promise\n ): DelayedOperation;\n\n /**\n * Verifies there's an operation currently in-progress on the AsyncQueue.\n * Unfortunately we can't verify that the running code is in the promise chain\n * of that operation, so this isn't a foolproof check, but it should be enough\n * to catch some bugs.\n */\n verifyOperationInProgress(): void;\n}\n\n/**\n * Returns a FirestoreError that can be surfaced to the user if the provided\n * error is an IndexedDbTransactionError. Re-throws the error otherwise.\n */\nexport function wrapInUserErrorIfRecoverable(\n e: Error,\n msg: string\n): FirestoreError {\n logError(LOG_TAG, `${msg}: ${e}`);\n if (isIndexedDbTransactionError(e)) {\n return new FirestoreError(Code.UNAVAILABLE, `${msg}: ${e}`);\n } else {\n throw e;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isIndexedDbTransactionError } from '../local/simple_db';\nimport { getDocument } from '../platform/dom';\nimport { ExponentialBackoff } from '../remote/backoff';\n\nimport { debugAssert, fail } from './assert';\nimport { AsyncQueue, DelayedOperation, TimerId } from './async_queue';\nimport { FirestoreError } from './error';\nimport { logDebug, logError } from './log';\nimport { Deferred } from './promise';\n\nconst LOG_TAG = 'AsyncQueue';\n\nexport class AsyncQueueImpl implements AsyncQueue {\n // The last promise in the queue.\n private tail: Promise;\n\n // A list of retryable operations. Retryable operations are run in order and\n // retried with backoff.\n private retryableOps: Array<() => Promise> = [];\n\n // Is this AsyncQueue being shut down? Once it is set to true, it will not\n // be changed again.\n private _isShuttingDown: boolean = false;\n\n // Operations scheduled to be queued in the future. Operations are\n // automatically removed after they are run or canceled.\n private delayedOperations: Array> = [];\n\n // visible for testing\n failure: FirestoreError | null = null;\n\n // Flag set while there's an outstanding AsyncQueue operation, used for\n // assertion sanity-checks.\n private operationInProgress = false;\n\n // Enabled during shutdown on Safari to prevent future access to IndexedDB.\n private skipNonRestrictedTasks = false;\n\n // List of TimerIds to fast-forward delays for.\n private timerIdsToSkip: TimerId[] = [];\n\n // Backoff timer used to schedule retries for retryable operations\n private backoff = new ExponentialBackoff(this, TimerId.AsyncQueueRetry);\n\n // Visibility handler that triggers an immediate retry of all retryable\n // operations. Meant to speed up recovery when we regain file system access\n // after page comes into foreground.\n private visibilityHandler: () => void = () => {\n const document = getDocument();\n if (document) {\n logDebug(\n LOG_TAG,\n 'Visibility state changed to ' + document.visibilityState\n );\n }\n this.backoff.skipBackoff();\n };\n\n constructor(tail: Promise = Promise.resolve()) {\n this.tail = tail;\n const document = getDocument();\n if (document && typeof document.addEventListener === 'function') {\n document.addEventListener('visibilitychange', this.visibilityHandler);\n }\n }\n\n get isShuttingDown(): boolean {\n return this._isShuttingDown;\n }\n\n /**\n * Adds a new operation to the queue without waiting for it to complete (i.e.\n * we ignore the Promise result).\n */\n enqueueAndForget(op: () => Promise): void {\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.enqueue(op);\n }\n\n enqueueAndForgetEvenWhileRestricted(\n op: () => Promise\n ): void {\n this.verifyNotFailed();\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.enqueueInternal(op);\n }\n\n enterRestrictedMode(purgeExistingTasks?: boolean): void {\n if (!this._isShuttingDown) {\n this._isShuttingDown = true;\n this.skipNonRestrictedTasks = purgeExistingTasks || false;\n const document = getDocument();\n if (document && typeof document.removeEventListener === 'function') {\n document.removeEventListener(\n 'visibilitychange',\n this.visibilityHandler\n );\n }\n }\n }\n\n enqueue(op: () => Promise): Promise {\n this.verifyNotFailed();\n if (this._isShuttingDown) {\n // Return a Promise which never resolves.\n return new Promise(() => {});\n }\n\n // Create a deferred Promise that we can return to the callee. This\n // allows us to return a \"hanging Promise\" only to the callee and still\n // advance the queue even when the operation is not run.\n const task = new Deferred();\n return this.enqueueInternal(() => {\n if (this._isShuttingDown && this.skipNonRestrictedTasks) {\n // We do not resolve 'task'\n return Promise.resolve();\n }\n\n op().then(task.resolve, task.reject);\n return task.promise;\n }).then(() => task.promise);\n }\n\n enqueueRetryable(op: () => Promise): void {\n this.enqueueAndForget(() => {\n this.retryableOps.push(op);\n return this.retryNextOp();\n });\n }\n\n /**\n * Runs the next operation from the retryable queue. If the operation fails,\n * reschedules with backoff.\n */\n private async retryNextOp(): Promise {\n if (this.retryableOps.length === 0) {\n return;\n }\n\n try {\n await this.retryableOps[0]();\n this.retryableOps.shift();\n this.backoff.reset();\n } catch (e) {\n if (isIndexedDbTransactionError(e as Error)) {\n logDebug(LOG_TAG, 'Operation failed with retryable error: ' + e);\n } else {\n throw e; // Failure will be handled by AsyncQueue\n }\n }\n\n if (this.retryableOps.length > 0) {\n // If there are additional operations, we re-schedule `retryNextOp()`.\n // This is necessary to run retryable operations that failed during\n // their initial attempt since we don't know whether they are already\n // enqueued. If, for example, `op1`, `op2`, `op3` are enqueued and `op1`\n // needs to be re-run, we will run `op1`, `op1`, `op2` using the\n // already enqueued calls to `retryNextOp()`. `op3()` will then run in the\n // call scheduled here.\n // Since `backoffAndRun()` cancels an existing backoff and schedules a\n // new backoff on every call, there is only ever a single additional\n // operation in the queue.\n this.backoff.backoffAndRun(() => this.retryNextOp());\n }\n }\n\n private enqueueInternal(op: () => Promise): Promise {\n const newTail = this.tail.then(() => {\n this.operationInProgress = true;\n return op()\n .catch((error: FirestoreError) => {\n this.failure = error;\n this.operationInProgress = false;\n const message = getMessageOrStack(error);\n logError('INTERNAL UNHANDLED ERROR: ', message);\n\n // Re-throw the error so that this.tail becomes a rejected Promise and\n // all further attempts to chain (via .then) will just short-circuit\n // and return the rejected Promise.\n throw error;\n })\n .then(result => {\n this.operationInProgress = false;\n return result;\n });\n });\n this.tail = newTail;\n return newTail;\n }\n\n enqueueAfterDelay(\n timerId: TimerId,\n delayMs: number,\n op: () => Promise\n ): DelayedOperation {\n this.verifyNotFailed();\n\n debugAssert(\n delayMs >= 0,\n `Attempted to schedule an operation with a negative delay of ${delayMs}`\n );\n\n // Fast-forward delays for timerIds that have been overridden.\n if (this.timerIdsToSkip.indexOf(timerId) > -1) {\n delayMs = 0;\n }\n\n const delayedOp = DelayedOperation.createAndSchedule(\n this,\n timerId,\n delayMs,\n op,\n removedOp =>\n this.removeDelayedOperation(removedOp as DelayedOperation)\n );\n this.delayedOperations.push(delayedOp as DelayedOperation);\n return delayedOp;\n }\n\n private verifyNotFailed(): void {\n if (this.failure) {\n fail(0xb815, 'AsyncQueue is already failed', {\n messageOrStack: getMessageOrStack(this.failure)\n });\n }\n }\n\n verifyOperationInProgress(): void {\n debugAssert(\n this.operationInProgress,\n 'verifyOpInProgress() called when no op in progress on this queue.'\n );\n }\n\n /**\n * Waits until all currently queued tasks are finished executing. Delayed\n * operations are not run.\n */\n async drain(): Promise {\n // Operations in the queue prior to draining may have enqueued additional\n // operations. Keep draining the queue until the tail is no longer advanced,\n // which indicates that no more new operations were enqueued and that all\n // operations were executed.\n let currentTail: Promise;\n do {\n currentTail = this.tail;\n await currentTail;\n } while (currentTail !== this.tail);\n }\n\n /**\n * For Tests: Determine if a delayed operation with a particular TimerId\n * exists.\n */\n containsDelayedOperation(timerId: TimerId): boolean {\n for (const op of this.delayedOperations) {\n if (op.timerId === timerId) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * For Tests: Runs some or all delayed operations early.\n *\n * @param lastTimerId - Delayed operations up to and including this TimerId\n * will be drained. Pass TimerId.All to run all delayed operations.\n * @returns a Promise that resolves once all operations have been run.\n */\n runAllDelayedOperationsUntil(lastTimerId: TimerId): Promise {\n // Note that draining may generate more delayed ops, so we do that first.\n return this.drain().then(() => {\n // Run ops in the same order they'd run if they ran naturally.\n /* eslint-disable-next-line @typescript-eslint/no-floating-promises */\n this.delayedOperations.sort((a, b) => a.targetTimeMs - b.targetTimeMs);\n\n for (const op of this.delayedOperations) {\n op.skipDelay();\n if (lastTimerId !== TimerId.All && op.timerId === lastTimerId) {\n break;\n }\n }\n\n return this.drain();\n });\n }\n\n /**\n * For Tests: Skip all subsequent delays for a timer id.\n */\n skipDelaysForTimerId(timerId: TimerId): void {\n this.timerIdsToSkip.push(timerId);\n }\n\n /** Called once a DelayedOperation is run or canceled. */\n private removeDelayedOperation(op: DelayedOperation): void {\n // NOTE: indexOf / slice are O(n), but delayedOperations is expected to be small.\n const index = this.delayedOperations.indexOf(op);\n debugAssert(index >= 0, 'Delayed operation not found.');\n /* eslint-disable-next-line @typescript-eslint/no-floating-promises */\n this.delayedOperations.splice(index, 1);\n }\n}\n\nexport function newAsyncQueue(): AsyncQueue {\n return new AsyncQueueImpl();\n}\n\n/**\n * Chrome includes Error.message in Error.stack. Other browsers do not.\n * This returns expected output of message + stack when available.\n * @param error - Error or FirestoreError\n */\nfunction getMessageOrStack(error: Error): string {\n let message = error.message || '';\n if (error.stack) {\n if (error.stack.includes(error.message)) {\n message = error.stack;\n } else {\n message = error.message + '\\n' + error.stack;\n }\n }\n return message;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getModularInstance } from '@firebase/util';\n\nimport { Transaction as InternalTransaction } from '../core/transaction';\nimport {\n DEFAULT_TRANSACTION_OPTIONS,\n TransactionOptions as TransactionOptionsInternal,\n validateTransactionOptions\n} from '../core/transaction_options';\nimport { TransactionRunner } from '../core/transaction_runner';\nimport { fail } from '../util/assert';\nimport { newAsyncQueue } from '../util/async_queue_impl';\nimport { cast } from '../util/input_validation';\nimport { Deferred } from '../util/promise';\n\nimport { getDatastore } from './components';\nimport { Firestore } from './database';\nimport { FieldPath } from './field_path';\nimport {\n DocumentData,\n DocumentReference,\n PartialWithFieldValue,\n SetOptions,\n UpdateData,\n WithFieldValue\n} from './reference';\nimport {\n applyFirestoreDataConverter,\n LiteUserDataWriter\n} from './reference_impl';\nimport { DocumentSnapshot } from './snapshot';\nimport { TransactionOptions } from './transaction_options';\nimport {\n newUserDataReader,\n parseSetData,\n parseUpdateData,\n parseUpdateVarargs,\n UserDataReader\n} from './user_data_reader';\nimport { validateReference } from './write_batch';\n\n// TODO(mrschmidt) Consider using `BaseTransaction` as the base class in the\n// legacy SDK.\n\n/**\n * A reference to a transaction.\n *\n * The `Transaction` object passed to a transaction's `updateFunction` provides\n * the methods to read and write data within the transaction context. See\n * {@link runTransaction}.\n */\nexport class Transaction {\n // This is the tree-shakeable version of the Transaction class used in the\n // legacy SDK. The class is a close copy but takes different input and output\n // types. The firestore-exp SDK further extends this class to return its API\n // type.\n\n private readonly _dataReader: UserDataReader;\n\n /** @hideconstructor */\n constructor(\n protected readonly _firestore: Firestore,\n private readonly _transaction: InternalTransaction\n ) {\n this._dataReader = newUserDataReader(_firestore);\n }\n\n /**\n * Reads the document referenced by the provided {@link DocumentReference}.\n *\n * @param documentRef - A reference to the document to be read.\n * @returns A `DocumentSnapshot` with the read data.\n */\n get(\n documentRef: DocumentReference\n ): Promise> {\n const ref = validateReference(documentRef, this._firestore);\n const userDataWriter = new LiteUserDataWriter(this._firestore);\n return this._transaction.lookup([ref._key]).then(docs => {\n if (!docs || docs.length !== 1) {\n return fail(0x5de9, 'Mismatch in docs returned from document lookup.');\n }\n const doc = docs[0];\n if (doc.isFoundDocument()) {\n return new DocumentSnapshot(\n this._firestore,\n userDataWriter,\n doc.key,\n doc,\n ref.converter\n );\n } else if (doc.isNoDocument()) {\n return new DocumentSnapshot(\n this._firestore,\n userDataWriter,\n ref._key,\n null,\n ref.converter\n );\n } else {\n throw fail(\n 0x4801,\n 'BatchGetDocumentsRequest returned unexpected document',\n {\n doc\n }\n );\n }\n });\n }\n\n /**\n * Writes to the document referred to by the provided {@link\n * DocumentReference}. If the document does not exist yet, it will be created.\n *\n * @param documentRef - A reference to the document to be set.\n * @param data - An object of the fields and values for the document.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns This `Transaction` instance. Used for chaining method calls.\n */\n set(\n documentRef: DocumentReference,\n data: WithFieldValue\n ): this;\n /**\n * Writes to the document referred to by the provided {@link\n * DocumentReference}. If the document does not exist yet, it will be created.\n * If you provide `merge` or `mergeFields`, the provided data can be merged\n * into an existing document.\n *\n * @param documentRef - A reference to the document to be set.\n * @param data - An object of the fields and values for the document.\n * @param options - An object to configure the set behavior.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns This `Transaction` instance. Used for chaining method calls.\n */\n set(\n documentRef: DocumentReference,\n data: PartialWithFieldValue,\n options: SetOptions\n ): this;\n set(\n documentRef: DocumentReference,\n value: PartialWithFieldValue,\n options?: SetOptions\n ): this {\n const ref = validateReference(documentRef, this._firestore);\n const convertedValue = applyFirestoreDataConverter(\n ref.converter,\n value,\n options\n );\n const parsed = parseSetData(\n this._dataReader,\n 'Transaction.set',\n ref._key,\n convertedValue,\n ref.converter !== null,\n options\n );\n this._transaction.set(ref._key, parsed);\n return this;\n }\n\n /**\n * Updates fields in the document referred to by the provided {@link\n * DocumentReference}. The update will fail if applied to a document that does\n * not exist.\n *\n * @param documentRef - A reference to the document to be updated.\n * @param data - An object containing the fields and values with which to\n * update the document. Fields can contain dots to reference nested fields\n * within the document.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns This `Transaction` instance. Used for chaining method calls.\n */\n update(\n documentRef: DocumentReference,\n data: UpdateData\n ): this;\n /**\n * Updates fields in the document referred to by the provided {@link\n * DocumentReference}. The update will fail if applied to a document that does\n * not exist.\n *\n * Nested fields can be updated by providing dot-separated field path\n * strings or by providing `FieldPath` objects.\n *\n * @param documentRef - A reference to the document to be updated.\n * @param field - The first field to update.\n * @param value - The first value.\n * @param moreFieldsAndValues - Additional key/value pairs.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns This `Transaction` instance. Used for chaining method calls.\n */\n update(\n documentRef: DocumentReference,\n field: string | FieldPath,\n value: unknown,\n ...moreFieldsAndValues: unknown[]\n ): this;\n update(\n documentRef: DocumentReference,\n fieldOrUpdateData: string | FieldPath | UpdateData,\n value?: unknown,\n ...moreFieldsAndValues: unknown[]\n ): this {\n const ref = validateReference(documentRef, this._firestore);\n\n // For Compat types, we have to \"extract\" the underlying types before\n // performing validation.\n fieldOrUpdateData = getModularInstance(fieldOrUpdateData);\n\n let parsed;\n if (\n typeof fieldOrUpdateData === 'string' ||\n fieldOrUpdateData instanceof FieldPath\n ) {\n parsed = parseUpdateVarargs(\n this._dataReader,\n 'Transaction.update',\n ref._key,\n fieldOrUpdateData,\n value,\n moreFieldsAndValues\n );\n } else {\n parsed = parseUpdateData(\n this._dataReader,\n 'Transaction.update',\n ref._key,\n fieldOrUpdateData\n );\n }\n\n this._transaction.update(ref._key, parsed);\n return this;\n }\n\n /**\n * Deletes the document referred to by the provided {@link DocumentReference}.\n *\n * @param documentRef - A reference to the document to be deleted.\n * @returns This `Transaction` instance. Used for chaining method calls.\n */\n delete(\n documentRef: DocumentReference\n ): this {\n const ref = validateReference(documentRef, this._firestore);\n this._transaction.delete(ref._key);\n return this;\n }\n}\n\n/**\n * Executes the given `updateFunction` and then attempts to commit the changes\n * applied within the transaction. If any document read within the transaction\n * has changed, Cloud Firestore retries the `updateFunction`. If it fails to\n * commit after 5 attempts, the transaction fails.\n *\n * The maximum number of writes allowed in a single transaction is 500.\n *\n * @param firestore - A reference to the Firestore database to run this\n * transaction against.\n * @param updateFunction - The function to execute within the transaction\n * context.\n * @param options - An options object to configure maximum number of attempts to\n * commit.\n * @returns If the transaction completed successfully or was explicitly aborted\n * (the `updateFunction` returned a failed promise), the promise returned by the\n * `updateFunction `is returned here. Otherwise, if the transaction failed, a\n * rejected promise with the corresponding failure error is returned.\n */\nexport function runTransaction(\n firestore: Firestore,\n updateFunction: (transaction: Transaction) => Promise,\n options?: TransactionOptions\n): Promise {\n firestore = cast(firestore, Firestore);\n const datastore = getDatastore(firestore);\n const optionsWithDefaults: TransactionOptionsInternal = {\n ...DEFAULT_TRANSACTION_OPTIONS,\n ...options\n };\n validateTransactionOptions(optionsWithDefaults);\n const deferred = new Deferred();\n new TransactionRunner(\n newAsyncQueue(),\n datastore,\n optionsWithDefaults,\n internalTransaction =>\n updateFunction(new Transaction(firestore, internalTransaction)),\n deferred\n ).run();\n return deferred.promise;\n}\n","/**\n * Firestore Lite\n *\n * @remarks Firestore Lite is a small online-only SDK that allows read\n * and write access to your Firestore database. All operations connect\n * directly to the backend, and `onSnapshot()` APIs are not supported.\n * @packageDocumentation\n */\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { registerFirestore } from './register';\nregisterFirestore();\n\nexport {\n aggregateQuerySnapshotEqual,\n getCount,\n getAggregate,\n count,\n sum,\n average,\n aggregateFieldEqual\n} from '../src/lite-api/aggregate';\n\nexport {\n AggregateField,\n AggregateFieldType,\n AggregateSpec,\n AggregateSpecData,\n AggregateQuerySnapshot,\n AggregateType\n} from '../src/lite-api/aggregate_types';\n\nexport { FirestoreSettings as Settings } from '../src/lite-api/settings';\n\nexport {\n Firestore as Firestore,\n EmulatorMockTokenOptions,\n initializeFirestore,\n getFirestore,\n terminate,\n connectFirestoreEmulator\n} from '../src/lite-api/database';\n\nexport {\n DocumentData,\n UpdateData,\n WithFieldValue,\n PartialWithFieldValue,\n SetOptions,\n DocumentReference,\n Query,\n CollectionReference,\n collection,\n collectionGroup,\n doc,\n refEqual,\n queryEqual\n} from '../src/lite-api/reference';\n\nexport {\n and,\n endAt,\n endBefore,\n startAt,\n startAfter,\n limit,\n limitToLast,\n where,\n or,\n orderBy,\n query,\n QueryConstraint,\n QueryConstraintType,\n QueryCompositeFilterConstraint,\n QueryFilterConstraint,\n QueryFieldFilterConstraint,\n QueryOrderByConstraint,\n QueryLimitConstraint,\n QueryNonFilterConstraint,\n QueryStartAtConstraint,\n QueryEndAtConstraint,\n OrderByDirection,\n WhereFilterOp\n} from '../src/lite-api/query';\n\nexport {\n addDoc,\n deleteDoc,\n updateDoc,\n setDoc,\n getDoc,\n getDocs\n} from '../src/lite-api/reference_impl';\n\nexport {\n Primitive,\n NestedUpdateFields,\n ChildUpdateFields,\n AddPrefixToKeys,\n UnionToIntersection\n} from '../src/lite-api/types';\n\n// TODO(firestorelite): Add tests when Queries are usable\nexport { FieldPath, documentId } from '../src/lite-api/field_path';\n\n// TODO(firestorelite): Add tests when setDoc() is available\nexport { FieldValue } from '../src/lite-api/field_value';\n\nexport {\n increment,\n arrayRemove,\n arrayUnion,\n serverTimestamp,\n deleteField,\n vector\n} from '../src/lite-api/field_value_impl';\n\nexport {\n FirestoreDataConverter,\n DocumentSnapshot,\n QueryDocumentSnapshot,\n QuerySnapshot,\n snapshotEqual\n} from '../src/lite-api/snapshot';\n\nexport { VectorValue } from '../src/lite-api/vector_value';\n\nexport { WriteBatch, writeBatch } from '../src/lite-api/write_batch';\n\nexport { TransactionOptions } from '../src/lite-api/transaction_options';\n\nexport { Transaction, runTransaction } from '../src/lite-api/transaction';\n\nexport { setLogLevel, LogLevelString as LogLevel } from '../src/util/log';\n\nexport { Bytes } from '../src/lite-api/bytes';\n\nexport { GeoPoint } from '../src/lite-api/geo_point';\n\nexport { Timestamp } from '../src/lite-api/timestamp';\n\nexport { FirestoreErrorCode, FirestoreError } from '../src/util/error';\n"],"names":["inspect","Logger","LogLevel","FirebaseError","app","_isFirebaseServerApp","generateRandomBytes","Integer","FieldPath","LOG_TAG","isCloudWorkstation","TYPE_KEY","_getProvider","getApp","getDefaultEmulatorHostnameAndPort","pingServer","updateEmulatorBanner","deepEqual","createMockUserToken","_removeServiceInstance","SDK_VERSION","_registerComponent","Component","registerVersion","version","getModularInstance","InternalFieldPath","fieldPathFromArgument","Transaction"],"mappings":";;;;;;;;;;;;;;AAAA;;;;;;;;;;;;;;;AAeG;AAEH;;;AAGG;AACU,MAAA,IAAI,CAAA;AAUf,IAAA,WAAA,CAAqB,GAAkB,EAAA;AAAlB,QAAA,IAAG,CAAA,GAAA,GAAH,GAAG,CAAe;AAAI,KAAA;AAE3C,IAAA,eAAe,GAAA;AACb,QAAA,OAAO,IAAI,CAAC,GAAG,IAAI,IAAI,CAAC;AACzB,KAAA;AAED;;;AAGG;AACH,IAAA,KAAK,GAAA;AACH,QAAA,IAAI,IAAI,CAAC,eAAe,EAAE,EAAE;AAC1B,YAAA,OAAO,MAAM,GAAG,IAAI,CAAC,GAAG,CAAC;AAC1B,SAAA;AAAM,aAAA;AACL,YAAA,OAAO,gBAAgB,CAAC;AACzB,SAAA;AACF,KAAA;AAED,IAAA,OAAO,CAAC,SAAe,EAAA;AACrB,QAAA,OAAO,SAAS,CAAC,GAAG,KAAK,IAAI,CAAC,GAA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OAAO,QAAQ,CAAC,OAAO,CAAC;AAC1B,CAAA;;ACvTA;;;;;;;AAOG;AAoBH,iBAAiB,EAAE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/index.node.mjs b/frontend-old/node_modules/@firebase/firestore/dist/lite/index.node.mjs new file mode 100644 index 0000000..7a3a3a8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/index.node.mjs @@ -0,0 +1,9798 @@ +import { _getProvider, getApp, _removeServiceInstance, _registerComponent, registerVersion, _isFirebaseServerApp, SDK_VERSION as SDK_VERSION$1 } from '@firebase/app'; +import { Component } from '@firebase/component'; +import { Logger, LogLevel } from '@firebase/logger'; +import { inspect } from 'util'; +import { FirebaseError, getDefaultEmulatorHostnameAndPort, isCloudWorkstation, pingServer, updateEmulatorBanner, deepEqual, createMockUserToken, getModularInstance } from '@firebase/util'; +import { Integer } from '@firebase/webchannel-wrapper/bloom-blob'; +import { randomBytes as randomBytes$1 } from 'crypto'; + +const version$1 = "4.9.2"; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Simple wrapper around a nullable UID. Mostly exists to make code more + * readable. + */ +class User { + constructor(uid) { + this.uid = uid; + } + isAuthenticated() { + return this.uid != null; + } + /** + * Returns a key representing this user, suitable for inclusion in a + * dictionary. + */ + toKey() { + if (this.isAuthenticated()) { + return 'uid:' + this.uid; + } + else { + return 'anonymous-user'; + } + } + isEqual(otherUser) { + return otherUser.uid === this.uid; + } +} +/** A user with a null UID. */ +User.UNAUTHENTICATED = new User(null); +// TODO(mikelehen): Look into getting a proper uid-equivalent for +// non-FirebaseAuth providers. +User.GOOGLE_CREDENTIALS = new User('google-credentials-uid'); +User.FIRST_PARTY = new User('first-party-uid'); +User.MOCK_USER = new User('mock-user'); + +const version = "12.3.0"; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +let SDK_VERSION = version; +function setSDKVersion(version) { + SDK_VERSION = version; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Formats an object as a JSON string, suitable for logging. */ +function formatJSON(value) { + // util.inspect() results in much more readable output than JSON.stringify() + return inspect(value, { depth: 100 }); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const logClient = new Logger('@firebase/firestore'); +/** + * Sets the verbosity of Cloud Firestore logs (debug, error, or silent). + * + * @param logLevel - The verbosity you set for activity and error logging. Can + * be any of the following values: + * + *
    + *
  • `debug` for the most verbose logging level, primarily for + * debugging.
  • + *
  • `error` to log errors only.
  • + *
  • `silent` to turn off logging.
  • + *
+ */ +function setLogLevel(logLevel) { + logClient.setLogLevel(logLevel); +} +function logDebug(msg, ...obj) { + if (logClient.logLevel <= LogLevel.DEBUG) { + const args = obj.map(argToString); + logClient.debug(`Firestore (${SDK_VERSION}): ${msg}`, ...args); + } +} +function logError(msg, ...obj) { + if (logClient.logLevel <= LogLevel.ERROR) { + const args = obj.map(argToString); + logClient.error(`Firestore (${SDK_VERSION}): ${msg}`, ...args); + } +} +/** + * @internal + */ +function logWarn(msg, ...obj) { + if (logClient.logLevel <= LogLevel.WARN) { + const args = obj.map(argToString); + logClient.warn(`Firestore (${SDK_VERSION}): ${msg}`, ...args); + } +} +/** + * Converts an additional log parameter to a string representation. + */ +function argToString(obj) { + if (typeof obj === 'string') { + return obj; + } + else { + try { + return formatJSON(obj); + } + catch (e) { + // Converting to JSON failed, just log the object directly + return obj; + } + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +function fail(id, messageOrContext, context) { + let message = 'Unexpected state'; + if (typeof messageOrContext === 'string') { + message = messageOrContext; + } + else { + context = messageOrContext; + } + _fail(id, message, context); +} +function _fail(id, failure, context) { + // Log the failure in addition to throw an exception, just in case the + // exception is swallowed. + let message = `FIRESTORE (${SDK_VERSION}) INTERNAL ASSERTION FAILED: ${failure} (ID: ${id.toString(16)})`; + if (context !== undefined) { + try { + const stringContext = JSON.stringify(context); + message += ' CONTEXT: ' + stringContext; + } + catch (e) { + message += ' CONTEXT: ' + context; + } + } + logError(message); + // NOTE: We don't use FirestoreError here because these are internal failures + // that cannot be handled by the user. (Also it would create a circular + // dependency between the error and assert modules which doesn't work.) + throw new Error(message); +} +function hardAssert(assertion, id, messageOrContext, context) { + let message = 'Unexpected state'; + if (typeof messageOrContext === 'string') { + message = messageOrContext; + } + else { + context = messageOrContext; + } + if (!assertion) { + _fail(id, message, context); + } +} +/** + * Casts `obj` to `T`. In non-production builds, verifies that `obj` is an + * instance of `T` before casting. + */ +function debugCast(obj, +// eslint-disable-next-line @typescript-eslint/no-explicit-any +constructor) { + return obj; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const Code = { + // Causes are copied from: + // https://github.com/grpc/grpc/blob/bceec94ea4fc5f0085d81235d8e1c06798dc341a/include/grpc%2B%2B/impl/codegen/status_code_enum.h + /** Not an error; returned on success. */ + OK: 'ok', + /** The operation was cancelled (typically by the caller). */ + CANCELLED: 'cancelled', + /** Unknown error or an error from a different error domain. */ + UNKNOWN: 'unknown', + /** + * Client specified an invalid argument. Note that this differs from + * FAILED_PRECONDITION. INVALID_ARGUMENT indicates arguments that are + * problematic regardless of the state of the system (e.g., a malformed file + * name). + */ + INVALID_ARGUMENT: 'invalid-argument', + /** + * Deadline expired before operation could complete. For operations that + * change the state of the system, this error may be returned even if the + * operation has completed successfully. For example, a successful response + * from a server could have been delayed long enough for the deadline to + * expire. + */ + DEADLINE_EXCEEDED: 'deadline-exceeded', + /** Some requested entity (e.g., file or directory) was not found. */ + NOT_FOUND: 'not-found', + /** + * Some entity that we attempted to create (e.g., file or directory) already + * exists. + */ + ALREADY_EXISTS: 'already-exists', + /** + * The caller does not have permission to execute the specified operation. + * PERMISSION_DENIED must not be used for rejections caused by exhausting + * some resource (use RESOURCE_EXHAUSTED instead for those errors). + * PERMISSION_DENIED must not be used if the caller cannot be identified + * (use UNAUTHENTICATED instead for those errors). + */ + PERMISSION_DENIED: 'permission-denied', + /** + * The request does not have valid authentication credentials for the + * operation. + */ + UNAUTHENTICATED: 'unauthenticated', + /** + * Some resource has been exhausted, perhaps a per-user quota, or perhaps the + * entire file system is out of space. + */ + RESOURCE_EXHAUSTED: 'resource-exhausted', + /** + * Operation was rejected because the system is not in a state required for + * the operation's execution. For example, directory to be deleted may be + * non-empty, an rmdir operation is applied to a non-directory, etc. + * + * A litmus test that may help a service implementor in deciding + * between FAILED_PRECONDITION, ABORTED, and UNAVAILABLE: + * (a) Use UNAVAILABLE if the client can retry just the failing call. + * (b) Use ABORTED if the client should retry at a higher-level + * (e.g., restarting a read-modify-write sequence). + * (c) Use FAILED_PRECONDITION if the client should not retry until + * the system state has been explicitly fixed. E.g., if an "rmdir" + * fails because the directory is non-empty, FAILED_PRECONDITION + * should be returned since the client should not retry unless + * they have first fixed up the directory by deleting files from it. + * (d) Use FAILED_PRECONDITION if the client performs conditional + * REST Get/Update/Delete on a resource and the resource on the + * server does not match the condition. E.g., conflicting + * read-modify-write on the same resource. + */ + FAILED_PRECONDITION: 'failed-precondition', + /** + * The operation was aborted, typically due to a concurrency issue like + * sequencer check failures, transaction aborts, etc. + * + * See litmus test above for deciding between FAILED_PRECONDITION, ABORTED, + * and UNAVAILABLE. + */ + ABORTED: 'aborted', + /** + * Operation was attempted past the valid range. E.g., seeking or reading + * past end of file. + * + * Unlike INVALID_ARGUMENT, this error indicates a problem that may be fixed + * if the system state changes. For example, a 32-bit file system will + * generate INVALID_ARGUMENT if asked to read at an offset that is not in the + * range [0,2^32-1], but it will generate OUT_OF_RANGE if asked to read from + * an offset past the current file size. + * + * There is a fair bit of overlap between FAILED_PRECONDITION and + * OUT_OF_RANGE. We recommend using OUT_OF_RANGE (the more specific error) + * when it applies so that callers who are iterating through a space can + * easily look for an OUT_OF_RANGE error to detect when they are done. + */ + OUT_OF_RANGE: 'out-of-range', + /** Operation is not implemented or not supported/enabled in this service. */ + UNIMPLEMENTED: 'unimplemented', + /** + * Internal errors. Means some invariants expected by underlying System has + * been broken. If you see one of these errors, Something is very broken. + */ + INTERNAL: 'internal', + /** + * The service is currently unavailable. This is a most likely a transient + * condition and may be corrected by retrying with a backoff. + * + * See litmus test above for deciding between FAILED_PRECONDITION, ABORTED, + * and UNAVAILABLE. + */ + UNAVAILABLE: 'unavailable', + /** Unrecoverable data loss or corruption. */ + DATA_LOSS: 'data-loss' +}; +/** An error returned by a Firestore operation. */ +class FirestoreError extends FirebaseError { + /** @hideconstructor */ + constructor( + /** + * The backend error code associated with this error. + */ + code, + /** + * A custom error description. + */ + message) { + super(code, message); + this.code = code; + this.message = message; + // HACK: We write a toString property directly because Error is not a real + // class and so inheritance does not work correctly. We could alternatively + // do the same "back-door inheritance" trick that FirebaseError does. + this.toString = () => `${this.name}: [code=${this.code}]: ${this.message}`; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class Deferred { + constructor() { + this.promise = new Promise((resolve, reject) => { + this.resolve = resolve; + this.reject = reject; + }); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class OAuthToken { + constructor(value, user) { + this.user = user; + this.type = 'OAuth'; + this.headers = new Map(); + this.headers.set('Authorization', `Bearer ${value}`); + } +} +/** + * A CredentialsProvider that always yields an empty token. + * @internal + */ +class EmptyAuthCredentialsProvider { + getToken() { + return Promise.resolve(null); + } + invalidateToken() { } + start(asyncQueue, changeListener) { + // Fire with initial user. + asyncQueue.enqueueRetryable(() => changeListener(User.UNAUTHENTICATED)); + } + shutdown() { } +} +/** + * A CredentialsProvider that always returns a constant token. Used for + * emulator token mocking. + */ +class EmulatorAuthCredentialsProvider { + constructor(token) { + this.token = token; + /** + * Stores the listener registered with setChangeListener() + * This isn't actually necessary since the UID never changes, but we use this + * to verify the listen contract is adhered to in tests. + */ + this.changeListener = null; + } + getToken() { + return Promise.resolve(this.token); + } + invalidateToken() { } + start(asyncQueue, changeListener) { + this.changeListener = changeListener; + // Fire with initial user. + asyncQueue.enqueueRetryable(() => changeListener(this.token.user)); + } + shutdown() { + this.changeListener = null; + } +} +/** Credential provider for the Lite SDK. */ +class LiteAuthCredentialsProvider { + constructor(authProvider) { + this.auth = null; + authProvider.onInit(auth => { + this.auth = auth; + }); + } + getToken() { + if (!this.auth) { + return Promise.resolve(null); + } + return this.auth.getToken().then(tokenData => { + if (tokenData) { + hardAssert(typeof tokenData.accessToken === 'string', 0xa539, { tokenData }); + return new OAuthToken(tokenData.accessToken, new User(this.auth.getUid())); + } + else { + return null; + } + }); + } + invalidateToken() { } + start(asyncQueue, changeListener) { } + shutdown() { } +} +/* + * FirstPartyToken provides a fresh token each time its value + * is requested, because if the token is too old, requests will be rejected. + * Technically this may no longer be necessary since the SDK should gracefully + * recover from unauthenticated errors (see b/33147818 for context), but it's + * safer to keep the implementation as-is. + */ +class FirstPartyToken { + constructor(sessionIndex, iamToken, authTokenFactory) { + this.sessionIndex = sessionIndex; + this.iamToken = iamToken; + this.authTokenFactory = authTokenFactory; + this.type = 'FirstParty'; + this.user = User.FIRST_PARTY; + this._headers = new Map(); + } + /** + * Gets an authorization token, using a provided factory function, or return + * null. + */ + getAuthToken() { + if (this.authTokenFactory) { + return this.authTokenFactory(); + } + else { + return null; + } + } + get headers() { + this._headers.set('X-Goog-AuthUser', this.sessionIndex); + // Use array notation to prevent minification + const authHeaderTokenValue = this.getAuthToken(); + if (authHeaderTokenValue) { + this._headers.set('Authorization', authHeaderTokenValue); + } + if (this.iamToken) { + this._headers.set('X-Goog-Iam-Authorization-Token', this.iamToken); + } + return this._headers; + } +} +/* + * Provides user credentials required for the Firestore JavaScript SDK + * to authenticate the user, using technique that is only available + * to applications hosted by Google. + */ +class FirstPartyAuthCredentialsProvider { + constructor(sessionIndex, iamToken, authTokenFactory) { + this.sessionIndex = sessionIndex; + this.iamToken = iamToken; + this.authTokenFactory = authTokenFactory; + } + getToken() { + return Promise.resolve(new FirstPartyToken(this.sessionIndex, this.iamToken, this.authTokenFactory)); + } + start(asyncQueue, changeListener) { + // Fire with initial uid. + asyncQueue.enqueueRetryable(() => changeListener(User.FIRST_PARTY)); + } + shutdown() { } + invalidateToken() { } +} +class AppCheckToken { + constructor(value) { + this.value = value; + this.type = 'AppCheck'; + this.headers = new Map(); + if (value && value.length > 0) { + this.headers.set('x-firebase-appcheck', this.value); + } + } +} +/** AppCheck token provider for the Lite SDK. */ +class LiteAppCheckTokenProvider { + constructor(app, appCheckProvider) { + this.appCheckProvider = appCheckProvider; + this.appCheck = null; + this.serverAppAppCheckToken = null; + if (_isFirebaseServerApp(app) && app.settings.appCheckToken) { + this.serverAppAppCheckToken = app.settings.appCheckToken; + } + appCheckProvider.onInit(appCheck => { + this.appCheck = appCheck; + }); + } + getToken() { + if (this.serverAppAppCheckToken) { + return Promise.resolve(new AppCheckToken(this.serverAppAppCheckToken)); + } + if (!this.appCheck) { + return Promise.resolve(null); + } + return this.appCheck.getToken().then(tokenResult => { + if (tokenResult) { + hardAssert(typeof tokenResult.token === 'string', 0x0d8e, { tokenResult }); + return new AppCheckToken(tokenResult.token); + } + else { + return null; + } + }); + } + invalidateToken() { } + start(asyncQueue, changeListener) { } + shutdown() { } +} +/** + * Builds a CredentialsProvider depending on the type of + * the credentials passed in. + */ +function makeAuthCredentialsProvider(credentials) { + if (!credentials) { + return new EmptyAuthCredentialsProvider(); + } + switch (credentials['type']) { + case 'firstParty': + return new FirstPartyAuthCredentialsProvider(credentials['sessionIndex'] || '0', credentials['iamToken'] || null, credentials['authTokenFactory'] || null); + case 'provider': + return credentials['client']; + default: + throw new FirestoreError(Code.INVALID_ARGUMENT, 'makeAuthCredentialsProvider failed due to invalid credential type'); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class DatabaseInfo { + /** + * Constructs a DatabaseInfo using the provided host, databaseId and + * persistenceKey. + * + * @param databaseId - The database to use. + * @param appId - The Firebase App Id. + * @param persistenceKey - A unique identifier for this Firestore's local + * storage (used in conjunction with the databaseId). + * @param host - The Firestore backend host to connect to. + * @param ssl - Whether to use SSL when connecting. + * @param forceLongPolling - Whether to use the forceLongPolling option + * when using WebChannel as the network transport. + * @param autoDetectLongPolling - Whether to use the detectBufferingProxy + * option when using WebChannel as the network transport. + * @param longPollingOptions Options that configure long-polling. + * @param useFetchStreams Whether to use the Fetch API instead of + * XMLHTTPRequest + */ + constructor(databaseId, appId, persistenceKey, host, ssl, forceLongPolling, autoDetectLongPolling, longPollingOptions, useFetchStreams, isUsingEmulator) { + this.databaseId = databaseId; + this.appId = appId; + this.persistenceKey = persistenceKey; + this.host = host; + this.ssl = ssl; + this.forceLongPolling = forceLongPolling; + this.autoDetectLongPolling = autoDetectLongPolling; + this.longPollingOptions = longPollingOptions; + this.useFetchStreams = useFetchStreams; + this.isUsingEmulator = isUsingEmulator; + } +} +/** The default database name for a project. */ +const DEFAULT_DATABASE_NAME = '(default)'; +/** + * Represents the database ID a Firestore client is associated with. + * @internal + */ +class DatabaseId { + constructor(projectId, database) { + this.projectId = projectId; + this.database = database ? database : DEFAULT_DATABASE_NAME; + } + static empty() { + return new DatabaseId('', ''); + } + get isDefaultDatabase() { + return this.database === DEFAULT_DATABASE_NAME; + } + isEqual(other) { + return (other instanceof DatabaseId && + other.projectId === this.projectId && + other.database === this.database); + } +} +function databaseIdFromApp(app, database) { + if (!Object.prototype.hasOwnProperty.apply(app.options, ['projectId'])) { + throw new FirestoreError(Code.INVALID_ARGUMENT, '"projectId" not provided in firebase.initializeApp.'); + } + return new DatabaseId(app.options.projectId, database); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Generates `nBytes` of random bytes. + * + * If `nBytes < 0` , an error will be thrown. + */ +function randomBytes(nBytes) { + return randomBytes$1(nBytes); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A utility class for generating unique alphanumeric IDs of a specified length. + * + * @internal + * Exported internally for testing purposes. + */ +class AutoId { + static newId() { + // Alphanumeric characters + const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; + // The largest byte value that is a multiple of `char.length`. + const maxMultiple = Math.floor(256 / chars.length) * chars.length; + let autoId = ''; + const targetLength = 20; + while (autoId.length < targetLength) { + const bytes = randomBytes(40); + for (let i = 0; i < bytes.length; ++i) { + // Only accept values that are [0, maxMultiple), this ensures they can + // be evenly mapped to indices of `chars` via a modulo operation. + if (autoId.length < targetLength && bytes[i] < maxMultiple) { + autoId += chars.charAt(bytes[i] % chars.length); + } + } + } + return autoId; + } +} +function primitiveComparator(left, right) { + if (left < right) { + return -1; + } + if (left > right) { + return 1; + } + return 0; +} +/** Compare strings in UTF-8 encoded byte order */ +function compareUtf8Strings(left, right) { + // Find the first differing character (a.k.a. "UTF-16 code unit") in the two strings and, + // if found, use that character to determine the relative ordering of the two strings as a + // whole. Comparing UTF-16 strings in UTF-8 byte order can be done simply and efficiently by + // comparing the UTF-16 code units (chars). This serendipitously works because of the way UTF-8 + // and UTF-16 happen to represent Unicode code points. + // + // After finding the first pair of differing characters, there are two cases: + // + // Case 1: Both characters are non-surrogates (code points less than or equal to 0xFFFF) or + // both are surrogates from a surrogate pair (that collectively represent code points greater + // than 0xFFFF). In this case their numeric order as UTF-16 code units is the same as the + // lexicographical order of their corresponding UTF-8 byte sequences. A direct comparison is + // sufficient. + // + // Case 2: One character is a surrogate and the other is not. In this case the surrogate- + // containing string is always ordered after the non-surrogate. This is because surrogates are + // used to represent code points greater than 0xFFFF which have 4-byte UTF-8 representations + // and are lexicographically greater than the 1, 2, or 3-byte representations of code points + // less than or equal to 0xFFFF. + // + // An example of why Case 2 is required is comparing the following two Unicode code points: + // + // |-----------------------|------------|---------------------|-----------------| + // | Name | Code Point | UTF-8 Encoding | UTF-16 Encoding | + // |-----------------------|------------|---------------------|-----------------| + // | Replacement Character | U+FFFD | 0xEF 0xBF 0xBD | 0xFFFD | + // | Grinning Face | U+1F600 | 0xF0 0x9F 0x98 0x80 | 0xD83D 0xDE00 | + // |-----------------------|------------|---------------------|-----------------| + // + // A lexicographical comparison of the UTF-8 encodings of these code points would order + // "Replacement Character" _before_ "Grinning Face" because 0xEF is less than 0xF0. However, a + // direct comparison of the UTF-16 code units, as would be done in case 1, would erroneously + // produce the _opposite_ ordering, because 0xFFFD is _greater than_ 0xD83D. As it turns out, + // this relative ordering holds for all comparisons of UTF-16 code points requiring a surrogate + // pair with those that do not. + const length = Math.min(left.length, right.length); + for (let i = 0; i < length; i++) { + const leftChar = left.charAt(i); + const rightChar = right.charAt(i); + if (leftChar !== rightChar) { + return isSurrogate(leftChar) === isSurrogate(rightChar) + ? primitiveComparator(leftChar, rightChar) + : isSurrogate(leftChar) + ? 1 + : -1; + } + } + // Use the lengths of the strings to determine the overall comparison result since either the + // strings were equal or one is a prefix of the other. + return primitiveComparator(left.length, right.length); +} +const MIN_SURROGATE = 0xd800; +const MAX_SURROGATE = 0xdfff; +function isSurrogate(s) { + const c = s.charCodeAt(0); + return c >= MIN_SURROGATE && c <= MAX_SURROGATE; +} +/** Helper to compare arrays using isEqual(). */ +function arrayEquals(left, right, comparator) { + if (left.length !== right.length) { + return false; + } + return left.every((value, index) => comparator(value, right[index])); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const DOCUMENT_KEY_NAME = '__name__'; +/** + * Path represents an ordered sequence of string segments. + */ +class BasePath { + constructor(segments, offset, length) { + if (offset === undefined) { + offset = 0; + } + else if (offset > segments.length) { + fail(0x027d, { + offset, + range: segments.length + }); + } + if (length === undefined) { + length = segments.length - offset; + } + else if (length > segments.length - offset) { + fail(0x06d2, { + length, + range: segments.length - offset + }); + } + this.segments = segments; + this.offset = offset; + this.len = length; + } + get length() { + return this.len; + } + isEqual(other) { + return BasePath.comparator(this, other) === 0; + } + child(nameOrPath) { + const segments = this.segments.slice(this.offset, this.limit()); + if (nameOrPath instanceof BasePath) { + nameOrPath.forEach(segment => { + segments.push(segment); + }); + } + else { + segments.push(nameOrPath); + } + return this.construct(segments); + } + /** The index of one past the last segment of the path. */ + limit() { + return this.offset + this.length; + } + popFirst(size) { + size = size === undefined ? 1 : size; + return this.construct(this.segments, this.offset + size, this.length - size); + } + popLast() { + return this.construct(this.segments, this.offset, this.length - 1); + } + firstSegment() { + return this.segments[this.offset]; + } + lastSegment() { + return this.get(this.length - 1); + } + get(index) { + return this.segments[this.offset + index]; + } + isEmpty() { + return this.length === 0; + } + isPrefixOf(other) { + if (other.length < this.length) { + return false; + } + for (let i = 0; i < this.length; i++) { + if (this.get(i) !== other.get(i)) { + return false; + } + } + return true; + } + isImmediateParentOf(potentialChild) { + if (this.length + 1 !== potentialChild.length) { + return false; + } + for (let i = 0; i < this.length; i++) { + if (this.get(i) !== potentialChild.get(i)) { + return false; + } + } + return true; + } + forEach(fn) { + for (let i = this.offset, end = this.limit(); i < end; i++) { + fn(this.segments[i]); + } + } + toArray() { + return this.segments.slice(this.offset, this.limit()); + } + /** + * Compare 2 paths segment by segment, prioritizing numeric IDs + * (e.g., "__id123__") in numeric ascending order, followed by string + * segments in lexicographical order. + */ + static comparator(p1, p2) { + const len = Math.min(p1.length, p2.length); + for (let i = 0; i < len; i++) { + const comparison = BasePath.compareSegments(p1.get(i), p2.get(i)); + if (comparison !== 0) { + return comparison; + } + } + return primitiveComparator(p1.length, p2.length); + } + static compareSegments(lhs, rhs) { + const isLhsNumeric = BasePath.isNumericId(lhs); + const isRhsNumeric = BasePath.isNumericId(rhs); + if (isLhsNumeric && !isRhsNumeric) { + // Only lhs is numeric + return -1; + } + else if (!isLhsNumeric && isRhsNumeric) { + // Only rhs is numeric + return 1; + } + else if (isLhsNumeric && isRhsNumeric) { + // both numeric + return BasePath.extractNumericId(lhs).compare(BasePath.extractNumericId(rhs)); + } + else { + // both non-numeric + return compareUtf8Strings(lhs, rhs); + } + } + // Checks if a segment is a numeric ID (starts with "__id" and ends with "__"). + static isNumericId(segment) { + return segment.startsWith('__id') && segment.endsWith('__'); + } + static extractNumericId(segment) { + return Integer.fromString(segment.substring(4, segment.length - 2)); + } +} +/** + * A slash-separated path for navigating resources (documents and collections) + * within Firestore. + * + * @internal + */ +class ResourcePath extends BasePath { + construct(segments, offset, length) { + return new ResourcePath(segments, offset, length); + } + canonicalString() { + // NOTE: The client is ignorant of any path segments containing escape + // sequences (e.g. __id123__) and just passes them through raw (they exist + // for legacy reasons and should not be used frequently). + return this.toArray().join('/'); + } + toString() { + return this.canonicalString(); + } + /** + * Returns a string representation of this path + * where each path segment has been encoded with + * `encodeURIComponent`. + */ + toUriEncodedString() { + return this.toArray().map(encodeURIComponent).join('/'); + } + /** + * Creates a resource path from the given slash-delimited string. If multiple + * arguments are provided, all components are combined. Leading and trailing + * slashes from all components are ignored. + */ + static fromString(...pathComponents) { + // NOTE: The client is ignorant of any path segments containing escape + // sequences (e.g. __id123__) and just passes them through raw (they exist + // for legacy reasons and should not be used frequently). + const segments = []; + for (const path of pathComponents) { + if (path.indexOf('//') >= 0) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid segment (${path}). Paths must not contain // in them.`); + } + // Strip leading and trailing slashed. + segments.push(...path.split('/').filter(segment => segment.length > 0)); + } + return new ResourcePath(segments); + } + static emptyPath() { + return new ResourcePath([]); + } +} +const identifierRegExp = /^[_a-zA-Z][_a-zA-Z0-9]*$/; +/** + * A dot-separated path for navigating sub-objects within a document. + * @internal + */ +class FieldPath$1 extends BasePath { + construct(segments, offset, length) { + return new FieldPath$1(segments, offset, length); + } + /** + * Returns true if the string could be used as a segment in a field path + * without escaping. + */ + static isValidIdentifier(segment) { + return identifierRegExp.test(segment); + } + canonicalString() { + return this.toArray() + .map(str => { + str = str.replace(/\\/g, '\\\\').replace(/`/g, '\\`'); + if (!FieldPath$1.isValidIdentifier(str)) { + str = '`' + str + '`'; + } + return str; + }) + .join('.'); + } + toString() { + return this.canonicalString(); + } + /** + * Returns true if this field references the key of a document. + */ + isKeyField() { + return this.length === 1 && this.get(0) === DOCUMENT_KEY_NAME; + } + /** + * The field designating the key of a document. + */ + static keyField() { + return new FieldPath$1([DOCUMENT_KEY_NAME]); + } + /** + * Parses a field string from the given server-formatted string. + * + * - Splitting the empty string is not allowed (for now at least). + * - Empty segments within the string (e.g. if there are two consecutive + * separators) are not allowed. + * + * TODO(b/37244157): we should make this more strict. Right now, it allows + * non-identifier path components, even if they aren't escaped. + */ + static fromServerFormat(path) { + const segments = []; + let current = ''; + let i = 0; + const addCurrentSegment = () => { + if (current.length === 0) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid field path (${path}). Paths must not be empty, begin ` + + `with '.', end with '.', or contain '..'`); + } + segments.push(current); + current = ''; + }; + let inBackticks = false; + while (i < path.length) { + const c = path[i]; + if (c === '\\') { + if (i + 1 === path.length) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Path has trailing escape character: ' + path); + } + const next = path[i + 1]; + if (!(next === '\\' || next === '.' || next === '`')) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Path has invalid escape sequence: ' + path); + } + current += next; + i += 2; + } + else if (c === '`') { + inBackticks = !inBackticks; + i++; + } + else if (c === '.' && !inBackticks) { + addCurrentSegment(); + i++; + } + else { + current += c; + i++; + } + } + addCurrentSegment(); + if (inBackticks) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Unterminated ` in path: ' + path); + } + return new FieldPath$1(segments); + } + static emptyPath() { + return new FieldPath$1([]); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @internal + */ +class DocumentKey { + constructor(path) { + this.path = path; + } + static fromPath(path) { + return new DocumentKey(ResourcePath.fromString(path)); + } + static fromName(name) { + return new DocumentKey(ResourcePath.fromString(name).popFirst(5)); + } + static empty() { + return new DocumentKey(ResourcePath.emptyPath()); + } + get collectionGroup() { + return this.path.popLast().lastSegment(); + } + /** Returns true if the document is in the specified collectionId. */ + hasCollectionId(collectionId) { + return (this.path.length >= 2 && + this.path.get(this.path.length - 2) === collectionId); + } + /** Returns the collection group (i.e. the name of the parent collection) for this key. */ + getCollectionGroup() { + return this.path.get(this.path.length - 2); + } + /** Returns the fully qualified path to the parent collection. */ + getCollectionPath() { + return this.path.popLast(); + } + isEqual(other) { + return (other !== null && ResourcePath.comparator(this.path, other.path) === 0); + } + toString() { + return this.path.toString(); + } + static comparator(k1, k2) { + return ResourcePath.comparator(k1.path, k2.path); + } + static isDocumentKey(path) { + return path.length % 2 === 0; + } + /** + * Creates and returns a new document key with the given segments. + * + * @param segments - The segments of the path to the document + * @returns A new instance of DocumentKey + */ + static fromSegments(segments) { + return new DocumentKey(new ResourcePath(segments.slice())); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +function validateNonEmptyArgument(functionName, argumentName, argument) { + if (!argument) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `Function ${functionName}() cannot be called with an empty ${argumentName}.`); + } +} +/** + * Validates that two boolean options are not set at the same time. + * @internal + */ +function validateIsNotUsedTogether(optionName1, argument1, optionName2, argument2) { + if (argument1 === true && argument2 === true) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `${optionName1} and ${optionName2} cannot be used together.`); + } +} +/** + * Validates that `path` refers to a document (indicated by the fact it contains + * an even numbers of segments). + */ +function validateDocumentPath(path) { + if (!DocumentKey.isDocumentKey(path)) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid document reference. Document references must have an even number of segments, but ${path} has ${path.length}.`); + } +} +/** + * Validates that `path` refers to a collection (indicated by the fact it + * contains an odd numbers of segments). + */ +function validateCollectionPath(path) { + if (DocumentKey.isDocumentKey(path)) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid collection reference. Collection references must have an odd number of segments, but ${path} has ${path.length}.`); + } +} +/** + * Returns true if it's a non-null object without a custom prototype + * (i.e. excludes Array, Date, etc.). + */ +function isPlainObject(input) { + return (typeof input === 'object' && + input !== null && + (Object.getPrototypeOf(input) === Object.prototype || + Object.getPrototypeOf(input) === null)); +} +/** Returns a string describing the type / value of the provided input. */ +function valueDescription(input) { + if (input === undefined) { + return 'undefined'; + } + else if (input === null) { + return 'null'; + } + else if (typeof input === 'string') { + if (input.length > 20) { + input = `${input.substring(0, 20)}...`; + } + return JSON.stringify(input); + } + else if (typeof input === 'number' || typeof input === 'boolean') { + return '' + input; + } + else if (typeof input === 'object') { + if (input instanceof Array) { + return 'an array'; + } + else { + const customObjectName = tryGetCustomObjectType(input); + if (customObjectName) { + return `a custom ${customObjectName} object`; + } + else { + return 'an object'; + } + } + } + else if (typeof input === 'function') { + return 'a function'; + } + else { + return fail(0x3029, { type: typeof input }); + } +} +/** try to get the constructor name for an object. */ +function tryGetCustomObjectType(input) { + if (input.constructor) { + return input.constructor.name; + } + return null; +} +/** + * Casts `obj` to `T`, optionally unwrapping Compat types to expose the + * underlying instance. Throws if `obj` is not an instance of `T`. + * + * This cast is used in the Lite and Full SDK to verify instance types for + * arguments passed to the public API. + * @internal + */ +function cast(obj, +// eslint-disable-next-line @typescript-eslint/no-explicit-any +constructor) { + if ('_delegate' in obj) { + // Unwrap Compat types + // eslint-disable-next-line @typescript-eslint/no-explicit-any + obj = obj._delegate; + } + if (!(obj instanceof constructor)) { + if (constructor.name === obj.constructor.name) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Type does not match the expected instance. Did you pass a ' + + `reference from a different Firestore SDK?`); + } + else { + const description = valueDescription(obj); + throw new FirestoreError(Code.INVALID_ARGUMENT, `Expected type '${constructor.name}', but it was: ${description}`); + } + } + return obj; +} +function validatePositiveNumber(functionName, n) { + if (n <= 0) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `Function ${functionName}() requires a positive number, but it was: ${n}.`); + } +} + +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Compares two `ExperimentalLongPollingOptions` objects for equality. + */ +function longPollingOptionsEqual(options1, options2) { + return options1.timeoutSeconds === options2.timeoutSeconds; +} +/** + * Creates and returns a new `ExperimentalLongPollingOptions` with the same + * option values as the given instance. + */ +function cloneLongPollingOptions(options) { + const clone = {}; + if (options.timeoutSeconds !== undefined) { + clone.timeoutSeconds = options.timeoutSeconds; + } + return clone; +} + +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * The value returned from the most recent invocation of + * `generateUniqueDebugId()`, or null if it has never been invoked. + */ +let lastUniqueDebugId = null; +/** + * Generates and returns an initial value for `lastUniqueDebugId`. + * + * The returned value is randomly selected from a range of integers that are + * represented as 8 hexadecimal digits. This means that (within reason) any + * numbers generated by incrementing the returned number by 1 will also be + * represented by 8 hexadecimal digits. This leads to all "IDs" having the same + * length when converted to a hexadecimal string, making reading logs containing + * these IDs easier to follow. And since the return value is randomly selected + * it will help to differentiate between logs from different executions. + */ +function generateInitialUniqueDebugId() { + const minResult = 0x10000000; + const maxResult = 0x90000000; + const resultRange = maxResult - minResult; + const resultOffset = Math.round(resultRange * Math.random()); + return minResult + resultOffset; +} +/** + * Generates and returns a unique ID as a hexadecimal string. + * + * The returned ID is intended to be used in debug logging messages to help + * correlate log messages that may be spatially separated in the logs, but + * logically related. For example, a network connection could include the same + * "debug ID" string in all of its log messages to help trace a specific + * connection over time. + * + * @return the 10-character generated ID (e.g. "0xa1b2c3d4"). + */ +function generateUniqueDebugId() { + if (lastUniqueDebugId === null) { + lastUniqueDebugId = generateInitialUniqueDebugId(); + } + else { + lastUniqueDebugId++; + } + return '0x' + lastUniqueDebugId.toString(16); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const LOG_TAG$3 = 'RestConnection'; +/** + * Maps RPC names to the corresponding REST endpoint name. + * + * We use array notation to avoid mangling. + */ +const RPC_NAME_URL_MAPPING = {}; +RPC_NAME_URL_MAPPING['BatchGetDocuments'] = 'batchGet'; +RPC_NAME_URL_MAPPING['Commit'] = 'commit'; +RPC_NAME_URL_MAPPING['RunQuery'] = 'runQuery'; +RPC_NAME_URL_MAPPING['RunAggregationQuery'] = 'runAggregationQuery'; +const RPC_URL_VERSION = 'v1'; +// SDK_VERSION is updated to different value at runtime depending on the entry point, +// so we need to get its value when we need it in a function. +function getGoogApiClientValue() { + return 'gl-js/ fire/' + SDK_VERSION; +} +/** + * Base class for all Rest-based connections to the backend (WebChannel and + * HTTP). + */ +class RestConnection { + get shouldResourcePathBeIncludedInRequest() { + // Both `invokeRPC()` and `invokeStreamingRPC()` use their `path` arguments to determine + // where to run the query, and expect the `request` to NOT specify the "path". + return false; + } + constructor(databaseInfo) { + this.databaseInfo = databaseInfo; + this.databaseId = databaseInfo.databaseId; + const proto = databaseInfo.ssl ? 'https' : 'http'; + const projectId = encodeURIComponent(this.databaseId.projectId); + const databaseId = encodeURIComponent(this.databaseId.database); + this.baseUrl = proto + '://' + databaseInfo.host; + this.databasePath = `projects/${projectId}/databases/${databaseId}`; + this.requestParams = + this.databaseId.database === DEFAULT_DATABASE_NAME + ? `project_id=${projectId}` + : `project_id=${projectId}&database_id=${databaseId}`; + } + invokeRPC(rpcName, path, req, authToken, appCheckToken) { + const streamId = generateUniqueDebugId(); + const url = this.makeUrl(rpcName, path.toUriEncodedString()); + logDebug(LOG_TAG$3, `Sending RPC '${rpcName}' ${streamId}:`, url, req); + const headers = { + 'google-cloud-resource-prefix': this.databasePath, + 'x-goog-request-params': this.requestParams + }; + this.modifyHeadersForRequest(headers, authToken, appCheckToken); + const { host } = new URL(url); + const forwardCredentials = isCloudWorkstation(host); + return this.performRPCRequest(rpcName, url, headers, req, forwardCredentials).then(response => { + logDebug(LOG_TAG$3, `Received RPC '${rpcName}' ${streamId}: `, response); + return response; + }, (err) => { + logWarn(LOG_TAG$3, `RPC '${rpcName}' ${streamId} failed with error: `, err, 'url: ', url, 'request:', req); + throw err; + }); + } + invokeStreamingRPC(rpcName, path, request, authToken, appCheckToken, expectedResponseCount) { + // The REST API automatically aggregates all of the streamed results, so we + // can just use the normal invoke() method. + return this.invokeRPC(rpcName, path, request, authToken, appCheckToken); + } + /** + * Modifies the headers for a request, adding any authorization token if + * present and any additional headers for the request. + */ + modifyHeadersForRequest(headers, authToken, appCheckToken) { + headers['X-Goog-Api-Client'] = getGoogApiClientValue(); + // Content-Type: text/plain will avoid preflight requests which might + // mess with CORS and redirects by proxies. If we add custom headers + // we will need to change this code to potentially use the $httpOverwrite + // parameter supported by ESF to avoid triggering preflight requests. + headers['Content-Type'] = 'text/plain'; + if (this.databaseInfo.appId) { + headers['X-Firebase-GMPID'] = this.databaseInfo.appId; + } + if (authToken) { + authToken.headers.forEach((value, key) => (headers[key] = value)); + } + if (appCheckToken) { + appCheckToken.headers.forEach((value, key) => (headers[key] = value)); + } + } + makeUrl(rpcName, path) { + const urlRpcName = RPC_NAME_URL_MAPPING[rpcName]; + return `${this.baseUrl}/${RPC_URL_VERSION}/${path}:${urlRpcName}`; + } + /** + * Closes and cleans up any resources associated with the connection. This + * implementation is a no-op because there are no resources associated + * with the RestConnection that need to be cleaned up. + */ + terminate() { + // No-op + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Error Codes describing the different ways GRPC can fail. These are copied + * directly from GRPC's sources here: + * + * https://github.com/grpc/grpc/blob/bceec94ea4fc5f0085d81235d8e1c06798dc341a/include/grpc%2B%2B/impl/codegen/status_code_enum.h + * + * Important! The names of these identifiers matter because the string forms + * are used for reverse lookups from the webchannel stream. Do NOT change the + * names of these identifiers or change this into a const enum. + */ +var RpcCode; +(function (RpcCode) { + RpcCode[RpcCode["OK"] = 0] = "OK"; + RpcCode[RpcCode["CANCELLED"] = 1] = "CANCELLED"; + RpcCode[RpcCode["UNKNOWN"] = 2] = "UNKNOWN"; + RpcCode[RpcCode["INVALID_ARGUMENT"] = 3] = "INVALID_ARGUMENT"; + RpcCode[RpcCode["DEADLINE_EXCEEDED"] = 4] = "DEADLINE_EXCEEDED"; + RpcCode[RpcCode["NOT_FOUND"] = 5] = "NOT_FOUND"; + RpcCode[RpcCode["ALREADY_EXISTS"] = 6] = "ALREADY_EXISTS"; + RpcCode[RpcCode["PERMISSION_DENIED"] = 7] = "PERMISSION_DENIED"; + RpcCode[RpcCode["UNAUTHENTICATED"] = 16] = "UNAUTHENTICATED"; + RpcCode[RpcCode["RESOURCE_EXHAUSTED"] = 8] = "RESOURCE_EXHAUSTED"; + RpcCode[RpcCode["FAILED_PRECONDITION"] = 9] = "FAILED_PRECONDITION"; + RpcCode[RpcCode["ABORTED"] = 10] = "ABORTED"; + RpcCode[RpcCode["OUT_OF_RANGE"] = 11] = "OUT_OF_RANGE"; + RpcCode[RpcCode["UNIMPLEMENTED"] = 12] = "UNIMPLEMENTED"; + RpcCode[RpcCode["INTERNAL"] = 13] = "INTERNAL"; + RpcCode[RpcCode["UNAVAILABLE"] = 14] = "UNAVAILABLE"; + RpcCode[RpcCode["DATA_LOSS"] = 15] = "DATA_LOSS"; +})(RpcCode || (RpcCode = {})); +/** + * Determines whether an error code represents a permanent error when received + * in response to a non-write operation. + * + * See isPermanentWriteError for classifying write errors. + */ +function isPermanentError(code) { + switch (code) { + case Code.OK: + return fail(0xfdaa); + case Code.CANCELLED: + case Code.UNKNOWN: + case Code.DEADLINE_EXCEEDED: + case Code.RESOURCE_EXHAUSTED: + case Code.INTERNAL: + case Code.UNAVAILABLE: + // Unauthenticated means something went wrong with our token and we need + // to retry with new credentials which will happen automatically. + case Code.UNAUTHENTICATED: + return false; + case Code.INVALID_ARGUMENT: + case Code.NOT_FOUND: + case Code.ALREADY_EXISTS: + case Code.PERMISSION_DENIED: + case Code.FAILED_PRECONDITION: + // Aborted might be retried in some scenarios, but that is dependent on + // the context and should handled individually by the calling code. + // See https://cloud.google.com/apis/design/errors. + case Code.ABORTED: + case Code.OUT_OF_RANGE: + case Code.UNIMPLEMENTED: + case Code.DATA_LOSS: + return true; + default: + return fail(0x3c6b, { code }); + } +} +/** + * Converts an HTTP Status Code to the equivalent error code. + * + * @param status - An HTTP Status Code, like 200, 404, 503, etc. + * @returns The equivalent Code. Unknown status codes are mapped to + * Code.UNKNOWN. + */ +function mapCodeFromHttpStatus(status) { + if (status === undefined) { + logError('RPC_ERROR', 'HTTP error has no status'); + return Code.UNKNOWN; + } + // The canonical error codes for Google APIs [1] specify mapping onto HTTP + // status codes but the mapping is not bijective. In each case of ambiguity + // this function chooses a primary error. + // + // [1] + // https://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto + switch (status) { + case 200: // OK + return Code.OK; + case 400: // Bad Request + return Code.FAILED_PRECONDITION; + // Other possibilities based on the forward mapping + // return Code.INVALID_ARGUMENT; + // return Code.OUT_OF_RANGE; + case 401: // Unauthorized + return Code.UNAUTHENTICATED; + case 403: // Forbidden + return Code.PERMISSION_DENIED; + case 404: // Not Found + return Code.NOT_FOUND; + case 409: // Conflict + return Code.ABORTED; + // Other possibilities: + // return Code.ALREADY_EXISTS; + case 416: // Range Not Satisfiable + return Code.OUT_OF_RANGE; + case 429: // Too Many Requests + return Code.RESOURCE_EXHAUSTED; + case 499: // Client Closed Request + return Code.CANCELLED; + case 500: // Internal Server Error + return Code.UNKNOWN; + // Other possibilities: + // return Code.INTERNAL; + // return Code.DATA_LOSS; + case 501: // Unimplemented + return Code.UNIMPLEMENTED; + case 503: // Service Unavailable + return Code.UNAVAILABLE; + case 504: // Gateway Timeout + return Code.DEADLINE_EXCEEDED; + default: + if (status >= 200 && status < 300) { + return Code.OK; + } + if (status >= 400 && status < 500) { + return Code.FAILED_PRECONDITION; + } + if (status >= 500 && status < 600) { + return Code.INTERNAL; + } + return Code.UNKNOWN; + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A Rest-based connection that relies on the native HTTP stack + * (e.g. `fetch` or a polyfill). + */ +class FetchConnection extends RestConnection { + openStream(rpcName, token) { + throw new Error('Not supported by FetchConnection'); + } + async performRPCRequest(rpcName, url, headers, body, forwardCredentials) { + const requestJson = JSON.stringify(body); + let response; + try { + const fetchArgs = { + method: 'POST', + headers, + body: requestJson + }; + if (forwardCredentials) { + fetchArgs.credentials = 'include'; + } + response = await fetch(url, fetchArgs); + } + catch (e) { + const err = e; + throw new FirestoreError(mapCodeFromHttpStatus(err.status), 'Request failed with error: ' + err.statusText); + } + if (!response.ok) { + let errorResponse = await response.json(); + if (Array.isArray(errorResponse)) { + errorResponse = errorResponse[0]; + } + const errorMessage = errorResponse?.error?.message; + throw new FirestoreError(mapCodeFromHttpStatus(response.status), `Request failed with error: ${errorMessage ?? response.statusText}`); + } + return response.json(); + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Initializes the HTTP connection for the REST API. */ +function newConnection(databaseInfo) { + return new FetchConnection(databaseInfo); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +function objectSize(obj) { + let count = 0; + for (const key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + count++; + } + } + return count; +} +function forEach(obj, fn) { + for (const key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + fn(key, obj[key]); + } + } +} +function mapToArray(obj, fn) { + const result = []; + for (const key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + result.push(fn(obj[key], key, obj)); + } + } + return result; +} +function isEmpty(obj) { + for (const key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + return false; + } + } + return true; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Returns whether a variable is either undefined or null. + */ +function isNullOrUndefined(value) { + return value === null || value === undefined; +} +/** Returns whether the value represents -0. */ +function isNegativeZero(value) { + // Detect if the value is -0.0. Based on polyfill from + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is + return value === 0 && 1 / value === 1 / -0; +} +/** + * Returns whether a value is an integer and in the safe integer range + * @param value - The value to test for being an integer and in the safe range + */ +function isSafeInteger(value) { + return (typeof value === 'number' && + Number.isInteger(value) && + !isNegativeZero(value) && + value <= Number.MAX_SAFE_INTEGER && + value >= Number.MIN_SAFE_INTEGER); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Converts a Base64 encoded string to a binary string. */ +function decodeBase64(encoded) { + // Note: We used to validate the base64 string here via a regular expression. + // This was removed to improve the performance of indexing. + return Buffer.from(encoded, 'base64').toString('binary'); +} +/** Converts a binary string to a Base64 encoded string. */ +function encodeBase64(raw) { + return Buffer.from(raw, 'binary').toString('base64'); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Immutable class that represents a "proto" byte string. + * + * Proto byte strings can either be Base64-encoded strings or Uint8Arrays when + * sent on the wire. This class abstracts away this differentiation by holding + * the proto byte string in a common class that must be converted into a string + * before being sent as a proto. + * @internal + */ +class ByteString { + constructor(binaryString) { + this.binaryString = binaryString; + } + static fromBase64String(base64) { + const binaryString = decodeBase64(base64); + return new ByteString(binaryString); + } + static fromUint8Array(array) { + // TODO(indexing); Remove the copy of the byte string here as this method + // is frequently called during indexing. + const binaryString = binaryStringFromUint8Array(array); + return new ByteString(binaryString); + } + [Symbol.iterator]() { + let i = 0; + return { + next: () => { + if (i < this.binaryString.length) { + return { value: this.binaryString.charCodeAt(i++), done: false }; + } + else { + return { value: undefined, done: true }; + } + } + }; + } + toBase64() { + return encodeBase64(this.binaryString); + } + toUint8Array() { + return uint8ArrayFromBinaryString(this.binaryString); + } + approximateByteSize() { + return this.binaryString.length * 2; + } + compareTo(other) { + return primitiveComparator(this.binaryString, other.binaryString); + } + isEqual(other) { + return this.binaryString === other.binaryString; + } +} +ByteString.EMPTY_BYTE_STRING = new ByteString(''); +/** + * Helper function to convert an Uint8array to a binary string. + */ +function binaryStringFromUint8Array(array) { + let binaryString = ''; + for (let i = 0; i < array.length; ++i) { + binaryString += String.fromCharCode(array[i]); + } + return binaryString; +} +/** + * Helper function to convert a binary string to an Uint8Array. + */ +function uint8ArrayFromBinaryString(binaryString) { + const buffer = new Uint8Array(binaryString.length); + for (let i = 0; i < binaryString.length; i++) { + buffer[i] = binaryString.charCodeAt(i); + } + return buffer; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// A RegExp matching ISO 8601 UTC timestamps with optional fraction. +const ISO_TIMESTAMP_REG_EXP = new RegExp(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.(\d+))?Z$/); +/** + * Converts the possible Proto values for a timestamp value into a "seconds and + * nanos" representation. + */ +function normalizeTimestamp(date) { + hardAssert(!!date, 0x986a); + // The json interface (for the browser) will return an iso timestamp string, + // while the proto js library (for node) will return a + // google.protobuf.Timestamp instance. + if (typeof date === 'string') { + // The date string can have higher precision (nanos) than the Date class + // (millis), so we do some custom parsing here. + // Parse the nanos right out of the string. + let nanos = 0; + const fraction = ISO_TIMESTAMP_REG_EXP.exec(date); + hardAssert(!!fraction, 0xb5de, { + timestamp: date + }); + if (fraction[1]) { + // Pad the fraction out to 9 digits (nanos). + let nanoStr = fraction[1]; + nanoStr = (nanoStr + '000000000').substr(0, 9); + nanos = Number(nanoStr); + } + // Parse the date to get the seconds. + const parsedDate = new Date(date); + const seconds = Math.floor(parsedDate.getTime() / 1000); + return { seconds, nanos }; + } + else { + // TODO(b/37282237): Use strings for Proto3 timestamps + // assert(!this.options.useProto3Json, + // 'The timestamp instance format requires Proto JS.'); + const seconds = normalizeNumber(date.seconds); + const nanos = normalizeNumber(date.nanos); + return { seconds, nanos }; + } +} +/** + * Converts the possible Proto types for numbers into a JavaScript number. + * Returns 0 if the value is not numeric. + */ +function normalizeNumber(value) { + // TODO(bjornick): Handle int64 greater than 53 bits. + if (typeof value === 'number') { + return value; + } + else if (typeof value === 'string') { + return Number(value); + } + else { + return 0; + } +} +/** Converts the possible Proto types for Blobs into a ByteString. */ +function normalizeByteString(blob) { + if (typeof blob === 'string') { + return ByteString.fromBase64String(blob); + } + else { + return ByteString.fromUint8Array(blob); + } +} + +/** + * @license + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Helper function to define a JSON schema {@link Property}. + * @private + * @internal + */ +function property(typeString, optionalValue) { + const result = { + typeString + }; + if (optionalValue) { + result.value = optionalValue; + } + return result; +} +/** + * Validates the JSON object based on the provided schema, and narrows the type to the provided + * JSON schema. + * @private + * @internal + * + * @param json A JSON object to validate. + * @param scheme a {@link JsonSchema} that defines the properties to validate. + * @returns true if the JSON schema exists within the object. Throws a FirestoreError otherwise. + */ +function validateJSON(json, schema) { + if (!isPlainObject(json)) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'JSON must be an object'); + } + let error = undefined; + for (const key in schema) { + if (schema[key]) { + const typeString = schema[key].typeString; + const value = 'value' in schema[key] ? { value: schema[key].value } : undefined; + if (!(key in json)) { + error = `JSON missing required field: '${key}'`; + break; + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const fieldValue = json[key]; + if (typeString && typeof fieldValue !== typeString) { + error = `JSON field '${key}' must be a ${typeString}.`; + break; + } + else if (value !== undefined && fieldValue !== value.value) { + error = `Expected '${key}' field to equal '${value.value}'`; + break; + } + } + } + if (error) { + throw new FirestoreError(Code.INVALID_ARGUMENT, error); + } + return true; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// The earliest date supported by Firestore timestamps (0001-01-01T00:00:00Z). +const MIN_SECONDS = -62135596800; +// Number of nanoseconds in a millisecond. +const MS_TO_NANOS = 1e6; +/** + * A `Timestamp` represents a point in time independent of any time zone or + * calendar, represented as seconds and fractions of seconds at nanosecond + * resolution in UTC Epoch time. + * + * It is encoded using the Proleptic Gregorian Calendar which extends the + * Gregorian calendar backwards to year one. It is encoded assuming all minutes + * are 60 seconds long, i.e. leap seconds are "smeared" so that no leap second + * table is needed for interpretation. Range is from 0001-01-01T00:00:00Z to + * 9999-12-31T23:59:59.999999999Z. + * + * For examples and further specifications, refer to the + * {@link https://github.com/google/protobuf/blob/master/src/google/protobuf/timestamp.proto | Timestamp definition}. + */ +class Timestamp { + /** + * Creates a new timestamp with the current date, with millisecond precision. + * + * @returns a new timestamp representing the current date. + */ + static now() { + return Timestamp.fromMillis(Date.now()); + } + /** + * Creates a new timestamp from the given date. + * + * @param date - The date to initialize the `Timestamp` from. + * @returns A new `Timestamp` representing the same point in time as the given + * date. + */ + static fromDate(date) { + return Timestamp.fromMillis(date.getTime()); + } + /** + * Creates a new timestamp from the given number of milliseconds. + * + * @param milliseconds - Number of milliseconds since Unix epoch + * 1970-01-01T00:00:00Z. + * @returns A new `Timestamp` representing the same point in time as the given + * number of milliseconds. + */ + static fromMillis(milliseconds) { + const seconds = Math.floor(milliseconds / 1000); + const nanos = Math.floor((milliseconds - seconds * 1000) * MS_TO_NANOS); + return new Timestamp(seconds, nanos); + } + /** + * Creates a new timestamp. + * + * @param seconds - The number of seconds of UTC time since Unix epoch + * 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to + * 9999-12-31T23:59:59Z inclusive. + * @param nanoseconds - The non-negative fractions of a second at nanosecond + * resolution. Negative second values with fractions must still have + * non-negative nanoseconds values that count forward in time. Must be + * from 0 to 999,999,999 inclusive. + */ + constructor( + /** + * The number of seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z. + */ + seconds, + /** + * The fractions of a second at nanosecond resolution.* + */ + nanoseconds) { + this.seconds = seconds; + this.nanoseconds = nanoseconds; + if (nanoseconds < 0) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Timestamp nanoseconds out of range: ' + nanoseconds); + } + if (nanoseconds >= 1e9) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Timestamp nanoseconds out of range: ' + nanoseconds); + } + if (seconds < MIN_SECONDS) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Timestamp seconds out of range: ' + seconds); + } + // This will break in the year 10,000. + if (seconds >= 253402300800) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Timestamp seconds out of range: ' + seconds); + } + } + /** + * Converts a `Timestamp` to a JavaScript `Date` object. This conversion + * causes a loss of precision since `Date` objects only support millisecond + * precision. + * + * @returns JavaScript `Date` object representing the same point in time as + * this `Timestamp`, with millisecond precision. + */ + toDate() { + return new Date(this.toMillis()); + } + /** + * Converts a `Timestamp` to a numeric timestamp (in milliseconds since + * epoch). This operation causes a loss of precision. + * + * @returns The point in time corresponding to this timestamp, represented as + * the number of milliseconds since Unix epoch 1970-01-01T00:00:00Z. + */ + toMillis() { + return this.seconds * 1000 + this.nanoseconds / MS_TO_NANOS; + } + _compareTo(other) { + if (this.seconds === other.seconds) { + return primitiveComparator(this.nanoseconds, other.nanoseconds); + } + return primitiveComparator(this.seconds, other.seconds); + } + /** + * Returns true if this `Timestamp` is equal to the provided one. + * + * @param other - The `Timestamp` to compare against. + * @returns true if this `Timestamp` is equal to the provided one. + */ + isEqual(other) { + return (other.seconds === this.seconds && other.nanoseconds === this.nanoseconds); + } + /** Returns a textual representation of this `Timestamp`. */ + toString() { + return ('Timestamp(seconds=' + + this.seconds + + ', nanoseconds=' + + this.nanoseconds + + ')'); + } + /** + * Returns a JSON-serializable representation of this `Timestamp`. + */ + toJSON() { + return { + type: Timestamp._jsonSchemaVersion, + seconds: this.seconds, + nanoseconds: this.nanoseconds + }; + } + /** + * Builds a `Timestamp` instance from a JSON object created by {@link Timestamp.toJSON}. + */ + static fromJSON(json) { + if (validateJSON(json, Timestamp._jsonSchema)) { + return new Timestamp(json.seconds, json.nanoseconds); + } + } + /** + * Converts this object to a primitive string, which allows `Timestamp` objects + * to be compared using the `>`, `<=`, `>=` and `>` operators. + */ + valueOf() { + // This method returns a string of the form . where + // is translated to have a non-negative value and both + // and are left-padded with zeroes to be a consistent length. + // Strings with this format then have a lexicographical ordering that matches + // the expected ordering. The translation is done to avoid having + // a leading negative sign (i.e. a leading '-' character) in its string + // representation, which would affect its lexicographical ordering. + const adjustedSeconds = this.seconds - MIN_SECONDS; + // Note: Up to 12 decimal digits are required to represent all valid + // 'seconds' values. + const formattedSeconds = String(adjustedSeconds).padStart(12, '0'); + const formattedNanoseconds = String(this.nanoseconds).padStart(9, '0'); + return formattedSeconds + '.' + formattedNanoseconds; + } +} +Timestamp._jsonSchemaVersion = 'firestore/timestamp/1.0'; +Timestamp._jsonSchema = { + type: property('string', Timestamp._jsonSchemaVersion), + seconds: property('number'), + nanoseconds: property('number') +}; + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Represents a locally-applied ServerTimestamp. + * + * Server Timestamps are backed by MapValues that contain an internal field + * `__type__` with a value of `server_timestamp`. The previous value and local + * write time are stored in its `__previous_value__` and `__local_write_time__` + * fields respectively. + * + * Notes: + * - ServerTimestampValue instances are created as the result of applying a + * transform. They can only exist in the local view of a document. Therefore + * they do not need to be parsed or serialized. + * - When evaluated locally (e.g. for snapshot.data()), they by default + * evaluate to `null`. This behavior can be configured by passing custom + * FieldValueOptions to value(). + * - With respect to other ServerTimestampValues, they sort by their + * localWriteTime. + */ +const SERVER_TIMESTAMP_SENTINEL = 'server_timestamp'; +const TYPE_KEY$1 = '__type__'; +const PREVIOUS_VALUE_KEY = '__previous_value__'; +const LOCAL_WRITE_TIME_KEY = '__local_write_time__'; +function isServerTimestamp(value) { + const type = (value?.mapValue?.fields || {})[TYPE_KEY$1]?.stringValue; + return type === SERVER_TIMESTAMP_SENTINEL; +} +/** + * Returns the value of the field before this ServerTimestamp was set. + * + * Preserving the previous values allows the user to display the last resoled + * value until the backend responds with the timestamp. + */ +function getPreviousValue(value) { + const previousValue = value.mapValue.fields[PREVIOUS_VALUE_KEY]; + if (isServerTimestamp(previousValue)) { + return getPreviousValue(previousValue); + } + return previousValue; +} +/** + * Returns the local time at which this timestamp was first set. + */ +function getLocalWriteTime(value) { + const localWriteTime = normalizeTimestamp(value.mapValue.fields[LOCAL_WRITE_TIME_KEY].timestampValue); + return new Timestamp(localWriteTime.seconds, localWriteTime.nanos); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const TYPE_KEY = '__type__'; +const MAX_VALUE_TYPE = '__max__'; +const MAX_VALUE = { + mapValue: { + fields: { + '__type__': { stringValue: MAX_VALUE_TYPE } + } + } +}; +const VECTOR_VALUE_SENTINEL = '__vector__'; +const VECTOR_MAP_VECTORS_KEY = 'value'; +/** Extracts the backend's type order for the provided value. */ +function typeOrder(value) { + if ('nullValue' in value) { + return 0 /* TypeOrder.NullValue */; + } + else if ('booleanValue' in value) { + return 1 /* TypeOrder.BooleanValue */; + } + else if ('integerValue' in value || 'doubleValue' in value) { + return 2 /* TypeOrder.NumberValue */; + } + else if ('timestampValue' in value) { + return 3 /* TypeOrder.TimestampValue */; + } + else if ('stringValue' in value) { + return 5 /* TypeOrder.StringValue */; + } + else if ('bytesValue' in value) { + return 6 /* TypeOrder.BlobValue */; + } + else if ('referenceValue' in value) { + return 7 /* TypeOrder.RefValue */; + } + else if ('geoPointValue' in value) { + return 8 /* TypeOrder.GeoPointValue */; + } + else if ('arrayValue' in value) { + return 9 /* TypeOrder.ArrayValue */; + } + else if ('mapValue' in value) { + if (isServerTimestamp(value)) { + return 4 /* TypeOrder.ServerTimestampValue */; + } + else if (isMaxValue(value)) { + return 9007199254740991 /* TypeOrder.MaxValue */; + } + else if (isVectorValue(value)) { + return 10 /* TypeOrder.VectorValue */; + } + return 11 /* TypeOrder.ObjectValue */; + } + else { + return fail(0x6e87, { value }); + } +} +/** Tests `left` and `right` for equality based on the backend semantics. */ +function valueEquals(left, right) { + if (left === right) { + return true; + } + const leftType = typeOrder(left); + const rightType = typeOrder(right); + if (leftType !== rightType) { + return false; + } + switch (leftType) { + case 0 /* TypeOrder.NullValue */: + return true; + case 1 /* TypeOrder.BooleanValue */: + return left.booleanValue === right.booleanValue; + case 4 /* TypeOrder.ServerTimestampValue */: + return getLocalWriteTime(left).isEqual(getLocalWriteTime(right)); + case 3 /* TypeOrder.TimestampValue */: + return timestampEquals(left, right); + case 5 /* TypeOrder.StringValue */: + return left.stringValue === right.stringValue; + case 6 /* TypeOrder.BlobValue */: + return blobEquals(left, right); + case 7 /* TypeOrder.RefValue */: + return left.referenceValue === right.referenceValue; + case 8 /* TypeOrder.GeoPointValue */: + return geoPointEquals(left, right); + case 2 /* TypeOrder.NumberValue */: + return numberEquals(left, right); + case 9 /* TypeOrder.ArrayValue */: + return arrayEquals(left.arrayValue.values || [], right.arrayValue.values || [], valueEquals); + case 10 /* TypeOrder.VectorValue */: + case 11 /* TypeOrder.ObjectValue */: + return objectEquals(left, right); + case 9007199254740991 /* TypeOrder.MaxValue */: + return true; + default: + return fail(0xcbf8, { left }); + } +} +function timestampEquals(left, right) { + if (typeof left.timestampValue === 'string' && + typeof right.timestampValue === 'string' && + left.timestampValue.length === right.timestampValue.length) { + // Use string equality for ISO 8601 timestamps + return left.timestampValue === right.timestampValue; + } + const leftTimestamp = normalizeTimestamp(left.timestampValue); + const rightTimestamp = normalizeTimestamp(right.timestampValue); + return (leftTimestamp.seconds === rightTimestamp.seconds && + leftTimestamp.nanos === rightTimestamp.nanos); +} +function geoPointEquals(left, right) { + return (normalizeNumber(left.geoPointValue.latitude) === + normalizeNumber(right.geoPointValue.latitude) && + normalizeNumber(left.geoPointValue.longitude) === + normalizeNumber(right.geoPointValue.longitude)); +} +function blobEquals(left, right) { + return normalizeByteString(left.bytesValue).isEqual(normalizeByteString(right.bytesValue)); +} +function numberEquals(left, right) { + if ('integerValue' in left && 'integerValue' in right) { + return (normalizeNumber(left.integerValue) === normalizeNumber(right.integerValue)); + } + else if ('doubleValue' in left && 'doubleValue' in right) { + const n1 = normalizeNumber(left.doubleValue); + const n2 = normalizeNumber(right.doubleValue); + if (n1 === n2) { + return isNegativeZero(n1) === isNegativeZero(n2); + } + else { + return isNaN(n1) && isNaN(n2); + } + } + return false; +} +function objectEquals(left, right) { + const leftMap = left.mapValue.fields || {}; + const rightMap = right.mapValue.fields || {}; + if (objectSize(leftMap) !== objectSize(rightMap)) { + return false; + } + for (const key in leftMap) { + if (leftMap.hasOwnProperty(key)) { + if (rightMap[key] === undefined || + !valueEquals(leftMap[key], rightMap[key])) { + return false; + } + } + } + return true; +} +/** Returns true if the ArrayValue contains the specified element. */ +function arrayValueContains(haystack, needle) { + return ((haystack.values || []).find(v => valueEquals(v, needle)) !== undefined); +} +function valueCompare(left, right) { + if (left === right) { + return 0; + } + const leftType = typeOrder(left); + const rightType = typeOrder(right); + if (leftType !== rightType) { + return primitiveComparator(leftType, rightType); + } + switch (leftType) { + case 0 /* TypeOrder.NullValue */: + case 9007199254740991 /* TypeOrder.MaxValue */: + return 0; + case 1 /* TypeOrder.BooleanValue */: + return primitiveComparator(left.booleanValue, right.booleanValue); + case 2 /* TypeOrder.NumberValue */: + return compareNumbers(left, right); + case 3 /* TypeOrder.TimestampValue */: + return compareTimestamps(left.timestampValue, right.timestampValue); + case 4 /* TypeOrder.ServerTimestampValue */: + return compareTimestamps(getLocalWriteTime(left), getLocalWriteTime(right)); + case 5 /* TypeOrder.StringValue */: + return compareUtf8Strings(left.stringValue, right.stringValue); + case 6 /* TypeOrder.BlobValue */: + return compareBlobs(left.bytesValue, right.bytesValue); + case 7 /* TypeOrder.RefValue */: + return compareReferences(left.referenceValue, right.referenceValue); + case 8 /* TypeOrder.GeoPointValue */: + return compareGeoPoints(left.geoPointValue, right.geoPointValue); + case 9 /* TypeOrder.ArrayValue */: + return compareArrays(left.arrayValue, right.arrayValue); + case 10 /* TypeOrder.VectorValue */: + return compareVectors(left.mapValue, right.mapValue); + case 11 /* TypeOrder.ObjectValue */: + return compareMaps(left.mapValue, right.mapValue); + default: + throw fail(0x5ae0, { leftType }); + } +} +function compareNumbers(left, right) { + const leftNumber = normalizeNumber(left.integerValue || left.doubleValue); + const rightNumber = normalizeNumber(right.integerValue || right.doubleValue); + if (leftNumber < rightNumber) { + return -1; + } + else if (leftNumber > rightNumber) { + return 1; + } + else if (leftNumber === rightNumber) { + return 0; + } + else { + // one or both are NaN. + if (isNaN(leftNumber)) { + return isNaN(rightNumber) ? 0 : -1; + } + else { + return 1; + } + } +} +function compareTimestamps(left, right) { + if (typeof left === 'string' && + typeof right === 'string' && + left.length === right.length) { + return primitiveComparator(left, right); + } + const leftTimestamp = normalizeTimestamp(left); + const rightTimestamp = normalizeTimestamp(right); + const comparison = primitiveComparator(leftTimestamp.seconds, rightTimestamp.seconds); + if (comparison !== 0) { + return comparison; + } + return primitiveComparator(leftTimestamp.nanos, rightTimestamp.nanos); +} +function compareReferences(leftPath, rightPath) { + const leftSegments = leftPath.split('/'); + const rightSegments = rightPath.split('/'); + for (let i = 0; i < leftSegments.length && i < rightSegments.length; i++) { + const comparison = primitiveComparator(leftSegments[i], rightSegments[i]); + if (comparison !== 0) { + return comparison; + } + } + return primitiveComparator(leftSegments.length, rightSegments.length); +} +function compareGeoPoints(left, right) { + const comparison = primitiveComparator(normalizeNumber(left.latitude), normalizeNumber(right.latitude)); + if (comparison !== 0) { + return comparison; + } + return primitiveComparator(normalizeNumber(left.longitude), normalizeNumber(right.longitude)); +} +function compareBlobs(left, right) { + const leftBytes = normalizeByteString(left); + const rightBytes = normalizeByteString(right); + return leftBytes.compareTo(rightBytes); +} +function compareArrays(left, right) { + const leftArray = left.values || []; + const rightArray = right.values || []; + for (let i = 0; i < leftArray.length && i < rightArray.length; ++i) { + const compare = valueCompare(leftArray[i], rightArray[i]); + if (compare) { + return compare; + } + } + return primitiveComparator(leftArray.length, rightArray.length); +} +function compareVectors(left, right) { + const leftMap = left.fields || {}; + const rightMap = right.fields || {}; + // The vector is a map, but only vector value is compared. + const leftArrayValue = leftMap[VECTOR_MAP_VECTORS_KEY]?.arrayValue; + const rightArrayValue = rightMap[VECTOR_MAP_VECTORS_KEY]?.arrayValue; + const lengthCompare = primitiveComparator(leftArrayValue?.values?.length || 0, rightArrayValue?.values?.length || 0); + if (lengthCompare !== 0) { + return lengthCompare; + } + return compareArrays(leftArrayValue, rightArrayValue); +} +function compareMaps(left, right) { + if (left === MAX_VALUE.mapValue && right === MAX_VALUE.mapValue) { + return 0; + } + else if (left === MAX_VALUE.mapValue) { + return 1; + } + else if (right === MAX_VALUE.mapValue) { + return -1; + } + const leftMap = left.fields || {}; + const leftKeys = Object.keys(leftMap); + const rightMap = right.fields || {}; + const rightKeys = Object.keys(rightMap); + // Even though MapValues are likely sorted correctly based on their insertion + // order (e.g. when received from the backend), local modifications can bring + // elements out of order. We need to re-sort the elements to ensure that + // canonical IDs are independent of insertion order. + leftKeys.sort(); + rightKeys.sort(); + for (let i = 0; i < leftKeys.length && i < rightKeys.length; ++i) { + const keyCompare = compareUtf8Strings(leftKeys[i], rightKeys[i]); + if (keyCompare !== 0) { + return keyCompare; + } + const compare = valueCompare(leftMap[leftKeys[i]], rightMap[rightKeys[i]]); + if (compare !== 0) { + return compare; + } + } + return primitiveComparator(leftKeys.length, rightKeys.length); +} +/** Returns a reference value for the provided database and key. */ +function refValue(databaseId, key) { + return { + referenceValue: `projects/${databaseId.projectId}/databases/${databaseId.database}/documents/${key.path.canonicalString()}` + }; +} +/** Returns true if `value` is an ArrayValue. */ +function isArray(value) { + return !!value && 'arrayValue' in value; +} +/** Returns true if `value` is a NullValue. */ +function isNullValue(value) { + return !!value && 'nullValue' in value; +} +/** Returns true if `value` is NaN. */ +function isNanValue(value) { + return !!value && 'doubleValue' in value && isNaN(Number(value.doubleValue)); +} +/** Returns true if `value` is a MapValue. */ +function isMapValue(value) { + return !!value && 'mapValue' in value; +} +/** Returns true if `value` is a VetorValue. */ +function isVectorValue(value) { + const type = (value?.mapValue?.fields || {})[TYPE_KEY]?.stringValue; + return type === VECTOR_VALUE_SENTINEL; +} +/** Creates a deep copy of `source`. */ +function deepClone(source) { + if (source.geoPointValue) { + return { geoPointValue: { ...source.geoPointValue } }; + } + else if (source.timestampValue && + typeof source.timestampValue === 'object') { + return { timestampValue: { ...source.timestampValue } }; + } + else if (source.mapValue) { + const target = { mapValue: { fields: {} } }; + forEach(source.mapValue.fields, (key, val) => (target.mapValue.fields[key] = deepClone(val))); + return target; + } + else if (source.arrayValue) { + const target = { arrayValue: { values: [] } }; + for (let i = 0; i < (source.arrayValue.values || []).length; ++i) { + target.arrayValue.values[i] = deepClone(source.arrayValue.values[i]); + } + return target; + } + else { + return { ...source }; + } +} +/** Returns true if the Value represents the canonical {@link #MAX_VALUE} . */ +function isMaxValue(value) { + return ((((value.mapValue || {}).fields || {})['__type__'] || {}).stringValue === + MAX_VALUE_TYPE); +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Represents a bound of a query. + * + * The bound is specified with the given components representing a position and + * whether it's just before or just after the position (relative to whatever the + * query order is). + * + * The position represents a logical index position for a query. It's a prefix + * of values for the (potentially implicit) order by clauses of a query. + * + * Bound provides a function to determine whether a document comes before or + * after a bound. This is influenced by whether the position is just before or + * just after the provided values. + */ +class Bound { + constructor(position, inclusive) { + this.position = position; + this.inclusive = inclusive; + } +} +function boundEquals(left, right) { + if (left === null) { + return right === null; + } + else if (right === null) { + return false; + } + if (left.inclusive !== right.inclusive || + left.position.length !== right.position.length) { + return false; + } + for (let i = 0; i < left.position.length; i++) { + const leftPosition = left.position[i]; + const rightPosition = right.position[i]; + if (!valueEquals(leftPosition, rightPosition)) { + return false; + } + } + return true; +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class Filter { +} +class FieldFilter extends Filter { + constructor(field, op, value) { + super(); + this.field = field; + this.op = op; + this.value = value; + } + /** + * Creates a filter based on the provided arguments. + */ + static create(field, op, value) { + if (field.isKeyField()) { + if (op === "in" /* Operator.IN */ || op === "not-in" /* Operator.NOT_IN */) { + return this.createKeyFieldInFilter(field, op, value); + } + else { + return new KeyFieldFilter(field, op, value); + } + } + else if (op === "array-contains" /* Operator.ARRAY_CONTAINS */) { + return new ArrayContainsFilter(field, value); + } + else if (op === "in" /* Operator.IN */) { + return new InFilter(field, value); + } + else if (op === "not-in" /* Operator.NOT_IN */) { + return new NotInFilter(field, value); + } + else if (op === "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */) { + return new ArrayContainsAnyFilter(field, value); + } + else { + return new FieldFilter(field, op, value); + } + } + static createKeyFieldInFilter(field, op, value) { + return op === "in" /* Operator.IN */ + ? new KeyFieldInFilter(field, value) + : new KeyFieldNotInFilter(field, value); + } + matches(doc) { + const other = doc.data.field(this.field); + // Types do not have to match in NOT_EQUAL filters. + if (this.op === "!=" /* Operator.NOT_EQUAL */) { + return (other !== null && + other.nullValue === undefined && + this.matchesComparison(valueCompare(other, this.value))); + } + // Only compare types with matching backend order (such as double and int). + return (other !== null && + typeOrder(this.value) === typeOrder(other) && + this.matchesComparison(valueCompare(other, this.value))); + } + matchesComparison(comparison) { + switch (this.op) { + case "<" /* Operator.LESS_THAN */: + return comparison < 0; + case "<=" /* Operator.LESS_THAN_OR_EQUAL */: + return comparison <= 0; + case "==" /* Operator.EQUAL */: + return comparison === 0; + case "!=" /* Operator.NOT_EQUAL */: + return comparison !== 0; + case ">" /* Operator.GREATER_THAN */: + return comparison > 0; + case ">=" /* Operator.GREATER_THAN_OR_EQUAL */: + return comparison >= 0; + default: + return fail(0xb8a2, { + operator: this.op + }); + } + } + isInequality() { + return ([ + "<" /* Operator.LESS_THAN */, + "<=" /* Operator.LESS_THAN_OR_EQUAL */, + ">" /* Operator.GREATER_THAN */, + ">=" /* Operator.GREATER_THAN_OR_EQUAL */, + "!=" /* Operator.NOT_EQUAL */, + "not-in" /* Operator.NOT_IN */ + ].indexOf(this.op) >= 0); + } + getFlattenedFilters() { + return [this]; + } + getFilters() { + return [this]; + } +} +class CompositeFilter extends Filter { + constructor(filters, op) { + super(); + this.filters = filters; + this.op = op; + this.memoizedFlattenedFilters = null; + } + /** + * Creates a filter based on the provided arguments. + */ + static create(filters, op) { + return new CompositeFilter(filters, op); + } + matches(doc) { + if (compositeFilterIsConjunction(this)) { + // For conjunctions, all filters must match, so return false if any filter doesn't match. + return this.filters.find(filter => !filter.matches(doc)) === undefined; + } + else { + // For disjunctions, at least one filter should match. + return this.filters.find(filter => filter.matches(doc)) !== undefined; + } + } + getFlattenedFilters() { + if (this.memoizedFlattenedFilters !== null) { + return this.memoizedFlattenedFilters; + } + this.memoizedFlattenedFilters = this.filters.reduce((result, subfilter) => { + return result.concat(subfilter.getFlattenedFilters()); + }, []); + return this.memoizedFlattenedFilters; + } + // Returns a mutable copy of `this.filters` + getFilters() { + return Object.assign([], this.filters); + } +} +function compositeFilterIsConjunction(compositeFilter) { + return compositeFilter.op === "and" /* CompositeOperator.AND */; +} +function filterEquals(f1, f2) { + if (f1 instanceof FieldFilter) { + return fieldFilterEquals(f1, f2); + } + else if (f1 instanceof CompositeFilter) { + return compositeFilterEquals(f1, f2); + } + else { + fail(0x4bef); + } +} +function fieldFilterEquals(f1, f2) { + return (f2 instanceof FieldFilter && + f1.op === f2.op && + f1.field.isEqual(f2.field) && + valueEquals(f1.value, f2.value)); +} +function compositeFilterEquals(f1, f2) { + if (f2 instanceof CompositeFilter && + f1.op === f2.op && + f1.filters.length === f2.filters.length) { + const subFiltersMatch = f1.filters.reduce((result, f1Filter, index) => result && filterEquals(f1Filter, f2.filters[index]), true); + return subFiltersMatch; + } + return false; +} +/** Filter that matches on key fields (i.e. '__name__'). */ +class KeyFieldFilter extends FieldFilter { + constructor(field, op, value) { + super(field, op, value); + this.key = DocumentKey.fromName(value.referenceValue); + } + matches(doc) { + const comparison = DocumentKey.comparator(doc.key, this.key); + return this.matchesComparison(comparison); + } +} +/** Filter that matches on key fields within an array. */ +class KeyFieldInFilter extends FieldFilter { + constructor(field, value) { + super(field, "in" /* Operator.IN */, value); + this.keys = extractDocumentKeysFromArrayValue("in" /* Operator.IN */, value); + } + matches(doc) { + return this.keys.some(key => key.isEqual(doc.key)); + } +} +/** Filter that matches on key fields not present within an array. */ +class KeyFieldNotInFilter extends FieldFilter { + constructor(field, value) { + super(field, "not-in" /* Operator.NOT_IN */, value); + this.keys = extractDocumentKeysFromArrayValue("not-in" /* Operator.NOT_IN */, value); + } + matches(doc) { + return !this.keys.some(key => key.isEqual(doc.key)); + } +} +function extractDocumentKeysFromArrayValue(op, value) { + return (value.arrayValue?.values || []).map(v => { + return DocumentKey.fromName(v.referenceValue); + }); +} +/** A Filter that implements the array-contains operator. */ +class ArrayContainsFilter extends FieldFilter { + constructor(field, value) { + super(field, "array-contains" /* Operator.ARRAY_CONTAINS */, value); + } + matches(doc) { + const other = doc.data.field(this.field); + return isArray(other) && arrayValueContains(other.arrayValue, this.value); + } +} +/** A Filter that implements the IN operator. */ +class InFilter extends FieldFilter { + constructor(field, value) { + super(field, "in" /* Operator.IN */, value); + } + matches(doc) { + const other = doc.data.field(this.field); + return other !== null && arrayValueContains(this.value.arrayValue, other); + } +} +/** A Filter that implements the not-in operator. */ +class NotInFilter extends FieldFilter { + constructor(field, value) { + super(field, "not-in" /* Operator.NOT_IN */, value); + } + matches(doc) { + if (arrayValueContains(this.value.arrayValue, { nullValue: 'NULL_VALUE' })) { + return false; + } + const other = doc.data.field(this.field); + return (other !== null && + other.nullValue === undefined && + !arrayValueContains(this.value.arrayValue, other)); + } +} +/** A Filter that implements the array-contains-any operator. */ +class ArrayContainsAnyFilter extends FieldFilter { + constructor(field, value) { + super(field, "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */, value); + } + matches(doc) { + const other = doc.data.field(this.field); + if (!isArray(other) || !other.arrayValue.values) { + return false; + } + return other.arrayValue.values.some(val => arrayValueContains(this.value.arrayValue, val)); + } +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An ordering on a field, in some Direction. Direction defaults to ASCENDING. + */ +class OrderBy { + constructor(field, dir = "asc" /* Direction.ASCENDING */) { + this.field = field; + this.dir = dir; + } +} +function orderByEquals(left, right) { + return left.dir === right.dir && left.field.isEqual(right.field); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A version of a document in Firestore. This corresponds to the version + * timestamp, such as update_time or read_time. + */ +class SnapshotVersion { + static fromTimestamp(value) { + return new SnapshotVersion(value); + } + static min() { + return new SnapshotVersion(new Timestamp(0, 0)); + } + static max() { + return new SnapshotVersion(new Timestamp(253402300799, 1e9 - 1)); + } + constructor(timestamp) { + this.timestamp = timestamp; + } + compareTo(other) { + return this.timestamp._compareTo(other.timestamp); + } + isEqual(other) { + return this.timestamp.isEqual(other.timestamp); + } + /** Returns a number representation of the version for use in spec tests. */ + toMicroseconds() { + // Convert to microseconds. + return this.timestamp.seconds * 1e6 + this.timestamp.nanoseconds / 1000; + } + toString() { + return 'SnapshotVersion(' + this.timestamp.toString() + ')'; + } + toTimestamp() { + return this.timestamp; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// An immutable sorted map implementation, based on a Left-leaning Red-Black +// tree. +class SortedMap { + constructor(comparator, root) { + this.comparator = comparator; + this.root = root ? root : LLRBNode.EMPTY; + } + // Returns a copy of the map, with the specified key/value added or replaced. + insert(key, value) { + return new SortedMap(this.comparator, this.root + .insert(key, value, this.comparator) + .copy(null, null, LLRBNode.BLACK, null, null)); + } + // Returns a copy of the map, with the specified key removed. + remove(key) { + return new SortedMap(this.comparator, this.root + .remove(key, this.comparator) + .copy(null, null, LLRBNode.BLACK, null, null)); + } + // Returns the value of the node with the given key, or null. + get(key) { + let node = this.root; + while (!node.isEmpty()) { + const cmp = this.comparator(key, node.key); + if (cmp === 0) { + return node.value; + } + else if (cmp < 0) { + node = node.left; + } + else if (cmp > 0) { + node = node.right; + } + } + return null; + } + // Returns the index of the element in this sorted map, or -1 if it doesn't + // exist. + indexOf(key) { + // Number of nodes that were pruned when descending right + let prunedNodes = 0; + let node = this.root; + while (!node.isEmpty()) { + const cmp = this.comparator(key, node.key); + if (cmp === 0) { + return prunedNodes + node.left.size; + } + else if (cmp < 0) { + node = node.left; + } + else { + // Count all nodes left of the node plus the node itself + prunedNodes += node.left.size + 1; + node = node.right; + } + } + // Node not found + return -1; + } + isEmpty() { + return this.root.isEmpty(); + } + // Returns the total number of nodes in the map. + get size() { + return this.root.size; + } + // Returns the minimum key in the map. + minKey() { + return this.root.minKey(); + } + // Returns the maximum key in the map. + maxKey() { + return this.root.maxKey(); + } + // Traverses the map in key order and calls the specified action function + // for each key/value pair. If action returns true, traversal is aborted. + // Returns the first truthy value returned by action, or the last falsey + // value returned by action. + inorderTraversal(action) { + return this.root.inorderTraversal(action); + } + forEach(fn) { + this.inorderTraversal((k, v) => { + fn(k, v); + return false; + }); + } + toString() { + const descriptions = []; + this.inorderTraversal((k, v) => { + descriptions.push(`${k}:${v}`); + return false; + }); + return `{${descriptions.join(', ')}}`; + } + // Traverses the map in reverse key order and calls the specified action + // function for each key/value pair. If action returns true, traversal is + // aborted. + // Returns the first truthy value returned by action, or the last falsey + // value returned by action. + reverseTraversal(action) { + return this.root.reverseTraversal(action); + } + // Returns an iterator over the SortedMap. + getIterator() { + return new SortedMapIterator(this.root, null, this.comparator, false); + } + getIteratorFrom(key) { + return new SortedMapIterator(this.root, key, this.comparator, false); + } + getReverseIterator() { + return new SortedMapIterator(this.root, null, this.comparator, true); + } + getReverseIteratorFrom(key) { + return new SortedMapIterator(this.root, key, this.comparator, true); + } +} // end SortedMap +// An iterator over an LLRBNode. +class SortedMapIterator { + constructor(node, startKey, comparator, isReverse) { + this.isReverse = isReverse; + this.nodeStack = []; + let cmp = 1; + while (!node.isEmpty()) { + cmp = startKey ? comparator(node.key, startKey) : 1; + // flip the comparison if we're going in reverse + if (startKey && isReverse) { + cmp *= -1; + } + if (cmp < 0) { + // This node is less than our start key. ignore it + if (this.isReverse) { + node = node.left; + } + else { + node = node.right; + } + } + else if (cmp === 0) { + // This node is exactly equal to our start key. Push it on the stack, + // but stop iterating; + this.nodeStack.push(node); + break; + } + else { + // This node is greater than our start key, add it to the stack and move + // to the next one + this.nodeStack.push(node); + if (this.isReverse) { + node = node.right; + } + else { + node = node.left; + } + } + } + } + getNext() { + let node = this.nodeStack.pop(); + const result = { key: node.key, value: node.value }; + if (this.isReverse) { + node = node.left; + while (!node.isEmpty()) { + this.nodeStack.push(node); + node = node.right; + } + } + else { + node = node.right; + while (!node.isEmpty()) { + this.nodeStack.push(node); + node = node.left; + } + } + return result; + } + hasNext() { + return this.nodeStack.length > 0; + } + peek() { + if (this.nodeStack.length === 0) { + return null; + } + const node = this.nodeStack[this.nodeStack.length - 1]; + return { key: node.key, value: node.value }; + } +} // end SortedMapIterator +// Represents a node in a Left-leaning Red-Black tree. +class LLRBNode { + constructor(key, value, color, left, right) { + this.key = key; + this.value = value; + this.color = color != null ? color : LLRBNode.RED; + this.left = left != null ? left : LLRBNode.EMPTY; + this.right = right != null ? right : LLRBNode.EMPTY; + this.size = this.left.size + 1 + this.right.size; + } + // Returns a copy of the current node, optionally replacing pieces of it. + copy(key, value, color, left, right) { + 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); + } + isEmpty() { + return false; + } + // Traverses the tree in key order and calls the specified action function + // for each node. If action returns true, traversal is aborted. + // Returns the first truthy value returned by action, or the last falsey + // value returned by action. + inorderTraversal(action) { + return (this.left.inorderTraversal(action) || + action(this.key, this.value) || + this.right.inorderTraversal(action)); + } + // Traverses the tree in reverse key order and calls the specified action + // function for each node. If action returns true, traversal is aborted. + // Returns the first truthy value returned by action, or the last falsey + // value returned by action. + reverseTraversal(action) { + return (this.right.reverseTraversal(action) || + action(this.key, this.value) || + this.left.reverseTraversal(action)); + } + // Returns the minimum node in the tree. + min() { + if (this.left.isEmpty()) { + return this; + } + else { + return this.left.min(); + } + } + // Returns the maximum key in the tree. + minKey() { + return this.min().key; + } + // Returns the maximum key in the tree. + maxKey() { + if (this.right.isEmpty()) { + return this.key; + } + else { + return this.right.maxKey(); + } + } + // Returns new tree, with the key/value added. + insert(key, value, comparator) { + let n = this; + const cmp = comparator(key, n.key); + if (cmp < 0) { + n = n.copy(null, null, null, n.left.insert(key, value, comparator), null); + } + else if (cmp === 0) { + n = n.copy(null, value, null, null, null); + } + else { + n = n.copy(null, null, null, null, n.right.insert(key, value, comparator)); + } + return n.fixUp(); + } + removeMin() { + if (this.left.isEmpty()) { + return LLRBNode.EMPTY; + } + let n = this; + if (!n.left.isRed() && !n.left.left.isRed()) { + n = n.moveRedLeft(); + } + n = n.copy(null, null, null, n.left.removeMin(), null); + return n.fixUp(); + } + // Returns new tree, with the specified item removed. + remove(key, comparator) { + let smallest; + let n = this; + if (comparator(key, n.key) < 0) { + if (!n.left.isEmpty() && !n.left.isRed() && !n.left.left.isRed()) { + n = n.moveRedLeft(); + } + n = n.copy(null, null, null, n.left.remove(key, comparator), null); + } + else { + if (n.left.isRed()) { + n = n.rotateRight(); + } + if (!n.right.isEmpty() && !n.right.isRed() && !n.right.left.isRed()) { + n = n.moveRedRight(); + } + if (comparator(key, n.key) === 0) { + if (n.right.isEmpty()) { + return LLRBNode.EMPTY; + } + else { + smallest = n.right.min(); + n = n.copy(smallest.key, smallest.value, null, null, n.right.removeMin()); + } + } + n = n.copy(null, null, null, null, n.right.remove(key, comparator)); + } + return n.fixUp(); + } + isRed() { + return this.color; + } + // Returns new tree after performing any needed rotations. + fixUp() { + let n = this; + if (n.right.isRed() && !n.left.isRed()) { + n = n.rotateLeft(); + } + if (n.left.isRed() && n.left.left.isRed()) { + n = n.rotateRight(); + } + if (n.left.isRed() && n.right.isRed()) { + n = n.colorFlip(); + } + return n; + } + moveRedLeft() { + let n = this.colorFlip(); + if (n.right.left.isRed()) { + n = n.copy(null, null, null, null, n.right.rotateRight()); + n = n.rotateLeft(); + n = n.colorFlip(); + } + return n; + } + moveRedRight() { + let n = this.colorFlip(); + if (n.left.left.isRed()) { + n = n.rotateRight(); + n = n.colorFlip(); + } + return n; + } + rotateLeft() { + const nl = this.copy(null, null, LLRBNode.RED, null, this.right.left); + return this.right.copy(null, null, this.color, nl, null); + } + rotateRight() { + const nr = this.copy(null, null, LLRBNode.RED, this.left.right, null); + return this.left.copy(null, null, this.color, null, nr); + } + colorFlip() { + const left = this.left.copy(null, null, !this.left.color, null, null); + const right = this.right.copy(null, null, !this.right.color, null, null); + return this.copy(null, null, !this.color, left, right); + } + // For testing. + checkMaxDepth() { + const blackDepth = this.check(); + if (Math.pow(2.0, blackDepth) <= this.size + 1) { + return true; + } + else { + return false; + } + } + // In a balanced RB tree, the black-depth (number of black nodes) from root to + // leaves is equal on both sides. This function verifies that or asserts. + check() { + if (this.isRed() && this.left.isRed()) { + throw fail(0xaad2, { + key: this.key, + value: this.value + }); + } + if (this.right.isRed()) { + throw fail(0x3721, { + key: this.key, + value: this.value + }); + } + const blackDepth = this.left.check(); + if (blackDepth !== this.right.check()) { + throw fail(0x6d2d); + } + else { + return blackDepth + (this.isRed() ? 0 : 1); + } + } +} // end LLRBNode +// Empty node is shared between all LLRB trees. +// eslint-disable-next-line @typescript-eslint/no-explicit-any +LLRBNode.EMPTY = null; +LLRBNode.RED = true; +LLRBNode.BLACK = false; +// Represents an empty node (a leaf node in the Red-Black Tree). +class LLRBEmptyNode { + constructor() { + this.size = 0; + } + get key() { + throw fail(0xe1a6); + } + get value() { + throw fail(0x3f0d); + } + get color() { + throw fail(0x4157); + } + get left() { + throw fail(0x741e); + } + get right() { + throw fail(0x901e); + } + // Returns a copy of the current node. + copy(key, value, color, left, right) { + return this; + } + // Returns a copy of the tree, with the specified key/value added. + insert(key, value, comparator) { + return new LLRBNode(key, value); + } + // Returns a copy of the tree, with the specified key removed. + remove(key, comparator) { + return this; + } + isEmpty() { + return true; + } + inorderTraversal(action) { + return false; + } + reverseTraversal(action) { + return false; + } + minKey() { + return null; + } + maxKey() { + return null; + } + isRed() { + return false; + } + // For testing. + checkMaxDepth() { + return true; + } + check() { + return 0; + } +} // end LLRBEmptyNode +LLRBNode.EMPTY = new LLRBEmptyNode(); + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * SortedSet is an immutable (copy-on-write) collection that holds elements + * in order specified by the provided comparator. + * + * NOTE: if provided comparator returns 0 for two elements, we consider them to + * be equal! + */ +class SortedSet { + constructor(comparator) { + this.comparator = comparator; + this.data = new SortedMap(this.comparator); + } + has(elem) { + return this.data.get(elem) !== null; + } + first() { + return this.data.minKey(); + } + last() { + return this.data.maxKey(); + } + get size() { + return this.data.size; + } + indexOf(elem) { + return this.data.indexOf(elem); + } + /** Iterates elements in order defined by "comparator" */ + forEach(cb) { + this.data.inorderTraversal((k, v) => { + cb(k); + return false; + }); + } + /** Iterates over `elem`s such that: range[0] <= elem < range[1]. */ + forEachInRange(range, cb) { + const iter = this.data.getIteratorFrom(range[0]); + while (iter.hasNext()) { + const elem = iter.getNext(); + if (this.comparator(elem.key, range[1]) >= 0) { + return; + } + cb(elem.key); + } + } + /** + * Iterates over `elem`s such that: start <= elem until false is returned. + */ + forEachWhile(cb, start) { + let iter; + if (start !== undefined) { + iter = this.data.getIteratorFrom(start); + } + else { + iter = this.data.getIterator(); + } + while (iter.hasNext()) { + const elem = iter.getNext(); + const result = cb(elem.key); + if (!result) { + return; + } + } + } + /** Finds the least element greater than or equal to `elem`. */ + firstAfterOrEqual(elem) { + const iter = this.data.getIteratorFrom(elem); + return iter.hasNext() ? iter.getNext().key : null; + } + getIterator() { + return new SortedSetIterator(this.data.getIterator()); + } + getIteratorFrom(key) { + return new SortedSetIterator(this.data.getIteratorFrom(key)); + } + /** Inserts or updates an element */ + add(elem) { + return this.copy(this.data.remove(elem).insert(elem, true)); + } + /** Deletes an element */ + delete(elem) { + if (!this.has(elem)) { + return this; + } + return this.copy(this.data.remove(elem)); + } + isEmpty() { + return this.data.isEmpty(); + } + unionWith(other) { + let result = this; + // Make sure `result` always refers to the larger one of the two sets. + if (result.size < other.size) { + result = other; + other = this; + } + other.forEach(elem => { + result = result.add(elem); + }); + return result; + } + isEqual(other) { + if (!(other instanceof SortedSet)) { + return false; + } + if (this.size !== other.size) { + return false; + } + const thisIt = this.data.getIterator(); + const otherIt = other.data.getIterator(); + while (thisIt.hasNext()) { + const thisElem = thisIt.getNext().key; + const otherElem = otherIt.getNext().key; + if (this.comparator(thisElem, otherElem) !== 0) { + return false; + } + } + return true; + } + toArray() { + const res = []; + this.forEach(targetId => { + res.push(targetId); + }); + return res; + } + toString() { + const result = []; + this.forEach(elem => result.push(elem)); + return 'SortedSet(' + result.toString() + ')'; + } + copy(data) { + const result = new SortedSet(this.comparator); + result.data = data; + return result; + } +} +class SortedSetIterator { + constructor(iter) { + this.iter = iter; + } + getNext() { + return this.iter.getNext().key; + } + hasNext() { + return this.iter.hasNext(); + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Provides a set of fields that can be used to partially patch a document. + * FieldMask is used in conjunction with ObjectValue. + * Examples: + * foo - Overwrites foo entirely with the provided value. If foo is not + * present in the companion ObjectValue, the field is deleted. + * foo.bar - Overwrites only the field bar of the object foo. + * If foo is not an object, foo is replaced with an object + * containing foo + */ +class FieldMask { + constructor(fields) { + this.fields = fields; + // TODO(dimond): validation of FieldMask + // Sort the field mask to support `FieldMask.isEqual()` and assert below. + fields.sort(FieldPath$1.comparator); + } + static empty() { + return new FieldMask([]); + } + /** + * Returns a new FieldMask object that is the result of adding all the given + * fields paths to this field mask. + */ + unionWith(extraFields) { + let mergedMaskSet = new SortedSet(FieldPath$1.comparator); + for (const fieldPath of this.fields) { + mergedMaskSet = mergedMaskSet.add(fieldPath); + } + for (const fieldPath of extraFields) { + mergedMaskSet = mergedMaskSet.add(fieldPath); + } + return new FieldMask(mergedMaskSet.toArray()); + } + /** + * Verifies that `fieldPath` is included by at least one field in this field + * mask. + * + * This is an O(n) operation, where `n` is the size of the field mask. + */ + covers(fieldPath) { + for (const fieldMaskPath of this.fields) { + if (fieldMaskPath.isPrefixOf(fieldPath)) { + return true; + } + } + return false; + } + isEqual(other) { + return arrayEquals(this.fields, other.fields, (l, r) => l.isEqual(r)); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An ObjectValue represents a MapValue in the Firestore Proto and offers the + * ability to add and remove fields (via the ObjectValueBuilder). + */ +class ObjectValue { + constructor(value) { + this.value = value; + } + static empty() { + return new ObjectValue({ mapValue: {} }); + } + /** + * Returns the value at the given path or null. + * + * @param path - the path to search + * @returns The value at the path or null if the path is not set. + */ + field(path) { + if (path.isEmpty()) { + return this.value; + } + else { + let currentLevel = this.value; + for (let i = 0; i < path.length - 1; ++i) { + currentLevel = (currentLevel.mapValue.fields || {})[path.get(i)]; + if (!isMapValue(currentLevel)) { + return null; + } + } + currentLevel = (currentLevel.mapValue.fields || {})[path.lastSegment()]; + return currentLevel || null; + } + } + /** + * Sets the field to the provided value. + * + * @param path - The field path to set. + * @param value - The value to set. + */ + set(path, value) { + const fieldsMap = this.getFieldsMap(path.popLast()); + fieldsMap[path.lastSegment()] = deepClone(value); + } + /** + * Sets the provided fields to the provided values. + * + * @param data - A map of fields to values (or null for deletes). + */ + setAll(data) { + let parent = FieldPath$1.emptyPath(); + let upserts = {}; + let deletes = []; + data.forEach((value, path) => { + if (!parent.isImmediateParentOf(path)) { + // Insert the accumulated changes at this parent location + const fieldsMap = this.getFieldsMap(parent); + this.applyChanges(fieldsMap, upserts, deletes); + upserts = {}; + deletes = []; + parent = path.popLast(); + } + if (value) { + upserts[path.lastSegment()] = deepClone(value); + } + else { + deletes.push(path.lastSegment()); + } + }); + const fieldsMap = this.getFieldsMap(parent); + this.applyChanges(fieldsMap, upserts, deletes); + } + /** + * Removes the field at the specified path. If there is no field at the + * specified path, nothing is changed. + * + * @param path - The field path to remove. + */ + delete(path) { + const nestedValue = this.field(path.popLast()); + if (isMapValue(nestedValue) && nestedValue.mapValue.fields) { + delete nestedValue.mapValue.fields[path.lastSegment()]; + } + } + isEqual(other) { + return valueEquals(this.value, other.value); + } + /** + * Returns the map that contains the leaf element of `path`. If the parent + * entry does not yet exist, or if it is not a map, a new map will be created. + */ + getFieldsMap(path) { + let current = this.value; + if (!current.mapValue.fields) { + current.mapValue = { fields: {} }; + } + for (let i = 0; i < path.length; ++i) { + let next = current.mapValue.fields[path.get(i)]; + if (!isMapValue(next) || !next.mapValue.fields) { + next = { mapValue: { fields: {} } }; + current.mapValue.fields[path.get(i)] = next; + } + current = next; + } + return current.mapValue.fields; + } + /** + * Modifies `fieldsMap` by adding, replacing or deleting the specified + * entries. + */ + applyChanges(fieldsMap, inserts, deletes) { + forEach(inserts, (key, val) => (fieldsMap[key] = val)); + for (const field of deletes) { + delete fieldsMap[field]; + } + } + clone() { + return new ObjectValue(deepClone(this.value)); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Represents a document in Firestore with a key, version, data and whether it + * has local mutations applied to it. + * + * Documents can transition between states via `convertToFoundDocument()`, + * `convertToNoDocument()` and `convertToUnknownDocument()`. If a document does + * not transition to one of these states even after all mutations have been + * applied, `isValidDocument()` returns false and the document should be removed + * from all views. + */ +class MutableDocument { + constructor(key, documentType, version, readTime, createTime, data, documentState) { + this.key = key; + this.documentType = documentType; + this.version = version; + this.readTime = readTime; + this.createTime = createTime; + this.data = data; + this.documentState = documentState; + } + /** + * Creates a document with no known version or data, but which can serve as + * base document for mutations. + */ + static newInvalidDocument(documentKey) { + return new MutableDocument(documentKey, 0 /* DocumentType.INVALID */, + /* version */ SnapshotVersion.min(), + /* readTime */ SnapshotVersion.min(), + /* createTime */ SnapshotVersion.min(), ObjectValue.empty(), 0 /* DocumentState.SYNCED */); + } + /** + * Creates a new document that is known to exist with the given data at the + * given version. + */ + static newFoundDocument(documentKey, version, createTime, value) { + return new MutableDocument(documentKey, 1 /* DocumentType.FOUND_DOCUMENT */, + /* version */ version, + /* readTime */ SnapshotVersion.min(), + /* createTime */ createTime, value, 0 /* DocumentState.SYNCED */); + } + /** Creates a new document that is known to not exist at the given version. */ + static newNoDocument(documentKey, version) { + return new MutableDocument(documentKey, 2 /* DocumentType.NO_DOCUMENT */, + /* version */ version, + /* readTime */ SnapshotVersion.min(), + /* createTime */ SnapshotVersion.min(), ObjectValue.empty(), 0 /* DocumentState.SYNCED */); + } + /** + * Creates a new document that is known to exist at the given version but + * whose data is not known (e.g. a document that was updated without a known + * base document). + */ + static newUnknownDocument(documentKey, version) { + return new MutableDocument(documentKey, 3 /* DocumentType.UNKNOWN_DOCUMENT */, + /* version */ version, + /* readTime */ SnapshotVersion.min(), + /* createTime */ SnapshotVersion.min(), ObjectValue.empty(), 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */); + } + /** + * Changes the document type to indicate that it exists and that its version + * and data are known. + */ + convertToFoundDocument(version, value) { + // If a document is switching state from being an invalid or deleted + // document to a valid (FOUND_DOCUMENT) document, either due to receiving an + // update from Watch or due to applying a local set mutation on top + // of a deleted document, our best guess about its createTime would be the + // version at which the document transitioned to a FOUND_DOCUMENT. + if (this.createTime.isEqual(SnapshotVersion.min()) && + (this.documentType === 2 /* DocumentType.NO_DOCUMENT */ || + this.documentType === 0 /* DocumentType.INVALID */)) { + this.createTime = version; + } + this.version = version; + this.documentType = 1 /* DocumentType.FOUND_DOCUMENT */; + this.data = value; + this.documentState = 0 /* DocumentState.SYNCED */; + return this; + } + /** + * Changes the document type to indicate that it doesn't exist at the given + * version. + */ + convertToNoDocument(version) { + this.version = version; + this.documentType = 2 /* DocumentType.NO_DOCUMENT */; + this.data = ObjectValue.empty(); + this.documentState = 0 /* DocumentState.SYNCED */; + return this; + } + /** + * Changes the document type to indicate that it exists at a given version but + * that its data is not known (e.g. a document that was updated without a known + * base document). + */ + convertToUnknownDocument(version) { + this.version = version; + this.documentType = 3 /* DocumentType.UNKNOWN_DOCUMENT */; + this.data = ObjectValue.empty(); + this.documentState = 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */; + return this; + } + setHasCommittedMutations() { + this.documentState = 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */; + return this; + } + setHasLocalMutations() { + this.documentState = 1 /* DocumentState.HAS_LOCAL_MUTATIONS */; + this.version = SnapshotVersion.min(); + return this; + } + setReadTime(readTime) { + this.readTime = readTime; + return this; + } + get hasLocalMutations() { + return this.documentState === 1 /* DocumentState.HAS_LOCAL_MUTATIONS */; + } + get hasCommittedMutations() { + return this.documentState === 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */; + } + get hasPendingWrites() { + return this.hasLocalMutations || this.hasCommittedMutations; + } + isValidDocument() { + return this.documentType !== 0 /* DocumentType.INVALID */; + } + isFoundDocument() { + return this.documentType === 1 /* DocumentType.FOUND_DOCUMENT */; + } + isNoDocument() { + return this.documentType === 2 /* DocumentType.NO_DOCUMENT */; + } + isUnknownDocument() { + return this.documentType === 3 /* DocumentType.UNKNOWN_DOCUMENT */; + } + isEqual(other) { + return (other instanceof MutableDocument && + this.key.isEqual(other.key) && + this.version.isEqual(other.version) && + this.documentType === other.documentType && + this.documentState === other.documentState && + this.data.isEqual(other.data)); + } + mutableCopy() { + return new MutableDocument(this.key, this.documentType, this.version, this.readTime, this.createTime, this.data.clone(), this.documentState); + } + toString() { + return (`Document(${this.key}, ${this.version}, ${JSON.stringify(this.data.value)}, ` + + `{createTime: ${this.createTime}}), ` + + `{documentType: ${this.documentType}}), ` + + `{documentState: ${this.documentState}})`); + } +} + +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// Visible for testing +class TargetImpl { + constructor(path, collectionGroup = null, orderBy = [], filters = [], limit = null, startAt = null, endAt = null) { + this.path = path; + this.collectionGroup = collectionGroup; + this.orderBy = orderBy; + this.filters = filters; + this.limit = limit; + this.startAt = startAt; + this.endAt = endAt; + this.memoizedCanonicalId = null; + } +} +/** + * Initializes a Target with a path and optional additional query constraints. + * Path must currently be empty if this is a collection group query. + * + * NOTE: you should always construct `Target` from `Query.toTarget` instead of + * using this factory method, because `Query` provides an implicit `orderBy` + * property. + */ +function newTarget(path, collectionGroup = null, orderBy = [], filters = [], limit = null, startAt = null, endAt = null) { + return new TargetImpl(path, collectionGroup, orderBy, filters, limit, startAt, endAt); +} +function targetEquals(left, right) { + if (left.limit !== right.limit) { + return false; + } + if (left.orderBy.length !== right.orderBy.length) { + return false; + } + for (let i = 0; i < left.orderBy.length; i++) { + if (!orderByEquals(left.orderBy[i], right.orderBy[i])) { + return false; + } + } + if (left.filters.length !== right.filters.length) { + return false; + } + for (let i = 0; i < left.filters.length; i++) { + if (!filterEquals(left.filters[i], right.filters[i])) { + return false; + } + } + if (left.collectionGroup !== right.collectionGroup) { + return false; + } + if (!left.path.isEqual(right.path)) { + return false; + } + if (!boundEquals(left.startAt, right.startAt)) { + return false; + } + return boundEquals(left.endAt, right.endAt); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Query encapsulates all the query attributes we support in the SDK. It can + * be run against the LocalStore, as well as be converted to a `Target` to + * query the RemoteStore results. + * + * Visible for testing. + */ +class QueryImpl { + /** + * Initializes a Query with a path and optional additional query constraints. + * Path must currently be empty if this is a collection group query. + */ + constructor(path, collectionGroup = null, explicitOrderBy = [], filters = [], limit = null, limitType = "F" /* LimitType.First */, startAt = null, endAt = null) { + this.path = path; + this.collectionGroup = collectionGroup; + this.explicitOrderBy = explicitOrderBy; + this.filters = filters; + this.limit = limit; + this.limitType = limitType; + this.startAt = startAt; + this.endAt = endAt; + this.memoizedNormalizedOrderBy = null; + // The corresponding `Target` of this `Query` instance, for use with + // non-aggregate queries. + this.memoizedTarget = null; + // The corresponding `Target` of this `Query` instance, for use with + // aggregate queries. Unlike targets for non-aggregate queries, + // aggregate query targets do not contain normalized order-bys, they only + // contain explicit order-bys. + this.memoizedAggregateTarget = null; + if (this.startAt) ; + if (this.endAt) ; + } +} +/** Creates a new Query for a query that matches all documents at `path` */ +function newQueryForPath(path) { + return new QueryImpl(path); +} +// Returns the sorted set of inequality filter fields used in this query. +function getInequalityFilterFields(query) { + let result = new SortedSet(FieldPath$1.comparator); + query.filters.forEach((filter) => { + const subFilters = filter.getFlattenedFilters(); + subFilters.forEach((filter) => { + if (filter.isInequality()) { + result = result.add(filter.field); + } + }); + }); + return result; +} +/** + * Creates a new Query for a collection group query that matches all documents + * within the provided collection group. + */ +function newQueryForCollectionGroup(collectionId) { + return new QueryImpl(ResourcePath.emptyPath(), collectionId); +} +/** + * Returns whether the query matches a collection group rather than a specific + * collection. + */ +function isCollectionGroupQuery(query) { + return query.collectionGroup !== null; +} +/** + * Returns the normalized order-by constraint that is used to execute the Query, + * which can be different from the order-by constraints the user provided (e.g. + * the SDK and backend always orders by `__name__`). The normalized order-by + * includes implicit order-bys in addition to the explicit user provided + * order-bys. + */ +function queryNormalizedOrderBy(query) { + const queryImpl = debugCast(query); + if (queryImpl.memoizedNormalizedOrderBy === null) { + queryImpl.memoizedNormalizedOrderBy = []; + const fieldsNormalized = new Set(); + // Any explicit order by fields should be added as is. + for (const orderBy of queryImpl.explicitOrderBy) { + queryImpl.memoizedNormalizedOrderBy.push(orderBy); + fieldsNormalized.add(orderBy.field.canonicalString()); + } + // The order of the implicit ordering always matches the last explicit order by. + const lastDirection = queryImpl.explicitOrderBy.length > 0 + ? queryImpl.explicitOrderBy[queryImpl.explicitOrderBy.length - 1].dir + : "asc" /* Direction.ASCENDING */; + // Any inequality fields not explicitly ordered should be implicitly ordered in a lexicographical + // order. When there are multiple inequality filters on the same field, the field should be added + // only once. + // Note: `SortedSet` sorts the key field before other fields. However, we want the key + // field to be sorted last. + const inequalityFields = getInequalityFilterFields(queryImpl); + inequalityFields.forEach(field => { + if (!fieldsNormalized.has(field.canonicalString()) && + !field.isKeyField()) { + queryImpl.memoizedNormalizedOrderBy.push(new OrderBy(field, lastDirection)); + } + }); + // Add the document key field to the last if it is not explicitly ordered. + if (!fieldsNormalized.has(FieldPath$1.keyField().canonicalString())) { + queryImpl.memoizedNormalizedOrderBy.push(new OrderBy(FieldPath$1.keyField(), lastDirection)); + } + } + return queryImpl.memoizedNormalizedOrderBy; +} +/** + * Converts this `Query` instance to its corresponding `Target` representation. + */ +function queryToTarget(query) { + const queryImpl = debugCast(query); + if (!queryImpl.memoizedTarget) { + queryImpl.memoizedTarget = _queryToTarget(queryImpl, queryNormalizedOrderBy(query)); + } + return queryImpl.memoizedTarget; +} +/** + * Converts this `Query` instance to its corresponding `Target` representation, + * for use within an aggregate query. Unlike targets for non-aggregate queries, + * aggregate query targets do not contain normalized order-bys, they only + * contain explicit order-bys. + */ +function queryToAggregateTarget(query) { + const queryImpl = debugCast(query); + if (!queryImpl.memoizedAggregateTarget) { + // Do not include implicit order-bys for aggregate queries. + queryImpl.memoizedAggregateTarget = _queryToTarget(queryImpl, query.explicitOrderBy); + } + return queryImpl.memoizedAggregateTarget; +} +function _queryToTarget(queryImpl, orderBys) { + if (queryImpl.limitType === "F" /* LimitType.First */) { + return newTarget(queryImpl.path, queryImpl.collectionGroup, orderBys, queryImpl.filters, queryImpl.limit, queryImpl.startAt, queryImpl.endAt); + } + else { + // Flip the orderBy directions since we want the last results + orderBys = orderBys.map(orderBy => { + const dir = orderBy.dir === "desc" /* Direction.DESCENDING */ + ? "asc" /* Direction.ASCENDING */ + : "desc" /* Direction.DESCENDING */; + return new OrderBy(orderBy.field, dir); + }); + // We need to swap the cursors to match the now-flipped query ordering. + const startAt = queryImpl.endAt + ? new Bound(queryImpl.endAt.position, queryImpl.endAt.inclusive) + : null; + const endAt = queryImpl.startAt + ? new Bound(queryImpl.startAt.position, queryImpl.startAt.inclusive) + : null; + // Now return as a LimitType.First query. + return newTarget(queryImpl.path, queryImpl.collectionGroup, orderBys, queryImpl.filters, queryImpl.limit, startAt, endAt); + } +} +function queryWithAddedFilter(query, filter) { + const newFilters = query.filters.concat([filter]); + return new QueryImpl(query.path, query.collectionGroup, query.explicitOrderBy.slice(), newFilters, query.limit, query.limitType, query.startAt, query.endAt); +} +function queryWithAddedOrderBy(query, orderBy) { + // TODO(dimond): validate that orderBy does not list the same key twice. + const newOrderBy = query.explicitOrderBy.concat([orderBy]); + return new QueryImpl(query.path, query.collectionGroup, newOrderBy, query.filters.slice(), query.limit, query.limitType, query.startAt, query.endAt); +} +function queryWithLimit(query, limit, limitType) { + return new QueryImpl(query.path, query.collectionGroup, query.explicitOrderBy.slice(), query.filters.slice(), limit, limitType, query.startAt, query.endAt); +} +function queryWithStartAt(query, bound) { + return new QueryImpl(query.path, query.collectionGroup, query.explicitOrderBy.slice(), query.filters.slice(), query.limit, query.limitType, bound, query.endAt); +} +function queryWithEndAt(query, bound) { + return new QueryImpl(query.path, query.collectionGroup, query.explicitOrderBy.slice(), query.filters.slice(), query.limit, query.limitType, query.startAt, bound); +} +function queryEquals(left, right) { + return (targetEquals(queryToTarget(left), queryToTarget(right)) && + left.limitType === right.limitType); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Returns an DoubleValue for `value` that is encoded based the serializer's + * `useProto3Json` setting. + */ +function toDouble(serializer, value) { + if (serializer.useProto3Json) { + if (isNaN(value)) { + return { doubleValue: 'NaN' }; + } + else if (value === Infinity) { + return { doubleValue: 'Infinity' }; + } + else if (value === -Infinity) { + return { doubleValue: '-Infinity' }; + } + } + return { doubleValue: isNegativeZero(value) ? '-0' : value }; +} +/** + * Returns an IntegerValue for `value`. + */ +function toInteger(value) { + return { integerValue: '' + value }; +} +/** + * Returns a value for a number that's appropriate to put into a proto. + * The return value is an IntegerValue if it can safely represent the value, + * otherwise a DoubleValue is returned. + */ +function toNumber(serializer, value) { + return isSafeInteger(value) ? toInteger(value) : toDouble(serializer, value); +} + +/** + * @license + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Used to represent a field transform on a mutation. */ +class TransformOperation { + constructor() { + // Make sure that the structural type of `TransformOperation` is unique. + // See https://github.com/microsoft/TypeScript/issues/5451 + this._ = undefined; + } +} +/** Transforms a value into a server-generated timestamp. */ +class ServerTimestampTransform extends TransformOperation { +} +/** Transforms an array value via a union operation. */ +class ArrayUnionTransformOperation extends TransformOperation { + constructor(elements) { + super(); + this.elements = elements; + } +} +/** Transforms an array value via a remove operation. */ +class ArrayRemoveTransformOperation extends TransformOperation { + constructor(elements) { + super(); + this.elements = elements; + } +} +/** + * Implements the backend semantics for locally computed NUMERIC_ADD (increment) + * transforms. Converts all field values to integers or doubles, but unlike the + * backend does not cap integer values at 2^63. Instead, JavaScript number + * arithmetic is used and precision loss can occur for values greater than 2^53. + */ +class NumericIncrementTransformOperation extends TransformOperation { + constructor(serializer, operand) { + super(); + this.serializer = serializer; + this.operand = operand; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** A field path and the TransformOperation to perform upon it. */ +class FieldTransform { + constructor(field, transform) { + this.field = field; + this.transform = transform; + } +} +/** + * Encodes a precondition for a mutation. This follows the model that the + * backend accepts with the special case of an explicit "empty" precondition + * (meaning no precondition). + */ +class Precondition { + constructor(updateTime, exists) { + this.updateTime = updateTime; + this.exists = exists; + } + /** Creates a new empty Precondition. */ + static none() { + return new Precondition(); + } + /** Creates a new Precondition with an exists flag. */ + static exists(exists) { + return new Precondition(undefined, exists); + } + /** Creates a new Precondition based on a version a document exists at. */ + static updateTime(version) { + return new Precondition(version); + } + /** Returns whether this Precondition is empty. */ + get isNone() { + return this.updateTime === undefined && this.exists === undefined; + } + isEqual(other) { + return (this.exists === other.exists && + (this.updateTime + ? !!other.updateTime && this.updateTime.isEqual(other.updateTime) + : !other.updateTime)); + } +} +/** + * A mutation describes a self-contained change to a document. Mutations can + * create, replace, delete, and update subsets of documents. + * + * Mutations not only act on the value of the document but also its version. + * + * For local mutations (mutations that haven't been committed yet), we preserve + * the existing version for Set and Patch mutations. For Delete mutations, we + * reset the version to 0. + * + * Here's the expected transition table. + * + * MUTATION APPLIED TO RESULTS IN + * + * SetMutation Document(v3) Document(v3) + * SetMutation NoDocument(v3) Document(v0) + * SetMutation InvalidDocument(v0) Document(v0) + * PatchMutation Document(v3) Document(v3) + * PatchMutation NoDocument(v3) NoDocument(v3) + * PatchMutation InvalidDocument(v0) UnknownDocument(v3) + * DeleteMutation Document(v3) NoDocument(v0) + * DeleteMutation NoDocument(v3) NoDocument(v0) + * DeleteMutation InvalidDocument(v0) NoDocument(v0) + * + * For acknowledged mutations, we use the updateTime of the WriteResponse as + * the resulting version for Set and Patch mutations. As deletes have no + * explicit update time, we use the commitTime of the WriteResponse for + * Delete mutations. + * + * If a mutation is acknowledged by the backend but fails the precondition check + * locally, we transition to an `UnknownDocument` and rely on Watch to send us + * the updated version. + * + * Field transforms are used only with Patch and Set Mutations. We use the + * `updateTransforms` message to store transforms, rather than the `transforms`s + * messages. + * + * ## Subclassing Notes + * + * Every type of mutation needs to implement its own applyToRemoteDocument() and + * applyToLocalView() to implement the actual behavior of applying the mutation + * to some source document (see `setMutationApplyToRemoteDocument()` for an + * example). + */ +class Mutation { +} +/** + * A mutation that creates or replaces the document at the given key with the + * object value contents. + */ +class SetMutation extends Mutation { + constructor(key, value, precondition, fieldTransforms = []) { + super(); + this.key = key; + this.value = value; + this.precondition = precondition; + this.fieldTransforms = fieldTransforms; + this.type = 0 /* MutationType.Set */; + } + getFieldMask() { + return null; + } +} +/** + * A mutation that modifies fields of the document at the given key with the + * given values. The values are applied through a field mask: + * + * * When a field is in both the mask and the values, the corresponding field + * is updated. + * * When a field is in neither the mask nor the values, the corresponding + * field is unmodified. + * * When a field is in the mask but not in the values, the corresponding field + * is deleted. + * * When a field is not in the mask but is in the values, the values map is + * ignored. + */ +class PatchMutation extends Mutation { + constructor(key, data, fieldMask, precondition, fieldTransforms = []) { + super(); + this.key = key; + this.data = data; + this.fieldMask = fieldMask; + this.precondition = precondition; + this.fieldTransforms = fieldTransforms; + this.type = 1 /* MutationType.Patch */; + } + getFieldMask() { + return this.fieldMask; + } +} +/** A mutation that deletes the document at the given key. */ +class DeleteMutation extends Mutation { + constructor(key, precondition) { + super(); + this.key = key; + this.precondition = precondition; + this.type = 2 /* MutationType.Delete */; + this.fieldTransforms = []; + } + getFieldMask() { + return null; + } +} +/** + * A mutation that verifies the existence of the document at the given key with + * the provided precondition. + * + * The `verify` operation is only used in Transactions, and this class serves + * primarily to facilitate serialization into protos. + */ +class VerifyMutation extends Mutation { + constructor(key, precondition) { + super(); + this.key = key; + this.precondition = precondition; + this.type = 3 /* MutationType.Verify */; + this.fieldTransforms = []; + } + getFieldMask() { + return null; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const DIRECTIONS = (() => { + const dirs = {}; + dirs["asc" /* Direction.ASCENDING */] = 'ASCENDING'; + dirs["desc" /* Direction.DESCENDING */] = 'DESCENDING'; + return dirs; +})(); +const OPERATORS = (() => { + const ops = {}; + ops["<" /* Operator.LESS_THAN */] = 'LESS_THAN'; + ops["<=" /* Operator.LESS_THAN_OR_EQUAL */] = 'LESS_THAN_OR_EQUAL'; + ops[">" /* Operator.GREATER_THAN */] = 'GREATER_THAN'; + ops[">=" /* Operator.GREATER_THAN_OR_EQUAL */] = 'GREATER_THAN_OR_EQUAL'; + ops["==" /* Operator.EQUAL */] = 'EQUAL'; + ops["!=" /* Operator.NOT_EQUAL */] = 'NOT_EQUAL'; + ops["array-contains" /* Operator.ARRAY_CONTAINS */] = 'ARRAY_CONTAINS'; + ops["in" /* Operator.IN */] = 'IN'; + ops["not-in" /* Operator.NOT_IN */] = 'NOT_IN'; + ops["array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */] = 'ARRAY_CONTAINS_ANY'; + return ops; +})(); +const COMPOSITE_OPERATORS = (() => { + const ops = {}; + ops["and" /* CompositeOperator.AND */] = 'AND'; + ops["or" /* CompositeOperator.OR */] = 'OR'; + return ops; +})(); +function assertPresent(value, description) { +} +/** + * This class generates JsonObject values for the Datastore API suitable for + * sending to either GRPC stub methods or via the JSON/HTTP REST API. + * + * The serializer supports both Protobuf.js and Proto3 JSON formats. By + * setting `useProto3Json` to true, the serializer will use the Proto3 JSON + * format. + * + * For a description of the Proto3 JSON format check + * https://developers.google.com/protocol-buffers/docs/proto3#json + * + * TODO(klimt): We can remove the databaseId argument if we keep the full + * resource name in documents. + */ +class JsonProtoSerializer { + constructor(databaseId, useProto3Json) { + this.databaseId = databaseId; + this.useProto3Json = useProto3Json; + } +} +/** + * Returns a value for a number (or null) that's appropriate to put into + * a google.protobuf.Int32Value proto. + * DO NOT USE THIS FOR ANYTHING ELSE. + * This method cheats. It's typed as returning "number" because that's what + * our generated proto interfaces say Int32Value must be. But GRPC actually + * expects a { value: } struct. + */ +function toInt32Proto(serializer, val) { + if (serializer.useProto3Json || isNullOrUndefined(val)) { + return val; + } + else { + return { value: val }; + } +} +/** + * Returns a value for a Date that's appropriate to put into a proto. + */ +function toTimestamp(serializer, timestamp) { + if (serializer.useProto3Json) { + // Serialize to ISO-8601 date format, but with full nano resolution. + // Since JS Date has only millis, let's only use it for the seconds and + // then manually add the fractions to the end. + const jsDateStr = new Date(timestamp.seconds * 1000).toISOString(); + // Remove .xxx frac part and Z in the end. + const strUntilSeconds = jsDateStr.replace(/\.\d*/, '').replace('Z', ''); + // Pad the fraction out to 9 digits (nanos). + const nanoStr = ('000000000' + timestamp.nanoseconds).slice(-9); + return `${strUntilSeconds}.${nanoStr}Z`; + } + else { + return { + seconds: '' + timestamp.seconds, + nanos: timestamp.nanoseconds + // eslint-disable-next-line @typescript-eslint/no-explicit-any + }; + } +} +/** + * Returns a Timestamp typed object given protobuf timestamp value. + */ +function fromTimestamp(date) { + const timestamp = normalizeTimestamp(date); + return new Timestamp(timestamp.seconds, timestamp.nanos); +} +/** + * Returns a value for bytes that's appropriate to put in a proto. + * + * Visible for testing. + */ +function toBytes(serializer, bytes) { + if (serializer.useProto3Json) { + return bytes.toBase64(); + } + else { + return bytes.toUint8Array(); + } +} +function toVersion(serializer, version) { + return toTimestamp(serializer, version.toTimestamp()); +} +function fromVersion(version) { + hardAssert(!!version, 0xc050); + return SnapshotVersion.fromTimestamp(fromTimestamp(version)); +} +function toResourceName(databaseId, path) { + return toResourcePath(databaseId, path).canonicalString(); +} +function toResourcePath(databaseId, path) { + const resourcePath = fullyQualifiedPrefixPath(databaseId).child('documents'); + return path === undefined ? resourcePath : resourcePath.child(path); +} +function fromResourceName(name) { + const resource = ResourcePath.fromString(name); + hardAssert(isValidResourceName(resource), 0x27ce, { key: resource.toString() }); + return resource; +} +function toName(serializer, key) { + return toResourceName(serializer.databaseId, key.path); +} +function fromName(serializer, name) { + const resource = fromResourceName(name); + if (resource.get(1) !== serializer.databaseId.projectId) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Tried to deserialize key from different project: ' + + resource.get(1) + + ' vs ' + + serializer.databaseId.projectId); + } + if (resource.get(3) !== serializer.databaseId.database) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Tried to deserialize key from different database: ' + + resource.get(3) + + ' vs ' + + serializer.databaseId.database); + } + return new DocumentKey(extractLocalPathFromResourceName(resource)); +} +function toQueryPath(serializer, path) { + return toResourceName(serializer.databaseId, path); +} +function fullyQualifiedPrefixPath(databaseId) { + return new ResourcePath([ + 'projects', + databaseId.projectId, + 'databases', + databaseId.database + ]); +} +function extractLocalPathFromResourceName(resourceName) { + hardAssert(resourceName.length > 4 && resourceName.get(4) === 'documents', 0x71a3, { key: resourceName.toString() }); + return resourceName.popFirst(5); +} +/** Creates a Document proto from key and fields (but no create/update time) */ +function toMutationDocument(serializer, key, fields) { + return { + name: toName(serializer, key), + fields: fields.value.mapValue.fields + }; +} +function fromDocument(serializer, document, hasCommittedMutations) { + const key = fromName(serializer, document.name); + const version = fromVersion(document.updateTime); + // If we read a document from persistence that is missing createTime, it's due + // to older SDK versions not storing this information. In such cases, we'll + // set the createTime to zero. This can be removed in the long term. + const createTime = document.createTime + ? fromVersion(document.createTime) + : SnapshotVersion.min(); + const data = new ObjectValue({ mapValue: { fields: document.fields } }); + const result = MutableDocument.newFoundDocument(key, version, createTime, data); + if (hasCommittedMutations) { + result.setHasCommittedMutations(); + } + return hasCommittedMutations ? result.setHasCommittedMutations() : result; +} +function fromFound(serializer, doc) { + hardAssert(!!doc.found, 0xaa33); + assertPresent(doc.found.name); + assertPresent(doc.found.updateTime); + const key = fromName(serializer, doc.found.name); + const version = fromVersion(doc.found.updateTime); + const createTime = doc.found.createTime + ? fromVersion(doc.found.createTime) + : SnapshotVersion.min(); + const data = new ObjectValue({ mapValue: { fields: doc.found.fields } }); + return MutableDocument.newFoundDocument(key, version, createTime, data); +} +function fromMissing(serializer, result) { + hardAssert(!!result.missing, 0x0f36); + hardAssert(!!result.readTime, 0x5995); + const key = fromName(serializer, result.missing); + const version = fromVersion(result.readTime); + return MutableDocument.newNoDocument(key, version); +} +function fromBatchGetDocumentsResponse(serializer, result) { + if ('found' in result) { + return fromFound(serializer, result); + } + else if ('missing' in result) { + return fromMissing(serializer, result); + } + return fail(0x1c42, { result }); +} +function toMutation(serializer, mutation) { + let result; + if (mutation instanceof SetMutation) { + result = { + update: toMutationDocument(serializer, mutation.key, mutation.value) + }; + } + else if (mutation instanceof DeleteMutation) { + result = { delete: toName(serializer, mutation.key) }; + } + else if (mutation instanceof PatchMutation) { + result = { + update: toMutationDocument(serializer, mutation.key, mutation.data), + updateMask: toDocumentMask(mutation.fieldMask) + }; + } + else if (mutation instanceof VerifyMutation) { + result = { + verify: toName(serializer, mutation.key) + }; + } + else { + return fail(0x40d7, { + mutationType: mutation.type + }); + } + if (mutation.fieldTransforms.length > 0) { + result.updateTransforms = mutation.fieldTransforms.map(transform => toFieldTransform(serializer, transform)); + } + if (!mutation.precondition.isNone) { + result.currentDocument = toPrecondition(serializer, mutation.precondition); + } + return result; +} +function toPrecondition(serializer, precondition) { + if (precondition.updateTime !== undefined) { + return { + updateTime: toVersion(serializer, precondition.updateTime) + }; + } + else if (precondition.exists !== undefined) { + return { exists: precondition.exists }; + } + else { + return fail(0x6b69); + } +} +function toFieldTransform(serializer, fieldTransform) { + const transform = fieldTransform.transform; + if (transform instanceof ServerTimestampTransform) { + return { + fieldPath: fieldTransform.field.canonicalString(), + setToServerValue: 'REQUEST_TIME' + }; + } + else if (transform instanceof ArrayUnionTransformOperation) { + return { + fieldPath: fieldTransform.field.canonicalString(), + appendMissingElements: { + values: transform.elements + } + }; + } + else if (transform instanceof ArrayRemoveTransformOperation) { + return { + fieldPath: fieldTransform.field.canonicalString(), + removeAllFromArray: { + values: transform.elements + } + }; + } + else if (transform instanceof NumericIncrementTransformOperation) { + return { + fieldPath: fieldTransform.field.canonicalString(), + increment: transform.operand + }; + } + else { + throw fail(0x51c2, { + transform: fieldTransform.transform + }); + } +} +function toQueryTarget(serializer, target) { + // Dissect the path into parent, collectionId, and optional key filter. + const queryTarget = { structuredQuery: {} }; + const path = target.path; + let parent; + if (target.collectionGroup !== null) { + parent = path; + queryTarget.structuredQuery.from = [ + { + collectionId: target.collectionGroup, + allDescendants: true + } + ]; + } + else { + parent = path.popLast(); + queryTarget.structuredQuery.from = [{ collectionId: path.lastSegment() }]; + } + queryTarget.parent = toQueryPath(serializer, parent); + const where = toFilters(target.filters); + if (where) { + queryTarget.structuredQuery.where = where; + } + const orderBy = toOrder(target.orderBy); + if (orderBy) { + queryTarget.structuredQuery.orderBy = orderBy; + } + const limit = toInt32Proto(serializer, target.limit); + if (limit !== null) { + queryTarget.structuredQuery.limit = limit; + } + if (target.startAt) { + queryTarget.structuredQuery.startAt = toStartAtCursor(target.startAt); + } + if (target.endAt) { + queryTarget.structuredQuery.endAt = toEndAtCursor(target.endAt); + } + return { queryTarget, parent }; +} +function toRunAggregationQueryRequest(serializer, target, aggregates, skipAliasing) { + const { queryTarget, parent } = toQueryTarget(serializer, target); + const aliasMap = {}; + const aggregations = []; + let aggregationNum = 0; + aggregates.forEach(aggregate => { + // Map all client-side aliases to a unique short-form + // alias. This avoids issues with client-side aliases that + // exceed the 1500-byte string size limit. + const serverAlias = skipAliasing + ? aggregate.alias + : `aggregate_${aggregationNum++}`; + aliasMap[serverAlias] = aggregate.alias; + if (aggregate.aggregateType === 'count') { + aggregations.push({ + alias: serverAlias, + count: {} + }); + } + else if (aggregate.aggregateType === 'avg') { + aggregations.push({ + alias: serverAlias, + avg: { + field: toFieldPathReference(aggregate.fieldPath) + } + }); + } + else if (aggregate.aggregateType === 'sum') { + aggregations.push({ + alias: serverAlias, + sum: { + field: toFieldPathReference(aggregate.fieldPath) + } + }); + } + }); + return { + request: { + structuredAggregationQuery: { + aggregations, + structuredQuery: queryTarget.structuredQuery + }, + parent: queryTarget.parent + }, + aliasMap, + parent + }; +} +function toFilters(filters) { + if (filters.length === 0) { + return; + } + return toFilter(CompositeFilter.create(filters, "and" /* CompositeOperator.AND */)); +} +function toOrder(orderBys) { + if (orderBys.length === 0) { + return; + } + return orderBys.map(order => toPropertyOrder(order)); +} +function toStartAtCursor(cursor) { + return { + before: cursor.inclusive, + values: cursor.position + }; +} +function toEndAtCursor(cursor) { + return { + before: !cursor.inclusive, + values: cursor.position + }; +} +// visible for testing +function toDirection(dir) { + return DIRECTIONS[dir]; +} +// visible for testing +function toOperatorName(op) { + return OPERATORS[op]; +} +function toCompositeOperatorName(op) { + return COMPOSITE_OPERATORS[op]; +} +function toFieldPathReference(path) { + return { fieldPath: path.canonicalString() }; +} +// visible for testing +function toPropertyOrder(orderBy) { + return { + field: toFieldPathReference(orderBy.field), + direction: toDirection(orderBy.dir) + }; +} +// visible for testing +function toFilter(filter) { + if (filter instanceof FieldFilter) { + return toUnaryOrFieldFilter(filter); + } + else if (filter instanceof CompositeFilter) { + return toCompositeFilter(filter); + } + else { + return fail(0xd65d, { filter }); + } +} +function toCompositeFilter(filter) { + const protos = filter.getFilters().map(filter => toFilter(filter)); + if (protos.length === 1) { + return protos[0]; + } + return { + compositeFilter: { + op: toCompositeOperatorName(filter.op), + filters: protos + } + }; +} +function toUnaryOrFieldFilter(filter) { + if (filter.op === "==" /* Operator.EQUAL */) { + if (isNanValue(filter.value)) { + return { + unaryFilter: { + field: toFieldPathReference(filter.field), + op: 'IS_NAN' + } + }; + } + else if (isNullValue(filter.value)) { + return { + unaryFilter: { + field: toFieldPathReference(filter.field), + op: 'IS_NULL' + } + }; + } + } + else if (filter.op === "!=" /* Operator.NOT_EQUAL */) { + if (isNanValue(filter.value)) { + return { + unaryFilter: { + field: toFieldPathReference(filter.field), + op: 'IS_NOT_NAN' + } + }; + } + else if (isNullValue(filter.value)) { + return { + unaryFilter: { + field: toFieldPathReference(filter.field), + op: 'IS_NOT_NULL' + } + }; + } + } + return { + fieldFilter: { + field: toFieldPathReference(filter.field), + op: toOperatorName(filter.op), + value: filter.value + } + }; +} +function toDocumentMask(fieldMask) { + const canonicalFields = []; + fieldMask.fields.forEach(field => canonicalFields.push(field.canonicalString())); + return { + fieldPaths: canonicalFields + }; +} +function isValidResourceName(path) { + // Resource names have at least 4 components (project ID, database ID) + return (path.length >= 4 && + path.get(0) === 'projects' && + path.get(2) === 'databases'); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +function newSerializer(databaseId) { + return new JsonProtoSerializer(databaseId, /* useProto3Json= */ true); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const LOG_TAG$2 = 'ExponentialBackoff'; +/** + * Initial backoff time in milliseconds after an error. + * Set to 1s according to https://cloud.google.com/apis/design/errors. + */ +const DEFAULT_BACKOFF_INITIAL_DELAY_MS = 1000; +const DEFAULT_BACKOFF_FACTOR = 1.5; +/** Maximum backoff time in milliseconds */ +const DEFAULT_BACKOFF_MAX_DELAY_MS = 60 * 1000; +/** + * A helper for running delayed tasks following an exponential backoff curve + * between attempts. + * + * Each delay is made up of a "base" delay which follows the exponential + * backoff curve, and a +/- 50% "jitter" that is calculated and added to the + * base delay. This prevents clients from accidentally synchronizing their + * delays causing spikes of load to the backend. + */ +class ExponentialBackoff { + constructor( + /** + * The AsyncQueue to run backoff operations on. + */ + queue, + /** + * The ID to use when scheduling backoff operations on the AsyncQueue. + */ + timerId, + /** + * The initial delay (used as the base delay on the first retry attempt). + * Note that jitter will still be applied, so the actual delay could be as + * little as 0.5*initialDelayMs. + */ + initialDelayMs = DEFAULT_BACKOFF_INITIAL_DELAY_MS, + /** + * The multiplier to use to determine the extended base delay after each + * attempt. + */ + backoffFactor = DEFAULT_BACKOFF_FACTOR, + /** + * The maximum base delay after which no further backoff is performed. + * Note that jitter will still be applied, so the actual delay could be as + * much as 1.5*maxDelayMs. + */ + maxDelayMs = DEFAULT_BACKOFF_MAX_DELAY_MS) { + this.queue = queue; + this.timerId = timerId; + this.initialDelayMs = initialDelayMs; + this.backoffFactor = backoffFactor; + this.maxDelayMs = maxDelayMs; + this.currentBaseMs = 0; + this.timerPromise = null; + /** The last backoff attempt, as epoch milliseconds. */ + this.lastAttemptTime = Date.now(); + this.reset(); + } + /** + * Resets the backoff delay. + * + * The very next backoffAndWait() will have no delay. If it is called again + * (i.e. due to an error), initialDelayMs (plus jitter) will be used, and + * subsequent ones will increase according to the backoffFactor. + */ + reset() { + this.currentBaseMs = 0; + } + /** + * Resets the backoff delay to the maximum delay (e.g. for use after a + * RESOURCE_EXHAUSTED error). + */ + resetToMax() { + this.currentBaseMs = this.maxDelayMs; + } + /** + * Returns a promise that resolves after currentDelayMs, and increases the + * delay for any subsequent attempts. If there was a pending backoff operation + * already, it will be canceled. + */ + backoffAndRun(op) { + // Cancel any pending backoff operation. + this.cancel(); + // First schedule using the current base (which may be 0 and should be + // honored as such). + const desiredDelayWithJitterMs = Math.floor(this.currentBaseMs + this.jitterDelayMs()); + // Guard against lastAttemptTime being in the future due to a clock change. + const delaySoFarMs = Math.max(0, Date.now() - this.lastAttemptTime); + // Guard against the backoff delay already being past. + const remainingDelayMs = Math.max(0, desiredDelayWithJitterMs - delaySoFarMs); + if (remainingDelayMs > 0) { + logDebug(LOG_TAG$2, `Backing off for ${remainingDelayMs} ms ` + + `(base delay: ${this.currentBaseMs} ms, ` + + `delay with jitter: ${desiredDelayWithJitterMs} ms, ` + + `last attempt: ${delaySoFarMs} ms ago)`); + } + this.timerPromise = this.queue.enqueueAfterDelay(this.timerId, remainingDelayMs, () => { + this.lastAttemptTime = Date.now(); + return op(); + }); + // Apply backoff factor to determine next delay and ensure it is within + // bounds. + this.currentBaseMs *= this.backoffFactor; + if (this.currentBaseMs < this.initialDelayMs) { + this.currentBaseMs = this.initialDelayMs; + } + if (this.currentBaseMs > this.maxDelayMs) { + this.currentBaseMs = this.maxDelayMs; + } + } + skipBackoff() { + if (this.timerPromise !== null) { + this.timerPromise.skipDelay(); + this.timerPromise = null; + } + } + cancel() { + if (this.timerPromise !== null) { + this.timerPromise.cancel(); + this.timerPromise = null; + } + } + /** Returns a random value in the range [-currentBaseMs/2, currentBaseMs/2] */ + jitterDelayMs() { + return (Math.random() - 0.5) * this.currentBaseMs; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Datastore and its related methods are a wrapper around the external Google + * Cloud Datastore grpc API, which provides an interface that is more convenient + * for the rest of the client SDK architecture to consume. + */ +class Datastore { +} +/** + * An implementation of Datastore that exposes additional state for internal + * consumption. + */ +class DatastoreImpl extends Datastore { + constructor(authCredentials, appCheckCredentials, connection, serializer) { + super(); + this.authCredentials = authCredentials; + this.appCheckCredentials = appCheckCredentials; + this.connection = connection; + this.serializer = serializer; + this.terminated = false; + } + verifyInitialized() { + if (this.terminated) { + throw new FirestoreError(Code.FAILED_PRECONDITION, 'The client has already been terminated.'); + } + } + /** Invokes the provided RPC with auth and AppCheck tokens. */ + invokeRPC(rpcName, databaseId, resourcePath, request) { + this.verifyInitialized(); + return Promise.all([ + this.authCredentials.getToken(), + this.appCheckCredentials.getToken() + ]) + .then(([authToken, appCheckToken]) => { + return this.connection.invokeRPC(rpcName, toResourcePath(databaseId, resourcePath), request, authToken, appCheckToken); + }) + .catch((error) => { + if (error.name === 'FirebaseError') { + if (error.code === Code.UNAUTHENTICATED) { + this.authCredentials.invalidateToken(); + this.appCheckCredentials.invalidateToken(); + } + throw error; + } + else { + throw new FirestoreError(Code.UNKNOWN, error.toString()); + } + }); + } + /** Invokes the provided RPC with streamed results with auth and AppCheck tokens. */ + invokeStreamingRPC(rpcName, databaseId, resourcePath, request, expectedResponseCount) { + this.verifyInitialized(); + return Promise.all([ + this.authCredentials.getToken(), + this.appCheckCredentials.getToken() + ]) + .then(([authToken, appCheckToken]) => { + return this.connection.invokeStreamingRPC(rpcName, toResourcePath(databaseId, resourcePath), request, authToken, appCheckToken, expectedResponseCount); + }) + .catch((error) => { + if (error.name === 'FirebaseError') { + if (error.code === Code.UNAUTHENTICATED) { + this.authCredentials.invalidateToken(); + this.appCheckCredentials.invalidateToken(); + } + throw error; + } + else { + throw new FirestoreError(Code.UNKNOWN, error.toString()); + } + }); + } + terminate() { + this.terminated = true; + this.connection.terminate(); + } +} +// TODO(firestorexp): Make sure there is only one Datastore instance per +// firestore-exp client. +function newDatastore(authCredentials, appCheckCredentials, connection, serializer) { + return new DatastoreImpl(authCredentials, appCheckCredentials, connection, serializer); +} +async function invokeCommitRpc(datastore, mutations) { + const datastoreImpl = debugCast(datastore); + const request = { + writes: mutations.map(m => toMutation(datastoreImpl.serializer, m)) + }; + await datastoreImpl.invokeRPC('Commit', datastoreImpl.serializer.databaseId, ResourcePath.emptyPath(), request); +} +async function invokeBatchGetDocumentsRpc(datastore, keys) { + const datastoreImpl = debugCast(datastore); + const request = { + documents: keys.map(k => toName(datastoreImpl.serializer, k)) + }; + const response = await datastoreImpl.invokeStreamingRPC('BatchGetDocuments', datastoreImpl.serializer.databaseId, ResourcePath.emptyPath(), request, keys.length); + const docs = new Map(); + response.forEach(proto => { + const doc = fromBatchGetDocumentsResponse(datastoreImpl.serializer, proto); + docs.set(doc.key.toString(), doc); + }); + const result = []; + keys.forEach(key => { + const doc = docs.get(key.toString()); + hardAssert(!!doc, 0xd7c2, { + key + }); + result.push(doc); + }); + return result; +} +async function invokeRunQueryRpc(datastore, query) { + const datastoreImpl = debugCast(datastore); + const { queryTarget, parent } = toQueryTarget(datastoreImpl.serializer, queryToTarget(query)); + const response = await datastoreImpl.invokeStreamingRPC('RunQuery', datastoreImpl.serializer.databaseId, parent, { + structuredQuery: queryTarget.structuredQuery + }); + return (response + // Omit RunQueryResponses that only contain readTimes. + .filter(proto => !!proto.document) + .map(proto => fromDocument(datastoreImpl.serializer, proto.document, undefined))); +} +async function invokeRunAggregationQueryRpc(datastore, query, aggregates) { + const datastoreImpl = debugCast(datastore); + const { request, aliasMap, parent } = toRunAggregationQueryRequest(datastoreImpl.serializer, queryToAggregateTarget(query), aggregates); + if (!datastoreImpl.connection.shouldResourcePathBeIncludedInRequest) { + delete request.parent; + } + const response = await datastoreImpl.invokeStreamingRPC('RunAggregationQuery', datastoreImpl.serializer.databaseId, parent, request, + /*expectedResponseCount=*/ 1); + // Omit RunAggregationQueryResponse that only contain readTimes. + const filteredResult = response.filter(proto => !!proto.result); + hardAssert(filteredResult.length === 1, 0xfcd7); + // Remap the short-form aliases that were sent to the server + // to the client-side aliases. Users will access the results + // using the client-side alias. + const unmappedAggregateFields = filteredResult[0].result?.aggregateFields; + const remappedFields = Object.keys(unmappedAggregateFields).reduce((accumulator, key) => { + accumulator[aliasMap[key]] = unmappedAggregateFields[key]; + return accumulator; + }, {}); + return remappedFields; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const LOG_TAG$1 = 'ComponentProvider'; +/** + * An instance map that ensures only one Datastore exists per Firestore + * instance. + */ +const datastoreInstances = new Map(); +/** + * Returns an initialized and started Datastore for the given Firestore + * instance. Callers must invoke removeComponents() when the Firestore + * instance is terminated. + */ +function getDatastore(firestore) { + if (firestore._terminated) { + throw new FirestoreError(Code.FAILED_PRECONDITION, 'The client has already been terminated.'); + } + if (!datastoreInstances.has(firestore)) { + logDebug(LOG_TAG$1, 'Initializing Datastore'); + const databaseInfo = makeDatabaseInfo(firestore._databaseId, firestore.app.options.appId || '', firestore._persistenceKey, firestore._freezeSettings()); + const connection = newConnection(databaseInfo); + const serializer = newSerializer(firestore._databaseId); + const datastore = newDatastore(firestore._authCredentials, firestore._appCheckCredentials, connection, serializer); + datastoreInstances.set(firestore, datastore); + } + return datastoreInstances.get(firestore); +} +/** + * Removes all components associated with the provided instance. Must be called + * when the `Firestore` instance is terminated. + */ +function removeComponents(firestore) { + const datastore = datastoreInstances.get(firestore); + if (datastore) { + logDebug(LOG_TAG$1, 'Removing Datastore'); + datastoreInstances.delete(firestore); + datastore.terminate(); + } +} +function makeDatabaseInfo(databaseId, appId, persistenceKey, settings) { + return new DatabaseInfo(databaseId, appId, persistenceKey, settings.host, settings.ssl, settings.experimentalForceLongPolling, settings.experimentalAutoDetectLongPolling, cloneLongPollingOptions(settings.experimentalLongPollingOptions), settings.useFetchStreams, settings.isUsingEmulator); +} + +/** + * @license + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const LRU_COLLECTION_DISABLED = -1; +const LRU_DEFAULT_CACHE_SIZE_BYTES = 40 * 1024 * 1024; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Verifies whether `e` is an IndexedDbTransactionError. */ +function isIndexedDbTransactionError(e) { + // Use name equality, as instanceof checks on errors don't work with errors + // that wrap other errors. + return e.name === 'IndexedDbTransactionError'; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const LRU_MINIMUM_CACHE_SIZE_BYTES = 1 * 1024 * 1024; + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// settings() defaults: +const DEFAULT_HOST = 'firestore.googleapis.com'; +const DEFAULT_SSL = true; +// The minimum long-polling timeout is hardcoded on the server. The value here +// should be kept in sync with the value used by the server, as the server will +// silently ignore a value below the minimum and fall back to the default. +// Googlers see b/266868871 for relevant discussion. +const MIN_LONG_POLLING_TIMEOUT_SECONDS = 5; +// No maximum long-polling timeout is configured in the server, and defaults to +// 30 seconds, which is what Watch appears to use. +// Googlers see b/266868871 for relevant discussion. +const MAX_LONG_POLLING_TIMEOUT_SECONDS = 30; +// Whether long-polling auto-detected is enabled by default. +const DEFAULT_AUTO_DETECT_LONG_POLLING = true; +/** + * A concrete type describing all the values that can be applied via a + * user-supplied `FirestoreSettings` object. This is a separate type so that + * defaults can be supplied and the value can be checked for equality. + */ +class FirestoreSettingsImpl { + constructor(settings) { + if (settings.host === undefined) { + if (settings.ssl !== undefined) { + throw new FirestoreError(Code.INVALID_ARGUMENT, "Can't provide ssl option if host option is not set"); + } + this.host = DEFAULT_HOST; + this.ssl = DEFAULT_SSL; + } + else { + this.host = settings.host; + this.ssl = settings.ssl ?? DEFAULT_SSL; + } + this.isUsingEmulator = settings.emulatorOptions !== undefined; + this.credentials = settings.credentials; + this.ignoreUndefinedProperties = !!settings.ignoreUndefinedProperties; + this.localCache = settings.localCache; + if (settings.cacheSizeBytes === undefined) { + this.cacheSizeBytes = LRU_DEFAULT_CACHE_SIZE_BYTES; + } + else { + if (settings.cacheSizeBytes !== LRU_COLLECTION_DISABLED && + settings.cacheSizeBytes < LRU_MINIMUM_CACHE_SIZE_BYTES) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `cacheSizeBytes must be at least ${LRU_MINIMUM_CACHE_SIZE_BYTES}`); + } + else { + this.cacheSizeBytes = settings.cacheSizeBytes; + } + } + validateIsNotUsedTogether('experimentalForceLongPolling', settings.experimentalForceLongPolling, 'experimentalAutoDetectLongPolling', settings.experimentalAutoDetectLongPolling); + this.experimentalForceLongPolling = !!settings.experimentalForceLongPolling; + if (this.experimentalForceLongPolling) { + this.experimentalAutoDetectLongPolling = false; + } + else if (settings.experimentalAutoDetectLongPolling === undefined) { + this.experimentalAutoDetectLongPolling = DEFAULT_AUTO_DETECT_LONG_POLLING; + } + else { + // For backwards compatibility, coerce the value to boolean even though + // the TypeScript compiler has narrowed the type to boolean already. + // noinspection PointlessBooleanExpressionJS + this.experimentalAutoDetectLongPolling = + !!settings.experimentalAutoDetectLongPolling; + } + this.experimentalLongPollingOptions = cloneLongPollingOptions(settings.experimentalLongPollingOptions ?? {}); + validateLongPollingOptions(this.experimentalLongPollingOptions); + this.useFetchStreams = !!settings.useFetchStreams; + } + isEqual(other) { + return (this.host === other.host && + this.ssl === other.ssl && + this.credentials === other.credentials && + this.cacheSizeBytes === other.cacheSizeBytes && + this.experimentalForceLongPolling === + other.experimentalForceLongPolling && + this.experimentalAutoDetectLongPolling === + other.experimentalAutoDetectLongPolling && + longPollingOptionsEqual(this.experimentalLongPollingOptions, other.experimentalLongPollingOptions) && + this.ignoreUndefinedProperties === other.ignoreUndefinedProperties && + this.useFetchStreams === other.useFetchStreams); + } +} +function validateLongPollingOptions(options) { + if (options.timeoutSeconds !== undefined) { + if (isNaN(options.timeoutSeconds)) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `invalid long polling timeout: ` + + `${options.timeoutSeconds} (must not be NaN)`); + } + if (options.timeoutSeconds < MIN_LONG_POLLING_TIMEOUT_SECONDS) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `invalid long polling timeout: ${options.timeoutSeconds} ` + + `(minimum allowed value is ${MIN_LONG_POLLING_TIMEOUT_SECONDS})`); + } + if (options.timeoutSeconds > MAX_LONG_POLLING_TIMEOUT_SECONDS) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `invalid long polling timeout: ${options.timeoutSeconds} ` + + `(maximum allowed value is ${MAX_LONG_POLLING_TIMEOUT_SECONDS})`); + } + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * The Cloud Firestore service interface. + * + * Do not call this constructor directly. Instead, use {@link (getFirestore:1)}. + */ +class Firestore { + /** @hideconstructor */ + constructor(_authCredentials, _appCheckCredentials, _databaseId, _app) { + this._authCredentials = _authCredentials; + this._appCheckCredentials = _appCheckCredentials; + this._databaseId = _databaseId; + this._app = _app; + /** + * Whether it's a Firestore or Firestore Lite instance. + */ + this.type = 'firestore-lite'; + this._persistenceKey = '(lite)'; + this._settings = new FirestoreSettingsImpl({}); + this._settingsFrozen = false; + this._emulatorOptions = {}; + // A task that is assigned when the terminate() is invoked and resolved when + // all components have shut down. Otherwise, Firestore is not terminated, + // which can mean either the FirestoreClient is in the process of starting, + // or restarting. + this._terminateTask = 'notTerminated'; + } + /** + * The {@link @firebase/app#FirebaseApp} associated with this `Firestore` service + * instance. + */ + get app() { + if (!this._app) { + throw new FirestoreError(Code.FAILED_PRECONDITION, "Firestore was not initialized using the Firebase SDK. 'app' is " + + 'not available'); + } + return this._app; + } + get _initialized() { + return this._settingsFrozen; + } + get _terminated() { + return this._terminateTask !== 'notTerminated'; + } + _setSettings(settings) { + if (this._settingsFrozen) { + throw new FirestoreError(Code.FAILED_PRECONDITION, 'Firestore has already been started and its settings can no longer ' + + 'be changed. You can only modify settings before calling any other ' + + 'methods on a Firestore object.'); + } + this._settings = new FirestoreSettingsImpl(settings); + this._emulatorOptions = settings.emulatorOptions || {}; + if (settings.credentials !== undefined) { + this._authCredentials = makeAuthCredentialsProvider(settings.credentials); + } + } + _getSettings() { + return this._settings; + } + _getEmulatorOptions() { + return this._emulatorOptions; + } + _freezeSettings() { + this._settingsFrozen = true; + return this._settings; + } + _delete() { + // The `_terminateTask` must be assigned future that completes when + // terminate is complete. The existence of this future puts SDK in state + // that will not accept further API interaction. + if (this._terminateTask === 'notTerminated') { + this._terminateTask = this._terminate(); + } + return this._terminateTask; + } + async _restart() { + // The `_terminateTask` must equal 'notTerminated' after restart to + // signal that client is in a state that accepts API calls. + if (this._terminateTask === 'notTerminated') { + await this._terminate(); + } + else { + this._terminateTask = 'notTerminated'; + } + } + /** Returns a JSON-serializable representation of this `Firestore` instance. */ + toJSON() { + return { + app: this._app, + databaseId: this._databaseId, + settings: this._settings + }; + } + /** + * Terminates all components used by this client. Subclasses can override + * this method to clean up their own dependencies, but must also call this + * method. + * + * Only ever called once. + */ + _terminate() { + removeComponents(this); + return Promise.resolve(); + } +} +function initializeFirestore(app, settings, databaseId) { + if (!databaseId) { + databaseId = DEFAULT_DATABASE_NAME; + } + const provider = _getProvider(app, 'firestore/lite'); + if (provider.isInitialized(databaseId)) { + throw new FirestoreError(Code.FAILED_PRECONDITION, 'Firestore can only be initialized once per app.'); + } + return provider.initialize({ + options: settings, + instanceIdentifier: databaseId + }); +} +function getFirestore(appOrDatabaseId, optionalDatabaseId) { + const app = typeof appOrDatabaseId === 'object' ? appOrDatabaseId : getApp(); + const databaseId = typeof appOrDatabaseId === 'string' + ? appOrDatabaseId + : optionalDatabaseId || '(default)'; + const db = _getProvider(app, 'firestore/lite').getImmediate({ + identifier: databaseId + }); + if (!db._initialized) { + const emulator = getDefaultEmulatorHostnameAndPort('firestore'); + if (emulator) { + connectFirestoreEmulator(db, ...emulator); + } + } + return db; +} +/** + * Modify this instance to communicate with the Cloud Firestore emulator. + * + * Note: This must be called before this instance has been used to do any + * operations. + * + * @param firestore - The `Firestore` instance to configure to connect to the + * emulator. + * @param host - the emulator host (ex: localhost). + * @param port - the emulator port (ex: 9000). + * @param options.mockUserToken - the mock auth token to use for unit testing + * Security Rules. + */ +function connectFirestoreEmulator(firestore, host, port, options = {}) { + firestore = cast(firestore, Firestore); + const useSsl = isCloudWorkstation(host); + const settings = firestore._getSettings(); + const existingConfig = { + ...settings, + emulatorOptions: firestore._getEmulatorOptions() + }; + const newHostSetting = `${host}:${port}`; + if (useSsl) { + void pingServer(`https://${newHostSetting}`); + updateEmulatorBanner('Firestore', true); + } + if (settings.host !== DEFAULT_HOST && settings.host !== newHostSetting) { + logWarn('Host has been set in both settings() and connectFirestoreEmulator(), emulator host ' + + 'will be used.'); + } + const newConfig = { + ...settings, + host: newHostSetting, + ssl: useSsl, + emulatorOptions: options + }; + // No-op if the new configuration matches the current configuration. This supports SSR + // enviornments which might call `connectFirestoreEmulator` multiple times as a standard practice. + if (deepEqual(newConfig, existingConfig)) { + return; + } + firestore._setSettings(newConfig); + if (options.mockUserToken) { + let token; + let user; + if (typeof options.mockUserToken === 'string') { + token = options.mockUserToken; + user = User.MOCK_USER; + } + else { + // Let createMockUserToken validate first (catches common mistakes like + // invalid field "uid" and missing field "sub" / "user_id".) + token = createMockUserToken(options.mockUserToken, firestore._app?.options.projectId); + const uid = options.mockUserToken.sub || options.mockUserToken.user_id; + if (!uid) { + throw new FirestoreError(Code.INVALID_ARGUMENT, "mockUserToken must contain 'sub' or 'user_id' field!"); + } + user = new User(uid); + } + firestore._authCredentials = new EmulatorAuthCredentialsProvider(new OAuthToken(token, user)); + } +} +/** + * Terminates the provided `Firestore` instance. + * + * After calling `terminate()` only the `clearIndexedDbPersistence()` functions + * may be used. Any other function will throw a `FirestoreError`. Termination + * does not cancel any pending writes, and any promises that are awaiting a + * response from the server will not be resolved. + * + * To restart after termination, create a new instance of `Firestore` with + * {@link (getFirestore:1)}. + * + * Note: Under normal circumstances, calling `terminate()` is not required. This + * function is useful only when you want to force this instance to release all of + * its resources or in combination with {@link clearIndexedDbPersistence} to + * ensure that all local state is destroyed between test runs. + * + * @param firestore - The `Firestore` instance to terminate. + * @returns A `Promise` that is resolved when the instance has been successfully + * terminated. + */ +function terminate(firestore) { + firestore = cast(firestore, Firestore); + _removeServiceInstance(firestore.app, 'firestore/lite'); + return firestore._delete(); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +function registerFirestore() { + setSDKVersion(`${SDK_VERSION$1}_lite`); + _registerComponent(new Component('firestore/lite', (container, { instanceIdentifier: databaseId, options: settings }) => { + const app = container.getProvider('app').getImmediate(); + const firestoreInstance = new Firestore(new LiteAuthCredentialsProvider(container.getProvider('auth-internal')), new LiteAppCheckTokenProvider(app, container.getProvider('app-check-internal')), databaseIdFromApp(app, databaseId), app); + if (settings) { + firestoreInstance._setSettings(settings); + } + return firestoreInstance; + }, 'PUBLIC').setMultipleInstances(true)); + // RUNTIME_ENV and BUILD_TARGET are replaced by real values during the compilation + registerVersion('firestore-lite', version$1, 'node'); + registerVersion('firestore-lite', version$1, 'esm2020'); +} + +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Concrete implementation of the Aggregate type. + */ +class AggregateImpl { + constructor(alias, aggregateType, fieldPath) { + this.alias = alias; + this.aggregateType = aggregateType; + this.fieldPath = fieldPath; + } +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Represents an aggregation that can be performed by Firestore. + */ +// eslint-disable-next-line @typescript-eslint/no-unused-vars +class AggregateField { + /** + * Create a new AggregateField + * @param aggregateType Specifies the type of aggregation operation to perform. + * @param _internalFieldPath Optionally specifies the field that is aggregated. + * @internal + */ + constructor(aggregateType = 'count', _internalFieldPath) { + this._internalFieldPath = _internalFieldPath; + /** A type string to uniquely identify instances of this class. */ + this.type = 'AggregateField'; + this.aggregateType = aggregateType; + } +} +/** + * The results of executing an aggregation query. + */ +class AggregateQuerySnapshot { + /** @hideconstructor */ + constructor(query, _userDataWriter, _data) { + this._userDataWriter = _userDataWriter; + this._data = _data; + /** A type string to uniquely identify instances of this class. */ + this.type = 'AggregateQuerySnapshot'; + this.query = query; + } + /** + * Returns the results of the aggregations performed over the underlying + * query. + * + * The keys of the returned object will be the same as those of the + * `AggregateSpec` object specified to the aggregation method, and the values + * will be the corresponding aggregation result. + * + * @returns The results of the aggregations performed over the underlying + * query. + */ + data() { + return this._userDataWriter.convertObjectMap(this._data); + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A `Query` refers to a query which you can read or listen to. You can also + * construct refined `Query` objects by adding filters and ordering. + */ +class Query { + // This is the lite version of the Query class in the main SDK. + /** @hideconstructor protected */ + constructor(firestore, + /** + * If provided, the `FirestoreDataConverter` associated with this instance. + */ + converter, _query) { + this.converter = converter; + this._query = _query; + /** The type of this Firestore reference. */ + this.type = 'query'; + this.firestore = firestore; + } + withConverter(converter) { + return new Query(this.firestore, converter, this._query); + } +} +/** + * A `DocumentReference` refers to a document location in a Firestore database + * and can be used to write, read, or listen to the location. The document at + * the referenced location may or may not exist. + */ +class DocumentReference { + /** @hideconstructor */ + constructor(firestore, + /** + * If provided, the `FirestoreDataConverter` associated with this instance. + */ + converter, _key) { + this.converter = converter; + this._key = _key; + /** The type of this Firestore reference. */ + this.type = 'document'; + this.firestore = firestore; + } + get _path() { + return this._key.path; + } + /** + * The document's identifier within its collection. + */ + get id() { + return this._key.path.lastSegment(); + } + /** + * A string representing the path of the referenced document (relative + * to the root of the database). + */ + get path() { + return this._key.path.canonicalString(); + } + /** + * The collection this `DocumentReference` belongs to. + */ + get parent() { + return new CollectionReference(this.firestore, this.converter, this._key.path.popLast()); + } + withConverter(converter) { + return new DocumentReference(this.firestore, converter, this._key); + } + /** + * Returns a JSON-serializable representation of this `DocumentReference` instance. + * + * @returns a JSON representation of this object. + */ + toJSON() { + return { + type: DocumentReference._jsonSchemaVersion, + referencePath: this._key.toString() + }; + } + static fromJSON(firestore, json, converter) { + if (validateJSON(json, DocumentReference._jsonSchema)) { + return new DocumentReference(firestore, converter ? converter : null, new DocumentKey(ResourcePath.fromString(json.referencePath))); + } + } +} +DocumentReference._jsonSchemaVersion = 'firestore/documentReference/1.0'; +DocumentReference._jsonSchema = { + type: property('string', DocumentReference._jsonSchemaVersion), + referencePath: property('string') +}; +/** + * A `CollectionReference` object can be used for adding documents, getting + * document references, and querying for documents (using {@link (query:1)}). + */ +class CollectionReference extends Query { + /** @hideconstructor */ + constructor(firestore, converter, _path) { + super(firestore, converter, newQueryForPath(_path)); + this._path = _path; + /** The type of this Firestore reference. */ + this.type = 'collection'; + } + /** The collection's identifier. */ + get id() { + return this._query.path.lastSegment(); + } + /** + * A string representing the path of the referenced collection (relative + * to the root of the database). + */ + get path() { + return this._query.path.canonicalString(); + } + /** + * A reference to the containing `DocumentReference` if this is a + * subcollection. If this isn't a subcollection, the reference is null. + */ + get parent() { + const parentPath = this._path.popLast(); + if (parentPath.isEmpty()) { + return null; + } + else { + return new DocumentReference(this.firestore, + /* converter= */ null, new DocumentKey(parentPath)); + } + } + withConverter(converter) { + return new CollectionReference(this.firestore, converter, this._path); + } +} +function collection(parent, path, ...pathSegments) { + parent = getModularInstance(parent); + validateNonEmptyArgument('collection', 'path', path); + if (parent instanceof Firestore) { + const absolutePath = ResourcePath.fromString(path, ...pathSegments); + validateCollectionPath(absolutePath); + return new CollectionReference(parent, /* converter= */ null, absolutePath); + } + else { + if (!(parent instanceof DocumentReference) && + !(parent instanceof CollectionReference)) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Expected first argument to collection() to be a CollectionReference, ' + + 'a DocumentReference or FirebaseFirestore'); + } + const absolutePath = parent._path.child(ResourcePath.fromString(path, ...pathSegments)); + validateCollectionPath(absolutePath); + return new CollectionReference(parent.firestore, + /* converter= */ null, absolutePath); + } +} +// TODO(firestorelite): Consider using ErrorFactory - +// https://github.com/firebase/firebase-js-sdk/blob/0131e1f/packages/util/src/errors.ts#L106 +/** + * Creates and returns a new `Query` instance that includes all documents in the + * database that are contained in a collection or subcollection with the + * given `collectionId`. + * + * @param firestore - A reference to the root `Firestore` instance. + * @param collectionId - Identifies the collections to query over. Every + * collection or subcollection with this ID as the last segment of its path + * will be included. Cannot contain a slash. + * @returns The created `Query`. + */ +function collectionGroup(firestore, collectionId) { + firestore = cast(firestore, Firestore); + validateNonEmptyArgument('collectionGroup', 'collection id', collectionId); + if (collectionId.indexOf('/') >= 0) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid collection ID '${collectionId}' passed to function ` + + `collectionGroup(). Collection IDs must not contain '/'.`); + } + return new Query(firestore, + /* converter= */ null, newQueryForCollectionGroup(collectionId)); +} +function doc(parent, path, ...pathSegments) { + parent = getModularInstance(parent); + // We allow omission of 'pathString' but explicitly prohibit passing in both + // 'undefined' and 'null'. + if (arguments.length === 1) { + path = AutoId.newId(); + } + validateNonEmptyArgument('doc', 'path', path); + if (parent instanceof Firestore) { + const absolutePath = ResourcePath.fromString(path, ...pathSegments); + validateDocumentPath(absolutePath); + return new DocumentReference(parent, + /* converter= */ null, new DocumentKey(absolutePath)); + } + else { + if (!(parent instanceof DocumentReference) && + !(parent instanceof CollectionReference)) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Expected first argument to collection() to be a CollectionReference, ' + + 'a DocumentReference or FirebaseFirestore'); + } + const absolutePath = parent._path.child(ResourcePath.fromString(path, ...pathSegments)); + validateDocumentPath(absolutePath); + return new DocumentReference(parent.firestore, parent instanceof CollectionReference ? parent.converter : null, new DocumentKey(absolutePath)); + } +} +/** + * Returns true if the provided references are equal. + * + * @param left - A reference to compare. + * @param right - A reference to compare. + * @returns true if the references point to the same location in the same + * Firestore database. + */ +function refEqual(left, right) { + left = getModularInstance(left); + right = getModularInstance(right); + if ((left instanceof DocumentReference || + left instanceof CollectionReference) && + (right instanceof DocumentReference || right instanceof CollectionReference)) { + return (left.firestore === right.firestore && + left.path === right.path && + left.converter === right.converter); + } + return false; +} +/** + * Returns true if the provided queries point to the same collection and apply + * the same constraints. + * + * @param left - A `Query` to compare. + * @param right - A `Query` to compare. + * @returns true if the references point to the same location in the same + * Firestore database. + */ +function queryEqual(left, right) { + left = getModularInstance(left); + right = getModularInstance(right); + if (left instanceof Query && right instanceof Query) { + return (left.firestore === right.firestore && + queryEquals(left._query, right._query) && + left.converter === right.converter); + } + return false; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An immutable object representing an array of bytes. + */ +class Bytes { + /** @hideconstructor */ + constructor(byteString) { + this._byteString = byteString; + } + /** + * Creates a new `Bytes` object from the given Base64 string, converting it to + * bytes. + * + * @param base64 - The Base64 string used to create the `Bytes` object. + */ + static fromBase64String(base64) { + try { + return new Bytes(ByteString.fromBase64String(base64)); + } + catch (e) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Failed to construct data from Base64 string: ' + e); + } + } + /** + * Creates a new `Bytes` object from the given Uint8Array. + * + * @param array - The Uint8Array used to create the `Bytes` object. + */ + static fromUint8Array(array) { + return new Bytes(ByteString.fromUint8Array(array)); + } + /** + * Returns the underlying bytes as a Base64-encoded string. + * + * @returns The Base64-encoded string created from the `Bytes` object. + */ + toBase64() { + return this._byteString.toBase64(); + } + /** + * Returns the underlying bytes in a new `Uint8Array`. + * + * @returns The Uint8Array created from the `Bytes` object. + */ + toUint8Array() { + return this._byteString.toUint8Array(); + } + /** + * Returns a string representation of the `Bytes` object. + * + * @returns A string representation of the `Bytes` object. + */ + toString() { + return 'Bytes(base64: ' + this.toBase64() + ')'; + } + /** + * Returns true if this `Bytes` object is equal to the provided one. + * + * @param other - The `Bytes` object to compare against. + * @returns true if this `Bytes` object is equal to the provided one. + */ + isEqual(other) { + return this._byteString.isEqual(other._byteString); + } + /** + * Returns a JSON-serializable representation of this `Bytes` instance. + * + * @returns a JSON representation of this object. + */ + toJSON() { + return { + type: Bytes._jsonSchemaVersion, + bytes: this.toBase64() + }; + } + /** + * Builds a `Bytes` instance from a JSON object created by {@link Bytes.toJSON}. + * + * @param json a JSON object represention of a `Bytes` instance + * @returns an instance of {@link Bytes} if the JSON object could be parsed. Throws a + * {@link FirestoreError} if an error occurs. + */ + static fromJSON(json) { + if (validateJSON(json, Bytes._jsonSchema)) { + return Bytes.fromBase64String(json.bytes); + } + } +} +Bytes._jsonSchemaVersion = 'firestore/bytes/1.0'; +Bytes._jsonSchema = { + type: property('string', Bytes._jsonSchemaVersion), + bytes: property('string') +}; + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A `FieldPath` refers to a field in a document. The path may consist of a + * single field name (referring to a top-level field in the document), or a + * list of field names (referring to a nested field in the document). + * + * Create a `FieldPath` by providing field names. If more than one field + * name is provided, the path will point to a nested field in a document. + */ +class FieldPath { + /** + * Creates a `FieldPath` from the provided field names. If more than one field + * name is provided, the path will point to a nested field in a document. + * + * @param fieldNames - A list of field names. + */ + constructor(...fieldNames) { + for (let i = 0; i < fieldNames.length; ++i) { + if (fieldNames[i].length === 0) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid field name at argument $(i + 1). ` + + 'Field names must not be empty.'); + } + } + this._internalPath = new FieldPath$1(fieldNames); + } + /** + * Returns true if this `FieldPath` is equal to the provided one. + * + * @param other - The `FieldPath` to compare against. + * @returns true if this `FieldPath` is equal to the provided one. + */ + isEqual(other) { + return this._internalPath.isEqual(other._internalPath); + } +} +/** + * Returns a special sentinel `FieldPath` to refer to the ID of a document. + * It can be used in queries to sort or filter by the document ID. + */ +function documentId() { + return new FieldPath(DOCUMENT_KEY_NAME); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Sentinel values that can be used when writing document fields with `set()` + * or `update()`. + */ +class FieldValue { + /** + * @param _methodName - The public API endpoint that returns this class. + * @hideconstructor + */ + constructor(_methodName) { + this._methodName = _methodName; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An immutable object representing a geographic location in Firestore. The + * location is represented as latitude/longitude pair. + * + * Latitude values are in the range of [-90, 90]. + * Longitude values are in the range of [-180, 180]. + */ +class GeoPoint { + /** + * Creates a new immutable `GeoPoint` object with the provided latitude and + * longitude values. + * @param latitude - The latitude as number between -90 and 90. + * @param longitude - The longitude as number between -180 and 180. + */ + constructor(latitude, longitude) { + if (!isFinite(latitude) || latitude < -90 || latitude > 90) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Latitude must be a number between -90 and 90, but was: ' + latitude); + } + if (!isFinite(longitude) || longitude < -180 || longitude > 180) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Longitude must be a number between -180 and 180, but was: ' + longitude); + } + this._lat = latitude; + this._long = longitude; + } + /** + * The latitude of this `GeoPoint` instance. + */ + get latitude() { + return this._lat; + } + /** + * The longitude of this `GeoPoint` instance. + */ + get longitude() { + return this._long; + } + /** + * Returns true if this `GeoPoint` is equal to the provided one. + * + * @param other - The `GeoPoint` to compare against. + * @returns true if this `GeoPoint` is equal to the provided one. + */ + isEqual(other) { + return this._lat === other._lat && this._long === other._long; + } + /** + * Actually private to JS consumers of our API, so this function is prefixed + * with an underscore. + */ + _compareTo(other) { + return (primitiveComparator(this._lat, other._lat) || + primitiveComparator(this._long, other._long)); + } + /** + * Returns a JSON-serializable representation of this `GeoPoint` instance. + * + * @returns a JSON representation of this object. + */ + toJSON() { + return { + latitude: this._lat, + longitude: this._long, + type: GeoPoint._jsonSchemaVersion + }; + } + /** + * Builds a `GeoPoint` instance from a JSON object created by {@link GeoPoint.toJSON}. + * + * @param json a JSON object represention of a `GeoPoint` instance + * @returns an instance of {@link GeoPoint} if the JSON object could be parsed. Throws a + * {@link FirestoreError} if an error occurs. + */ + static fromJSON(json) { + if (validateJSON(json, GeoPoint._jsonSchema)) { + return new GeoPoint(json.latitude, json.longitude); + } + } +} +GeoPoint._jsonSchemaVersion = 'firestore/geoPoint/1.0'; +GeoPoint._jsonSchema = { + type: property('string', GeoPoint._jsonSchemaVersion), + latitude: property('number'), + longitude: property('number') +}; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Verifies equality for an array of primitives. + * + * @private + * @internal + * @param left Array of primitives. + * @param right Array of primitives. + * @return True if arrays are equal. + */ +function isPrimitiveArrayEqual(left, right) { + if (left.length !== right.length) { + return false; + } + for (let i = 0; i < left.length; ++i) { + if (left[i] !== right[i]) { + return false; + } + } + return true; +} + +/** + * @license + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Represents a vector type in Firestore documents. + * Create an instance with {@link vector}. + * + * @class VectorValue + */ +class VectorValue { + /** + * @private + * @internal + */ + constructor(values) { + // Making a copy of the parameter. + this._values = (values || []).map(n => n); + } + /** + * Returns a copy of the raw number array form of the vector. + */ + toArray() { + return this._values.map(n => n); + } + /** + * Returns `true` if the two `VectorValue` values have the same raw number arrays, returns `false` otherwise. + */ + isEqual(other) { + return isPrimitiveArrayEqual(this._values, other._values); + } + /** + * Returns a JSON-serializable representation of this `VectorValue` instance. + * + * @returns a JSON representation of this object. + */ + toJSON() { + return { + type: VectorValue._jsonSchemaVersion, + vectorValues: this._values + }; + } + /** + * Builds a `VectorValue` instance from a JSON object created by {@link VectorValue.toJSON}. + * + * @param json a JSON object represention of a `VectorValue` instance. + * @returns an instance of {@link VectorValue} if the JSON object could be parsed. Throws a + * {@link FirestoreError} if an error occurs. + */ + static fromJSON(json) { + if (validateJSON(json, VectorValue._jsonSchema)) { + if (Array.isArray(json.vectorValues) && + json.vectorValues.every(element => typeof element === 'number')) { + return new VectorValue(json.vectorValues); + } + throw new FirestoreError(Code.INVALID_ARGUMENT, "Expected 'vectorValues' field to be a number array"); + } + } +} +VectorValue._jsonSchemaVersion = 'firestore/vectorValue/1.0'; +VectorValue._jsonSchema = { + type: property('string', VectorValue._jsonSchemaVersion), + vectorValues: property('object') +}; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const RESERVED_FIELD_REGEX = /^__.*__$/; +/** The result of parsing document data (e.g. for a setData call). */ +class ParsedSetData { + constructor(data, fieldMask, fieldTransforms) { + this.data = data; + this.fieldMask = fieldMask; + this.fieldTransforms = fieldTransforms; + } + toMutation(key, precondition) { + if (this.fieldMask !== null) { + return new PatchMutation(key, this.data, this.fieldMask, precondition, this.fieldTransforms); + } + else { + return new SetMutation(key, this.data, precondition, this.fieldTransforms); + } + } +} +/** The result of parsing "update" data (i.e. for an updateData call). */ +class ParsedUpdateData { + constructor(data, + // The fieldMask does not include document transforms. + fieldMask, fieldTransforms) { + this.data = data; + this.fieldMask = fieldMask; + this.fieldTransforms = fieldTransforms; + } + toMutation(key, precondition) { + return new PatchMutation(key, this.data, this.fieldMask, precondition, this.fieldTransforms); + } +} +function isWrite(dataSource) { + switch (dataSource) { + case 0 /* UserDataSource.Set */: // fall through + case 2 /* UserDataSource.MergeSet */: // fall through + case 1 /* UserDataSource.Update */: + return true; + case 3 /* UserDataSource.Argument */: + case 4 /* UserDataSource.ArrayArgument */: + return false; + default: + throw fail(0x9c4b, { + dataSource + }); + } +} +/** A "context" object passed around while parsing user data. */ +class ParseContextImpl { + /** + * Initializes a ParseContext with the given source and path. + * + * @param settings - The settings for the parser. + * @param databaseId - The database ID of the Firestore instance. + * @param serializer - The serializer to use to generate the Value proto. + * @param ignoreUndefinedProperties - Whether to ignore undefined properties + * rather than throw. + * @param fieldTransforms - A mutable list of field transforms encountered + * while parsing the data. + * @param fieldMask - A mutable list of field paths encountered while parsing + * the data. + * + * TODO(b/34871131): We don't support array paths right now, so path can be + * null to indicate the context represents any location within an array (in + * which case certain features will not work and errors will be somewhat + * compromised). + */ + constructor(settings, databaseId, serializer, ignoreUndefinedProperties, fieldTransforms, fieldMask) { + this.settings = settings; + this.databaseId = databaseId; + this.serializer = serializer; + this.ignoreUndefinedProperties = ignoreUndefinedProperties; + // Minor hack: If fieldTransforms is undefined, we assume this is an + // external call and we need to validate the entire path. + if (fieldTransforms === undefined) { + this.validatePath(); + } + this.fieldTransforms = fieldTransforms || []; + this.fieldMask = fieldMask || []; + } + get path() { + return this.settings.path; + } + get dataSource() { + return this.settings.dataSource; + } + /** Returns a new context with the specified settings overwritten. */ + contextWith(configuration) { + return new ParseContextImpl({ ...this.settings, ...configuration }, this.databaseId, this.serializer, this.ignoreUndefinedProperties, this.fieldTransforms, this.fieldMask); + } + childContextForField(field) { + const childPath = this.path?.child(field); + const context = this.contextWith({ path: childPath, arrayElement: false }); + context.validatePathSegment(field); + return context; + } + childContextForFieldPath(field) { + const childPath = this.path?.child(field); + const context = this.contextWith({ path: childPath, arrayElement: false }); + context.validatePath(); + return context; + } + childContextForArray(index) { + // TODO(b/34871131): We don't support array paths right now; so make path + // undefined. + return this.contextWith({ path: undefined, arrayElement: true }); + } + createError(reason) { + return createError(reason, this.settings.methodName, this.settings.hasConverter || false, this.path, this.settings.targetDoc); + } + /** Returns 'true' if 'fieldPath' was traversed when creating this context. */ + contains(fieldPath) { + return (this.fieldMask.find(field => fieldPath.isPrefixOf(field)) !== undefined || + this.fieldTransforms.find(transform => fieldPath.isPrefixOf(transform.field)) !== undefined); + } + validatePath() { + // TODO(b/34871131): Remove null check once we have proper paths for fields + // within arrays. + if (!this.path) { + return; + } + for (let i = 0; i < this.path.length; i++) { + this.validatePathSegment(this.path.get(i)); + } + } + validatePathSegment(segment) { + if (segment.length === 0) { + throw this.createError('Document fields must not be empty'); + } + if (isWrite(this.dataSource) && RESERVED_FIELD_REGEX.test(segment)) { + throw this.createError('Document fields cannot begin and end with "__"'); + } + } +} +/** + * Helper for parsing raw user input (provided via the API) into internal model + * classes. + */ +class UserDataReader { + constructor(databaseId, ignoreUndefinedProperties, serializer) { + this.databaseId = databaseId; + this.ignoreUndefinedProperties = ignoreUndefinedProperties; + this.serializer = serializer || newSerializer(databaseId); + } + /** Creates a new top-level parse context. */ + createContext(dataSource, methodName, targetDoc, hasConverter = false) { + return new ParseContextImpl({ + dataSource, + methodName, + targetDoc, + path: FieldPath$1.emptyPath(), + arrayElement: false, + hasConverter + }, this.databaseId, this.serializer, this.ignoreUndefinedProperties); + } +} +function newUserDataReader(firestore) { + const settings = firestore._freezeSettings(); + const serializer = newSerializer(firestore._databaseId); + return new UserDataReader(firestore._databaseId, !!settings.ignoreUndefinedProperties, serializer); +} +/** Parse document data from a set() call. */ +function parseSetData(userDataReader, methodName, targetDoc, input, hasConverter, options = {}) { + const context = userDataReader.createContext(options.merge || options.mergeFields + ? 2 /* UserDataSource.MergeSet */ + : 0 /* UserDataSource.Set */, methodName, targetDoc, hasConverter); + validatePlainObject('Data must be an object, but it was:', context, input); + const updateData = parseObject(input, context); + let fieldMask; + let fieldTransforms; + if (options.merge) { + fieldMask = new FieldMask(context.fieldMask); + fieldTransforms = context.fieldTransforms; + } + else if (options.mergeFields) { + const validatedFieldPaths = []; + for (const stringOrFieldPath of options.mergeFields) { + const fieldPath = fieldPathFromArgument$1(methodName, stringOrFieldPath, targetDoc); + if (!context.contains(fieldPath)) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `Field '${fieldPath}' is specified in your field mask but missing from your input data.`); + } + if (!fieldMaskContains(validatedFieldPaths, fieldPath)) { + validatedFieldPaths.push(fieldPath); + } + } + fieldMask = new FieldMask(validatedFieldPaths); + fieldTransforms = context.fieldTransforms.filter(transform => fieldMask.covers(transform.field)); + } + else { + fieldMask = null; + fieldTransforms = context.fieldTransforms; + } + return new ParsedSetData(new ObjectValue(updateData), fieldMask, fieldTransforms); +} +class DeleteFieldValueImpl extends FieldValue { + _toFieldTransform(context) { + if (context.dataSource === 2 /* UserDataSource.MergeSet */) { + // No transform to add for a delete, but we need to add it to our + // fieldMask so it gets deleted. + context.fieldMask.push(context.path); + } + else if (context.dataSource === 1 /* UserDataSource.Update */) { + throw context.createError(`${this._methodName}() can only appear at the top level ` + + 'of your update data'); + } + else { + // We shouldn't encounter delete sentinels for queries or non-merge set() calls. + throw context.createError(`${this._methodName}() cannot be used with set() unless you pass ` + + '{merge:true}'); + } + return null; + } + isEqual(other) { + return other instanceof DeleteFieldValueImpl; + } +} +/** + * Creates a child context for parsing SerializableFieldValues. + * + * This is different than calling `ParseContext.contextWith` because it keeps + * the fieldTransforms and fieldMask separate. + * + * The created context has its `dataSource` set to `UserDataSource.Argument`. + * Although these values are used with writes, any elements in these FieldValues + * are not considered writes since they cannot contain any FieldValue sentinels, + * etc. + * + * @param fieldValue - The sentinel FieldValue for which to create a child + * context. + * @param context - The parent context. + * @param arrayElement - Whether or not the FieldValue has an array. + */ +function createSentinelChildContext(fieldValue, context, arrayElement) { + return new ParseContextImpl({ + dataSource: 3 /* UserDataSource.Argument */, + targetDoc: context.settings.targetDoc, + methodName: fieldValue._methodName, + arrayElement + }, context.databaseId, context.serializer, context.ignoreUndefinedProperties); +} +class ServerTimestampFieldValueImpl extends FieldValue { + _toFieldTransform(context) { + return new FieldTransform(context.path, new ServerTimestampTransform()); + } + isEqual(other) { + return other instanceof ServerTimestampFieldValueImpl; + } +} +class ArrayUnionFieldValueImpl extends FieldValue { + constructor(methodName, _elements) { + super(methodName); + this._elements = _elements; + } + _toFieldTransform(context) { + const parseContext = createSentinelChildContext(this, context, + /*array=*/ true); + const parsedElements = this._elements.map(element => parseData(element, parseContext)); + const arrayUnion = new ArrayUnionTransformOperation(parsedElements); + return new FieldTransform(context.path, arrayUnion); + } + isEqual(other) { + return (other instanceof ArrayUnionFieldValueImpl && + deepEqual(this._elements, other._elements)); + } +} +class ArrayRemoveFieldValueImpl extends FieldValue { + constructor(methodName, _elements) { + super(methodName); + this._elements = _elements; + } + _toFieldTransform(context) { + const parseContext = createSentinelChildContext(this, context, + /*array=*/ true); + const parsedElements = this._elements.map(element => parseData(element, parseContext)); + const arrayUnion = new ArrayRemoveTransformOperation(parsedElements); + return new FieldTransform(context.path, arrayUnion); + } + isEqual(other) { + return (other instanceof ArrayRemoveFieldValueImpl && + deepEqual(this._elements, other._elements)); + } +} +class NumericIncrementFieldValueImpl extends FieldValue { + constructor(methodName, _operand) { + super(methodName); + this._operand = _operand; + } + _toFieldTransform(context) { + const numericIncrement = new NumericIncrementTransformOperation(context.serializer, toNumber(context.serializer, this._operand)); + return new FieldTransform(context.path, numericIncrement); + } + isEqual(other) { + return (other instanceof NumericIncrementFieldValueImpl && + this._operand === other._operand); + } +} +/** Parse update data from an update() call. */ +function parseUpdateData(userDataReader, methodName, targetDoc, input) { + const context = userDataReader.createContext(1 /* UserDataSource.Update */, methodName, targetDoc); + validatePlainObject('Data must be an object, but it was:', context, input); + const fieldMaskPaths = []; + const updateData = ObjectValue.empty(); + forEach(input, (key, value) => { + const path = fieldPathFromDotSeparatedString(methodName, key, targetDoc); + // For Compat types, we have to "extract" the underlying types before + // performing validation. + value = getModularInstance(value); + const childContext = context.childContextForFieldPath(path); + if (value instanceof DeleteFieldValueImpl) { + // Add it to the field mask, but don't add anything to updateData. + fieldMaskPaths.push(path); + } + else { + const parsedValue = parseData(value, childContext); + if (parsedValue != null) { + fieldMaskPaths.push(path); + updateData.set(path, parsedValue); + } + } + }); + const mask = new FieldMask(fieldMaskPaths); + return new ParsedUpdateData(updateData, mask, context.fieldTransforms); +} +/** Parse update data from a list of field/value arguments. */ +function parseUpdateVarargs(userDataReader, methodName, targetDoc, field, value, moreFieldsAndValues) { + const context = userDataReader.createContext(1 /* UserDataSource.Update */, methodName, targetDoc); + const keys = [fieldPathFromArgument$1(methodName, field, targetDoc)]; + const values = [value]; + if (moreFieldsAndValues.length % 2 !== 0) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `Function ${methodName}() needs to be called with an even number ` + + 'of arguments that alternate between field names and values.'); + } + for (let i = 0; i < moreFieldsAndValues.length; i += 2) { + keys.push(fieldPathFromArgument$1(methodName, moreFieldsAndValues[i])); + values.push(moreFieldsAndValues[i + 1]); + } + const fieldMaskPaths = []; + const updateData = ObjectValue.empty(); + // We iterate in reverse order to pick the last value for a field if the + // user specified the field multiple times. + for (let i = keys.length - 1; i >= 0; --i) { + if (!fieldMaskContains(fieldMaskPaths, keys[i])) { + const path = keys[i]; + let value = values[i]; + // For Compat types, we have to "extract" the underlying types before + // performing validation. + value = getModularInstance(value); + const childContext = context.childContextForFieldPath(path); + if (value instanceof DeleteFieldValueImpl) { + // Add it to the field mask, but don't add anything to updateData. + fieldMaskPaths.push(path); + } + else { + const parsedValue = parseData(value, childContext); + if (parsedValue != null) { + fieldMaskPaths.push(path); + updateData.set(path, parsedValue); + } + } + } + } + const mask = new FieldMask(fieldMaskPaths); + return new ParsedUpdateData(updateData, mask, context.fieldTransforms); +} +/** + * Parse a "query value" (e.g. value in a where filter or a value in a cursor + * bound). + * + * @param allowArrays - Whether the query value is an array that may directly + * contain additional arrays (e.g. the operand of an `in` query). + */ +function parseQueryValue(userDataReader, methodName, input, allowArrays = false) { + const context = userDataReader.createContext(allowArrays ? 4 /* UserDataSource.ArrayArgument */ : 3 /* UserDataSource.Argument */, methodName); + const parsed = parseData(input, context); + return parsed; +} +/** + * Parses user data to Protobuf Values. + * + * @param input - Data to be parsed. + * @param context - A context object representing the current path being parsed, + * the source of the data being parsed, etc. + * @returns The parsed value, or null if the value was a FieldValue sentinel + * that should not be included in the resulting parsed data. + */ +function parseData(input, context) { + // Unwrap the API type from the Compat SDK. This will return the API type + // from firestore-exp. + input = getModularInstance(input); + if (looksLikeJsonObject(input)) { + validatePlainObject('Unsupported field value:', context, input); + return parseObject(input, context); + } + else if (input instanceof FieldValue) { + // FieldValues usually parse into transforms (except deleteField()) + // in which case we do not want to include this field in our parsed data + // (as doing so will overwrite the field directly prior to the transform + // trying to transform it). So we don't add this location to + // context.fieldMask and we return null as our parsing result. + parseSentinelFieldValue(input, context); + return null; + } + else if (input === undefined && context.ignoreUndefinedProperties) { + // If the input is undefined it can never participate in the fieldMask, so + // don't handle this below. If `ignoreUndefinedProperties` is false, + // `parseScalarValue` will reject an undefined value. + return null; + } + else { + // If context.path is null we are inside an array and we don't support + // field mask paths more granular than the top-level array. + if (context.path) { + context.fieldMask.push(context.path); + } + if (input instanceof Array) { + // TODO(b/34871131): Include the path containing the array in the error + // message. + // In the case of IN queries, the parsed data is an array (representing + // the set of values to be included for the IN query) that may directly + // contain additional arrays (each representing an individual field + // value), so we disable this validation. + if (context.settings.arrayElement && + context.dataSource !== 4 /* UserDataSource.ArrayArgument */) { + throw context.createError('Nested arrays are not supported'); + } + return parseArray(input, context); + } + else { + return parseScalarValue(input, context); + } + } +} +function parseObject(obj, context) { + const fields = {}; + if (isEmpty(obj)) { + // If we encounter an empty object, we explicitly add it to the update + // mask to ensure that the server creates a map entry. + if (context.path && context.path.length > 0) { + context.fieldMask.push(context.path); + } + } + else { + forEach(obj, (key, val) => { + const parsedValue = parseData(val, context.childContextForField(key)); + if (parsedValue != null) { + fields[key] = parsedValue; + } + }); + } + return { mapValue: { fields } }; +} +function parseArray(array, context) { + const values = []; + let entryIndex = 0; + for (const entry of array) { + let parsedEntry = parseData(entry, context.childContextForArray(entryIndex)); + if (parsedEntry == null) { + // Just include nulls in the array for fields being replaced with a + // sentinel. + parsedEntry = { nullValue: 'NULL_VALUE' }; + } + values.push(parsedEntry); + entryIndex++; + } + return { arrayValue: { values } }; +} +/** + * "Parses" the provided FieldValueImpl, adding any necessary transforms to + * context.fieldTransforms. + */ +function parseSentinelFieldValue(value, context) { + // Sentinels are only supported with writes, and not within arrays. + if (!isWrite(context.dataSource)) { + throw context.createError(`${value._methodName}() can only be used with update() and set()`); + } + if (!context.path) { + throw context.createError(`${value._methodName}() is not currently supported inside arrays`); + } + const fieldTransform = value._toFieldTransform(context); + if (fieldTransform) { + context.fieldTransforms.push(fieldTransform); + } +} +/** + * Helper to parse a scalar value (i.e. not an Object, Array, or FieldValue) + * + * @returns The parsed value + */ +function parseScalarValue(value, context) { + value = getModularInstance(value); + if (value === null) { + return { nullValue: 'NULL_VALUE' }; + } + else if (typeof value === 'number') { + return toNumber(context.serializer, value); + } + else if (typeof value === 'boolean') { + return { booleanValue: value }; + } + else if (typeof value === 'string') { + return { stringValue: value }; + } + else if (value instanceof Date) { + const timestamp = Timestamp.fromDate(value); + return { + timestampValue: toTimestamp(context.serializer, timestamp) + }; + } + else if (value instanceof Timestamp) { + // Firestore backend truncates precision down to microseconds. To ensure + // offline mode works the same with regards to truncation, perform the + // truncation immediately without waiting for the backend to do that. + const timestamp = new Timestamp(value.seconds, Math.floor(value.nanoseconds / 1000) * 1000); + return { + timestampValue: toTimestamp(context.serializer, timestamp) + }; + } + else if (value instanceof GeoPoint) { + return { + geoPointValue: { + latitude: value.latitude, + longitude: value.longitude + } + }; + } + else if (value instanceof Bytes) { + return { bytesValue: toBytes(context.serializer, value._byteString) }; + } + else if (value instanceof DocumentReference) { + const thisDb = context.databaseId; + const otherDb = value.firestore._databaseId; + if (!otherDb.isEqual(thisDb)) { + throw context.createError('Document reference is for database ' + + `${otherDb.projectId}/${otherDb.database} but should be ` + + `for database ${thisDb.projectId}/${thisDb.database}`); + } + return { + referenceValue: toResourceName(value.firestore._databaseId || context.databaseId, value._key.path) + }; + } + else if (value instanceof VectorValue) { + return parseVectorValue(value, context); + } + else { + throw context.createError(`Unsupported field value: ${valueDescription(value)}`); + } +} +/** + * Creates a new VectorValue proto value (using the internal format). + */ +function parseVectorValue(value, context) { + const mapValue = { + fields: { + [TYPE_KEY]: { + stringValue: VECTOR_VALUE_SENTINEL + }, + [VECTOR_MAP_VECTORS_KEY]: { + arrayValue: { + values: value.toArray().map(value => { + if (typeof value !== 'number') { + throw context.createError('VectorValues must only contain numeric values.'); + } + return toDouble(context.serializer, value); + }) + } + } + } + }; + return { mapValue }; +} +/** + * Checks whether an object looks like a JSON object that should be converted + * into a struct. Normal class/prototype instances are considered to look like + * JSON objects since they should be converted to a struct value. Arrays, Dates, + * GeoPoints, etc. are not considered to look like JSON objects since they map + * to specific FieldValue types other than ObjectValue. + */ +function looksLikeJsonObject(input) { + return (typeof input === 'object' && + input !== null && + !(input instanceof Array) && + !(input instanceof Date) && + !(input instanceof Timestamp) && + !(input instanceof GeoPoint) && + !(input instanceof Bytes) && + !(input instanceof DocumentReference) && + !(input instanceof FieldValue) && + !(input instanceof VectorValue)); +} +function validatePlainObject(message, context, input) { + if (!looksLikeJsonObject(input) || !isPlainObject(input)) { + const description = valueDescription(input); + if (description === 'an object') { + // Massage the error if it was an object. + throw context.createError(message + ' a custom object'); + } + else { + throw context.createError(message + ' ' + description); + } + } +} +/** + * Helper that calls fromDotSeparatedString() but wraps any error thrown. + */ +function fieldPathFromArgument$1(methodName, path, targetDoc) { + // If required, replace the FieldPath Compat class with the firestore-exp + // FieldPath. + path = getModularInstance(path); + if (path instanceof FieldPath) { + return path._internalPath; + } + else if (typeof path === 'string') { + return fieldPathFromDotSeparatedString(methodName, path); + } + else { + const message = 'Field path arguments must be of type string or '; + throw createError(message, methodName, + /* hasConverter= */ false, + /* path= */ undefined, targetDoc); + } +} +/** + * Matches any characters in a field path string that are reserved. + */ +const FIELD_PATH_RESERVED = new RegExp('[~\\*/\\[\\]]'); +/** + * Wraps fromDotSeparatedString with an error message about the method that + * was thrown. + * @param methodName - The publicly visible method name + * @param path - The dot-separated string form of a field path which will be + * split on dots. + * @param targetDoc - The document against which the field path will be + * evaluated. + */ +function fieldPathFromDotSeparatedString(methodName, path, targetDoc) { + const found = path.search(FIELD_PATH_RESERVED); + if (found >= 0) { + throw createError(`Invalid field path (${path}). Paths must not contain ` + + `'~', '*', '/', '[', or ']'`, methodName, + /* hasConverter= */ false, + /* path= */ undefined, targetDoc); + } + try { + return new FieldPath(...path.split('.'))._internalPath; + } + catch (e) { + throw createError(`Invalid field path (${path}). Paths must not be empty, ` + + `begin with '.', end with '.', or contain '..'`, methodName, + /* hasConverter= */ false, + /* path= */ undefined, targetDoc); + } +} +function createError(reason, methodName, hasConverter, path, targetDoc) { + const hasPath = path && !path.isEmpty(); + const hasDocument = targetDoc !== undefined; + let message = `Function ${methodName}() called with invalid data`; + if (hasConverter) { + message += ' (via `toFirestore()`)'; + } + message += '. '; + let description = ''; + if (hasPath || hasDocument) { + description += ' (found'; + if (hasPath) { + description += ` in field ${path}`; + } + if (hasDocument) { + description += ` in document ${targetDoc}`; + } + description += ')'; + } + return new FirestoreError(Code.INVALID_ARGUMENT, message + reason + description); +} +/** Checks `haystack` if FieldPath `needle` is present. Runs in O(n). */ +function fieldMaskContains(haystack, needle) { + return haystack.some(v => v.isEqual(needle)); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A `DocumentSnapshot` contains data read from a document in your Firestore + * database. The data can be extracted with `.data()` or `.get()` to + * get a specific field. + * + * For a `DocumentSnapshot` that points to a non-existing document, any data + * access will return 'undefined'. You can use the `exists()` method to + * explicitly verify a document's existence. + */ +class DocumentSnapshot { + // Note: This class is stripped down version of the DocumentSnapshot in + // the legacy SDK. The changes are: + // - No support for SnapshotMetadata. + // - No support for SnapshotOptions. + /** @hideconstructor protected */ + constructor(_firestore, _userDataWriter, _key, _document, _converter) { + this._firestore = _firestore; + this._userDataWriter = _userDataWriter; + this._key = _key; + this._document = _document; + this._converter = _converter; + } + /** Property of the `DocumentSnapshot` that provides the document's ID. */ + get id() { + return this._key.path.lastSegment(); + } + /** + * The `DocumentReference` for the document included in the `DocumentSnapshot`. + */ + get ref() { + return new DocumentReference(this._firestore, this._converter, this._key); + } + /** + * Signals whether or not the document at the snapshot's location exists. + * + * @returns true if the document exists. + */ + exists() { + return this._document !== null; + } + /** + * Retrieves all fields in the document as an `Object`. Returns `undefined` if + * the document doesn't exist. + * + * @returns An `Object` containing all fields in the document or `undefined` + * if the document doesn't exist. + */ + data() { + if (!this._document) { + return undefined; + } + else if (this._converter) { + // We only want to use the converter and create a new DocumentSnapshot + // if a converter has been provided. + const snapshot = new QueryDocumentSnapshot(this._firestore, this._userDataWriter, this._key, this._document, + /* converter= */ null); + return this._converter.fromFirestore(snapshot); + } + else { + return this._userDataWriter.convertValue(this._document.data.value); + } + } + /** + * Retrieves the field specified by `fieldPath`. Returns `undefined` if the + * document or field doesn't exist. + * + * @param fieldPath - The path (for example 'foo' or 'foo.bar') to a specific + * field. + * @returns The data at the specified field location or undefined if no such + * field exists in the document. + */ + // We are using `any` here to avoid an explicit cast by our users. + // eslint-disable-next-line @typescript-eslint/no-explicit-any + get(fieldPath) { + if (this._document) { + const value = this._document.data.field(fieldPathFromArgument('DocumentSnapshot.get', fieldPath)); + if (value !== null) { + return this._userDataWriter.convertValue(value); + } + } + return undefined; + } +} +/** + * A `QueryDocumentSnapshot` contains data read from a document in your + * Firestore database as part of a query. The document is guaranteed to exist + * and its data can be extracted with `.data()` or `.get()` to get a + * specific field. + * + * A `QueryDocumentSnapshot` offers the same API surface as a + * `DocumentSnapshot`. Since query results contain only existing documents, the + * `exists` property will always be true and `data()` will never return + * 'undefined'. + */ +class QueryDocumentSnapshot extends DocumentSnapshot { + /** + * Retrieves all fields in the document as an `Object`. + * + * @override + * @returns An `Object` containing all fields in the document. + */ + data() { + return super.data(); + } +} +/** + * A `QuerySnapshot` contains zero or more `DocumentSnapshot` objects + * representing the results of a query. The documents can be accessed as an + * array via the `docs` property or enumerated using the `forEach` method. The + * number of documents can be determined via the `empty` and `size` + * properties. + */ +class QuerySnapshot { + /** @hideconstructor */ + constructor(_query, _docs) { + this._docs = _docs; + this.query = _query; + } + /** An array of all the documents in the `QuerySnapshot`. */ + get docs() { + return [...this._docs]; + } + /** The number of documents in the `QuerySnapshot`. */ + get size() { + return this.docs.length; + } + /** True if there are no documents in the `QuerySnapshot`. */ + get empty() { + return this.docs.length === 0; + } + /** + * Enumerates all of the documents in the `QuerySnapshot`. + * + * @param callback - A callback to be called with a `QueryDocumentSnapshot` for + * each document in the snapshot. + * @param thisArg - The `this` binding for the callback. + */ + forEach(callback, thisArg) { + this._docs.forEach(callback, thisArg); + } +} +/** + * Returns true if the provided snapshots are equal. + * + * @param left - A snapshot to compare. + * @param right - A snapshot to compare. + * @returns true if the snapshots are equal. + */ +function snapshotEqual(left, right) { + left = getModularInstance(left); + right = getModularInstance(right); + if (left instanceof DocumentSnapshot && right instanceof DocumentSnapshot) { + return (left._firestore === right._firestore && + left._key.isEqual(right._key) && + (left._document === null + ? right._document === null + : left._document.isEqual(right._document)) && + left._converter === right._converter); + } + else if (left instanceof QuerySnapshot && right instanceof QuerySnapshot) { + return (queryEqual(left.query, right.query) && + arrayEquals(left.docs, right.docs, snapshotEqual)); + } + return false; +} +/** + * Helper that calls `fromDotSeparatedString()` but wraps any error thrown. + */ +function fieldPathFromArgument(methodName, arg) { + if (typeof arg === 'string') { + return fieldPathFromDotSeparatedString(methodName, arg); + } + else if (arg instanceof FieldPath) { + return arg._internalPath; + } + else { + return arg._delegate._internalPath; + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +function validateHasExplicitOrderByForLimitToLast(query) { + if (query.limitType === "L" /* LimitType.Last */ && + query.explicitOrderBy.length === 0) { + throw new FirestoreError(Code.UNIMPLEMENTED, 'limitToLast() queries require specifying at least one orderBy() clause'); + } +} +/** + * An `AppliableConstraint` is an abstraction of a constraint that can be applied + * to a Firestore query. + */ +class AppliableConstraint { +} +/** + * A `QueryConstraint` is used to narrow the set of documents returned by a + * Firestore query. `QueryConstraint`s are created by invoking {@link where}, + * {@link orderBy}, {@link (startAt:1)}, {@link (startAfter:1)}, {@link + * (endBefore:1)}, {@link (endAt:1)}, {@link limit}, {@link limitToLast} and + * can then be passed to {@link (query:1)} to create a new query instance that + * also contains this `QueryConstraint`. + */ +class QueryConstraint extends AppliableConstraint { +} +function query(query, queryConstraint, ...additionalQueryConstraints) { + let queryConstraints = []; + if (queryConstraint instanceof AppliableConstraint) { + queryConstraints.push(queryConstraint); + } + queryConstraints = queryConstraints.concat(additionalQueryConstraints); + validateQueryConstraintArray(queryConstraints); + for (const constraint of queryConstraints) { + query = constraint._apply(query); + } + return query; +} +/** + * A `QueryFieldFilterConstraint` is used to narrow the set of documents returned by + * a Firestore query by filtering on one or more document fields. + * `QueryFieldFilterConstraint`s are created by invoking {@link where} and can then + * be passed to {@link (query:1)} to create a new query instance that also contains + * this `QueryFieldFilterConstraint`. + */ +class QueryFieldFilterConstraint extends QueryConstraint { + /** + * @internal + */ + constructor(_field, _op, _value) { + super(); + this._field = _field; + this._op = _op; + this._value = _value; + /** The type of this query constraint */ + this.type = 'where'; + } + static _create(_field, _op, _value) { + return new QueryFieldFilterConstraint(_field, _op, _value); + } + _apply(query) { + const filter = this._parse(query); + validateNewFieldFilter(query._query, filter); + return new Query(query.firestore, query.converter, queryWithAddedFilter(query._query, filter)); + } + _parse(query) { + const reader = newUserDataReader(query.firestore); + const filter = newQueryFilter(query._query, 'where', reader, query.firestore._databaseId, this._field, this._op, this._value); + return filter; + } +} +/** + * Creates a {@link QueryFieldFilterConstraint} that enforces that documents + * must contain the specified field and that the value should satisfy the + * relation constraint provided. + * + * @param fieldPath - The path to compare + * @param opStr - The operation string (e.g "<", "<=", "==", "<", + * "<=", "!="). + * @param value - The value for comparison + * @returns The created {@link QueryFieldFilterConstraint}. + */ +function where(fieldPath, opStr, value) { + const op = opStr; + const field = fieldPathFromArgument('where', fieldPath); + return QueryFieldFilterConstraint._create(field, op, value); +} +/** + * A `QueryCompositeFilterConstraint` is used to narrow the set of documents + * returned by a Firestore query by performing the logical OR or AND of multiple + * {@link QueryFieldFilterConstraint}s or {@link QueryCompositeFilterConstraint}s. + * `QueryCompositeFilterConstraint`s are created by invoking {@link or} or + * {@link and} and can then be passed to {@link (query:1)} to create a new query + * instance that also contains the `QueryCompositeFilterConstraint`. + */ +class QueryCompositeFilterConstraint extends AppliableConstraint { + /** + * @internal + */ + constructor( + /** The type of this query constraint */ + type, _queryConstraints) { + super(); + this.type = type; + this._queryConstraints = _queryConstraints; + } + static _create(type, _queryConstraints) { + return new QueryCompositeFilterConstraint(type, _queryConstraints); + } + _parse(query) { + const parsedFilters = this._queryConstraints + .map(queryConstraint => { + return queryConstraint._parse(query); + }) + .filter(parsedFilter => parsedFilter.getFilters().length > 0); + if (parsedFilters.length === 1) { + return parsedFilters[0]; + } + return CompositeFilter.create(parsedFilters, this._getOperator()); + } + _apply(query) { + const parsedFilter = this._parse(query); + if (parsedFilter.getFilters().length === 0) { + // Return the existing query if not adding any more filters (e.g. an empty + // composite filter). + return query; + } + validateNewFilter(query._query, parsedFilter); + return new Query(query.firestore, query.converter, queryWithAddedFilter(query._query, parsedFilter)); + } + _getQueryConstraints() { + return this._queryConstraints; + } + _getOperator() { + return this.type === 'and' ? "and" /* CompositeOperator.AND */ : "or" /* CompositeOperator.OR */; + } +} +/** + * Creates a new {@link QueryCompositeFilterConstraint} that is a disjunction of + * the given filter constraints. A disjunction filter includes a document if it + * satisfies any of the given filters. + * + * @param queryConstraints - Optional. The list of + * {@link QueryFilterConstraint}s to perform a disjunction for. These must be + * created with calls to {@link where}, {@link or}, or {@link and}. + * @returns The newly created {@link QueryCompositeFilterConstraint}. + */ +function or(...queryConstraints) { + // Only support QueryFilterConstraints + queryConstraints.forEach(queryConstraint => validateQueryFilterConstraint('or', queryConstraint)); + return QueryCompositeFilterConstraint._create("or" /* CompositeOperator.OR */, queryConstraints); +} +/** + * Creates a new {@link QueryCompositeFilterConstraint} that is a conjunction of + * the given filter constraints. A conjunction filter includes a document if it + * satisfies all of the given filters. + * + * @param queryConstraints - Optional. The list of + * {@link QueryFilterConstraint}s to perform a conjunction for. These must be + * created with calls to {@link where}, {@link or}, or {@link and}. + * @returns The newly created {@link QueryCompositeFilterConstraint}. + */ +function and(...queryConstraints) { + // Only support QueryFilterConstraints + queryConstraints.forEach(queryConstraint => validateQueryFilterConstraint('and', queryConstraint)); + return QueryCompositeFilterConstraint._create("and" /* CompositeOperator.AND */, queryConstraints); +} +/** + * A `QueryOrderByConstraint` is used to sort the set of documents returned by a + * Firestore query. `QueryOrderByConstraint`s are created by invoking + * {@link orderBy} and can then be passed to {@link (query:1)} to create a new query + * instance that also contains this `QueryOrderByConstraint`. + * + * Note: Documents that do not contain the orderBy field will not be present in + * the query result. + */ +class QueryOrderByConstraint extends QueryConstraint { + /** + * @internal + */ + constructor(_field, _direction) { + super(); + this._field = _field; + this._direction = _direction; + /** The type of this query constraint */ + this.type = 'orderBy'; + } + static _create(_field, _direction) { + return new QueryOrderByConstraint(_field, _direction); + } + _apply(query) { + const orderBy = newQueryOrderBy(query._query, this._field, this._direction); + return new Query(query.firestore, query.converter, queryWithAddedOrderBy(query._query, orderBy)); + } +} +/** + * Creates a {@link QueryOrderByConstraint} that sorts the query result by the + * specified field, optionally in descending order instead of ascending. + * + * Note: Documents that do not contain the specified field will not be present + * in the query result. + * + * @param fieldPath - The field to sort by. + * @param directionStr - Optional direction to sort by ('asc' or 'desc'). If + * not specified, order will be ascending. + * @returns The created {@link QueryOrderByConstraint}. + */ +function orderBy(fieldPath, directionStr = 'asc') { + const direction = directionStr; + const path = fieldPathFromArgument('orderBy', fieldPath); + return QueryOrderByConstraint._create(path, direction); +} +/** + * A `QueryLimitConstraint` is used to limit the number of documents returned by + * a Firestore query. + * `QueryLimitConstraint`s are created by invoking {@link limit} or + * {@link limitToLast} and can then be passed to {@link (query:1)} to create a new + * query instance that also contains this `QueryLimitConstraint`. + */ +class QueryLimitConstraint extends QueryConstraint { + /** + * @internal + */ + constructor( + /** The type of this query constraint */ + type, _limit, _limitType) { + super(); + this.type = type; + this._limit = _limit; + this._limitType = _limitType; + } + static _create(type, _limit, _limitType) { + return new QueryLimitConstraint(type, _limit, _limitType); + } + _apply(query) { + return new Query(query.firestore, query.converter, queryWithLimit(query._query, this._limit, this._limitType)); + } +} +/** + * Creates a {@link QueryLimitConstraint} that only returns the first matching + * documents. + * + * @param limit - The maximum number of items to return. + * @returns The created {@link QueryLimitConstraint}. + */ +function limit(limit) { + validatePositiveNumber('limit', limit); + return QueryLimitConstraint._create('limit', limit, "F" /* LimitType.First */); +} +/** + * Creates a {@link QueryLimitConstraint} that only returns the last matching + * documents. + * + * You must specify at least one `orderBy` clause for `limitToLast` queries, + * otherwise an exception will be thrown during execution. + * + * @param limit - The maximum number of items to return. + * @returns The created {@link QueryLimitConstraint}. + */ +function limitToLast(limit) { + validatePositiveNumber('limitToLast', limit); + return QueryLimitConstraint._create('limitToLast', limit, "L" /* LimitType.Last */); +} +/** + * A `QueryStartAtConstraint` is used to exclude documents from the start of a + * result set returned by a Firestore query. + * `QueryStartAtConstraint`s are created by invoking {@link (startAt:1)} or + * {@link (startAfter:1)} and can then be passed to {@link (query:1)} to create a + * new query instance that also contains this `QueryStartAtConstraint`. + */ +class QueryStartAtConstraint extends QueryConstraint { + /** + * @internal + */ + constructor( + /** The type of this query constraint */ + type, _docOrFields, _inclusive) { + super(); + this.type = type; + this._docOrFields = _docOrFields; + this._inclusive = _inclusive; + } + static _create(type, _docOrFields, _inclusive) { + return new QueryStartAtConstraint(type, _docOrFields, _inclusive); + } + _apply(query) { + const bound = newQueryBoundFromDocOrFields(query, this.type, this._docOrFields, this._inclusive); + return new Query(query.firestore, query.converter, queryWithStartAt(query._query, bound)); + } +} +function startAt(...docOrFields) { + return QueryStartAtConstraint._create('startAt', docOrFields, + /*inclusive=*/ true); +} +function startAfter(...docOrFields) { + return QueryStartAtConstraint._create('startAfter', docOrFields, + /*inclusive=*/ false); +} +/** + * A `QueryEndAtConstraint` is used to exclude documents from the end of a + * result set returned by a Firestore query. + * `QueryEndAtConstraint`s are created by invoking {@link (endAt:1)} or + * {@link (endBefore:1)} and can then be passed to {@link (query:1)} to create a new + * query instance that also contains this `QueryEndAtConstraint`. + */ +class QueryEndAtConstraint extends QueryConstraint { + /** + * @internal + */ + constructor( + /** The type of this query constraint */ + type, _docOrFields, _inclusive) { + super(); + this.type = type; + this._docOrFields = _docOrFields; + this._inclusive = _inclusive; + } + static _create(type, _docOrFields, _inclusive) { + return new QueryEndAtConstraint(type, _docOrFields, _inclusive); + } + _apply(query) { + const bound = newQueryBoundFromDocOrFields(query, this.type, this._docOrFields, this._inclusive); + return new Query(query.firestore, query.converter, queryWithEndAt(query._query, bound)); + } +} +function endBefore(...docOrFields) { + return QueryEndAtConstraint._create('endBefore', docOrFields, + /*inclusive=*/ false); +} +function endAt(...docOrFields) { + return QueryEndAtConstraint._create('endAt', docOrFields, + /*inclusive=*/ true); +} +/** Helper function to create a bound from a document or fields */ +function newQueryBoundFromDocOrFields(query, methodName, docOrFields, inclusive) { + docOrFields[0] = getModularInstance(docOrFields[0]); + if (docOrFields[0] instanceof DocumentSnapshot) { + return newQueryBoundFromDocument(query._query, query.firestore._databaseId, methodName, docOrFields[0]._document, inclusive); + } + else { + const reader = newUserDataReader(query.firestore); + return newQueryBoundFromFields(query._query, query.firestore._databaseId, reader, methodName, docOrFields, inclusive); + } +} +function newQueryFilter(query, methodName, dataReader, databaseId, fieldPath, op, value) { + let fieldValue; + if (fieldPath.isKeyField()) { + if (op === "array-contains" /* Operator.ARRAY_CONTAINS */ || op === "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid Query. You can't perform '${op}' queries on documentId().`); + } + else if (op === "in" /* Operator.IN */ || op === "not-in" /* Operator.NOT_IN */) { + validateDisjunctiveFilterElements(value, op); + const referenceList = []; + for (const arrayValue of value) { + referenceList.push(parseDocumentIdValue(databaseId, query, arrayValue)); + } + fieldValue = { arrayValue: { values: referenceList } }; + } + else { + fieldValue = parseDocumentIdValue(databaseId, query, value); + } + } + else { + if (op === "in" /* Operator.IN */ || + op === "not-in" /* Operator.NOT_IN */ || + op === "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */) { + validateDisjunctiveFilterElements(value, op); + } + fieldValue = parseQueryValue(dataReader, methodName, value, + /* allowArrays= */ op === "in" /* Operator.IN */ || op === "not-in" /* Operator.NOT_IN */); + } + const filter = FieldFilter.create(fieldPath, op, fieldValue); + return filter; +} +function newQueryOrderBy(query, fieldPath, direction) { + if (query.startAt !== null) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid query. You must not call startAt() or startAfter() before ' + + 'calling orderBy().'); + } + if (query.endAt !== null) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid query. You must not call endAt() or endBefore() before ' + + 'calling orderBy().'); + } + const orderBy = new OrderBy(fieldPath, direction); + return orderBy; +} +/** + * Create a `Bound` from a query and a document. + * + * Note that the `Bound` will always include the key of the document + * and so only the provided document will compare equal to the returned + * position. + * + * Will throw if the document does not contain all fields of the order by + * of the query or if any of the fields in the order by are an uncommitted + * server timestamp. + */ +function newQueryBoundFromDocument(query, databaseId, methodName, doc, inclusive) { + if (!doc) { + throw new FirestoreError(Code.NOT_FOUND, `Can't use a DocumentSnapshot that doesn't exist for ` + + `${methodName}().`); + } + const components = []; + // Because people expect to continue/end a query at the exact document + // provided, we need to use the implicit sort order rather than the explicit + // sort order, because it's guaranteed to contain the document key. That way + // the position becomes unambiguous and the query continues/ends exactly at + // the provided document. Without the key (by using the explicit sort + // orders), multiple documents could match the position, yielding duplicate + // results. + for (const orderBy of queryNormalizedOrderBy(query)) { + if (orderBy.field.isKeyField()) { + components.push(refValue(databaseId, doc.key)); + } + else { + const value = doc.data.field(orderBy.field); + if (isServerTimestamp(value)) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid query. You are trying to start or end a query using a ' + + 'document for which the field "' + + orderBy.field + + '" is an uncommitted server timestamp. (Since the value of ' + + 'this field is unknown, you cannot start/end a query with it.)'); + } + else if (value !== null) { + components.push(value); + } + else { + const field = orderBy.field.canonicalString(); + throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid query. You are trying to start or end a query using a ` + + `document for which the field '${field}' (used as the ` + + `orderBy) does not exist.`); + } + } + } + return new Bound(components, inclusive); +} +/** + * Converts a list of field values to a `Bound` for the given query. + */ +function newQueryBoundFromFields(query, databaseId, dataReader, methodName, values, inclusive) { + // Use explicit order by's because it has to match the query the user made + const orderBy = query.explicitOrderBy; + if (values.length > orderBy.length) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `Too many arguments provided to ${methodName}(). ` + + `The number of arguments must be less than or equal to the ` + + `number of orderBy() clauses`); + } + const components = []; + for (let i = 0; i < values.length; i++) { + const rawValue = values[i]; + const orderByComponent = orderBy[i]; + if (orderByComponent.field.isKeyField()) { + if (typeof rawValue !== 'string') { + throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid query. Expected a string for document ID in ` + + `${methodName}(), but got a ${typeof rawValue}`); + } + if (!isCollectionGroupQuery(query) && rawValue.indexOf('/') !== -1) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid query. When querying a collection and ordering by documentId(), ` + + `the value passed to ${methodName}() must be a plain document ID, but ` + + `'${rawValue}' contains a slash.`); + } + const path = query.path.child(ResourcePath.fromString(rawValue)); + if (!DocumentKey.isDocumentKey(path)) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid query. When querying a collection group and ordering by ` + + `documentId(), the value passed to ${methodName}() must result in a ` + + `valid document path, but '${path}' is not because it contains an odd number ` + + `of segments.`); + } + const key = new DocumentKey(path); + components.push(refValue(databaseId, key)); + } + else { + const wrapped = parseQueryValue(dataReader, methodName, rawValue); + components.push(wrapped); + } + } + return new Bound(components, inclusive); +} +/** + * Parses the given `documentIdValue` into a `ReferenceValue`, throwing + * appropriate errors if the value is anything other than a `DocumentReference` + * or `string`, or if the string is malformed. + */ +function parseDocumentIdValue(databaseId, query, documentIdValue) { + documentIdValue = getModularInstance(documentIdValue); + if (typeof documentIdValue === 'string') { + if (documentIdValue === '') { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid query. When querying with documentId(), you ' + + 'must provide a valid document ID, but it was an empty string.'); + } + if (!isCollectionGroupQuery(query) && documentIdValue.indexOf('/') !== -1) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid query. When querying a collection by ` + + `documentId(), you must provide a plain document ID, but ` + + `'${documentIdValue}' contains a '/' character.`); + } + const path = query.path.child(ResourcePath.fromString(documentIdValue)); + if (!DocumentKey.isDocumentKey(path)) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid query. When querying a collection group by ` + + `documentId(), the value provided must result in a valid document path, ` + + `but '${path}' is not because it has an odd number of segments (${path.length}).`); + } + return refValue(databaseId, new DocumentKey(path)); + } + else if (documentIdValue instanceof DocumentReference) { + return refValue(databaseId, documentIdValue._key); + } + else { + throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid query. When querying with documentId(), you must provide a valid ` + + `string or a DocumentReference, but it was: ` + + `${valueDescription(documentIdValue)}.`); + } +} +/** + * Validates that the value passed into a disjunctive filter satisfies all + * array requirements. + */ +function validateDisjunctiveFilterElements(value, operator) { + if (!Array.isArray(value) || value.length === 0) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid Query. A non-empty array is required for ' + + `'${operator.toString()}' filters.`); + } +} +/** + * Given an operator, returns the set of operators that cannot be used with it. + * + * This is not a comprehensive check, and this function should be removed in the + * long term. Validations should occur in the Firestore backend. + * + * Operators in a query must adhere to the following set of rules: + * 1. Only one inequality per query. + * 2. `NOT_IN` cannot be used with array, disjunctive, or `NOT_EQUAL` operators. + */ +function conflictingOps(op) { + switch (op) { + case "!=" /* Operator.NOT_EQUAL */: + return ["!=" /* Operator.NOT_EQUAL */, "not-in" /* Operator.NOT_IN */]; + case "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */: + case "in" /* Operator.IN */: + return ["not-in" /* Operator.NOT_IN */]; + case "not-in" /* Operator.NOT_IN */: + return [ + "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */, + "in" /* Operator.IN */, + "not-in" /* Operator.NOT_IN */, + "!=" /* Operator.NOT_EQUAL */ + ]; + default: + return []; + } +} +function validateNewFieldFilter(query, fieldFilter) { + const conflictingOp = findOpInsideFilters(query.filters, conflictingOps(fieldFilter.op)); + if (conflictingOp !== null) { + // Special case when it's a duplicate op to give a slightly clearer error message. + if (conflictingOp === fieldFilter.op) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid query. You cannot use more than one ' + + `'${fieldFilter.op.toString()}' filter.`); + } + else { + throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid query. You cannot use '${fieldFilter.op.toString()}' filters ` + + `with '${conflictingOp.toString()}' filters.`); + } + } +} +function validateNewFilter(query, filter) { + let testQuery = query; + const subFilters = filter.getFlattenedFilters(); + for (const subFilter of subFilters) { + validateNewFieldFilter(testQuery, subFilter); + testQuery = queryWithAddedFilter(testQuery, subFilter); + } +} +// Checks if any of the provided filter operators are included in the given list of filters and +// returns the first one that is, or null if none are. +function findOpInsideFilters(filters, operators) { + for (const filter of filters) { + for (const fieldFilter of filter.getFlattenedFilters()) { + if (operators.indexOf(fieldFilter.op) >= 0) { + return fieldFilter.op; + } + } + } + return null; +} +function validateQueryFilterConstraint(functionName, queryConstraint) { + if (!(queryConstraint instanceof QueryFieldFilterConstraint) && + !(queryConstraint instanceof QueryCompositeFilterConstraint)) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `Function ${functionName}() requires AppliableConstraints created with a call to 'where(...)', 'or(...)', or 'and(...)'.`); + } +} +function validateQueryConstraintArray(queryConstraint) { + const compositeFilterCount = queryConstraint.filter(filter => filter instanceof QueryCompositeFilterConstraint).length; + const fieldFilterCount = queryConstraint.filter(filter => filter instanceof QueryFieldFilterConstraint).length; + if (compositeFilterCount > 1 || + (compositeFilterCount > 0 && fieldFilterCount > 0)) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'InvalidQuery. When using composite filters, you cannot use ' + + 'more than one filter at the top level. Consider nesting the multiple ' + + 'filters within an `and(...)` statement. For example: ' + + 'change `query(query, where(...), or(...))` to ' + + '`query(query, and(where(...), or(...)))`.'); + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Converts Firestore's internal types to the JavaScript types that we expose + * to the user. + * + * @internal + */ +class AbstractUserDataWriter { + convertValue(value, serverTimestampBehavior = 'none') { + switch (typeOrder(value)) { + case 0 /* TypeOrder.NullValue */: + return null; + case 1 /* TypeOrder.BooleanValue */: + return value.booleanValue; + case 2 /* TypeOrder.NumberValue */: + return normalizeNumber(value.integerValue || value.doubleValue); + case 3 /* TypeOrder.TimestampValue */: + return this.convertTimestamp(value.timestampValue); + case 4 /* TypeOrder.ServerTimestampValue */: + return this.convertServerTimestamp(value, serverTimestampBehavior); + case 5 /* TypeOrder.StringValue */: + return value.stringValue; + case 6 /* TypeOrder.BlobValue */: + return this.convertBytes(normalizeByteString(value.bytesValue)); + case 7 /* TypeOrder.RefValue */: + return this.convertReference(value.referenceValue); + case 8 /* TypeOrder.GeoPointValue */: + return this.convertGeoPoint(value.geoPointValue); + case 9 /* TypeOrder.ArrayValue */: + return this.convertArray(value.arrayValue, serverTimestampBehavior); + case 11 /* TypeOrder.ObjectValue */: + return this.convertObject(value.mapValue, serverTimestampBehavior); + case 10 /* TypeOrder.VectorValue */: + return this.convertVectorValue(value.mapValue); + default: + throw fail(0xf2a2, { + value + }); + } + } + convertObject(mapValue, serverTimestampBehavior) { + return this.convertObjectMap(mapValue.fields, serverTimestampBehavior); + } + /** + * @internal + */ + convertObjectMap(fields, serverTimestampBehavior = 'none') { + const result = {}; + forEach(fields, (key, value) => { + result[key] = this.convertValue(value, serverTimestampBehavior); + }); + return result; + } + /** + * @internal + */ + convertVectorValue(mapValue) { + const values = mapValue.fields?.[VECTOR_MAP_VECTORS_KEY].arrayValue?.values?.map(value => { + return normalizeNumber(value.doubleValue); + }); + return new VectorValue(values); + } + convertGeoPoint(value) { + return new GeoPoint(normalizeNumber(value.latitude), normalizeNumber(value.longitude)); + } + convertArray(arrayValue, serverTimestampBehavior) { + return (arrayValue.values || []).map(value => this.convertValue(value, serverTimestampBehavior)); + } + convertServerTimestamp(value, serverTimestampBehavior) { + switch (serverTimestampBehavior) { + case 'previous': + const previousValue = getPreviousValue(value); + if (previousValue == null) { + return null; + } + return this.convertValue(previousValue, serverTimestampBehavior); + case 'estimate': + return this.convertTimestamp(getLocalWriteTime(value)); + default: + return null; + } + } + convertTimestamp(value) { + const normalizedValue = normalizeTimestamp(value); + return new Timestamp(normalizedValue.seconds, normalizedValue.nanos); + } + convertDocumentKey(name, expectedDatabaseId) { + const resourcePath = ResourcePath.fromString(name); + hardAssert(isValidResourceName(resourcePath), 0x25d8, { name }); + const databaseId = new DatabaseId(resourcePath.get(1), resourcePath.get(3)); + const key = new DocumentKey(resourcePath.popFirst(5)); + if (!databaseId.isEqual(expectedDatabaseId)) { + // TODO(b/64130202): Somehow support foreign references. + logError(`Document ${key} contains a document ` + + `reference within a different database (` + + `${databaseId.projectId}/${databaseId.database}) which is not ` + + `supported. It will be treated as a reference in the current ` + + `database (${expectedDatabaseId.projectId}/${expectedDatabaseId.database}) ` + + `instead.`); + } + return key; + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Converts custom model object of type T into `DocumentData` by applying the + * converter if it exists. + * + * This function is used when converting user objects to `DocumentData` + * because we want to provide the user with a more specific error message if + * their `set()` or fails due to invalid data originating from a `toFirestore()` + * call. + */ +function applyFirestoreDataConverter(converter, value, options) { + let convertedValue; + if (converter) { + if (options && (options.merge || options.mergeFields)) { + // Cast to `any` in order to satisfy the union type constraint on + // toFirestore(). + // eslint-disable-next-line @typescript-eslint/no-explicit-any + convertedValue = converter.toFirestore(value, options); + } + else { + convertedValue = converter.toFirestore(value); + } + } + else { + convertedValue = value; + } + return convertedValue; +} +class LiteUserDataWriter extends AbstractUserDataWriter { + constructor(firestore) { + super(); + this.firestore = firestore; + } + convertBytes(bytes) { + return new Bytes(bytes); + } + convertReference(name) { + const key = this.convertDocumentKey(name, this.firestore._databaseId); + return new DocumentReference(this.firestore, /* converter= */ null, key); + } +} +/** + * Reads the document referred to by the specified document reference. + * + * All documents are directly fetched from the server, even if the document was + * previously read or modified. Recent modifications are only reflected in the + * retrieved `DocumentSnapshot` if they have already been applied by the + * backend. If the client is offline, the read fails. If you like to use + * caching or see local modifications, please use the full Firestore SDK. + * + * @param reference - The reference of the document to fetch. + * @returns A Promise resolved with a `DocumentSnapshot` containing the current + * document contents. + */ +function getDoc(reference) { + reference = cast(reference, DocumentReference); + const datastore = getDatastore(reference.firestore); + const userDataWriter = new LiteUserDataWriter(reference.firestore); + return invokeBatchGetDocumentsRpc(datastore, [reference._key]).then(result => { + hardAssert(result.length === 1, 0x3d02); + const document = result[0]; + return new DocumentSnapshot(reference.firestore, userDataWriter, reference._key, document.isFoundDocument() ? document : null, reference.converter); + }); +} +/** + * Executes the query and returns the results as a {@link QuerySnapshot}. + * + * All queries are executed directly by the server, even if the query was + * previously executed. Recent modifications are only reflected in the retrieved + * results if they have already been applied by the backend. If the client is + * offline, the operation fails. To see previously cached result and local + * modifications, use the full Firestore SDK. + * + * @param query - The `Query` to execute. + * @returns A Promise that will be resolved with the results of the query. + */ +function getDocs(query) { + query = cast(query, Query); + validateHasExplicitOrderByForLimitToLast(query._query); + const datastore = getDatastore(query.firestore); + const userDataWriter = new LiteUserDataWriter(query.firestore); + return invokeRunQueryRpc(datastore, query._query).then(result => { + const docs = result.map(doc => new QueryDocumentSnapshot(query.firestore, userDataWriter, doc.key, doc, query.converter)); + if (query._query.limitType === "L" /* LimitType.Last */) { + // Limit to last queries reverse the orderBy constraint that was + // specified by the user. As such, we need to reverse the order of the + // results to return the documents in the expected order. + docs.reverse(); + } + return new QuerySnapshot(query, docs); + }); +} +function setDoc(reference, data, options) { + reference = cast(reference, DocumentReference); + const convertedValue = applyFirestoreDataConverter(reference.converter, data, options); + const dataReader = newUserDataReader(reference.firestore); + const parsed = parseSetData(dataReader, 'setDoc', reference._key, convertedValue, reference.converter !== null, options); + const datastore = getDatastore(reference.firestore); + return invokeCommitRpc(datastore, [ + parsed.toMutation(reference._key, Precondition.none()) + ]); +} +function updateDoc(reference, fieldOrUpdateData, value, ...moreFieldsAndValues) { + reference = cast(reference, DocumentReference); + const dataReader = newUserDataReader(reference.firestore); + // For Compat types, we have to "extract" the underlying types before + // performing validation. + fieldOrUpdateData = getModularInstance(fieldOrUpdateData); + let parsed; + if (typeof fieldOrUpdateData === 'string' || + fieldOrUpdateData instanceof FieldPath) { + parsed = parseUpdateVarargs(dataReader, 'updateDoc', reference._key, fieldOrUpdateData, value, moreFieldsAndValues); + } + else { + parsed = parseUpdateData(dataReader, 'updateDoc', reference._key, fieldOrUpdateData); + } + const datastore = getDatastore(reference.firestore); + return invokeCommitRpc(datastore, [ + parsed.toMutation(reference._key, Precondition.exists(true)) + ]); +} +/** + * Deletes the document referred to by the specified `DocumentReference`. + * + * The deletion will only be reflected in document reads that occur after the + * returned promise resolves. If the client is offline, the + * delete fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @param reference - A reference to the document to delete. + * @returns A `Promise` resolved once the document has been successfully + * deleted from the backend. + */ +function deleteDoc(reference) { + reference = cast(reference, DocumentReference); + const datastore = getDatastore(reference.firestore); + return invokeCommitRpc(datastore, [ + new DeleteMutation(reference._key, Precondition.none()) + ]); +} +/** + * Add a new document to specified `CollectionReference` with the given data, + * assigning it a document ID automatically. + * + * The result of this write will only be reflected in document reads that occur + * after the returned promise resolves. If the client is offline, the + * write fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @param reference - A reference to the collection to add this document to. + * @param data - An Object containing the data for the new document. + * @throws Error - If the provided input is not a valid Firestore document. + * @returns A `Promise` resolved with a `DocumentReference` pointing to the + * newly created document after it has been written to the backend. + */ +function addDoc(reference, data) { + reference = cast(reference, CollectionReference); + const docRef = doc(reference); + const convertedValue = applyFirestoreDataConverter(reference.converter, data); + const dataReader = newUserDataReader(reference.firestore); + const parsed = parseSetData(dataReader, 'addDoc', docRef._key, convertedValue, docRef.converter !== null, {}); + const datastore = getDatastore(reference.firestore); + return invokeCommitRpc(datastore, [ + parsed.toMutation(docRef._key, Precondition.exists(false)) + ]).then(() => docRef); +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Calculates the number of documents in the result set of the given query + * without actually downloading the documents. + * + * Using this function to count the documents is efficient because only the + * final count, not the documents' data, is downloaded. This function can + * count the documents in cases where the result set is prohibitively large to + * download entirely (thousands of documents). + * + * @param query The query whose result set size is calculated. + * @returns A Promise that will be resolved with the count; the count can be + * retrieved from `snapshot.data().count`, where `snapshot` is the + * `AggregateQuerySnapshot` to which the returned Promise resolves. + */ +function getCount(query) { + const countQuerySpec = { + count: count() + }; + return getAggregate(query, countQuerySpec); +} +/** + * Calculates the specified aggregations over the documents in the result + * set of the given query without actually downloading the documents. + * + * Using this function to perform aggregations is efficient because only the + * final aggregation values, not the documents' data, are downloaded. This + * function can perform aggregations of the documents in cases where the result + * set is prohibitively large to download entirely (thousands of documents). + * + * @param query The query whose result set is aggregated over. + * @param aggregateSpec An `AggregateSpec` object that specifies the aggregates + * to perform over the result set. The AggregateSpec specifies aliases for each + * aggregate, which can be used to retrieve the aggregate result. + * @example + * ```typescript + * const aggregateSnapshot = await getAggregate(query, { + * countOfDocs: count(), + * totalHours: sum('hours'), + * averageScore: average('score') + * }); + * + * const countOfDocs: number = aggregateSnapshot.data().countOfDocs; + * const totalHours: number = aggregateSnapshot.data().totalHours; + * const averageScore: number | null = aggregateSnapshot.data().averageScore; + * ``` + */ +function getAggregate(query, aggregateSpec) { + const firestore = cast(query.firestore, Firestore); + const datastore = getDatastore(firestore); + const internalAggregates = mapToArray(aggregateSpec, (aggregate, alias) => { + return new AggregateImpl(alias, aggregate.aggregateType, aggregate._internalFieldPath); + }); + // Run the aggregation and convert the results + return invokeRunAggregationQueryRpc(datastore, query._query, internalAggregates).then(aggregateResult => convertToAggregateQuerySnapshot(firestore, query, aggregateResult)); +} +function convertToAggregateQuerySnapshot(firestore, query, aggregateResult) { + const userDataWriter = new LiteUserDataWriter(firestore); + const querySnapshot = new AggregateQuerySnapshot(query, userDataWriter, aggregateResult); + return querySnapshot; +} +/** + * Create an AggregateField object that can be used to compute the sum of + * a specified field over a range of documents in the result set of a query. + * @param field Specifies the field to sum across the result set. + */ +function sum(field) { + return new AggregateField('sum', fieldPathFromArgument$1('sum', field)); +} +/** + * Create an AggregateField object that can be used to compute the average of + * a specified field over a range of documents in the result set of a query. + * @param field Specifies the field to average across the result set. + */ +function average(field) { + return new AggregateField('avg', fieldPathFromArgument$1('average', field)); +} +/** + * Create an AggregateField object that can be used to compute the count of + * documents in the result set of a query. + */ +function count() { + return new AggregateField('count'); +} +/** + * Compares two 'AggregateField` instances for equality. + * + * @param left Compare this AggregateField to the `right`. + * @param right Compare this AggregateField to the `left`. + */ +function aggregateFieldEqual(left, right) { + return (left instanceof AggregateField && + right instanceof AggregateField && + left.aggregateType === right.aggregateType && + left._internalFieldPath?.canonicalString() === + right._internalFieldPath?.canonicalString()); +} +/** + * Compares two `AggregateQuerySnapshot` instances for equality. + * + * Two `AggregateQuerySnapshot` instances are considered "equal" if they have + * underlying queries that compare equal, and the same data. + * + * @param left - The first `AggregateQuerySnapshot` to compare. + * @param right - The second `AggregateQuerySnapshot` to compare. + * + * @returns `true` if the objects are "equal", as defined above, or `false` + * otherwise. + */ +function aggregateQuerySnapshotEqual(left, right) { + return (queryEqual(left.query, right.query) && deepEqual(left.data(), right.data())); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Returns a sentinel for use with {@link @firebase/firestore/lite#(updateDoc:1)} or + * {@link @firebase/firestore/lite#(setDoc:1)} with `{merge: true}` to mark a field for deletion. + */ +function deleteField() { + return new DeleteFieldValueImpl('deleteField'); +} +/** + * Returns a sentinel used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link @firebase/firestore/lite#(updateDoc:1)} to + * include a server-generated timestamp in the written data. + */ +function serverTimestamp() { + return new ServerTimestampFieldValueImpl('serverTimestamp'); +} +/** + * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link + * @firebase/firestore/lite#(updateDoc:1)} that tells the server to union the given elements with any array + * value that already exists on the server. Each specified element that doesn't + * already exist in the array will be added to the end. If the field being + * modified is not already an array it will be overwritten with an array + * containing exactly the specified elements. + * + * @param elements - The elements to union into the array. + * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or + * `updateDoc()`. + */ +function arrayUnion(...elements) { + // NOTE: We don't actually parse the data until it's used in set() or + // update() since we'd need the Firestore instance to do this. + return new ArrayUnionFieldValueImpl('arrayUnion', elements); +} +/** + * Returns a special value that can be used with {@link (setDoc:1)} or {@link + * updateDoc:1} that tells the server to remove the given elements from any + * array value that already exists on the server. All instances of each element + * specified will be removed from the array. If the field being modified is not + * already an array it will be overwritten with an empty array. + * + * @param elements - The elements to remove from the array. + * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or + * `updateDoc()` + */ +function arrayRemove(...elements) { + // NOTE: We don't actually parse the data until it's used in set() or + // update() since we'd need the Firestore instance to do this. + return new ArrayRemoveFieldValueImpl('arrayRemove', elements); +} +/** + * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link + * @firebase/firestore/lite#(updateDoc:1)} that tells the server to increment the field's current value by + * the given value. + * + * If either the operand or the current field value uses floating point + * precision, all arithmetic follows IEEE 754 semantics. If both values are + * integers, values outside of JavaScript's safe number range + * (`Number.MIN_SAFE_INTEGER` to `Number.MAX_SAFE_INTEGER`) are also subject to + * precision loss. Furthermore, once processed by the Firestore backend, all + * integer operations are capped between -2^63 and 2^63-1. + * + * If the current field value is not of type `number`, or if the field does not + * yet exist, the transformation sets the field to the given value. + * + * @param n - The value to increment by. + * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or + * `updateDoc()` + */ +function increment(n) { + return new NumericIncrementFieldValueImpl('increment', n); +} +/** + * Creates a new `VectorValue` constructed with a copy of the given array of numbers. + * + * @param values - Create a `VectorValue` instance with a copy of this array of numbers. + * + * @returns A new `VectorValue` constructed with a copy of the given array of numbers. + */ +function vector(values) { + return new VectorValue(values); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A write batch, used to perform multiple writes as a single atomic unit. + * + * A `WriteBatch` object can be acquired by calling {@link writeBatch}. It + * provides methods for adding writes to the write batch. None of the writes + * will be committed (or visible locally) until {@link WriteBatch.commit} is + * called. + */ +class WriteBatch { + /** @hideconstructor */ + constructor(_firestore, _commitHandler) { + this._firestore = _firestore; + this._commitHandler = _commitHandler; + this._mutations = []; + this._committed = false; + this._dataReader = newUserDataReader(_firestore); + } + set(documentRef, data, options) { + this._verifyNotCommitted(); + const ref = validateReference(documentRef, this._firestore); + const convertedValue = applyFirestoreDataConverter(ref.converter, data, options); + const parsed = parseSetData(this._dataReader, 'WriteBatch.set', ref._key, convertedValue, ref.converter !== null, options); + this._mutations.push(parsed.toMutation(ref._key, Precondition.none())); + return this; + } + update(documentRef, fieldOrUpdateData, value, ...moreFieldsAndValues) { + this._verifyNotCommitted(); + const ref = validateReference(documentRef, this._firestore); + // For Compat types, we have to "extract" the underlying types before + // performing validation. + fieldOrUpdateData = getModularInstance(fieldOrUpdateData); + let parsed; + if (typeof fieldOrUpdateData === 'string' || + fieldOrUpdateData instanceof FieldPath) { + parsed = parseUpdateVarargs(this._dataReader, 'WriteBatch.update', ref._key, fieldOrUpdateData, value, moreFieldsAndValues); + } + else { + parsed = parseUpdateData(this._dataReader, 'WriteBatch.update', ref._key, fieldOrUpdateData); + } + this._mutations.push(parsed.toMutation(ref._key, Precondition.exists(true))); + return this; + } + /** + * Deletes the document referred to by the provided {@link DocumentReference}. + * + * @param documentRef - A reference to the document to be deleted. + * @returns This `WriteBatch` instance. Used for chaining method calls. + */ + delete(documentRef) { + this._verifyNotCommitted(); + const ref = validateReference(documentRef, this._firestore); + this._mutations = this._mutations.concat(new DeleteMutation(ref._key, Precondition.none())); + return this; + } + /** + * Commits all of the writes in this write batch as a single atomic unit. + * + * The result of these writes will only be reflected in document reads that + * occur after the returned promise resolves. If the client is offline, the + * write fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @returns A `Promise` resolved once all of the writes in the batch have been + * successfully written to the backend as an atomic unit (note that it won't + * resolve while you're offline). + */ + commit() { + this._verifyNotCommitted(); + this._committed = true; + if (this._mutations.length > 0) { + return this._commitHandler(this._mutations); + } + return Promise.resolve(); + } + _verifyNotCommitted() { + if (this._committed) { + throw new FirestoreError(Code.FAILED_PRECONDITION, 'A write batch can no longer be used after commit() ' + + 'has been called.'); + } + } +} +function validateReference(documentRef, firestore) { + documentRef = getModularInstance(documentRef); + if (documentRef.firestore !== firestore) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Provided document reference is from a different Firestore instance.'); + } + else { + return documentRef; + } +} +/** + * Creates a write batch, used for performing multiple writes as a single + * atomic operation. The maximum number of writes allowed in a single WriteBatch + * is 500. + * + * The result of these writes will only be reflected in document reads that + * occur after the returned promise resolves. If the client is offline, the + * write fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @returns A `WriteBatch` that can be used to atomically execute multiple + * writes. + */ +function writeBatch(firestore) { + firestore = cast(firestore, Firestore); + const datastore = getDatastore(firestore); + return new WriteBatch(firestore, writes => invokeCommitRpc(datastore, writes)); +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const DEFAULT_TRANSACTION_OPTIONS = { + maxAttempts: 5 +}; +function validateTransactionOptions(options) { + if (options.maxAttempts < 1) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Max attempts must be at least 1'); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Internal transaction object responsible for accumulating the mutations to + * perform and the base versions for any documents read. + */ +class Transaction$1 { + constructor(datastore) { + this.datastore = datastore; + // The version of each document that was read during this transaction. + this.readVersions = new Map(); + this.mutations = []; + this.committed = false; + /** + * A deferred usage error that occurred previously in this transaction that + * will cause the transaction to fail once it actually commits. + */ + this.lastTransactionError = null; + /** + * Set of documents that have been written in the transaction. + * + * When there's more than one write to the same key in a transaction, any + * writes after the first are handled differently. + */ + this.writtenDocs = new Set(); + } + async lookup(keys) { + this.ensureCommitNotCalled(); + if (this.mutations.length > 0) { + this.lastTransactionError = new FirestoreError(Code.INVALID_ARGUMENT, 'Firestore transactions require all reads to be executed before all writes.'); + throw this.lastTransactionError; + } + const docs = await invokeBatchGetDocumentsRpc(this.datastore, keys); + docs.forEach(doc => this.recordVersion(doc)); + return docs; + } + set(key, data) { + this.write(data.toMutation(key, this.precondition(key))); + this.writtenDocs.add(key.toString()); + } + update(key, data) { + try { + this.write(data.toMutation(key, this.preconditionForUpdate(key))); + } + catch (e) { + this.lastTransactionError = e; + } + this.writtenDocs.add(key.toString()); + } + delete(key) { + this.write(new DeleteMutation(key, this.precondition(key))); + this.writtenDocs.add(key.toString()); + } + async commit() { + this.ensureCommitNotCalled(); + if (this.lastTransactionError) { + throw this.lastTransactionError; + } + const unwritten = this.readVersions; + // For each mutation, note that the doc was written. + this.mutations.forEach(mutation => { + unwritten.delete(mutation.key.toString()); + }); + // For each document that was read but not written to, we want to perform + // a `verify` operation. + unwritten.forEach((_, path) => { + const key = DocumentKey.fromPath(path); + this.mutations.push(new VerifyMutation(key, this.precondition(key))); + }); + await invokeCommitRpc(this.datastore, this.mutations); + this.committed = true; + } + recordVersion(doc) { + let docVersion; + if (doc.isFoundDocument()) { + docVersion = doc.version; + } + else if (doc.isNoDocument()) { + // Represent a deleted doc using SnapshotVersion.min(). + docVersion = SnapshotVersion.min(); + } + else { + throw fail(0xc542, { + documentName: doc.constructor.name + }); + } + const existingVersion = this.readVersions.get(doc.key.toString()); + if (existingVersion) { + if (!docVersion.isEqual(existingVersion)) { + // This transaction will fail no matter what. + throw new FirestoreError(Code.ABORTED, 'Document version changed between two reads.'); + } + } + else { + this.readVersions.set(doc.key.toString(), docVersion); + } + } + /** + * Returns the version of this document when it was read in this transaction, + * as a precondition, or no precondition if it was not read. + */ + precondition(key) { + const version = this.readVersions.get(key.toString()); + if (!this.writtenDocs.has(key.toString()) && version) { + if (version.isEqual(SnapshotVersion.min())) { + return Precondition.exists(false); + } + else { + return Precondition.updateTime(version); + } + } + else { + return Precondition.none(); + } + } + /** + * Returns the precondition for a document if the operation is an update. + */ + preconditionForUpdate(key) { + const version = this.readVersions.get(key.toString()); + // The first time a document is written, we want to take into account the + // read time and existence + if (!this.writtenDocs.has(key.toString()) && version) { + if (version.isEqual(SnapshotVersion.min())) { + // The document doesn't exist, so fail the transaction. + // This has to be validated locally because you can't send a + // precondition that a document does not exist without changing the + // semantics of the backend write to be an insert. This is the reverse + // of what we want, since we want to assert that the document doesn't + // exist but then send the update and have it fail. Since we can't + // express that to the backend, we have to validate locally. + // Note: this can change once we can send separate verify writes in the + // transaction. + throw new FirestoreError(Code.INVALID_ARGUMENT, "Can't update a document that doesn't exist."); + } + // Document exists, base precondition on document update time. + return Precondition.updateTime(version); + } + else { + // Document was not read, so we just use the preconditions for a blind + // update. + return Precondition.exists(true); + } + } + write(mutation) { + this.ensureCommitNotCalled(); + this.mutations.push(mutation); + } + ensureCommitNotCalled() { + } +} + +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * TransactionRunner encapsulates the logic needed to run and retry transactions + * with backoff. + */ +class TransactionRunner { + constructor(asyncQueue, datastore, options, updateFunction, deferred) { + this.asyncQueue = asyncQueue; + this.datastore = datastore; + this.options = options; + this.updateFunction = updateFunction; + this.deferred = deferred; + this.attemptsRemaining = options.maxAttempts; + this.backoff = new ExponentialBackoff(this.asyncQueue, "transaction_retry" /* TimerId.TransactionRetry */); + } + /** Runs the transaction and sets the result on deferred. */ + run() { + this.attemptsRemaining -= 1; + this.runWithBackOff(); + } + runWithBackOff() { + this.backoff.backoffAndRun(async () => { + const transaction = new Transaction$1(this.datastore); + const userPromise = this.tryRunUpdateFunction(transaction); + if (userPromise) { + userPromise + .then(result => { + this.asyncQueue.enqueueAndForget(() => { + return transaction + .commit() + .then(() => { + this.deferred.resolve(result); + }) + .catch(commitError => { + this.handleTransactionError(commitError); + }); + }); + }) + .catch(userPromiseError => { + this.handleTransactionError(userPromiseError); + }); + } + }); + } + tryRunUpdateFunction(transaction) { + try { + const userPromise = this.updateFunction(transaction); + if (isNullOrUndefined(userPromise) || + !userPromise.catch || + !userPromise.then) { + this.deferred.reject(Error('Transaction callback must return a Promise')); + return null; + } + return userPromise; + } + catch (error) { + // Do not retry errors thrown by user provided updateFunction. + this.deferred.reject(error); + return null; + } + } + handleTransactionError(error) { + if (this.attemptsRemaining > 0 && this.isRetryableTransactionError(error)) { + this.attemptsRemaining -= 1; + this.asyncQueue.enqueueAndForget(() => { + this.runWithBackOff(); + return Promise.resolve(); + }); + } + else { + this.deferred.reject(error); + } + } + isRetryableTransactionError(error) { + if (error?.name === 'FirebaseError') { + // In transactions, the backend will fail outdated reads with FAILED_PRECONDITION and + // non-matching document versions with ABORTED. These errors should be retried. + const code = error.code; + return (code === 'aborted' || + code === 'failed-precondition' || + code === 'already-exists' || + !isPermanentError(code)); + } + return false; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Represents an operation scheduled to be run in the future on an AsyncQueue. + * + * It is created via DelayedOperation.createAndSchedule(). + * + * Supports cancellation (via cancel()) and early execution (via skipDelay()). + * + * Note: We implement `PromiseLike` instead of `Promise`, as the `Promise` type + * in newer versions of TypeScript defines `finally`, which is not available in + * IE. + */ +class DelayedOperation { + constructor(asyncQueue, timerId, targetTimeMs, op, removalCallback) { + this.asyncQueue = asyncQueue; + this.timerId = timerId; + this.targetTimeMs = targetTimeMs; + this.op = op; + this.removalCallback = removalCallback; + this.deferred = new Deferred(); + this.then = this.deferred.promise.then.bind(this.deferred.promise); + // It's normal for the deferred promise to be canceled (due to cancellation) + // and so we attach a dummy catch callback to avoid + // 'UnhandledPromiseRejectionWarning' log spam. + this.deferred.promise.catch(err => { }); + } + get promise() { + return this.deferred.promise; + } + /** + * Creates and returns a DelayedOperation that has been scheduled to be + * executed on the provided asyncQueue after the provided delayMs. + * + * @param asyncQueue - The queue to schedule the operation on. + * @param id - A Timer ID identifying the type of operation this is. + * @param delayMs - The delay (ms) before the operation should be scheduled. + * @param op - The operation to run. + * @param removalCallback - A callback to be called synchronously once the + * operation is executed or canceled, notifying the AsyncQueue to remove it + * from its delayedOperations list. + * PORTING NOTE: This exists to prevent making removeDelayedOperation() and + * the DelayedOperation class public. + */ + static createAndSchedule(asyncQueue, timerId, delayMs, op, removalCallback) { + const targetTime = Date.now() + delayMs; + const delayedOp = new DelayedOperation(asyncQueue, timerId, targetTime, op, removalCallback); + delayedOp.start(delayMs); + return delayedOp; + } + /** + * Starts the timer. This is called immediately after construction by + * createAndSchedule(). + */ + start(delayMs) { + this.timerHandle = setTimeout(() => this.handleDelayElapsed(), delayMs); + } + /** + * Queues the operation to run immediately (if it hasn't already been run or + * canceled). + */ + skipDelay() { + return this.handleDelayElapsed(); + } + /** + * Cancels the operation if it hasn't already been executed or canceled. The + * promise will be rejected. + * + * As long as the operation has not yet been run, calling cancel() provides a + * guarantee that the operation will not be run. + */ + cancel(reason) { + if (this.timerHandle !== null) { + this.clearTimeout(); + this.deferred.reject(new FirestoreError(Code.CANCELLED, 'Operation cancelled' + (reason ? ': ' + reason : ''))); + } + } + handleDelayElapsed() { + this.asyncQueue.enqueueAndForget(() => { + if (this.timerHandle !== null) { + this.clearTimeout(); + return this.op().then(result => { + return this.deferred.resolve(result); + }); + } + else { + return Promise.resolve(); + } + }); + } + clearTimeout() { + if (this.timerHandle !== null) { + this.removalCallback(this); + clearTimeout(this.timerHandle); + this.timerHandle = null; + } + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const LOG_TAG = 'AsyncQueue'; +class AsyncQueueImpl { + constructor(tail = Promise.resolve()) { + // A list of retryable operations. Retryable operations are run in order and + // retried with backoff. + this.retryableOps = []; + // Is this AsyncQueue being shut down? Once it is set to true, it will not + // be changed again. + this._isShuttingDown = false; + // Operations scheduled to be queued in the future. Operations are + // automatically removed after they are run or canceled. + this.delayedOperations = []; + // visible for testing + this.failure = null; + // Flag set while there's an outstanding AsyncQueue operation, used for + // assertion sanity-checks. + this.operationInProgress = false; + // Enabled during shutdown on Safari to prevent future access to IndexedDB. + this.skipNonRestrictedTasks = false; + // List of TimerIds to fast-forward delays for. + this.timerIdsToSkip = []; + // Backoff timer used to schedule retries for retryable operations + this.backoff = new ExponentialBackoff(this, "async_queue_retry" /* TimerId.AsyncQueueRetry */); + // Visibility handler that triggers an immediate retry of all retryable + // operations. Meant to speed up recovery when we regain file system access + // after page comes into foreground. + this.visibilityHandler = () => { + this.backoff.skipBackoff(); + }; + this.tail = tail; + } + get isShuttingDown() { + return this._isShuttingDown; + } + /** + * Adds a new operation to the queue without waiting for it to complete (i.e. + * we ignore the Promise result). + */ + enqueueAndForget(op) { + // eslint-disable-next-line @typescript-eslint/no-floating-promises + this.enqueue(op); + } + enqueueAndForgetEvenWhileRestricted(op) { + this.verifyNotFailed(); + // eslint-disable-next-line @typescript-eslint/no-floating-promises + this.enqueueInternal(op); + } + enterRestrictedMode(purgeExistingTasks) { + if (!this._isShuttingDown) { + this._isShuttingDown = true; + this.skipNonRestrictedTasks = purgeExistingTasks || false; + } + } + enqueue(op) { + this.verifyNotFailed(); + if (this._isShuttingDown) { + // Return a Promise which never resolves. + return new Promise(() => { }); + } + // Create a deferred Promise that we can return to the callee. This + // allows us to return a "hanging Promise" only to the callee and still + // advance the queue even when the operation is not run. + const task = new Deferred(); + return this.enqueueInternal(() => { + if (this._isShuttingDown && this.skipNonRestrictedTasks) { + // We do not resolve 'task' + return Promise.resolve(); + } + op().then(task.resolve, task.reject); + return task.promise; + }).then(() => task.promise); + } + enqueueRetryable(op) { + this.enqueueAndForget(() => { + this.retryableOps.push(op); + return this.retryNextOp(); + }); + } + /** + * Runs the next operation from the retryable queue. If the operation fails, + * reschedules with backoff. + */ + async retryNextOp() { + if (this.retryableOps.length === 0) { + return; + } + try { + await this.retryableOps[0](); + this.retryableOps.shift(); + this.backoff.reset(); + } + catch (e) { + if (isIndexedDbTransactionError(e)) { + logDebug(LOG_TAG, 'Operation failed with retryable error: ' + e); + } + else { + throw e; // Failure will be handled by AsyncQueue + } + } + if (this.retryableOps.length > 0) { + // If there are additional operations, we re-schedule `retryNextOp()`. + // This is necessary to run retryable operations that failed during + // their initial attempt since we don't know whether they are already + // enqueued. If, for example, `op1`, `op2`, `op3` are enqueued and `op1` + // needs to be re-run, we will run `op1`, `op1`, `op2` using the + // already enqueued calls to `retryNextOp()`. `op3()` will then run in the + // call scheduled here. + // Since `backoffAndRun()` cancels an existing backoff and schedules a + // new backoff on every call, there is only ever a single additional + // operation in the queue. + this.backoff.backoffAndRun(() => this.retryNextOp()); + } + } + enqueueInternal(op) { + const newTail = this.tail.then(() => { + this.operationInProgress = true; + return op() + .catch((error) => { + this.failure = error; + this.operationInProgress = false; + const message = getMessageOrStack(error); + logError('INTERNAL UNHANDLED ERROR: ', message); + // Re-throw the error so that this.tail becomes a rejected Promise and + // all further attempts to chain (via .then) will just short-circuit + // and return the rejected Promise. + throw error; + }) + .then(result => { + this.operationInProgress = false; + return result; + }); + }); + this.tail = newTail; + return newTail; + } + enqueueAfterDelay(timerId, delayMs, op) { + this.verifyNotFailed(); + // Fast-forward delays for timerIds that have been overridden. + if (this.timerIdsToSkip.indexOf(timerId) > -1) { + delayMs = 0; + } + const delayedOp = DelayedOperation.createAndSchedule(this, timerId, delayMs, op, removedOp => this.removeDelayedOperation(removedOp)); + this.delayedOperations.push(delayedOp); + return delayedOp; + } + verifyNotFailed() { + if (this.failure) { + fail(0xb815, { + messageOrStack: getMessageOrStack(this.failure) + }); + } + } + verifyOperationInProgress() { + } + /** + * Waits until all currently queued tasks are finished executing. Delayed + * operations are not run. + */ + async drain() { + // Operations in the queue prior to draining may have enqueued additional + // operations. Keep draining the queue until the tail is no longer advanced, + // which indicates that no more new operations were enqueued and that all + // operations were executed. + let currentTail; + do { + currentTail = this.tail; + await currentTail; + } while (currentTail !== this.tail); + } + /** + * For Tests: Determine if a delayed operation with a particular TimerId + * exists. + */ + containsDelayedOperation(timerId) { + for (const op of this.delayedOperations) { + if (op.timerId === timerId) { + return true; + } + } + return false; + } + /** + * For Tests: Runs some or all delayed operations early. + * + * @param lastTimerId - Delayed operations up to and including this TimerId + * will be drained. Pass TimerId.All to run all delayed operations. + * @returns a Promise that resolves once all operations have been run. + */ + runAllDelayedOperationsUntil(lastTimerId) { + // Note that draining may generate more delayed ops, so we do that first. + return this.drain().then(() => { + // Run ops in the same order they'd run if they ran naturally. + /* eslint-disable-next-line @typescript-eslint/no-floating-promises */ + this.delayedOperations.sort((a, b) => a.targetTimeMs - b.targetTimeMs); + for (const op of this.delayedOperations) { + op.skipDelay(); + if (lastTimerId !== "all" /* TimerId.All */ && op.timerId === lastTimerId) { + break; + } + } + return this.drain(); + }); + } + /** + * For Tests: Skip all subsequent delays for a timer id. + */ + skipDelaysForTimerId(timerId) { + this.timerIdsToSkip.push(timerId); + } + /** Called once a DelayedOperation is run or canceled. */ + removeDelayedOperation(op) { + // NOTE: indexOf / slice are O(n), but delayedOperations is expected to be small. + const index = this.delayedOperations.indexOf(op); + /* eslint-disable-next-line @typescript-eslint/no-floating-promises */ + this.delayedOperations.splice(index, 1); + } +} +function newAsyncQueue() { + return new AsyncQueueImpl(); +} +/** + * Chrome includes Error.message in Error.stack. Other browsers do not. + * This returns expected output of message + stack when available. + * @param error - Error or FirestoreError + */ +function getMessageOrStack(error) { + let message = error.message || ''; + if (error.stack) { + if (error.stack.includes(error.message)) { + message = error.stack; + } + else { + message = error.message + '\n' + error.stack; + } + } + return message; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// TODO(mrschmidt) Consider using `BaseTransaction` as the base class in the +// legacy SDK. +/** + * A reference to a transaction. + * + * The `Transaction` object passed to a transaction's `updateFunction` provides + * the methods to read and write data within the transaction context. See + * {@link runTransaction}. + */ +class Transaction { + /** @hideconstructor */ + constructor(_firestore, _transaction) { + this._firestore = _firestore; + this._transaction = _transaction; + this._dataReader = newUserDataReader(_firestore); + } + /** + * Reads the document referenced by the provided {@link DocumentReference}. + * + * @param documentRef - A reference to the document to be read. + * @returns A `DocumentSnapshot` with the read data. + */ + get(documentRef) { + const ref = validateReference(documentRef, this._firestore); + const userDataWriter = new LiteUserDataWriter(this._firestore); + return this._transaction.lookup([ref._key]).then(docs => { + if (!docs || docs.length !== 1) { + return fail(0x5de9); + } + const doc = docs[0]; + if (doc.isFoundDocument()) { + return new DocumentSnapshot(this._firestore, userDataWriter, doc.key, doc, ref.converter); + } + else if (doc.isNoDocument()) { + return new DocumentSnapshot(this._firestore, userDataWriter, ref._key, null, ref.converter); + } + else { + throw fail(0x4801, { + doc + }); + } + }); + } + set(documentRef, value, options) { + const ref = validateReference(documentRef, this._firestore); + const convertedValue = applyFirestoreDataConverter(ref.converter, value, options); + const parsed = parseSetData(this._dataReader, 'Transaction.set', ref._key, convertedValue, ref.converter !== null, options); + this._transaction.set(ref._key, parsed); + return this; + } + update(documentRef, fieldOrUpdateData, value, ...moreFieldsAndValues) { + const ref = validateReference(documentRef, this._firestore); + // For Compat types, we have to "extract" the underlying types before + // performing validation. + fieldOrUpdateData = getModularInstance(fieldOrUpdateData); + let parsed; + if (typeof fieldOrUpdateData === 'string' || + fieldOrUpdateData instanceof FieldPath) { + parsed = parseUpdateVarargs(this._dataReader, 'Transaction.update', ref._key, fieldOrUpdateData, value, moreFieldsAndValues); + } + else { + parsed = parseUpdateData(this._dataReader, 'Transaction.update', ref._key, fieldOrUpdateData); + } + this._transaction.update(ref._key, parsed); + return this; + } + /** + * Deletes the document referred to by the provided {@link DocumentReference}. + * + * @param documentRef - A reference to the document to be deleted. + * @returns This `Transaction` instance. Used for chaining method calls. + */ + delete(documentRef) { + const ref = validateReference(documentRef, this._firestore); + this._transaction.delete(ref._key); + return this; + } +} +/** + * Executes the given `updateFunction` and then attempts to commit the changes + * applied within the transaction. If any document read within the transaction + * has changed, Cloud Firestore retries the `updateFunction`. If it fails to + * commit after 5 attempts, the transaction fails. + * + * The maximum number of writes allowed in a single transaction is 500. + * + * @param firestore - A reference to the Firestore database to run this + * transaction against. + * @param updateFunction - The function to execute within the transaction + * context. + * @param options - An options object to configure maximum number of attempts to + * commit. + * @returns If the transaction completed successfully or was explicitly aborted + * (the `updateFunction` returned a failed promise), the promise returned by the + * `updateFunction `is returned here. Otherwise, if the transaction failed, a + * rejected promise with the corresponding failure error is returned. + */ +function runTransaction(firestore, updateFunction, options) { + firestore = cast(firestore, Firestore); + const datastore = getDatastore(firestore); + const optionsWithDefaults = { + ...DEFAULT_TRANSACTION_OPTIONS, + ...options + }; + validateTransactionOptions(optionsWithDefaults); + const deferred = new Deferred(); + new TransactionRunner(newAsyncQueue(), datastore, optionsWithDefaults, internalTransaction => updateFunction(new Transaction(firestore, internalTransaction)), deferred).run(); + return deferred.promise; +} + +/** + * Firestore Lite + * + * @remarks Firestore Lite is a small online-only SDK that allows read + * and write access to your Firestore database. All operations connect + * directly to the backend, and `onSnapshot()` APIs are not supported. + * @packageDocumentation + */ +registerFirestore(); + +export { AggregateField, AggregateQuerySnapshot, Bytes, CollectionReference, DocumentReference, DocumentSnapshot, FieldPath, FieldValue, Firestore, FirestoreError, GeoPoint, Query, QueryCompositeFilterConstraint, QueryConstraint, QueryDocumentSnapshot, QueryEndAtConstraint, QueryFieldFilterConstraint, QueryLimitConstraint, QueryOrderByConstraint, QuerySnapshot, QueryStartAtConstraint, Timestamp, Transaction, VectorValue, WriteBatch, addDoc, aggregateFieldEqual, aggregateQuerySnapshotEqual, and, arrayRemove, arrayUnion, average, collection, collectionGroup, connectFirestoreEmulator, count, deleteDoc, deleteField, doc, documentId, endAt, endBefore, getAggregate, getCount, getDoc, getDocs, getFirestore, increment, initializeFirestore, limit, limitToLast, or, orderBy, query, queryEqual, refEqual, runTransaction, serverTimestamp, setDoc, setLogLevel, snapshotEqual, startAfter, startAt, sum, terminate, updateDoc, vector, where, writeBatch }; +//# sourceMappingURL=index.node.mjs.map diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/index.node.mjs.map b/frontend-old/node_modules/@firebase/firestore/dist/lite/index.node.mjs.map new file mode 100644 index 0000000..721a689 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/index.node.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"index.node.mjs","sources":["../../src/auth/user.ts","../../src/core/version.ts","../../src/platform/node/format_json.ts","../../src/util/log.ts","../../src/util/assert.ts","../../src/util/error.ts","../../src/util/promise.ts","../../src/api/credentials.ts","../../src/core/database_info.ts","../../src/platform/node/random_bytes.ts","../../src/util/misc.ts","../../src/model/path.ts","../../src/model/document_key.ts","../../src/util/input_validation.ts","../../src/api/long_polling_options.ts","../../src/util/debug_uid.ts","../../src/remote/rest_connection.ts","../../src/remote/rpc_error.ts","../../src/platform/browser_lite/fetch_connection.ts","../../src/platform/node_lite/connection.ts","../../src/util/obj.ts","../../src/util/types.ts","../../src/platform/node/base64.ts","../../src/util/byte_string.ts","../../src/model/normalize.ts","../../src/util/json_validation.ts","../../src/lite-api/timestamp.ts","../../src/model/server_timestamps.ts","../../src/model/values.ts","../../src/core/bound.ts","../../src/core/filter.ts","../../src/core/order_by.ts","../../src/core/snapshot_version.ts","../../src/util/sorted_map.ts","../../src/util/sorted_set.ts","../../src/model/field_mask.ts","../../src/model/object_value.ts","../../src/model/document.ts","../../src/core/target.ts","../../src/core/query.ts","../../src/remote/number_serializer.ts","../../src/model/transform_operation.ts","../../src/model/mutation.ts","../../src/remote/serializer.ts","../../src/platform/browser/serializer.ts","../../src/remote/backoff.ts","../../src/remote/datastore.ts","../../src/lite-api/components.ts","../../src/local/lru_garbage_collector.ts","../../src/local/simple_db.ts","../../src/local/lru_garbage_collector_impl.ts","../../src/lite-api/settings.ts","../../src/lite-api/database.ts","../../lite/register.ts","../../src/core/aggregate.ts","../../src/lite-api/aggregate_types.ts","../../src/lite-api/reference.ts","../../src/lite-api/bytes.ts","../../src/lite-api/field_path.ts","../../src/lite-api/field_value.ts","../../src/lite-api/geo_point.ts","../../src/util/array.ts","../../src/lite-api/vector_value.ts","../../src/lite-api/user_data_reader.ts","../../src/lite-api/snapshot.ts","../../src/lite-api/query.ts","../../src/lite-api/user_data_writer.ts","../../src/lite-api/reference_impl.ts","../../src/lite-api/aggregate.ts","../../src/lite-api/field_value_impl.ts","../../src/lite-api/write_batch.ts","../../src/core/transaction_options.ts","../../src/core/transaction.ts","../../src/core/transaction_runner.ts","../../src/util/async_queue.ts","../../src/util/async_queue_impl.ts","../../src/lite-api/transaction.ts","../../lite/index.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Simple wrapper around a nullable UID. Mostly exists to make code more\n * readable.\n */\nexport class User {\n /** A user with a null UID. */\n static readonly UNAUTHENTICATED = new User(null);\n\n // TODO(mikelehen): Look into getting a proper uid-equivalent for\n // non-FirebaseAuth providers.\n static readonly GOOGLE_CREDENTIALS = new User('google-credentials-uid');\n static readonly FIRST_PARTY = new User('first-party-uid');\n static readonly MOCK_USER = new User('mock-user');\n\n constructor(readonly uid: string | null) {}\n\n isAuthenticated(): boolean {\n return this.uid != null;\n }\n\n /**\n * Returns a key representing this user, suitable for inclusion in a\n * dictionary.\n */\n toKey(): string {\n if (this.isAuthenticated()) {\n return 'uid:' + this.uid;\n } else {\n return 'anonymous-user';\n }\n }\n\n isEqual(otherUser: User): boolean {\n return otherUser.uid === this.uid;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** The semver (www.semver.org) version of the SDK. */\nimport { version } from '../../../firebase/package.json';\nexport let SDK_VERSION = version;\nexport function setSDKVersion(version: string): void {\n SDK_VERSION = version;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { inspect } from 'util';\n\n/** Formats an object as a JSON string, suitable for logging. */\nexport function formatJSON(value: unknown): string {\n // util.inspect() results in much more readable output than JSON.stringify()\n return inspect(value, { depth: 100 });\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Logger, LogLevel, LogLevelString } from '@firebase/logger';\n\nimport { SDK_VERSION } from '../core/version';\nimport { formatJSON } from '../platform/format_json';\n\nexport { LogLevel, LogLevelString };\n\nconst logClient = new Logger('@firebase/firestore');\n\n// Helper methods are needed because variables can't be exported as read/write\nexport function getLogLevel(): LogLevel {\n return logClient.logLevel;\n}\n\n/**\n * Sets the verbosity of Cloud Firestore logs (debug, error, or silent).\n *\n * @param logLevel - The verbosity you set for activity and error logging. Can\n * be any of the following values:\n *\n *
    \n *
  • `debug` for the most verbose logging level, primarily for\n * debugging.
  • \n *
  • `error` to log errors only.
  • \n *
  • `silent` to turn off logging.
  • \n *
\n */\nexport function setLogLevel(logLevel: LogLevelString): void {\n logClient.setLogLevel(logLevel);\n}\n\nexport function logDebug(msg: string, ...obj: unknown[]): void {\n if (logClient.logLevel <= LogLevel.DEBUG) {\n const args = obj.map(argToString);\n logClient.debug(`Firestore (${SDK_VERSION}): ${msg}`, ...args);\n }\n}\n\nexport function logError(msg: string, ...obj: unknown[]): void {\n if (logClient.logLevel <= LogLevel.ERROR) {\n const args = obj.map(argToString);\n logClient.error(`Firestore (${SDK_VERSION}): ${msg}`, ...args);\n }\n}\n\n/**\n * @internal\n */\nexport function logWarn(msg: string, ...obj: unknown[]): void {\n if (logClient.logLevel <= LogLevel.WARN) {\n const args = obj.map(argToString);\n logClient.warn(`Firestore (${SDK_VERSION}): ${msg}`, ...args);\n }\n}\n\n/**\n * Converts an additional log parameter to a string representation.\n */\nfunction argToString(obj: unknown): string | unknown {\n if (typeof obj === 'string') {\n return obj;\n } else {\n try {\n return formatJSON(obj);\n } catch (e) {\n // Converting to JSON failed, just log the object directly\n return obj;\n }\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SDK_VERSION } from '../core/version';\n\nimport { logError } from './log';\n\n/**\n * Unconditionally fails, throwing an Error with the given message.\n * Messages are stripped in production builds.\n *\n * Returns `never` and can be used in expressions:\n * @example\n * let futureVar = fail('not implemented yet');\n *\n * @param code generate a new unique value with `yarn assertion-id:generate`\n * Search for an existing value using `yarn assertion-id:find X`\n */\nexport function fail(\n code: number,\n message: string,\n context?: Record\n): never;\n\n/**\n * Unconditionally fails, throwing an Error with the given message.\n * Messages are stripped in production builds.\n *\n * Returns `never` and can be used in expressions:\n * @example\n * let futureVar = fail('not implemented yet');\n *\n * @param id generate a new unique value with `yarn assertion-id:generate`\n * Search for an existing value using `yarn assertion-id:find X`\n */\nexport function fail(id: number, context?: Record): never;\n\nexport function fail(\n id: number,\n messageOrContext?: string | Record,\n context?: Record\n): never {\n let message = 'Unexpected state';\n if (typeof messageOrContext === 'string') {\n message = messageOrContext;\n } else {\n context = messageOrContext;\n }\n _fail(id, message, context);\n}\n\nfunction _fail(\n id: number,\n failure: string,\n context?: Record\n): never {\n // Log the failure in addition to throw an exception, just in case the\n // exception is swallowed.\n let message = `FIRESTORE (${SDK_VERSION}) INTERNAL ASSERTION FAILED: ${failure} (ID: ${id.toString(\n 16\n )})`;\n if (context !== undefined) {\n try {\n const stringContext = JSON.stringify(context);\n message += ' CONTEXT: ' + stringContext;\n } catch (e) {\n message += ' CONTEXT: ' + context;\n }\n }\n logError(message);\n\n // NOTE: We don't use FirestoreError here because these are internal failures\n // that cannot be handled by the user. (Also it would create a circular\n // dependency between the error and assert modules which doesn't work.)\n throw new Error(message);\n}\n\n/**\n * Fails if the given assertion condition is false, throwing an Error with the\n * given message if it did.\n *\n * Messages are stripped in production builds.\n *\n * @param id generate a new unique value with `yarn assertion-idgenerate`.\n * Search for an existing value using `yarn assertion-id:find X`\n */\nexport function hardAssert(\n assertion: boolean,\n id: number,\n message: string,\n context?: Record\n): asserts assertion;\n\n/**\n * Fails if the given assertion condition is false, throwing an Error with the\n * given message if it did.\n *\n * Messages are stripped in production builds.\n *\n * @param id generate a new unique value with `yarn assertion-id:generate`.\n * Search for an existing value using `yarn assertion-id:find X`\n */\nexport function hardAssert(\n assertion: boolean,\n id: number,\n context?: Record\n): asserts assertion;\n\nexport function hardAssert(\n assertion: boolean,\n id: number,\n messageOrContext?: string | Record,\n context?: Record\n): asserts assertion {\n let message = 'Unexpected state';\n if (typeof messageOrContext === 'string') {\n message = messageOrContext;\n } else {\n context = messageOrContext;\n }\n\n if (!assertion) {\n _fail(id, message, context);\n }\n}\n\n/**\n * Fails if the given assertion condition is false, throwing an Error with the\n * given message if it did.\n *\n * The code of callsites invoking this function are stripped out in production\n * builds. Any side-effects of code within the debugAssert() invocation will not\n * happen in this case.\n *\n * @internal\n */\nexport function debugAssert(\n assertion: boolean,\n message: string\n): asserts assertion {\n if (!assertion) {\n fail(0xdeb6, message);\n }\n}\n\n/**\n * Casts `obj` to `T`. In non-production builds, verifies that `obj` is an\n * instance of `T` before casting.\n */\nexport function debugCast(\n obj: object,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n constructor: { new (...args: any[]): T }\n): T | never {\n debugAssert(\n obj instanceof constructor,\n `Expected type '${constructor.name}', but was '${obj.constructor.name}'`\n );\n return obj as T;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseError } from '@firebase/util';\n\n/**\n * The set of Firestore status codes. The codes are the same at the ones\n * exposed by gRPC here:\n * https://github.com/grpc/grpc/blob/master/doc/statuscodes.md\n *\n * Possible values:\n * - 'cancelled': The operation was cancelled (typically by the caller).\n * - 'unknown': Unknown error or an error from a different error domain.\n * - 'invalid-argument': Client specified an invalid argument. Note that this\n * differs from 'failed-precondition'. 'invalid-argument' indicates\n * arguments that are problematic regardless of the state of the system\n * (e.g. an invalid field name).\n * - 'deadline-exceeded': Deadline expired before operation could complete.\n * For operations that change the state of the system, this error may be\n * returned even if the operation has completed successfully. For example,\n * a successful response from a server could have been delayed long enough\n * for the deadline to expire.\n * - 'not-found': Some requested document was not found.\n * - 'already-exists': Some document that we attempted to create already\n * exists.\n * - 'permission-denied': The caller does not have permission to execute the\n * specified operation.\n * - 'resource-exhausted': Some resource has been exhausted, perhaps a\n * per-user quota, or perhaps the entire file system is out of space.\n * - 'failed-precondition': Operation was rejected because the system is not\n * in a state required for the operation's execution.\n * - 'aborted': The operation was aborted, typically due to a concurrency\n * issue like transaction aborts, etc.\n * - 'out-of-range': Operation was attempted past the valid range.\n * - 'unimplemented': Operation is not implemented or not supported/enabled.\n * - 'internal': Internal errors. Means some invariants expected by\n * underlying system has been broken. If you see one of these errors,\n * something is very broken.\n * - 'unavailable': The service is currently unavailable. This is most likely\n * a transient condition and may be corrected by retrying with a backoff.\n * - 'data-loss': Unrecoverable data loss or corruption.\n * - 'unauthenticated': The request does not have valid authentication\n * credentials for the operation.\n */\nexport type FirestoreErrorCode =\n | 'cancelled'\n | 'unknown'\n | 'invalid-argument'\n | 'deadline-exceeded'\n | 'not-found'\n | 'already-exists'\n | 'permission-denied'\n | 'resource-exhausted'\n | 'failed-precondition'\n | 'aborted'\n | 'out-of-range'\n | 'unimplemented'\n | 'internal'\n | 'unavailable'\n | 'data-loss'\n | 'unauthenticated';\n\n/**\n * Error Codes describing the different ways Firestore can fail. These come\n * directly from GRPC.\n */\nexport type Code = FirestoreErrorCode;\n\nexport const Code = {\n // Causes are copied from:\n // https://github.com/grpc/grpc/blob/bceec94ea4fc5f0085d81235d8e1c06798dc341a/include/grpc%2B%2B/impl/codegen/status_code_enum.h\n /** Not an error; returned on success. */\n OK: 'ok' as FirestoreErrorCode,\n\n /** The operation was cancelled (typically by the caller). */\n CANCELLED: 'cancelled' as FirestoreErrorCode,\n\n /** Unknown error or an error from a different error domain. */\n UNKNOWN: 'unknown' as FirestoreErrorCode,\n\n /**\n * Client specified an invalid argument. Note that this differs from\n * FAILED_PRECONDITION. INVALID_ARGUMENT indicates arguments that are\n * problematic regardless of the state of the system (e.g., a malformed file\n * name).\n */\n INVALID_ARGUMENT: 'invalid-argument' as FirestoreErrorCode,\n\n /**\n * Deadline expired before operation could complete. For operations that\n * change the state of the system, this error may be returned even if the\n * operation has completed successfully. For example, a successful response\n * from a server could have been delayed long enough for the deadline to\n * expire.\n */\n DEADLINE_EXCEEDED: 'deadline-exceeded' as FirestoreErrorCode,\n\n /** Some requested entity (e.g., file or directory) was not found. */\n NOT_FOUND: 'not-found' as FirestoreErrorCode,\n\n /**\n * Some entity that we attempted to create (e.g., file or directory) already\n * exists.\n */\n ALREADY_EXISTS: 'already-exists' as FirestoreErrorCode,\n\n /**\n * The caller does not have permission to execute the specified operation.\n * PERMISSION_DENIED must not be used for rejections caused by exhausting\n * some resource (use RESOURCE_EXHAUSTED instead for those errors).\n * PERMISSION_DENIED must not be used if the caller cannot be identified\n * (use UNAUTHENTICATED instead for those errors).\n */\n PERMISSION_DENIED: 'permission-denied' as FirestoreErrorCode,\n\n /**\n * The request does not have valid authentication credentials for the\n * operation.\n */\n UNAUTHENTICATED: 'unauthenticated' as FirestoreErrorCode,\n\n /**\n * Some resource has been exhausted, perhaps a per-user quota, or perhaps the\n * entire file system is out of space.\n */\n RESOURCE_EXHAUSTED: 'resource-exhausted' as FirestoreErrorCode,\n\n /**\n * Operation was rejected because the system is not in a state required for\n * the operation's execution. For example, directory to be deleted may be\n * non-empty, an rmdir operation is applied to a non-directory, etc.\n *\n * A litmus test that may help a service implementor in deciding\n * between FAILED_PRECONDITION, ABORTED, and UNAVAILABLE:\n * (a) Use UNAVAILABLE if the client can retry just the failing call.\n * (b) Use ABORTED if the client should retry at a higher-level\n * (e.g., restarting a read-modify-write sequence).\n * (c) Use FAILED_PRECONDITION if the client should not retry until\n * the system state has been explicitly fixed. E.g., if an \"rmdir\"\n * fails because the directory is non-empty, FAILED_PRECONDITION\n * should be returned since the client should not retry unless\n * they have first fixed up the directory by deleting files from it.\n * (d) Use FAILED_PRECONDITION if the client performs conditional\n * REST Get/Update/Delete on a resource and the resource on the\n * server does not match the condition. E.g., conflicting\n * read-modify-write on the same resource.\n */\n FAILED_PRECONDITION: 'failed-precondition' as FirestoreErrorCode,\n\n /**\n * The operation was aborted, typically due to a concurrency issue like\n * sequencer check failures, transaction aborts, etc.\n *\n * See litmus test above for deciding between FAILED_PRECONDITION, ABORTED,\n * and UNAVAILABLE.\n */\n ABORTED: 'aborted' as FirestoreErrorCode,\n\n /**\n * Operation was attempted past the valid range. E.g., seeking or reading\n * past end of file.\n *\n * Unlike INVALID_ARGUMENT, this error indicates a problem that may be fixed\n * if the system state changes. For example, a 32-bit file system will\n * generate INVALID_ARGUMENT if asked to read at an offset that is not in the\n * range [0,2^32-1], but it will generate OUT_OF_RANGE if asked to read from\n * an offset past the current file size.\n *\n * There is a fair bit of overlap between FAILED_PRECONDITION and\n * OUT_OF_RANGE. We recommend using OUT_OF_RANGE (the more specific error)\n * when it applies so that callers who are iterating through a space can\n * easily look for an OUT_OF_RANGE error to detect when they are done.\n */\n OUT_OF_RANGE: 'out-of-range' as FirestoreErrorCode,\n\n /** Operation is not implemented or not supported/enabled in this service. */\n UNIMPLEMENTED: 'unimplemented' as FirestoreErrorCode,\n\n /**\n * Internal errors. Means some invariants expected by underlying System has\n * been broken. If you see one of these errors, Something is very broken.\n */\n INTERNAL: 'internal' as FirestoreErrorCode,\n\n /**\n * The service is currently unavailable. This is a most likely a transient\n * condition and may be corrected by retrying with a backoff.\n *\n * See litmus test above for deciding between FAILED_PRECONDITION, ABORTED,\n * and UNAVAILABLE.\n */\n UNAVAILABLE: 'unavailable' as FirestoreErrorCode,\n\n /** Unrecoverable data loss or corruption. */\n DATA_LOSS: 'data-loss' as FirestoreErrorCode\n};\n\n/** An error returned by a Firestore operation. */\nexport class FirestoreError extends FirebaseError {\n /** The stack of the error. */\n readonly stack?: string;\n\n /** @hideconstructor */\n constructor(\n /**\n * The backend error code associated with this error.\n */\n readonly code: FirestoreErrorCode,\n /**\n * A custom error description.\n */\n readonly message: string\n ) {\n super(code, message);\n\n // HACK: We write a toString property directly because Error is not a real\n // class and so inheritance does not work correctly. We could alternatively\n // do the same \"back-door inheritance\" trick that FirebaseError does.\n this.toString = () => `${this.name}: [code=${this.code}]: ${this.message}`;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport interface Resolver {\n (value: R | Promise): void;\n}\n\nexport interface Rejecter {\n (reason?: Error): void;\n}\n\nexport class Deferred {\n promise: Promise;\n // Assigned synchronously in constructor by Promise constructor callback.\n resolve!: Resolver;\n reject!: Rejecter;\n\n constructor() {\n this.promise = new Promise((resolve: Resolver, reject: Rejecter) => {\n this.resolve = resolve;\n this.reject = reject;\n });\n }\n}\n\n/**\n * Takes an array of values and a function from a value to a Promise. The function is run on each\n * value sequentially, waiting for the previous promise to resolve before starting the next one.\n * The returned promise resolves once the function has been run on all values.\n */\nexport function sequence(\n values: T[],\n fn: (value: T) => Promise\n): Promise {\n let p = Promise.resolve();\n for (const value of values) {\n p = p.then(() => fn(value));\n }\n return p;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseApp, _isFirebaseServerApp } from '@firebase/app';\nimport {\n AppCheckInternalComponentName,\n AppCheckTokenListener,\n AppCheckTokenResult,\n FirebaseAppCheckInternal\n} from '@firebase/app-check-interop-types';\nimport {\n FirebaseAuthInternal,\n FirebaseAuthInternalName\n} from '@firebase/auth-interop-types';\nimport { Provider } from '@firebase/component';\n\nimport { User } from '../auth/user';\nimport { debugAssert, hardAssert } from '../util/assert';\nimport { AsyncQueue } from '../util/async_queue';\nimport { Code, FirestoreError } from '../util/error';\nimport { logDebug } from '../util/log';\nimport { Deferred } from '../util/promise';\n\n// TODO(mikelehen): This should be split into multiple files and probably\n// moved to an auth/ folder to match other platforms.\n\n/**\n * @internal\n */\nexport type AuthTokenFactory = () => string;\n\n/**\n * @internal\n */\nexport interface FirstPartyCredentialsSettings {\n // These are external types. Prevent minification.\n ['type']: 'firstParty';\n ['sessionIndex']: string;\n ['iamToken']: string | null;\n ['authTokenFactory']: AuthTokenFactory | null;\n}\n\nexport interface ProviderCredentialsSettings {\n // These are external types. Prevent minification.\n ['type']: 'provider';\n ['client']: CredentialsProvider;\n}\n\n/** Settings for private credentials */\nexport type CredentialsSettings =\n | FirstPartyCredentialsSettings\n | ProviderCredentialsSettings;\n\nexport type TokenType = 'OAuth' | 'FirstParty' | 'AppCheck';\nexport interface Token {\n /** Type of token. */\n type: TokenType;\n\n /**\n * The user with which the token is associated (used for persisting user\n * state on disk, etc.).\n * This will be null for Tokens of the type 'AppCheck'.\n */\n user?: User;\n\n /** Header values to set for this token */\n headers: Map;\n}\n\nexport class OAuthToken implements Token {\n type = 'OAuth' as TokenType;\n headers = new Map();\n\n constructor(value: string, public user: User) {\n this.headers.set('Authorization', `Bearer ${value}`);\n }\n}\n\n/**\n * A Listener for credential change events. The listener should fetch a new\n * token and may need to invalidate other state if the current user has also\n * changed.\n */\nexport type CredentialChangeListener = (credential: T) => Promise;\n\n/**\n * Provides methods for getting the uid and token for the current user and\n * listening for changes.\n */\nexport interface CredentialsProvider {\n /**\n * Starts the credentials provider and specifies a listener to be notified of\n * credential changes (sign-in / sign-out, token changes). It is immediately\n * called once with the initial user.\n *\n * The change listener is invoked on the provided AsyncQueue.\n */\n start(\n asyncQueue: AsyncQueue,\n changeListener: CredentialChangeListener\n ): void;\n\n /** Requests a token for the current user. */\n getToken(): Promise;\n\n /**\n * Marks the last retrieved token as invalid, making the next GetToken request\n * force-refresh the token.\n */\n invalidateToken(): void;\n\n shutdown(): void;\n}\n\n/**\n * A CredentialsProvider that always yields an empty token.\n * @internal\n */\nexport class EmptyAuthCredentialsProvider implements CredentialsProvider {\n getToken(): Promise {\n return Promise.resolve(null);\n }\n\n invalidateToken(): void {}\n\n start(\n asyncQueue: AsyncQueue,\n changeListener: CredentialChangeListener\n ): void {\n // Fire with initial user.\n asyncQueue.enqueueRetryable(() => changeListener(User.UNAUTHENTICATED));\n }\n\n shutdown(): void {}\n}\n\n/**\n * A CredentialsProvider that always returns a constant token. Used for\n * emulator token mocking.\n */\nexport class EmulatorAuthCredentialsProvider\n implements CredentialsProvider\n{\n constructor(private token: Token) {}\n\n /**\n * Stores the listener registered with setChangeListener()\n * This isn't actually necessary since the UID never changes, but we use this\n * to verify the listen contract is adhered to in tests.\n */\n private changeListener: CredentialChangeListener | null = null;\n\n getToken(): Promise {\n return Promise.resolve(this.token);\n }\n\n invalidateToken(): void {}\n\n start(\n asyncQueue: AsyncQueue,\n changeListener: CredentialChangeListener\n ): void {\n debugAssert(\n !this.changeListener,\n 'Can only call setChangeListener() once.'\n );\n this.changeListener = changeListener;\n // Fire with initial user.\n asyncQueue.enqueueRetryable(() => changeListener(this.token.user!));\n }\n\n shutdown(): void {\n this.changeListener = null;\n }\n}\n\n/** Credential provider for the Lite SDK. */\nexport class LiteAuthCredentialsProvider implements CredentialsProvider {\n private auth: FirebaseAuthInternal | null = null;\n\n constructor(authProvider: Provider) {\n authProvider.onInit(auth => {\n this.auth = auth;\n });\n }\n\n getToken(): Promise {\n if (!this.auth) {\n return Promise.resolve(null);\n }\n\n return this.auth.getToken().then(tokenData => {\n if (tokenData) {\n hardAssert(\n typeof tokenData.accessToken === 'string',\n 0xa539,\n 'Invalid tokenData returned from getToken()',\n { tokenData }\n );\n return new OAuthToken(\n tokenData.accessToken,\n new User(this.auth!.getUid())\n );\n } else {\n return null;\n }\n });\n }\n\n invalidateToken(): void {}\n\n start(\n asyncQueue: AsyncQueue,\n changeListener: CredentialChangeListener\n ): void {}\n\n shutdown(): void {}\n}\n\nexport class FirebaseAuthCredentialsProvider\n implements CredentialsProvider\n{\n /**\n * The auth token listener registered with FirebaseApp, retained here so we\n * can unregister it.\n */\n private tokenListener: (() => void) | undefined;\n\n /** Tracks the current User. */\n private currentUser: User = User.UNAUTHENTICATED;\n\n /**\n * Counter used to detect if the token changed while a getToken request was\n * outstanding.\n */\n private tokenCounter = 0;\n\n private forceRefresh = false;\n\n private auth: FirebaseAuthInternal | null = null;\n\n constructor(private authProvider: Provider) {}\n\n start(\n asyncQueue: AsyncQueue,\n changeListener: CredentialChangeListener\n ): void {\n hardAssert(\n this.tokenListener === undefined,\n 0xa540,\n 'Token listener already added'\n );\n let lastTokenId = this.tokenCounter;\n\n // A change listener that prevents double-firing for the same token change.\n const guardedChangeListener: (user: User) => Promise = user => {\n if (this.tokenCounter !== lastTokenId) {\n lastTokenId = this.tokenCounter;\n return changeListener(user);\n } else {\n return Promise.resolve();\n }\n };\n\n // A promise that can be waited on to block on the next token change.\n // This promise is re-created after each change.\n let nextToken = new Deferred();\n\n this.tokenListener = () => {\n this.tokenCounter++;\n this.currentUser = this.getUser();\n nextToken.resolve();\n nextToken = new Deferred();\n asyncQueue.enqueueRetryable(() =>\n guardedChangeListener(this.currentUser)\n );\n };\n\n const awaitNextToken: () => void = () => {\n const currentTokenAttempt = nextToken;\n asyncQueue.enqueueRetryable(async () => {\n await currentTokenAttempt.promise;\n await guardedChangeListener(this.currentUser);\n });\n };\n\n const registerAuth = (auth: FirebaseAuthInternal): void => {\n logDebug('FirebaseAuthCredentialsProvider', 'Auth detected');\n this.auth = auth;\n if (this.tokenListener) {\n this.auth.addAuthTokenListener(this.tokenListener);\n awaitNextToken();\n }\n };\n\n this.authProvider.onInit(auth => registerAuth(auth));\n\n // Our users can initialize Auth right after Firestore, so we give it\n // a chance to register itself with the component framework before we\n // determine whether to start up in unauthenticated mode.\n setTimeout(() => {\n if (!this.auth) {\n const auth = this.authProvider.getImmediate({ optional: true });\n if (auth) {\n registerAuth(auth);\n } else {\n // If auth is still not available, proceed with `null` user\n logDebug('FirebaseAuthCredentialsProvider', 'Auth not yet detected');\n nextToken.resolve();\n nextToken = new Deferred();\n }\n }\n }, 0);\n\n awaitNextToken();\n }\n\n getToken(): Promise {\n debugAssert(\n this.tokenListener != null,\n 'FirebaseAuthCredentialsProvider not started.'\n );\n\n // Take note of the current value of the tokenCounter so that this method\n // can fail (with an ABORTED error) if there is a token change while the\n // request is outstanding.\n const initialTokenCounter = this.tokenCounter;\n const forceRefresh = this.forceRefresh;\n this.forceRefresh = false;\n\n if (!this.auth) {\n return Promise.resolve(null);\n }\n\n return this.auth.getToken(forceRefresh).then(tokenData => {\n // Cancel the request since the token changed while the request was\n // outstanding so the response is potentially for a previous user (which\n // user, we can't be sure).\n if (this.tokenCounter !== initialTokenCounter) {\n logDebug(\n 'FirebaseAuthCredentialsProvider',\n 'getToken aborted due to token change.'\n );\n return this.getToken();\n } else {\n if (tokenData) {\n hardAssert(\n typeof tokenData.accessToken === 'string',\n 0x7c5d,\n 'Invalid tokenData returned from getToken()',\n { tokenData }\n );\n return new OAuthToken(tokenData.accessToken, this.currentUser);\n } else {\n return null;\n }\n }\n });\n }\n\n invalidateToken(): void {\n this.forceRefresh = true;\n }\n\n shutdown(): void {\n if (this.auth && this.tokenListener) {\n this.auth.removeAuthTokenListener(this.tokenListener);\n }\n this.tokenListener = undefined;\n }\n\n // Auth.getUid() can return null even with a user logged in. It is because\n // getUid() is synchronous, but the auth code populating Uid is asynchronous.\n // This method should only be called in the AuthTokenListener callback\n // to guarantee to get the actual user.\n private getUser(): User {\n const currentUid = this.auth && this.auth.getUid();\n hardAssert(\n currentUid === null || typeof currentUid === 'string',\n 0x0807,\n 'Received invalid UID',\n { currentUid }\n );\n return new User(currentUid);\n }\n}\n\n/*\n * FirstPartyToken provides a fresh token each time its value\n * is requested, because if the token is too old, requests will be rejected.\n * Technically this may no longer be necessary since the SDK should gracefully\n * recover from unauthenticated errors (see b/33147818 for context), but it's\n * safer to keep the implementation as-is.\n */\nexport class FirstPartyToken implements Token {\n type = 'FirstParty' as TokenType;\n user = User.FIRST_PARTY;\n private _headers = new Map();\n\n constructor(\n private readonly sessionIndex: string,\n private readonly iamToken: string | null,\n private readonly authTokenFactory: AuthTokenFactory | null\n ) {}\n\n /**\n * Gets an authorization token, using a provided factory function, or return\n * null.\n */\n private getAuthToken(): string | null {\n if (this.authTokenFactory) {\n return this.authTokenFactory();\n } else {\n return null;\n }\n }\n\n get headers(): Map {\n this._headers.set('X-Goog-AuthUser', this.sessionIndex);\n // Use array notation to prevent minification\n const authHeaderTokenValue = this.getAuthToken();\n if (authHeaderTokenValue) {\n this._headers.set('Authorization', authHeaderTokenValue);\n }\n if (this.iamToken) {\n this._headers.set('X-Goog-Iam-Authorization-Token', this.iamToken);\n }\n\n return this._headers;\n }\n}\n\n/*\n * Provides user credentials required for the Firestore JavaScript SDK\n * to authenticate the user, using technique that is only available\n * to applications hosted by Google.\n */\nexport class FirstPartyAuthCredentialsProvider\n implements CredentialsProvider\n{\n constructor(\n private sessionIndex: string,\n private iamToken: string | null,\n private authTokenFactory: AuthTokenFactory | null\n ) {}\n\n getToken(): Promise {\n return Promise.resolve(\n new FirstPartyToken(\n this.sessionIndex,\n this.iamToken,\n this.authTokenFactory\n )\n );\n }\n\n start(\n asyncQueue: AsyncQueue,\n changeListener: CredentialChangeListener\n ): void {\n // Fire with initial uid.\n asyncQueue.enqueueRetryable(() => changeListener(User.FIRST_PARTY));\n }\n\n shutdown(): void {}\n\n invalidateToken(): void {}\n}\n\nexport class AppCheckToken implements Token {\n type = 'AppCheck' as TokenType;\n headers = new Map();\n\n constructor(private value: string) {\n if (value && value.length > 0) {\n this.headers.set('x-firebase-appcheck', this.value);\n }\n }\n}\n\nexport class FirebaseAppCheckTokenProvider\n implements CredentialsProvider\n{\n /**\n * The AppCheck token listener registered with FirebaseApp, retained here so\n * we can unregister it.\n */\n private tokenListener: AppCheckTokenListener | undefined;\n private forceRefresh = false;\n private appCheck: FirebaseAppCheckInternal | null = null;\n private latestAppCheckToken: string | null = null;\n private serverAppAppCheckToken: string | null = null;\n\n constructor(\n app: FirebaseApp,\n private appCheckProvider: Provider\n ) {\n if (_isFirebaseServerApp(app) && app.settings.appCheckToken) {\n this.serverAppAppCheckToken = app.settings.appCheckToken;\n }\n }\n\n start(\n asyncQueue: AsyncQueue,\n changeListener: CredentialChangeListener\n ): void {\n hardAssert(\n this.tokenListener === undefined,\n 0x0db8,\n 'Token listener already added'\n );\n\n const onTokenChanged: (\n tokenResult: AppCheckTokenResult\n ) => Promise = tokenResult => {\n if (tokenResult.error != null) {\n logDebug(\n 'FirebaseAppCheckTokenProvider',\n `Error getting App Check token; using placeholder token instead. Error: ${tokenResult.error.message}`\n );\n }\n const tokenUpdated = tokenResult.token !== this.latestAppCheckToken;\n this.latestAppCheckToken = tokenResult.token;\n logDebug(\n 'FirebaseAppCheckTokenProvider',\n `Received ${tokenUpdated ? 'new' : 'existing'} token.`\n );\n return tokenUpdated\n ? changeListener(tokenResult.token)\n : Promise.resolve();\n };\n\n this.tokenListener = (tokenResult: AppCheckTokenResult) => {\n asyncQueue.enqueueRetryable(() => onTokenChanged(tokenResult));\n };\n\n const registerAppCheck = (appCheck: FirebaseAppCheckInternal): void => {\n logDebug('FirebaseAppCheckTokenProvider', 'AppCheck detected');\n this.appCheck = appCheck;\n if (this.tokenListener) {\n this.appCheck.addTokenListener(this.tokenListener);\n }\n };\n\n this.appCheckProvider.onInit(appCheck => registerAppCheck(appCheck));\n\n // Our users can initialize AppCheck after Firestore, so we give it\n // a chance to register itself with the component framework.\n setTimeout(() => {\n if (!this.appCheck) {\n const appCheck = this.appCheckProvider.getImmediate({ optional: true });\n if (appCheck) {\n registerAppCheck(appCheck);\n } else {\n // If AppCheck is still not available, proceed without it.\n logDebug(\n 'FirebaseAppCheckTokenProvider',\n 'AppCheck not yet detected'\n );\n }\n }\n }, 0);\n }\n\n getToken(): Promise {\n if (this.serverAppAppCheckToken) {\n return Promise.resolve(new AppCheckToken(this.serverAppAppCheckToken));\n }\n debugAssert(\n this.tokenListener != null,\n 'FirebaseAppCheckTokenProvider not started.'\n );\n\n const forceRefresh = this.forceRefresh;\n this.forceRefresh = false;\n\n if (!this.appCheck) {\n return Promise.resolve(null);\n }\n\n return this.appCheck.getToken(forceRefresh).then(tokenResult => {\n if (tokenResult) {\n hardAssert(\n typeof tokenResult.token === 'string',\n 0xae0e,\n 'Invalid tokenResult returned from getToken()',\n { tokenResult }\n );\n this.latestAppCheckToken = tokenResult.token;\n return new AppCheckToken(tokenResult.token);\n } else {\n return null;\n }\n });\n }\n\n invalidateToken(): void {\n this.forceRefresh = true;\n }\n\n shutdown(): void {\n if (this.appCheck && this.tokenListener) {\n this.appCheck.removeTokenListener(this.tokenListener);\n }\n this.tokenListener = undefined;\n }\n}\n\n/**\n * An AppCheck token provider that always yields an empty token.\n * @internal\n */\nexport class EmptyAppCheckTokenProvider implements CredentialsProvider {\n getToken(): Promise {\n return Promise.resolve(new AppCheckToken(''));\n }\n\n invalidateToken(): void {}\n\n start(\n asyncQueue: AsyncQueue,\n changeListener: CredentialChangeListener\n ): void {}\n\n shutdown(): void {}\n}\n\n/** AppCheck token provider for the Lite SDK. */\nexport class LiteAppCheckTokenProvider implements CredentialsProvider {\n private appCheck: FirebaseAppCheckInternal | null = null;\n private serverAppAppCheckToken: string | null = null;\n\n constructor(\n app: FirebaseApp,\n private appCheckProvider: Provider\n ) {\n if (_isFirebaseServerApp(app) && app.settings.appCheckToken) {\n this.serverAppAppCheckToken = app.settings.appCheckToken;\n }\n appCheckProvider.onInit(appCheck => {\n this.appCheck = appCheck;\n });\n }\n\n getToken(): Promise {\n if (this.serverAppAppCheckToken) {\n return Promise.resolve(new AppCheckToken(this.serverAppAppCheckToken));\n }\n\n if (!this.appCheck) {\n return Promise.resolve(null);\n }\n\n return this.appCheck.getToken().then(tokenResult => {\n if (tokenResult) {\n hardAssert(\n typeof tokenResult.token === 'string',\n 0x0d8e,\n 'Invalid tokenResult returned from getToken()',\n { tokenResult }\n );\n return new AppCheckToken(tokenResult.token);\n } else {\n return null;\n }\n });\n }\n\n invalidateToken(): void {}\n\n start(\n asyncQueue: AsyncQueue,\n changeListener: CredentialChangeListener\n ): void {}\n\n shutdown(): void {}\n}\n\n/**\n * Builds a CredentialsProvider depending on the type of\n * the credentials passed in.\n */\nexport function makeAuthCredentialsProvider(\n credentials?: CredentialsSettings\n): CredentialsProvider {\n if (!credentials) {\n return new EmptyAuthCredentialsProvider();\n }\n switch (credentials['type']) {\n case 'firstParty':\n return new FirstPartyAuthCredentialsProvider(\n credentials['sessionIndex'] || '0',\n credentials['iamToken'] || null,\n credentials['authTokenFactory'] || null\n );\n\n case 'provider':\n return credentials['client'];\n\n default:\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'makeAuthCredentialsProvider failed due to invalid credential type'\n );\n }\n}\n","import { FirebaseApp } from '@firebase/app';\n\nimport { ExperimentalLongPollingOptions } from '../api/long_polling_options';\nimport { Code, FirestoreError } from '../util/error';\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport class DatabaseInfo {\n /**\n * Constructs a DatabaseInfo using the provided host, databaseId and\n * persistenceKey.\n *\n * @param databaseId - The database to use.\n * @param appId - The Firebase App Id.\n * @param persistenceKey - A unique identifier for this Firestore's local\n * storage (used in conjunction with the databaseId).\n * @param host - The Firestore backend host to connect to.\n * @param ssl - Whether to use SSL when connecting.\n * @param forceLongPolling - Whether to use the forceLongPolling option\n * when using WebChannel as the network transport.\n * @param autoDetectLongPolling - Whether to use the detectBufferingProxy\n * option when using WebChannel as the network transport.\n * @param longPollingOptions Options that configure long-polling.\n * @param useFetchStreams Whether to use the Fetch API instead of\n * XMLHTTPRequest\n */\n constructor(\n readonly databaseId: DatabaseId,\n readonly appId: string,\n readonly persistenceKey: string,\n readonly host: string,\n readonly ssl: boolean,\n readonly forceLongPolling: boolean,\n readonly autoDetectLongPolling: boolean,\n readonly longPollingOptions: ExperimentalLongPollingOptions,\n readonly useFetchStreams: boolean,\n readonly isUsingEmulator: boolean\n ) {}\n}\n\n/** The default database name for a project. */\nexport const DEFAULT_DATABASE_NAME = '(default)';\n\n/**\n * Represents the database ID a Firestore client is associated with.\n * @internal\n */\nexport class DatabaseId {\n readonly database: string;\n constructor(readonly projectId: string, database?: string) {\n this.database = database ? database : DEFAULT_DATABASE_NAME;\n }\n\n static empty(): DatabaseId {\n return new DatabaseId('', '');\n }\n\n get isDefaultDatabase(): boolean {\n return this.database === DEFAULT_DATABASE_NAME;\n }\n\n isEqual(other: {}): boolean {\n return (\n other instanceof DatabaseId &&\n other.projectId === this.projectId &&\n other.database === this.database\n );\n }\n}\n\nexport function databaseIdFromApp(\n app: FirebaseApp,\n database?: string\n): DatabaseId {\n if (!Object.prototype.hasOwnProperty.apply(app.options, ['projectId'])) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n '\"projectId\" not provided in firebase.initializeApp.'\n );\n }\n\n return new DatabaseId(app.options.projectId!, database);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { randomBytes as generateRandomBytes } from 'crypto';\n\nimport { debugAssert } from '../../util/assert';\n\n/**\n * Generates `nBytes` of random bytes.\n *\n * If `nBytes < 0` , an error will be thrown.\n */\nexport function randomBytes(nBytes: number): Uint8Array {\n debugAssert(nBytes >= 0, `Expecting non-negative nBytes, got: ${nBytes}`);\n return generateRandomBytes(nBytes);\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { randomBytes } from '../platform/random_bytes';\n\nimport { debugAssert } from './assert';\n\nexport type EventHandler = (value: E) => void;\nexport interface Indexable {\n [k: string]: unknown;\n}\n\n/**\n * A utility class for generating unique alphanumeric IDs of a specified length.\n *\n * @internal\n * Exported internally for testing purposes.\n */\nexport class AutoId {\n static newId(): string {\n // Alphanumeric characters\n const chars =\n 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';\n // The largest byte value that is a multiple of `char.length`.\n const maxMultiple = Math.floor(256 / chars.length) * chars.length;\n debugAssert(\n 0 < maxMultiple && maxMultiple < 256,\n `Expect maxMultiple to be (0, 256), but got ${maxMultiple}`\n );\n\n let autoId = '';\n const targetLength = 20;\n while (autoId.length < targetLength) {\n const bytes = randomBytes(40);\n for (let i = 0; i < bytes.length; ++i) {\n // Only accept values that are [0, maxMultiple), this ensures they can\n // be evenly mapped to indices of `chars` via a modulo operation.\n if (autoId.length < targetLength && bytes[i] < maxMultiple) {\n autoId += chars.charAt(bytes[i] % chars.length);\n }\n }\n }\n debugAssert(autoId.length === targetLength, 'Invalid auto ID: ' + autoId);\n\n return autoId;\n }\n}\n\nexport function primitiveComparator(left: T, right: T): number {\n if (left < right) {\n return -1;\n }\n if (left > right) {\n return 1;\n }\n return 0;\n}\n\nexport interface Equatable {\n isEqual(other: T): boolean;\n}\n\n/** Compare strings in UTF-8 encoded byte order */\nexport function compareUtf8Strings(left: string, right: string): number {\n // Find the first differing character (a.k.a. \"UTF-16 code unit\") in the two strings and,\n // if found, use that character to determine the relative ordering of the two strings as a\n // whole. Comparing UTF-16 strings in UTF-8 byte order can be done simply and efficiently by\n // comparing the UTF-16 code units (chars). This serendipitously works because of the way UTF-8\n // and UTF-16 happen to represent Unicode code points.\n //\n // After finding the first pair of differing characters, there are two cases:\n //\n // Case 1: Both characters are non-surrogates (code points less than or equal to 0xFFFF) or\n // both are surrogates from a surrogate pair (that collectively represent code points greater\n // than 0xFFFF). In this case their numeric order as UTF-16 code units is the same as the\n // lexicographical order of their corresponding UTF-8 byte sequences. A direct comparison is\n // sufficient.\n //\n // Case 2: One character is a surrogate and the other is not. In this case the surrogate-\n // containing string is always ordered after the non-surrogate. This is because surrogates are\n // used to represent code points greater than 0xFFFF which have 4-byte UTF-8 representations\n // and are lexicographically greater than the 1, 2, or 3-byte representations of code points\n // less than or equal to 0xFFFF.\n //\n // An example of why Case 2 is required is comparing the following two Unicode code points:\n //\n // |-----------------------|------------|---------------------|-----------------|\n // | Name | Code Point | UTF-8 Encoding | UTF-16 Encoding |\n // |-----------------------|------------|---------------------|-----------------|\n // | Replacement Character | U+FFFD | 0xEF 0xBF 0xBD | 0xFFFD |\n // | Grinning Face | U+1F600 | 0xF0 0x9F 0x98 0x80 | 0xD83D 0xDE00 |\n // |-----------------------|------------|---------------------|-----------------|\n //\n // A lexicographical comparison of the UTF-8 encodings of these code points would order\n // \"Replacement Character\" _before_ \"Grinning Face\" because 0xEF is less than 0xF0. However, a\n // direct comparison of the UTF-16 code units, as would be done in case 1, would erroneously\n // produce the _opposite_ ordering, because 0xFFFD is _greater than_ 0xD83D. As it turns out,\n // this relative ordering holds for all comparisons of UTF-16 code points requiring a surrogate\n // pair with those that do not.\n const length = Math.min(left.length, right.length);\n for (let i = 0; i < length; i++) {\n const leftChar = left.charAt(i);\n const rightChar = right.charAt(i);\n if (leftChar !== rightChar) {\n return isSurrogate(leftChar) === isSurrogate(rightChar)\n ? primitiveComparator(leftChar, rightChar)\n : isSurrogate(leftChar)\n ? 1\n : -1;\n }\n }\n\n // Use the lengths of the strings to determine the overall comparison result since either the\n // strings were equal or one is a prefix of the other.\n return primitiveComparator(left.length, right.length);\n}\n\nconst MIN_SURROGATE = 0xd800;\nconst MAX_SURROGATE = 0xdfff;\n\nexport function isSurrogate(s: string): boolean {\n debugAssert(s.length === 1, `s.length == ${s.length}, but expected 1`);\n const c = s.charCodeAt(0);\n return c >= MIN_SURROGATE && c <= MAX_SURROGATE;\n}\n\nexport interface Iterable {\n forEach: (cb: (v: V) => void) => void;\n}\n\n/** Helper to compare arrays using isEqual(). */\nexport function arrayEquals(\n left: T[],\n right: T[],\n comparator: (l: T, r: T) => boolean\n): boolean {\n if (left.length !== right.length) {\n return false;\n }\n return left.every((value, index) => comparator(value, right[index]));\n}\n/**\n * Returns the immediate lexicographically-following string. This is useful to\n * construct an inclusive range for indexeddb iterators.\n */\nexport function immediateSuccessor(s: string): string {\n // Return the input string, with an additional NUL byte appended.\n return s + '\\0';\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Integer } from '@firebase/webchannel-wrapper/bloom-blob';\n\nimport { debugAssert, fail } from '../util/assert';\nimport { Code, FirestoreError } from '../util/error';\nimport { compareUtf8Strings, primitiveComparator } from '../util/misc';\n\nexport const DOCUMENT_KEY_NAME = '__name__';\n\n/**\n * Path represents an ordered sequence of string segments.\n */\nabstract class BasePath> {\n private segments: string[];\n private offset: number;\n private len: number;\n\n constructor(segments: string[], offset?: number, length?: number) {\n if (offset === undefined) {\n offset = 0;\n } else if (offset > segments.length) {\n fail(0x027d, 'offset out of range', {\n offset,\n range: segments.length\n });\n }\n\n if (length === undefined) {\n length = segments.length - offset;\n } else if (length > segments.length - offset) {\n fail(0x06d2, 'length out of range', {\n length,\n range: segments.length - offset\n });\n }\n this.segments = segments;\n this.offset = offset;\n this.len = length;\n }\n\n /**\n * Abstract constructor method to construct an instance of B with the given\n * parameters.\n */\n protected abstract construct(\n segments: string[],\n offset?: number,\n length?: number\n ): B;\n\n /**\n * Returns a String representation.\n *\n * Implementing classes are required to provide deterministic implementations as\n * the String representation is used to obtain canonical Query IDs.\n */\n abstract toString(): string;\n\n get length(): number {\n return this.len;\n }\n\n isEqual(other: B): boolean {\n return BasePath.comparator(this, other) === 0;\n }\n\n child(nameOrPath: string | B): B {\n const segments = this.segments.slice(this.offset, this.limit());\n if (nameOrPath instanceof BasePath) {\n nameOrPath.forEach(segment => {\n segments.push(segment);\n });\n } else {\n segments.push(nameOrPath);\n }\n return this.construct(segments);\n }\n\n /** The index of one past the last segment of the path. */\n private limit(): number {\n return this.offset + this.length;\n }\n\n popFirst(size?: number): B {\n size = size === undefined ? 1 : size;\n debugAssert(\n this.length >= size,\n \"Can't call popFirst() with less segments\"\n );\n return this.construct(\n this.segments,\n this.offset + size,\n this.length - size\n );\n }\n\n popLast(): B {\n debugAssert(!this.isEmpty(), \"Can't call popLast() on empty path\");\n return this.construct(this.segments, this.offset, this.length - 1);\n }\n\n firstSegment(): string {\n debugAssert(!this.isEmpty(), \"Can't call firstSegment() on empty path\");\n return this.segments[this.offset];\n }\n\n lastSegment(): string {\n debugAssert(!this.isEmpty(), \"Can't call lastSegment() on empty path\");\n return this.get(this.length - 1);\n }\n\n get(index: number): string {\n debugAssert(index < this.length, 'Index out of range');\n return this.segments[this.offset + index];\n }\n\n isEmpty(): boolean {\n return this.length === 0;\n }\n\n isPrefixOf(other: this): boolean {\n if (other.length < this.length) {\n return false;\n }\n\n for (let i = 0; i < this.length; i++) {\n if (this.get(i) !== other.get(i)) {\n return false;\n }\n }\n\n return true;\n }\n\n isImmediateParentOf(potentialChild: this): boolean {\n if (this.length + 1 !== potentialChild.length) {\n return false;\n }\n\n for (let i = 0; i < this.length; i++) {\n if (this.get(i) !== potentialChild.get(i)) {\n return false;\n }\n }\n\n return true;\n }\n\n forEach(fn: (segment: string) => void): void {\n for (let i = this.offset, end = this.limit(); i < end; i++) {\n fn(this.segments[i]);\n }\n }\n\n toArray(): string[] {\n return this.segments.slice(this.offset, this.limit());\n }\n\n /**\n * Compare 2 paths segment by segment, prioritizing numeric IDs\n * (e.g., \"__id123__\") in numeric ascending order, followed by string\n * segments in lexicographical order.\n */\n static comparator>(\n p1: BasePath,\n p2: BasePath\n ): number {\n const len = Math.min(p1.length, p2.length);\n for (let i = 0; i < len; i++) {\n const comparison = BasePath.compareSegments(p1.get(i), p2.get(i));\n if (comparison !== 0) {\n return comparison;\n }\n }\n return primitiveComparator(p1.length, p2.length);\n }\n\n private static compareSegments(lhs: string, rhs: string): number {\n const isLhsNumeric = BasePath.isNumericId(lhs);\n const isRhsNumeric = BasePath.isNumericId(rhs);\n\n if (isLhsNumeric && !isRhsNumeric) {\n // Only lhs is numeric\n return -1;\n } else if (!isLhsNumeric && isRhsNumeric) {\n // Only rhs is numeric\n return 1;\n } else if (isLhsNumeric && isRhsNumeric) {\n // both numeric\n return BasePath.extractNumericId(lhs).compare(\n BasePath.extractNumericId(rhs)\n );\n } else {\n // both non-numeric\n return compareUtf8Strings(lhs, rhs);\n }\n }\n\n // Checks if a segment is a numeric ID (starts with \"__id\" and ends with \"__\").\n private static isNumericId(segment: string): boolean {\n return segment.startsWith('__id') && segment.endsWith('__');\n }\n\n private static extractNumericId(segment: string): Integer {\n return Integer.fromString(segment.substring(4, segment.length - 2));\n }\n}\n\n/**\n * A slash-separated path for navigating resources (documents and collections)\n * within Firestore.\n *\n * @internal\n */\nexport class ResourcePath extends BasePath {\n protected construct(\n segments: string[],\n offset?: number,\n length?: number\n ): ResourcePath {\n return new ResourcePath(segments, offset, length);\n }\n\n canonicalString(): string {\n // NOTE: The client is ignorant of any path segments containing escape\n // sequences (e.g. __id123__) and just passes them through raw (they exist\n // for legacy reasons and should not be used frequently).\n\n return this.toArray().join('/');\n }\n\n toString(): string {\n return this.canonicalString();\n }\n\n /**\n * Returns a string representation of this path\n * where each path segment has been encoded with\n * `encodeURIComponent`.\n */\n toUriEncodedString(): string {\n return this.toArray().map(encodeURIComponent).join('/');\n }\n\n /**\n * Creates a resource path from the given slash-delimited string. If multiple\n * arguments are provided, all components are combined. Leading and trailing\n * slashes from all components are ignored.\n */\n static fromString(...pathComponents: string[]): ResourcePath {\n // NOTE: The client is ignorant of any path segments containing escape\n // sequences (e.g. __id123__) and just passes them through raw (they exist\n // for legacy reasons and should not be used frequently).\n\n const segments: string[] = [];\n for (const path of pathComponents) {\n if (path.indexOf('//') >= 0) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid segment (${path}). Paths must not contain // in them.`\n );\n }\n // Strip leading and trailing slashed.\n segments.push(...path.split('/').filter(segment => segment.length > 0));\n }\n\n return new ResourcePath(segments);\n }\n\n static emptyPath(): ResourcePath {\n return new ResourcePath([]);\n }\n}\n\nconst identifierRegExp = /^[_a-zA-Z][_a-zA-Z0-9]*$/;\n\n/**\n * A dot-separated path for navigating sub-objects within a document.\n * @internal\n */\nexport class FieldPath extends BasePath {\n protected construct(\n segments: string[],\n offset?: number,\n length?: number\n ): FieldPath {\n return new FieldPath(segments, offset, length);\n }\n\n /**\n * Returns true if the string could be used as a segment in a field path\n * without escaping.\n */\n private static isValidIdentifier(segment: string): boolean {\n return identifierRegExp.test(segment);\n }\n\n canonicalString(): string {\n return this.toArray()\n .map(str => {\n str = str.replace(/\\\\/g, '\\\\\\\\').replace(/`/g, '\\\\`');\n if (!FieldPath.isValidIdentifier(str)) {\n str = '`' + str + '`';\n }\n return str;\n })\n .join('.');\n }\n\n toString(): string {\n return this.canonicalString();\n }\n\n /**\n * Returns true if this field references the key of a document.\n */\n isKeyField(): boolean {\n return this.length === 1 && this.get(0) === DOCUMENT_KEY_NAME;\n }\n\n /**\n * The field designating the key of a document.\n */\n static keyField(): FieldPath {\n return new FieldPath([DOCUMENT_KEY_NAME]);\n }\n\n /**\n * Parses a field string from the given server-formatted string.\n *\n * - Splitting the empty string is not allowed (for now at least).\n * - Empty segments within the string (e.g. if there are two consecutive\n * separators) are not allowed.\n *\n * TODO(b/37244157): we should make this more strict. Right now, it allows\n * non-identifier path components, even if they aren't escaped.\n */\n static fromServerFormat(path: string): FieldPath {\n const segments: string[] = [];\n let current = '';\n let i = 0;\n\n const addCurrentSegment = (): void => {\n if (current.length === 0) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid field path (${path}). Paths must not be empty, begin ` +\n `with '.', end with '.', or contain '..'`\n );\n }\n segments.push(current);\n current = '';\n };\n\n let inBackticks = false;\n\n while (i < path.length) {\n const c = path[i];\n if (c === '\\\\') {\n if (i + 1 === path.length) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Path has trailing escape character: ' + path\n );\n }\n const next = path[i + 1];\n if (!(next === '\\\\' || next === '.' || next === '`')) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Path has invalid escape sequence: ' + path\n );\n }\n current += next;\n i += 2;\n } else if (c === '`') {\n inBackticks = !inBackticks;\n i++;\n } else if (c === '.' && !inBackticks) {\n addCurrentSegment();\n i++;\n } else {\n current += c;\n i++;\n }\n }\n addCurrentSegment();\n\n if (inBackticks) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Unterminated ` in path: ' + path\n );\n }\n\n return new FieldPath(segments);\n }\n\n static emptyPath(): FieldPath {\n return new FieldPath([]);\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { debugAssert } from '../util/assert';\n\nimport { ResourcePath } from './path';\n\n/**\n * @internal\n */\nexport class DocumentKey {\n constructor(readonly path: ResourcePath) {\n debugAssert(\n DocumentKey.isDocumentKey(path),\n 'Invalid DocumentKey with an odd number of segments: ' +\n path.toArray().join('/')\n );\n }\n\n static fromPath(path: string): DocumentKey {\n return new DocumentKey(ResourcePath.fromString(path));\n }\n\n static fromName(name: string): DocumentKey {\n return new DocumentKey(ResourcePath.fromString(name).popFirst(5));\n }\n\n static empty(): DocumentKey {\n return new DocumentKey(ResourcePath.emptyPath());\n }\n\n get collectionGroup(): string {\n debugAssert(\n !this.path.isEmpty(),\n 'Cannot get collection group for empty key'\n );\n return this.path.popLast().lastSegment();\n }\n\n /** Returns true if the document is in the specified collectionId. */\n hasCollectionId(collectionId: string): boolean {\n return (\n this.path.length >= 2 &&\n this.path.get(this.path.length - 2) === collectionId\n );\n }\n\n /** Returns the collection group (i.e. the name of the parent collection) for this key. */\n getCollectionGroup(): string {\n debugAssert(\n !this.path.isEmpty(),\n 'Cannot get collection group for empty key'\n );\n return this.path.get(this.path.length - 2);\n }\n\n /** Returns the fully qualified path to the parent collection. */\n getCollectionPath(): ResourcePath {\n return this.path.popLast();\n }\n\n isEqual(other: DocumentKey | null): boolean {\n return (\n other !== null && ResourcePath.comparator(this.path, other.path) === 0\n );\n }\n\n toString(): string {\n return this.path.toString();\n }\n\n static comparator(k1: DocumentKey, k2: DocumentKey): number {\n return ResourcePath.comparator(k1.path, k2.path);\n }\n\n static isDocumentKey(path: ResourcePath): boolean {\n return path.length % 2 === 0;\n }\n\n /**\n * Creates and returns a new document key with the given segments.\n *\n * @param segments - The segments of the path to the document\n * @returns A new instance of DocumentKey\n */\n static fromSegments(segments: string[]): DocumentKey {\n return new DocumentKey(new ResourcePath(segments.slice()));\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DocumentKey } from '../model/document_key';\nimport { ResourcePath } from '../model/path';\n\nimport { fail } from './assert';\nimport { Code, FirestoreError } from './error';\n\n/** Types accepted by validateType() and related methods for validation. */\nexport type ValidationType =\n | 'undefined'\n | 'object'\n | 'function'\n | 'boolean'\n | 'number'\n | 'string'\n | 'non-empty string';\n\nexport function validateNonEmptyArgument(\n functionName: string,\n argumentName: string,\n argument?: string\n): asserts argument is string {\n if (!argument) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Function ${functionName}() cannot be called with an empty ${argumentName}.`\n );\n }\n}\n\n/**\n * Validates that two boolean options are not set at the same time.\n * @internal\n */\nexport function validateIsNotUsedTogether(\n optionName1: string,\n argument1: boolean | undefined,\n optionName2: string,\n argument2: boolean | undefined\n): void {\n if (argument1 === true && argument2 === true) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `${optionName1} and ${optionName2} cannot be used together.`\n );\n }\n}\n\n/**\n * Validates that `path` refers to a document (indicated by the fact it contains\n * an even numbers of segments).\n */\nexport function validateDocumentPath(path: ResourcePath): void {\n if (!DocumentKey.isDocumentKey(path)) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid document reference. Document references must have an even number of segments, but ${path} has ${path.length}.`\n );\n }\n}\n\n/**\n * Validates that `path` refers to a collection (indicated by the fact it\n * contains an odd numbers of segments).\n */\nexport function validateCollectionPath(path: ResourcePath): void {\n if (DocumentKey.isDocumentKey(path)) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid collection reference. Collection references must have an odd number of segments, but ${path} has ${path.length}.`\n );\n }\n}\n\n/**\n * Returns true if it's a non-null object without a custom prototype\n * (i.e. excludes Array, Date, etc.).\n */\nexport function isPlainObject(input: unknown): boolean {\n return (\n typeof input === 'object' &&\n input !== null &&\n (Object.getPrototypeOf(input) === Object.prototype ||\n Object.getPrototypeOf(input) === null)\n );\n}\n\n/** Returns a string describing the type / value of the provided input. */\nexport function valueDescription(input: unknown): string {\n if (input === undefined) {\n return 'undefined';\n } else if (input === null) {\n return 'null';\n } else if (typeof input === 'string') {\n if (input.length > 20) {\n input = `${input.substring(0, 20)}...`;\n }\n return JSON.stringify(input);\n } else if (typeof input === 'number' || typeof input === 'boolean') {\n return '' + input;\n } else if (typeof input === 'object') {\n if (input instanceof Array) {\n return 'an array';\n } else {\n const customObjectName = tryGetCustomObjectType(input!);\n if (customObjectName) {\n return `a custom ${customObjectName} object`;\n } else {\n return 'an object';\n }\n }\n } else if (typeof input === 'function') {\n return 'a function';\n } else {\n return fail(0x3029, 'Unknown wrong type', { type: typeof input });\n }\n}\n\n/** try to get the constructor name for an object. */\nexport function tryGetCustomObjectType(input: object): string | null {\n if (input.constructor) {\n return input.constructor.name;\n }\n return null;\n}\n\n/**\n * Casts `obj` to `T`, optionally unwrapping Compat types to expose the\n * underlying instance. Throws if `obj` is not an instance of `T`.\n *\n * This cast is used in the Lite and Full SDK to verify instance types for\n * arguments passed to the public API.\n * @internal\n */\nexport function cast(\n obj: object,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n constructor: { new (...args: any[]): T }\n): T | never {\n if ('_delegate' in obj) {\n // Unwrap Compat types\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n obj = (obj as any)._delegate;\n }\n\n if (!(obj instanceof constructor)) {\n if (constructor.name === obj.constructor.name) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Type does not match the expected instance. Did you pass a ' +\n `reference from a different Firestore SDK?`\n );\n } else {\n const description = valueDescription(obj);\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Expected type '${constructor.name}', but it was: ${description}`\n );\n }\n }\n return obj as T;\n}\n\nexport function validatePositiveNumber(functionName: string, n: number): void {\n if (n <= 0) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Function ${functionName}() requires a positive number, but it was: ${n}.`\n );\n }\n}\n","/**\n * @license\n * Copyright 2023 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Options that configure the SDK’s underlying network transport (WebChannel)\n * when long-polling is used.\n *\n * Note: This interface is \"experimental\" and is subject to change.\n *\n * See `FirestoreSettings.experimentalAutoDetectLongPolling`,\n * `FirestoreSettings.experimentalForceLongPolling`, and\n * `FirestoreSettings.experimentalLongPollingOptions`.\n */\nexport interface ExperimentalLongPollingOptions {\n /**\n * The desired maximum timeout interval, in seconds, to complete a\n * long-polling GET response. Valid values are between 5 and 30, inclusive.\n * Floating point values are allowed and will be rounded to the nearest\n * millisecond.\n *\n * By default, when long-polling is used the \"hanging GET\" request sent by\n * the client times out after 30 seconds. To request a different timeout\n * from the server, set this setting with the desired timeout.\n *\n * Changing the default timeout may be useful, for example, if the buffering\n * proxy that necessitated enabling long-polling in the first place has a\n * shorter timeout for hanging GET requests, in which case setting the\n * long-polling timeout to a shorter value, such as 25 seconds, may fix\n * prematurely-closed hanging GET requests.\n * For example, see https://github.com/firebase/firebase-js-sdk/issues/6987.\n */\n timeoutSeconds?: number;\n}\n\n/**\n * Compares two `ExperimentalLongPollingOptions` objects for equality.\n */\nexport function longPollingOptionsEqual(\n options1: ExperimentalLongPollingOptions,\n options2: ExperimentalLongPollingOptions\n): boolean {\n return options1.timeoutSeconds === options2.timeoutSeconds;\n}\n\n/**\n * Creates and returns a new `ExperimentalLongPollingOptions` with the same\n * option values as the given instance.\n */\nexport function cloneLongPollingOptions(\n options: ExperimentalLongPollingOptions\n): ExperimentalLongPollingOptions {\n const clone: ExperimentalLongPollingOptions = {};\n\n if (options.timeoutSeconds !== undefined) {\n clone.timeoutSeconds = options.timeoutSeconds;\n }\n\n return clone;\n}\n","/**\n * @license\n * Copyright 2023 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * The value returned from the most recent invocation of\n * `generateUniqueDebugId()`, or null if it has never been invoked.\n */\nlet lastUniqueDebugId: number | null = null;\n\n/**\n * Generates and returns an initial value for `lastUniqueDebugId`.\n *\n * The returned value is randomly selected from a range of integers that are\n * represented as 8 hexadecimal digits. This means that (within reason) any\n * numbers generated by incrementing the returned number by 1 will also be\n * represented by 8 hexadecimal digits. This leads to all \"IDs\" having the same\n * length when converted to a hexadecimal string, making reading logs containing\n * these IDs easier to follow. And since the return value is randomly selected\n * it will help to differentiate between logs from different executions.\n */\nfunction generateInitialUniqueDebugId(): number {\n const minResult = 0x10000000;\n const maxResult = 0x90000000;\n const resultRange = maxResult - minResult;\n const resultOffset = Math.round(resultRange * Math.random());\n return minResult + resultOffset;\n}\n\n/**\n * Generates and returns a unique ID as a hexadecimal string.\n *\n * The returned ID is intended to be used in debug logging messages to help\n * correlate log messages that may be spatially separated in the logs, but\n * logically related. For example, a network connection could include the same\n * \"debug ID\" string in all of its log messages to help trace a specific\n * connection over time.\n *\n * @return the 10-character generated ID (e.g. \"0xa1b2c3d4\").\n */\nexport function generateUniqueDebugId(): string {\n if (lastUniqueDebugId === null) {\n lastUniqueDebugId = generateInitialUniqueDebugId();\n } else {\n lastUniqueDebugId++;\n }\n return '0x' + lastUniqueDebugId.toString(16);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isCloudWorkstation } from '@firebase/util';\n\nimport { SDK_VERSION } from '../../src/core/version';\nimport { Token } from '../api/credentials';\nimport {\n DatabaseId,\n DatabaseInfo,\n DEFAULT_DATABASE_NAME\n} from '../core/database_info';\nimport { ResourcePath } from '../model/path';\nimport { debugAssert } from '../util/assert';\nimport { generateUniqueDebugId } from '../util/debug_uid';\nimport { FirestoreError } from '../util/error';\nimport { logDebug, logWarn } from '../util/log';\nimport { StringMap } from '../util/types';\n\nimport { Connection, Stream } from './connection';\n\nconst LOG_TAG = 'RestConnection';\n\n/**\n * Maps RPC names to the corresponding REST endpoint name.\n *\n * We use array notation to avoid mangling.\n */\nconst RPC_NAME_URL_MAPPING: StringMap = {};\n\nRPC_NAME_URL_MAPPING['BatchGetDocuments'] = 'batchGet';\nRPC_NAME_URL_MAPPING['Commit'] = 'commit';\nRPC_NAME_URL_MAPPING['RunQuery'] = 'runQuery';\nRPC_NAME_URL_MAPPING['RunAggregationQuery'] = 'runAggregationQuery';\n\nconst RPC_URL_VERSION = 'v1';\n\n// SDK_VERSION is updated to different value at runtime depending on the entry point,\n// so we need to get its value when we need it in a function.\nfunction getGoogApiClientValue(): string {\n return 'gl-js/ fire/' + SDK_VERSION;\n}\n/**\n * Base class for all Rest-based connections to the backend (WebChannel and\n * HTTP).\n */\nexport abstract class RestConnection implements Connection {\n protected readonly databaseId: DatabaseId;\n protected readonly baseUrl: string;\n private readonly databasePath: string;\n private readonly requestParams: string;\n\n get shouldResourcePathBeIncludedInRequest(): boolean {\n // Both `invokeRPC()` and `invokeStreamingRPC()` use their `path` arguments to determine\n // where to run the query, and expect the `request` to NOT specify the \"path\".\n return false;\n }\n\n constructor(private readonly databaseInfo: DatabaseInfo) {\n this.databaseId = databaseInfo.databaseId;\n const proto = databaseInfo.ssl ? 'https' : 'http';\n const projectId = encodeURIComponent(this.databaseId.projectId);\n const databaseId = encodeURIComponent(this.databaseId.database);\n this.baseUrl = proto + '://' + databaseInfo.host;\n this.databasePath = `projects/${projectId}/databases/${databaseId}`;\n this.requestParams =\n this.databaseId.database === DEFAULT_DATABASE_NAME\n ? `project_id=${projectId}`\n : `project_id=${projectId}&database_id=${databaseId}`;\n }\n\n invokeRPC(\n rpcName: string,\n path: ResourcePath,\n req: Req,\n authToken: Token | null,\n appCheckToken: Token | null\n ): Promise {\n const streamId = generateUniqueDebugId();\n const url = this.makeUrl(rpcName, path.toUriEncodedString());\n logDebug(LOG_TAG, `Sending RPC '${rpcName}' ${streamId}:`, url, req);\n\n const headers: StringMap = {\n 'google-cloud-resource-prefix': this.databasePath,\n 'x-goog-request-params': this.requestParams\n };\n this.modifyHeadersForRequest(headers, authToken, appCheckToken);\n\n const { host } = new URL(url);\n const forwardCredentials = isCloudWorkstation(host);\n return this.performRPCRequest(\n rpcName,\n url,\n headers,\n req,\n forwardCredentials\n ).then(\n response => {\n logDebug(LOG_TAG, `Received RPC '${rpcName}' ${streamId}: `, response);\n return response;\n },\n (err: FirestoreError) => {\n logWarn(\n LOG_TAG,\n `RPC '${rpcName}' ${streamId} failed with error: `,\n err,\n 'url: ',\n url,\n 'request:',\n req\n );\n throw err;\n }\n );\n }\n\n invokeStreamingRPC(\n rpcName: string,\n path: ResourcePath,\n request: Req,\n authToken: Token | null,\n appCheckToken: Token | null,\n expectedResponseCount?: number\n ): Promise {\n // The REST API automatically aggregates all of the streamed results, so we\n // can just use the normal invoke() method.\n return this.invokeRPC(\n rpcName,\n path,\n request,\n authToken,\n appCheckToken\n );\n }\n\n abstract openStream(\n rpcName: string,\n authToken: Token | null,\n appCheckToken: Token | null\n ): Stream;\n\n /**\n * Modifies the headers for a request, adding any authorization token if\n * present and any additional headers for the request.\n */\n protected modifyHeadersForRequest(\n headers: StringMap,\n authToken: Token | null,\n appCheckToken: Token | null\n ): void {\n headers['X-Goog-Api-Client'] = getGoogApiClientValue();\n\n // Content-Type: text/plain will avoid preflight requests which might\n // mess with CORS and redirects by proxies. If we add custom headers\n // we will need to change this code to potentially use the $httpOverwrite\n // parameter supported by ESF to avoid triggering preflight requests.\n headers['Content-Type'] = 'text/plain';\n\n if (this.databaseInfo.appId) {\n headers['X-Firebase-GMPID'] = this.databaseInfo.appId;\n }\n\n if (authToken) {\n authToken.headers.forEach((value, key) => (headers[key] = value));\n }\n if (appCheckToken) {\n appCheckToken.headers.forEach((value, key) => (headers[key] = value));\n }\n }\n\n /**\n * Performs an RPC request using an implementation specific networking layer.\n */\n protected abstract performRPCRequest(\n rpcName: string,\n url: string,\n headers: StringMap,\n body: Req,\n _forwardCredentials: boolean\n ): Promise;\n\n private makeUrl(rpcName: string, path: string): string {\n const urlRpcName = RPC_NAME_URL_MAPPING[rpcName];\n debugAssert(\n urlRpcName !== undefined,\n 'Unknown REST mapping for: ' + rpcName\n );\n return `${this.baseUrl}/${RPC_URL_VERSION}/${path}:${urlRpcName}`;\n }\n\n /**\n * Closes and cleans up any resources associated with the connection. This\n * implementation is a no-op because there are no resources associated\n * with the RestConnection that need to be cleaned up.\n */\n terminate(): void {\n // No-op\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { fail } from '../util/assert';\nimport { Code } from '../util/error';\nimport { logError } from '../util/log';\n\n/**\n * Error Codes describing the different ways GRPC can fail. These are copied\n * directly from GRPC's sources here:\n *\n * https://github.com/grpc/grpc/blob/bceec94ea4fc5f0085d81235d8e1c06798dc341a/include/grpc%2B%2B/impl/codegen/status_code_enum.h\n *\n * Important! The names of these identifiers matter because the string forms\n * are used for reverse lookups from the webchannel stream. Do NOT change the\n * names of these identifiers or change this into a const enum.\n */\nenum RpcCode {\n OK = 0,\n CANCELLED = 1,\n UNKNOWN = 2,\n INVALID_ARGUMENT = 3,\n DEADLINE_EXCEEDED = 4,\n NOT_FOUND = 5,\n ALREADY_EXISTS = 6,\n PERMISSION_DENIED = 7,\n UNAUTHENTICATED = 16,\n RESOURCE_EXHAUSTED = 8,\n FAILED_PRECONDITION = 9,\n ABORTED = 10,\n OUT_OF_RANGE = 11,\n UNIMPLEMENTED = 12,\n INTERNAL = 13,\n UNAVAILABLE = 14,\n DATA_LOSS = 15\n}\n\n/**\n * Determines whether an error code represents a permanent error when received\n * in response to a non-write operation.\n *\n * See isPermanentWriteError for classifying write errors.\n */\nexport function isPermanentError(code: Code): boolean {\n switch (code) {\n case Code.OK:\n return fail(0xfdaa, 'Treated status OK as error');\n case Code.CANCELLED:\n case Code.UNKNOWN:\n case Code.DEADLINE_EXCEEDED:\n case Code.RESOURCE_EXHAUSTED:\n case Code.INTERNAL:\n case Code.UNAVAILABLE:\n // Unauthenticated means something went wrong with our token and we need\n // to retry with new credentials which will happen automatically.\n case Code.UNAUTHENTICATED:\n return false;\n case Code.INVALID_ARGUMENT:\n case Code.NOT_FOUND:\n case Code.ALREADY_EXISTS:\n case Code.PERMISSION_DENIED:\n case Code.FAILED_PRECONDITION:\n // Aborted might be retried in some scenarios, but that is dependent on\n // the context and should handled individually by the calling code.\n // See https://cloud.google.com/apis/design/errors.\n case Code.ABORTED:\n case Code.OUT_OF_RANGE:\n case Code.UNIMPLEMENTED:\n case Code.DATA_LOSS:\n return true;\n default:\n return fail(0x3c6b, 'Unknown status code', { code });\n }\n}\n\n/**\n * Determines whether an error code represents a permanent error when received\n * in response to a write operation.\n *\n * Write operations must be handled specially because as of b/119437764, ABORTED\n * errors on the write stream should be retried too (even though ABORTED errors\n * are not generally retryable).\n *\n * Note that during the initial handshake on the write stream an ABORTED error\n * signals that we should discard our stream token (i.e. it is permanent). This\n * means a handshake error should be classified with isPermanentError, above.\n */\nexport function isPermanentWriteError(code: Code): boolean {\n return isPermanentError(code) && code !== Code.ABORTED;\n}\n\n/**\n * Maps an error Code from a GRPC status identifier like 'NOT_FOUND'.\n *\n * @returns The Code equivalent to the given status string or undefined if\n * there is no match.\n */\nexport function mapCodeFromRpcStatus(status: string): Code | undefined {\n // lookup by string\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const code: RpcCode = RpcCode[status as any] as any;\n if (code === undefined) {\n return undefined;\n }\n\n return mapCodeFromRpcCode(code);\n}\n\n/**\n * Maps an error Code from GRPC status code number, like 0, 1, or 14. These\n * are not the same as HTTP status codes.\n *\n * @returns The Code equivalent to the given GRPC status code. Fails if there\n * is no match.\n */\nexport function mapCodeFromRpcCode(code: number | undefined): Code {\n if (code === undefined) {\n // This shouldn't normally happen, but in certain error cases (like trying\n // to send invalid proto messages) we may get an error with no GRPC code.\n logError('GRPC error has no .code');\n return Code.UNKNOWN;\n }\n\n switch (code) {\n case RpcCode.OK:\n return Code.OK;\n case RpcCode.CANCELLED:\n return Code.CANCELLED;\n case RpcCode.UNKNOWN:\n return Code.UNKNOWN;\n case RpcCode.DEADLINE_EXCEEDED:\n return Code.DEADLINE_EXCEEDED;\n case RpcCode.RESOURCE_EXHAUSTED:\n return Code.RESOURCE_EXHAUSTED;\n case RpcCode.INTERNAL:\n return Code.INTERNAL;\n case RpcCode.UNAVAILABLE:\n return Code.UNAVAILABLE;\n case RpcCode.UNAUTHENTICATED:\n return Code.UNAUTHENTICATED;\n case RpcCode.INVALID_ARGUMENT:\n return Code.INVALID_ARGUMENT;\n case RpcCode.NOT_FOUND:\n return Code.NOT_FOUND;\n case RpcCode.ALREADY_EXISTS:\n return Code.ALREADY_EXISTS;\n case RpcCode.PERMISSION_DENIED:\n return Code.PERMISSION_DENIED;\n case RpcCode.FAILED_PRECONDITION:\n return Code.FAILED_PRECONDITION;\n case RpcCode.ABORTED:\n return Code.ABORTED;\n case RpcCode.OUT_OF_RANGE:\n return Code.OUT_OF_RANGE;\n case RpcCode.UNIMPLEMENTED:\n return Code.UNIMPLEMENTED;\n case RpcCode.DATA_LOSS:\n return Code.DATA_LOSS;\n default:\n return fail(0x999b, 'Unknown status code', { code });\n }\n}\n\n/**\n * Maps an RPC code from a Code. This is the reverse operation from\n * mapCodeFromRpcCode and should really only be used in tests.\n */\nexport function mapRpcCodeFromCode(code: Code | undefined): number {\n if (code === undefined) {\n return RpcCode.OK;\n }\n\n switch (code) {\n case Code.OK:\n return RpcCode.OK;\n case Code.CANCELLED:\n return RpcCode.CANCELLED;\n case Code.UNKNOWN:\n return RpcCode.UNKNOWN;\n case Code.DEADLINE_EXCEEDED:\n return RpcCode.DEADLINE_EXCEEDED;\n case Code.RESOURCE_EXHAUSTED:\n return RpcCode.RESOURCE_EXHAUSTED;\n case Code.INTERNAL:\n return RpcCode.INTERNAL;\n case Code.UNAVAILABLE:\n return RpcCode.UNAVAILABLE;\n case Code.UNAUTHENTICATED:\n return RpcCode.UNAUTHENTICATED;\n case Code.INVALID_ARGUMENT:\n return RpcCode.INVALID_ARGUMENT;\n case Code.NOT_FOUND:\n return RpcCode.NOT_FOUND;\n case Code.ALREADY_EXISTS:\n return RpcCode.ALREADY_EXISTS;\n case Code.PERMISSION_DENIED:\n return RpcCode.PERMISSION_DENIED;\n case Code.FAILED_PRECONDITION:\n return RpcCode.FAILED_PRECONDITION;\n case Code.ABORTED:\n return RpcCode.ABORTED;\n case Code.OUT_OF_RANGE:\n return RpcCode.OUT_OF_RANGE;\n case Code.UNIMPLEMENTED:\n return RpcCode.UNIMPLEMENTED;\n case Code.DATA_LOSS:\n return RpcCode.DATA_LOSS;\n default:\n return fail(0x3019, 'Unknown status code', { code });\n }\n}\n\n/**\n * Converts an HTTP Status Code to the equivalent error code.\n *\n * @param status - An HTTP Status Code, like 200, 404, 503, etc.\n * @returns The equivalent Code. Unknown status codes are mapped to\n * Code.UNKNOWN.\n */\nexport function mapCodeFromHttpStatus(status?: number): Code {\n if (status === undefined) {\n logError('RPC_ERROR', 'HTTP error has no status');\n return Code.UNKNOWN;\n }\n\n // The canonical error codes for Google APIs [1] specify mapping onto HTTP\n // status codes but the mapping is not bijective. In each case of ambiguity\n // this function chooses a primary error.\n //\n // [1]\n // https://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto\n switch (status) {\n case 200: // OK\n return Code.OK;\n\n case 400: // Bad Request\n return Code.FAILED_PRECONDITION;\n // Other possibilities based on the forward mapping\n // return Code.INVALID_ARGUMENT;\n // return Code.OUT_OF_RANGE;\n\n case 401: // Unauthorized\n return Code.UNAUTHENTICATED;\n\n case 403: // Forbidden\n return Code.PERMISSION_DENIED;\n\n case 404: // Not Found\n return Code.NOT_FOUND;\n\n case 409: // Conflict\n return Code.ABORTED;\n // Other possibilities:\n // return Code.ALREADY_EXISTS;\n\n case 416: // Range Not Satisfiable\n return Code.OUT_OF_RANGE;\n\n case 429: // Too Many Requests\n return Code.RESOURCE_EXHAUSTED;\n\n case 499: // Client Closed Request\n return Code.CANCELLED;\n\n case 500: // Internal Server Error\n return Code.UNKNOWN;\n // Other possibilities:\n // return Code.INTERNAL;\n // return Code.DATA_LOSS;\n\n case 501: // Unimplemented\n return Code.UNIMPLEMENTED;\n\n case 503: // Service Unavailable\n return Code.UNAVAILABLE;\n\n case 504: // Gateway Timeout\n return Code.DEADLINE_EXCEEDED;\n\n default:\n if (status >= 200 && status < 300) {\n return Code.OK;\n }\n if (status >= 400 && status < 500) {\n return Code.FAILED_PRECONDITION;\n }\n if (status >= 500 && status < 600) {\n return Code.INTERNAL;\n }\n return Code.UNKNOWN;\n }\n}\n\n/**\n * Converts an HTTP response's error status to the equivalent error code.\n *\n * @param status - An HTTP error response status (\"FAILED_PRECONDITION\",\n * \"UNKNOWN\", etc.)\n * @returns The equivalent Code. Non-matching responses are mapped to\n * Code.UNKNOWN.\n */\nexport function mapCodeFromHttpResponseErrorStatus(status: string): Code {\n const serverError = status.toLowerCase().replace(/_/g, '-');\n return Object.values(Code).indexOf(serverError as Code) >= 0\n ? (serverError as Code)\n : Code.UNKNOWN;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Token } from '../../api/credentials';\nimport { Stream } from '../../remote/connection';\nimport { RestConnection } from '../../remote/rest_connection';\nimport { mapCodeFromHttpStatus } from '../../remote/rpc_error';\nimport { FirestoreError } from '../../util/error';\nimport { StringMap } from '../../util/types';\n\n/**\n * A Rest-based connection that relies on the native HTTP stack\n * (e.g. `fetch` or a polyfill).\n */\nexport class FetchConnection extends RestConnection {\n openStream(\n rpcName: string,\n token: Token | null\n ): Stream {\n throw new Error('Not supported by FetchConnection');\n }\n\n protected async performRPCRequest(\n rpcName: string,\n url: string,\n headers: StringMap,\n body: Req,\n forwardCredentials: boolean\n ): Promise {\n const requestJson = JSON.stringify(body);\n let response: Response;\n\n try {\n const fetchArgs: RequestInit = {\n method: 'POST',\n headers,\n body: requestJson\n };\n if (forwardCredentials) {\n fetchArgs.credentials = 'include';\n }\n response = await fetch(url, fetchArgs);\n } catch (e) {\n const err = e as { status: number | undefined; statusText: string };\n throw new FirestoreError(\n mapCodeFromHttpStatus(err.status),\n 'Request failed with error: ' + err.statusText\n );\n }\n\n if (!response.ok) {\n let errorResponse = await response.json();\n if (Array.isArray(errorResponse)) {\n errorResponse = errorResponse[0];\n }\n const errorMessage = errorResponse?.error?.message;\n throw new FirestoreError(\n mapCodeFromHttpStatus(response.status),\n `Request failed with error: ${errorMessage ?? response.statusText}`\n );\n }\n\n return response.json();\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DatabaseInfo } from '../../core/database_info';\nimport { Connection } from '../../remote/connection';\nimport { FetchConnection } from '../browser_lite/fetch_connection';\n\nexport { newConnectivityMonitor } from '../browser/connection';\n\n/** Initializes the HTTP connection for the REST API. */\nexport function newConnection(databaseInfo: DatabaseInfo): Connection {\n return new FetchConnection(databaseInfo);\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { debugAssert } from './assert';\n\nexport interface Dict {\n [stringKey: string]: V;\n}\n\nexport function objectSize(obj: object): number {\n let count = 0;\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n count++;\n }\n }\n return count;\n}\n\nexport function forEach(\n obj: Dict | undefined,\n fn: (key: string, val: V) => void\n): void {\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n fn(key, obj[key]);\n }\n }\n}\n\nexport function mapToArray(\n obj: Dict,\n fn: (element: V, key: string, obj: Dict) => R\n): R[] {\n const result: R[] = [];\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n result.push(fn(obj[key], key, obj));\n }\n }\n return result;\n}\n\nexport function isEmpty(obj: Dict): boolean {\n debugAssert(\n obj != null && typeof obj === 'object',\n 'isEmpty() expects object parameter.'\n );\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n return false;\n }\n }\n return true;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** Sentinel value that sorts before any Mutation Batch ID. */\nexport const BATCHID_UNKNOWN = -1;\n\n// An Object whose keys and values are strings.\nexport interface StringMap {\n [key: string]: string;\n}\n\n/**\n * Returns whether a variable is either undefined or null.\n */\nexport function isNullOrUndefined(value: unknown): value is null | undefined {\n return value === null || value === undefined;\n}\n\n/** Returns whether the value represents -0. */\nexport function isNegativeZero(value: number): boolean {\n // Detect if the value is -0.0. Based on polyfill from\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is\n return value === 0 && 1 / value === 1 / -0;\n}\n\n/**\n * Returns whether a value is an integer and in the safe integer range\n * @param value - The value to test for being an integer and in the safe range\n */\nexport function isSafeInteger(value: unknown): boolean {\n return (\n typeof value === 'number' &&\n Number.isInteger(value) &&\n !isNegativeZero(value) &&\n value <= Number.MAX_SAFE_INTEGER &&\n value >= Number.MIN_SAFE_INTEGER\n );\n}\n\n/** The subset of the browser's Window interface used by the SDK. */\nexport interface WindowLike {\n readonly localStorage: Storage;\n readonly indexedDB: IDBFactory | null;\n addEventListener(type: string, listener: EventListener): void;\n removeEventListener(type: string, listener: EventListener): void;\n}\n\n/** The subset of the browser's Document interface used by the SDK. */\nexport interface DocumentLike {\n readonly visibilityState: DocumentVisibilityState;\n addEventListener(type: string, listener: EventListener): void;\n removeEventListener(type: string, listener: EventListener): void;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** Converts a Base64 encoded string to a binary string. */\n\nexport function decodeBase64(encoded: string): string {\n // Note: We used to validate the base64 string here via a regular expression.\n // This was removed to improve the performance of indexing.\n return Buffer.from(encoded, 'base64').toString('binary');\n}\n\n/** Converts a binary string to a Base64 encoded string. */\nexport function encodeBase64(raw: string): string {\n return Buffer.from(raw, 'binary').toString('base64');\n}\n\n/** True if and only if the Base64 conversion functions are available. */\nexport function isBase64Available(): boolean {\n return true;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { decodeBase64, encodeBase64 } from '../platform/base64';\n\nimport { primitiveComparator } from './misc';\n\n/**\n * Immutable class that represents a \"proto\" byte string.\n *\n * Proto byte strings can either be Base64-encoded strings or Uint8Arrays when\n * sent on the wire. This class abstracts away this differentiation by holding\n * the proto byte string in a common class that must be converted into a string\n * before being sent as a proto.\n * @internal\n */\nexport class ByteString {\n static readonly EMPTY_BYTE_STRING = new ByteString('');\n\n private constructor(private readonly binaryString: string) {}\n\n static fromBase64String(base64: string): ByteString {\n const binaryString = decodeBase64(base64);\n return new ByteString(binaryString);\n }\n\n static fromUint8Array(array: Uint8Array): ByteString {\n // TODO(indexing); Remove the copy of the byte string here as this method\n // is frequently called during indexing.\n const binaryString = binaryStringFromUint8Array(array);\n return new ByteString(binaryString);\n }\n\n [Symbol.iterator](): Iterator {\n let i = 0;\n return {\n next: () => {\n if (i < this.binaryString.length) {\n return { value: this.binaryString.charCodeAt(i++), done: false };\n } else {\n return { value: undefined, done: true };\n }\n }\n };\n }\n\n toBase64(): string {\n return encodeBase64(this.binaryString);\n }\n\n toUint8Array(): Uint8Array {\n return uint8ArrayFromBinaryString(this.binaryString);\n }\n\n approximateByteSize(): number {\n return this.binaryString.length * 2;\n }\n\n compareTo(other: ByteString): number {\n return primitiveComparator(this.binaryString, other.binaryString);\n }\n\n isEqual(other: ByteString): boolean {\n return this.binaryString === other.binaryString;\n }\n}\n\n/**\n * Helper function to convert an Uint8array to a binary string.\n */\nexport function binaryStringFromUint8Array(array: Uint8Array): string {\n let binaryString = '';\n for (let i = 0; i < array.length; ++i) {\n binaryString += String.fromCharCode(array[i]);\n }\n return binaryString;\n}\n\n/**\n * Helper function to convert a binary string to an Uint8Array.\n */\nexport function uint8ArrayFromBinaryString(binaryString: string): Uint8Array {\n const buffer = new Uint8Array(binaryString.length);\n for (let i = 0; i < binaryString.length; i++) {\n buffer[i] = binaryString.charCodeAt(i);\n }\n return buffer;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Timestamp } from '../protos/firestore_proto_api';\nimport { hardAssert } from '../util/assert';\nimport { ByteString } from '../util/byte_string';\n\n// A RegExp matching ISO 8601 UTC timestamps with optional fraction.\nconst ISO_TIMESTAMP_REG_EXP = new RegExp(\n /^\\d{4}-\\d\\d-\\d\\dT\\d\\d:\\d\\d:\\d\\d(?:\\.(\\d+))?Z$/\n);\n\n/**\n * Converts the possible Proto values for a timestamp value into a \"seconds and\n * nanos\" representation.\n */\nexport function normalizeTimestamp(date: Timestamp): {\n seconds: number;\n nanos: number;\n} {\n hardAssert(!!date, 0x986a, 'Cannot normalize null or undefined timestamp.');\n\n // The json interface (for the browser) will return an iso timestamp string,\n // while the proto js library (for node) will return a\n // google.protobuf.Timestamp instance.\n if (typeof date === 'string') {\n // The date string can have higher precision (nanos) than the Date class\n // (millis), so we do some custom parsing here.\n\n // Parse the nanos right out of the string.\n let nanos = 0;\n const fraction = ISO_TIMESTAMP_REG_EXP.exec(date);\n hardAssert(!!fraction, 0xb5de, 'invalid timestamp', {\n timestamp: date\n });\n if (fraction[1]) {\n // Pad the fraction out to 9 digits (nanos).\n let nanoStr = fraction[1];\n nanoStr = (nanoStr + '000000000').substr(0, 9);\n nanos = Number(nanoStr);\n }\n\n // Parse the date to get the seconds.\n const parsedDate = new Date(date);\n const seconds = Math.floor(parsedDate.getTime() / 1000);\n\n return { seconds, nanos };\n } else {\n // TODO(b/37282237): Use strings for Proto3 timestamps\n // assert(!this.options.useProto3Json,\n // 'The timestamp instance format requires Proto JS.');\n const seconds = normalizeNumber(date.seconds);\n const nanos = normalizeNumber(date.nanos);\n return { seconds, nanos };\n }\n}\n\n/**\n * Converts the possible Proto types for numbers into a JavaScript number.\n * Returns 0 if the value is not numeric.\n */\nexport function normalizeNumber(value: number | string | undefined): number {\n // TODO(bjornick): Handle int64 greater than 53 bits.\n if (typeof value === 'number') {\n return value;\n } else if (typeof value === 'string') {\n return Number(value);\n } else {\n return 0;\n }\n}\n\n/** Converts the possible Proto types for Blobs into a ByteString. */\nexport function normalizeByteString(blob: string | Uint8Array): ByteString {\n if (typeof blob === 'string') {\n return ByteString.fromBase64String(blob);\n } else {\n return ByteString.fromUint8Array(blob);\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isPlainObject } from '../util/input_validation';\n\nimport { Code, FirestoreError } from './error';\n\n/**\n * A list of data types Firestore objects may serialize in their toJSON implemenetations.\n * @private\n * @internal\n */\nexport type JsonTypeDesc =\n | 'object'\n | 'string'\n | 'number'\n | 'boolean'\n | 'null'\n | 'undefined';\n\n/**\n * An association of JsonTypeDesc values to their native types.\n * @private\n * @internal\n */\nexport type TSType = T extends 'object'\n ? object\n : T extends 'string'\n ? string\n : T extends 'number'\n ? number\n : T extends 'boolean'\n ? boolean\n : T extends 'null'\n ? null\n : T extends 'undefined'\n ? undefined\n : never;\n\n/**\n * The representation of a JSON object property name and its type value.\n * @private\n * @internal\n */\nexport interface Property {\n value?: TSType;\n typeString: JsonTypeDesc;\n}\n\n/**\n * A type Firestore data types may use to define the fields used in their JSON serialization.\n * @private\n * @internal\n */\nexport interface JsonSchema {\n [key: string]: Property;\n}\n\n/**\n * Associates the JSON property type to the native type and sets them to be Required.\n * @private\n * @internal\n */\nexport type Json = {\n [K in keyof T]: Required['value'];\n};\n\n/**\n * Helper function to define a JSON schema {@link Property}.\n * @private\n * @internal\n */\nexport function property(\n typeString: T,\n optionalValue?: TSType\n): Property {\n const result: Property = {\n typeString\n };\n if (optionalValue) {\n result.value = optionalValue;\n }\n return result;\n}\n\n/**\n * Validates the JSON object based on the provided schema, and narrows the type to the provided\n * JSON schema.\n * @private\n * @internal\n *\n * @param json A JSON object to validate.\n * @param scheme a {@link JsonSchema} that defines the properties to validate.\n * @returns true if the JSON schema exists within the object. Throws a FirestoreError otherwise.\n */\nexport function validateJSON(\n json: object,\n schema: S\n): json is Json {\n if (!isPlainObject(json)) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'JSON must be an object');\n }\n let error: string | undefined = undefined;\n for (const key in schema) {\n if (schema[key]) {\n const typeString = schema[key].typeString;\n const value: { value: unknown } | undefined =\n 'value' in schema[key] ? { value: schema[key].value } : undefined;\n if (!(key in json)) {\n error = `JSON missing required field: '${key}'`;\n break;\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const fieldValue = (json as any)[key];\n if (typeString && typeof fieldValue !== typeString) {\n error = `JSON field '${key}' must be a ${typeString}.`;\n break;\n } else if (value !== undefined && fieldValue !== value.value) {\n error = `Expected '${key}' field to equal '${value.value}'`;\n break;\n }\n }\n }\n if (error) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, error);\n }\n return true;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Code, FirestoreError } from '../util/error';\n// API extractor fails importing 'property' unless we also explicitly import 'Property'.\n// eslint-disable-next-line @typescript-eslint/no-unused-vars, unused-imports/no-unused-imports-ts\nimport { Property, property, validateJSON } from '../util/json_validation';\nimport { primitiveComparator } from '../util/misc';\n\n// The earliest date supported by Firestore timestamps (0001-01-01T00:00:00Z).\nconst MIN_SECONDS = -62135596800;\n\n// Number of nanoseconds in a millisecond.\nconst MS_TO_NANOS = 1e6;\n\n/**\n * A `Timestamp` represents a point in time independent of any time zone or\n * calendar, represented as seconds and fractions of seconds at nanosecond\n * resolution in UTC Epoch time.\n *\n * It is encoded using the Proleptic Gregorian Calendar which extends the\n * Gregorian calendar backwards to year one. It is encoded assuming all minutes\n * are 60 seconds long, i.e. leap seconds are \"smeared\" so that no leap second\n * table is needed for interpretation. Range is from 0001-01-01T00:00:00Z to\n * 9999-12-31T23:59:59.999999999Z.\n *\n * For examples and further specifications, refer to the\n * {@link https://github.com/google/protobuf/blob/master/src/google/protobuf/timestamp.proto | Timestamp definition}.\n */\nexport class Timestamp {\n /**\n * Creates a new timestamp with the current date, with millisecond precision.\n *\n * @returns a new timestamp representing the current date.\n */\n static now(): Timestamp {\n return Timestamp.fromMillis(Date.now());\n }\n\n /**\n * Creates a new timestamp from the given date.\n *\n * @param date - The date to initialize the `Timestamp` from.\n * @returns A new `Timestamp` representing the same point in time as the given\n * date.\n */\n static fromDate(date: Date): Timestamp {\n return Timestamp.fromMillis(date.getTime());\n }\n\n /**\n * Creates a new timestamp from the given number of milliseconds.\n *\n * @param milliseconds - Number of milliseconds since Unix epoch\n * 1970-01-01T00:00:00Z.\n * @returns A new `Timestamp` representing the same point in time as the given\n * number of milliseconds.\n */\n static fromMillis(milliseconds: number): Timestamp {\n const seconds = Math.floor(milliseconds / 1000);\n const nanos = Math.floor((milliseconds - seconds * 1000) * MS_TO_NANOS);\n return new Timestamp(seconds, nanos);\n }\n\n /**\n * Creates a new timestamp.\n *\n * @param seconds - The number of seconds of UTC time since Unix epoch\n * 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to\n * 9999-12-31T23:59:59Z inclusive.\n * @param nanoseconds - The non-negative fractions of a second at nanosecond\n * resolution. Negative second values with fractions must still have\n * non-negative nanoseconds values that count forward in time. Must be\n * from 0 to 999,999,999 inclusive.\n */\n constructor(\n /**\n * The number of seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z.\n */\n readonly seconds: number,\n /**\n * The fractions of a second at nanosecond resolution.*\n */\n readonly nanoseconds: number\n ) {\n if (nanoseconds < 0) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Timestamp nanoseconds out of range: ' + nanoseconds\n );\n }\n if (nanoseconds >= 1e9) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Timestamp nanoseconds out of range: ' + nanoseconds\n );\n }\n if (seconds < MIN_SECONDS) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Timestamp seconds out of range: ' + seconds\n );\n }\n // This will break in the year 10,000.\n if (seconds >= 253402300800) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Timestamp seconds out of range: ' + seconds\n );\n }\n }\n\n /**\n * Converts a `Timestamp` to a JavaScript `Date` object. This conversion\n * causes a loss of precision since `Date` objects only support millisecond\n * precision.\n *\n * @returns JavaScript `Date` object representing the same point in time as\n * this `Timestamp`, with millisecond precision.\n */\n toDate(): Date {\n return new Date(this.toMillis());\n }\n\n /**\n * Converts a `Timestamp` to a numeric timestamp (in milliseconds since\n * epoch). This operation causes a loss of precision.\n *\n * @returns The point in time corresponding to this timestamp, represented as\n * the number of milliseconds since Unix epoch 1970-01-01T00:00:00Z.\n */\n toMillis(): number {\n return this.seconds * 1000 + this.nanoseconds / MS_TO_NANOS;\n }\n\n _compareTo(other: Timestamp): number {\n if (this.seconds === other.seconds) {\n return primitiveComparator(this.nanoseconds, other.nanoseconds);\n }\n return primitiveComparator(this.seconds, other.seconds);\n }\n\n /**\n * Returns true if this `Timestamp` is equal to the provided one.\n *\n * @param other - The `Timestamp` to compare against.\n * @returns true if this `Timestamp` is equal to the provided one.\n */\n isEqual(other: Timestamp): boolean {\n return (\n other.seconds === this.seconds && other.nanoseconds === this.nanoseconds\n );\n }\n\n /** Returns a textual representation of this `Timestamp`. */\n toString(): string {\n return (\n 'Timestamp(seconds=' +\n this.seconds +\n ', nanoseconds=' +\n this.nanoseconds +\n ')'\n );\n }\n\n static _jsonSchemaVersion: string = 'firestore/timestamp/1.0';\n static _jsonSchema = {\n type: property('string', Timestamp._jsonSchemaVersion),\n seconds: property('number'),\n nanoseconds: property('number')\n };\n\n /**\n * Returns a JSON-serializable representation of this `Timestamp`.\n */\n toJSON(): { seconds: number; nanoseconds: number; type: string } {\n return {\n type: Timestamp._jsonSchemaVersion,\n seconds: this.seconds,\n nanoseconds: this.nanoseconds\n };\n }\n\n /**\n * Builds a `Timestamp` instance from a JSON object created by {@link Timestamp.toJSON}.\n */\n static fromJSON(json: object): Timestamp {\n if (validateJSON(json, Timestamp._jsonSchema)) {\n return new Timestamp(json.seconds, json.nanoseconds);\n }\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Unexpected error creating Timestamp from JSON.'\n );\n }\n\n /**\n * Converts this object to a primitive string, which allows `Timestamp` objects\n * to be compared using the `>`, `<=`, `>=` and `>` operators.\n */\n valueOf(): string {\n // This method returns a string of the form . where\n // is translated to have a non-negative value and both \n // and are left-padded with zeroes to be a consistent length.\n // Strings with this format then have a lexicographical ordering that matches\n // the expected ordering. The translation is done to avoid having\n // a leading negative sign (i.e. a leading '-' character) in its string\n // representation, which would affect its lexicographical ordering.\n const adjustedSeconds = this.seconds - MIN_SECONDS;\n // Note: Up to 12 decimal digits are required to represent all valid\n // 'seconds' values.\n const formattedSeconds = String(adjustedSeconds).padStart(12, '0');\n const formattedNanoseconds = String(this.nanoseconds).padStart(9, '0');\n return formattedSeconds + '.' + formattedNanoseconds;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Timestamp } from '../lite-api/timestamp';\nimport {\n Value as ProtoValue,\n MapValue as ProtoMapValue\n} from '../protos/firestore_proto_api';\n\nimport { normalizeTimestamp } from './normalize';\n\n/**\n * Represents a locally-applied ServerTimestamp.\n *\n * Server Timestamps are backed by MapValues that contain an internal field\n * `__type__` with a value of `server_timestamp`. The previous value and local\n * write time are stored in its `__previous_value__` and `__local_write_time__`\n * fields respectively.\n *\n * Notes:\n * - ServerTimestampValue instances are created as the result of applying a\n * transform. They can only exist in the local view of a document. Therefore\n * they do not need to be parsed or serialized.\n * - When evaluated locally (e.g. for snapshot.data()), they by default\n * evaluate to `null`. This behavior can be configured by passing custom\n * FieldValueOptions to value().\n * - With respect to other ServerTimestampValues, they sort by their\n * localWriteTime.\n */\n\nconst SERVER_TIMESTAMP_SENTINEL = 'server_timestamp';\nconst TYPE_KEY = '__type__';\nconst PREVIOUS_VALUE_KEY = '__previous_value__';\nconst LOCAL_WRITE_TIME_KEY = '__local_write_time__';\n\nexport function isServerTimestamp(value: ProtoValue | null): boolean {\n const type = (value?.mapValue?.fields || {})[TYPE_KEY]?.stringValue;\n return type === SERVER_TIMESTAMP_SENTINEL;\n}\n\n/**\n * Creates a new ServerTimestamp proto value (using the internal format).\n */\nexport function serverTimestamp(\n localWriteTime: Timestamp,\n previousValue: ProtoValue | null\n): ProtoValue {\n const mapValue: ProtoMapValue = {\n fields: {\n [TYPE_KEY]: {\n stringValue: SERVER_TIMESTAMP_SENTINEL\n },\n [LOCAL_WRITE_TIME_KEY]: {\n timestampValue: {\n seconds: localWriteTime.seconds,\n nanos: localWriteTime.nanoseconds\n }\n }\n }\n };\n\n // We should avoid storing deeply nested server timestamp map values\n // because we never use the intermediate \"previous values\".\n // For example:\n // previous: 42L, add: t1, result: t1 -> 42L\n // previous: t1, add: t2, result: t2 -> 42L (NOT t2 -> t1 -> 42L)\n // previous: t2, add: t3, result: t3 -> 42L (NOT t3 -> t2 -> t1 -> 42L)\n // `getPreviousValue` recursively traverses server timestamps to find the\n // least recent Value.\n if (previousValue && isServerTimestamp(previousValue)) {\n previousValue = getPreviousValue(previousValue);\n }\n if (previousValue) {\n mapValue.fields![PREVIOUS_VALUE_KEY] = previousValue;\n }\n\n return { mapValue };\n}\n\n/**\n * Returns the value of the field before this ServerTimestamp was set.\n *\n * Preserving the previous values allows the user to display the last resoled\n * value until the backend responds with the timestamp.\n */\nexport function getPreviousValue(value: ProtoValue): ProtoValue | null {\n const previousValue = value.mapValue!.fields![PREVIOUS_VALUE_KEY];\n\n if (isServerTimestamp(previousValue)) {\n return getPreviousValue(previousValue);\n }\n return previousValue;\n}\n\n/**\n * Returns the local time at which this timestamp was first set.\n */\nexport function getLocalWriteTime(value: ProtoValue): Timestamp {\n const localWriteTime = normalizeTimestamp(\n value.mapValue!.fields![LOCAL_WRITE_TIME_KEY].timestampValue!\n );\n return new Timestamp(localWriteTime.seconds, localWriteTime.nanos);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DatabaseId } from '../core/database_info';\nimport {\n ArrayValue,\n LatLng,\n MapValue,\n Timestamp,\n Value as ProtoValue,\n Value\n} from '../protos/firestore_proto_api';\nimport { fail } from '../util/assert';\nimport {\n arrayEquals,\n compareUtf8Strings,\n primitiveComparator\n} from '../util/misc';\nimport { forEach, objectSize } from '../util/obj';\nimport { isNegativeZero } from '../util/types';\n\nimport { DocumentKey } from './document_key';\nimport {\n normalizeByteString,\n normalizeNumber,\n normalizeTimestamp\n} from './normalize';\nimport {\n getLocalWriteTime,\n getPreviousValue,\n isServerTimestamp\n} from './server_timestamps';\nimport { TypeOrder } from './type_order';\n\nexport const TYPE_KEY = '__type__';\nconst MAX_VALUE_TYPE = '__max__';\nexport const MAX_VALUE: Value = {\n mapValue: {\n fields: {\n '__type__': { stringValue: MAX_VALUE_TYPE }\n }\n }\n};\n\nexport const VECTOR_VALUE_SENTINEL = '__vector__';\nexport const VECTOR_MAP_VECTORS_KEY = 'value';\n\nexport const MIN_VALUE: Value = {\n nullValue: 'NULL_VALUE'\n};\n\n/** Extracts the backend's type order for the provided value. */\nexport function typeOrder(value: Value): TypeOrder {\n if ('nullValue' in value) {\n return TypeOrder.NullValue;\n } else if ('booleanValue' in value) {\n return TypeOrder.BooleanValue;\n } else if ('integerValue' in value || 'doubleValue' in value) {\n return TypeOrder.NumberValue;\n } else if ('timestampValue' in value) {\n return TypeOrder.TimestampValue;\n } else if ('stringValue' in value) {\n return TypeOrder.StringValue;\n } else if ('bytesValue' in value) {\n return TypeOrder.BlobValue;\n } else if ('referenceValue' in value) {\n return TypeOrder.RefValue;\n } else if ('geoPointValue' in value) {\n return TypeOrder.GeoPointValue;\n } else if ('arrayValue' in value) {\n return TypeOrder.ArrayValue;\n } else if ('mapValue' in value) {\n if (isServerTimestamp(value)) {\n return TypeOrder.ServerTimestampValue;\n } else if (isMaxValue(value)) {\n return TypeOrder.MaxValue;\n } else if (isVectorValue(value)) {\n return TypeOrder.VectorValue;\n }\n return TypeOrder.ObjectValue;\n } else {\n return fail(0x6e87, 'Invalid value type', { value });\n }\n}\n\n/** Tests `left` and `right` for equality based on the backend semantics. */\nexport function valueEquals(left: Value, right: Value): boolean {\n if (left === right) {\n return true;\n }\n\n const leftType = typeOrder(left);\n const rightType = typeOrder(right);\n if (leftType !== rightType) {\n return false;\n }\n\n switch (leftType) {\n case TypeOrder.NullValue:\n return true;\n case TypeOrder.BooleanValue:\n return left.booleanValue === right.booleanValue;\n case TypeOrder.ServerTimestampValue:\n return getLocalWriteTime(left).isEqual(getLocalWriteTime(right));\n case TypeOrder.TimestampValue:\n return timestampEquals(left, right);\n case TypeOrder.StringValue:\n return left.stringValue === right.stringValue;\n case TypeOrder.BlobValue:\n return blobEquals(left, right);\n case TypeOrder.RefValue:\n return left.referenceValue === right.referenceValue;\n case TypeOrder.GeoPointValue:\n return geoPointEquals(left, right);\n case TypeOrder.NumberValue:\n return numberEquals(left, right);\n case TypeOrder.ArrayValue:\n return arrayEquals(\n left.arrayValue!.values || [],\n right.arrayValue!.values || [],\n valueEquals\n );\n case TypeOrder.VectorValue:\n case TypeOrder.ObjectValue:\n return objectEquals(left, right);\n case TypeOrder.MaxValue:\n return true;\n default:\n return fail(0xcbf8, 'Unexpected value type', { left });\n }\n}\n\nfunction timestampEquals(left: Value, right: Value): boolean {\n if (\n typeof left.timestampValue === 'string' &&\n typeof right.timestampValue === 'string' &&\n left.timestampValue.length === right.timestampValue.length\n ) {\n // Use string equality for ISO 8601 timestamps\n return left.timestampValue === right.timestampValue;\n }\n\n const leftTimestamp = normalizeTimestamp(left.timestampValue!);\n const rightTimestamp = normalizeTimestamp(right.timestampValue!);\n return (\n leftTimestamp.seconds === rightTimestamp.seconds &&\n leftTimestamp.nanos === rightTimestamp.nanos\n );\n}\n\nfunction geoPointEquals(left: Value, right: Value): boolean {\n return (\n normalizeNumber(left.geoPointValue!.latitude) ===\n normalizeNumber(right.geoPointValue!.latitude) &&\n normalizeNumber(left.geoPointValue!.longitude) ===\n normalizeNumber(right.geoPointValue!.longitude)\n );\n}\n\nfunction blobEquals(left: Value, right: Value): boolean {\n return normalizeByteString(left.bytesValue!).isEqual(\n normalizeByteString(right.bytesValue!)\n );\n}\n\nexport function numberEquals(left: Value, right: Value): boolean {\n if ('integerValue' in left && 'integerValue' in right) {\n return (\n normalizeNumber(left.integerValue) === normalizeNumber(right.integerValue)\n );\n } else if ('doubleValue' in left && 'doubleValue' in right) {\n const n1 = normalizeNumber(left.doubleValue!);\n const n2 = normalizeNumber(right.doubleValue!);\n\n if (n1 === n2) {\n return isNegativeZero(n1) === isNegativeZero(n2);\n } else {\n return isNaN(n1) && isNaN(n2);\n }\n }\n\n return false;\n}\n\nfunction objectEquals(left: Value, right: Value): boolean {\n const leftMap = left.mapValue!.fields || {};\n const rightMap = right.mapValue!.fields || {};\n\n if (objectSize(leftMap) !== objectSize(rightMap)) {\n return false;\n }\n\n for (const key in leftMap) {\n if (leftMap.hasOwnProperty(key)) {\n if (\n rightMap[key] === undefined ||\n !valueEquals(leftMap[key], rightMap[key])\n ) {\n return false;\n }\n }\n }\n return true;\n}\n\n/** Returns true if the ArrayValue contains the specified element. */\nexport function arrayValueContains(\n haystack: ArrayValue,\n needle: Value\n): boolean {\n return (\n (haystack.values || []).find(v => valueEquals(v, needle)) !== undefined\n );\n}\n\nexport function valueCompare(left: Value, right: Value): number {\n if (left === right) {\n return 0;\n }\n\n const leftType = typeOrder(left);\n const rightType = typeOrder(right);\n\n if (leftType !== rightType) {\n return primitiveComparator(leftType, rightType);\n }\n\n switch (leftType) {\n case TypeOrder.NullValue:\n case TypeOrder.MaxValue:\n return 0;\n case TypeOrder.BooleanValue:\n return primitiveComparator(left.booleanValue!, right.booleanValue!);\n case TypeOrder.NumberValue:\n return compareNumbers(left, right);\n case TypeOrder.TimestampValue:\n return compareTimestamps(left.timestampValue!, right.timestampValue!);\n case TypeOrder.ServerTimestampValue:\n return compareTimestamps(\n getLocalWriteTime(left),\n getLocalWriteTime(right)\n );\n case TypeOrder.StringValue:\n return compareUtf8Strings(left.stringValue!, right.stringValue!);\n case TypeOrder.BlobValue:\n return compareBlobs(left.bytesValue!, right.bytesValue!);\n case TypeOrder.RefValue:\n return compareReferences(left.referenceValue!, right.referenceValue!);\n case TypeOrder.GeoPointValue:\n return compareGeoPoints(left.geoPointValue!, right.geoPointValue!);\n case TypeOrder.ArrayValue:\n return compareArrays(left.arrayValue!, right.arrayValue!);\n case TypeOrder.VectorValue:\n return compareVectors(left.mapValue!, right.mapValue!);\n case TypeOrder.ObjectValue:\n return compareMaps(left.mapValue!, right.mapValue!);\n default:\n throw fail(0x5ae0, 'Invalid value type', { leftType });\n }\n}\n\nfunction compareNumbers(left: Value, right: Value): number {\n const leftNumber = normalizeNumber(left.integerValue || left.doubleValue);\n const rightNumber = normalizeNumber(right.integerValue || right.doubleValue);\n\n if (leftNumber < rightNumber) {\n return -1;\n } else if (leftNumber > rightNumber) {\n return 1;\n } else if (leftNumber === rightNumber) {\n return 0;\n } else {\n // one or both are NaN.\n if (isNaN(leftNumber)) {\n return isNaN(rightNumber) ? 0 : -1;\n } else {\n return 1;\n }\n }\n}\n\nfunction compareTimestamps(left: Timestamp, right: Timestamp): number {\n if (\n typeof left === 'string' &&\n typeof right === 'string' &&\n left.length === right.length\n ) {\n return primitiveComparator(left, right);\n }\n\n const leftTimestamp = normalizeTimestamp(left);\n const rightTimestamp = normalizeTimestamp(right);\n\n const comparison = primitiveComparator(\n leftTimestamp.seconds,\n rightTimestamp.seconds\n );\n if (comparison !== 0) {\n return comparison;\n }\n return primitiveComparator(leftTimestamp.nanos, rightTimestamp.nanos);\n}\n\nfunction compareReferences(leftPath: string, rightPath: string): number {\n const leftSegments = leftPath.split('/');\n const rightSegments = rightPath.split('/');\n for (let i = 0; i < leftSegments.length && i < rightSegments.length; i++) {\n const comparison = primitiveComparator(leftSegments[i], rightSegments[i]);\n if (comparison !== 0) {\n return comparison;\n }\n }\n return primitiveComparator(leftSegments.length, rightSegments.length);\n}\n\nfunction compareGeoPoints(left: LatLng, right: LatLng): number {\n const comparison = primitiveComparator(\n normalizeNumber(left.latitude),\n normalizeNumber(right.latitude)\n );\n if (comparison !== 0) {\n return comparison;\n }\n return primitiveComparator(\n normalizeNumber(left.longitude),\n normalizeNumber(right.longitude)\n );\n}\n\nfunction compareBlobs(\n left: string | Uint8Array,\n right: string | Uint8Array\n): number {\n const leftBytes = normalizeByteString(left);\n const rightBytes = normalizeByteString(right);\n return leftBytes.compareTo(rightBytes);\n}\n\nfunction compareArrays(left: ArrayValue, right: ArrayValue): number {\n const leftArray = left.values || [];\n const rightArray = right.values || [];\n\n for (let i = 0; i < leftArray.length && i < rightArray.length; ++i) {\n const compare = valueCompare(leftArray[i], rightArray[i]);\n if (compare) {\n return compare;\n }\n }\n return primitiveComparator(leftArray.length, rightArray.length);\n}\n\nfunction compareVectors(left: MapValue, right: MapValue): number {\n const leftMap = left.fields || {};\n const rightMap = right.fields || {};\n\n // The vector is a map, but only vector value is compared.\n const leftArrayValue = leftMap[VECTOR_MAP_VECTORS_KEY]?.arrayValue;\n const rightArrayValue = rightMap[VECTOR_MAP_VECTORS_KEY]?.arrayValue;\n\n const lengthCompare = primitiveComparator(\n leftArrayValue?.values?.length || 0,\n rightArrayValue?.values?.length || 0\n );\n if (lengthCompare !== 0) {\n return lengthCompare;\n }\n\n return compareArrays(leftArrayValue!, rightArrayValue!);\n}\n\nfunction compareMaps(left: MapValue, right: MapValue): number {\n if (left === MAX_VALUE.mapValue && right === MAX_VALUE.mapValue) {\n return 0;\n } else if (left === MAX_VALUE.mapValue) {\n return 1;\n } else if (right === MAX_VALUE.mapValue) {\n return -1;\n }\n\n const leftMap = left.fields || {};\n const leftKeys = Object.keys(leftMap);\n const rightMap = right.fields || {};\n const rightKeys = Object.keys(rightMap);\n\n // Even though MapValues are likely sorted correctly based on their insertion\n // order (e.g. when received from the backend), local modifications can bring\n // elements out of order. We need to re-sort the elements to ensure that\n // canonical IDs are independent of insertion order.\n leftKeys.sort();\n rightKeys.sort();\n\n for (let i = 0; i < leftKeys.length && i < rightKeys.length; ++i) {\n const keyCompare = compareUtf8Strings(leftKeys[i], rightKeys[i]);\n if (keyCompare !== 0) {\n return keyCompare;\n }\n const compare = valueCompare(leftMap[leftKeys[i]], rightMap[rightKeys[i]]);\n if (compare !== 0) {\n return compare;\n }\n }\n\n return primitiveComparator(leftKeys.length, rightKeys.length);\n}\n\n/**\n * Generates the canonical ID for the provided field value (as used in Target\n * serialization).\n */\nexport function canonicalId(value: Value): string {\n return canonifyValue(value);\n}\n\nfunction canonifyValue(value: Value): string {\n if ('nullValue' in value) {\n return 'null';\n } else if ('booleanValue' in value) {\n return '' + value.booleanValue!;\n } else if ('integerValue' in value) {\n return '' + value.integerValue!;\n } else if ('doubleValue' in value) {\n return '' + value.doubleValue!;\n } else if ('timestampValue' in value) {\n return canonifyTimestamp(value.timestampValue!);\n } else if ('stringValue' in value) {\n return value.stringValue!;\n } else if ('bytesValue' in value) {\n return canonifyByteString(value.bytesValue!);\n } else if ('referenceValue' in value) {\n return canonifyReference(value.referenceValue!);\n } else if ('geoPointValue' in value) {\n return canonifyGeoPoint(value.geoPointValue!);\n } else if ('arrayValue' in value) {\n return canonifyArray(value.arrayValue!);\n } else if ('mapValue' in value) {\n return canonifyMap(value.mapValue!);\n } else {\n return fail(0xee4d, 'Invalid value type', { value });\n }\n}\n\nfunction canonifyByteString(byteString: string | Uint8Array): string {\n return normalizeByteString(byteString).toBase64();\n}\n\nfunction canonifyTimestamp(timestamp: Timestamp): string {\n const normalizedTimestamp = normalizeTimestamp(timestamp);\n return `time(${normalizedTimestamp.seconds},${normalizedTimestamp.nanos})`;\n}\n\nfunction canonifyGeoPoint(geoPoint: LatLng): string {\n return `geo(${geoPoint.latitude},${geoPoint.longitude})`;\n}\n\nfunction canonifyReference(referenceValue: string): string {\n return DocumentKey.fromName(referenceValue).toString();\n}\n\nfunction canonifyMap(mapValue: MapValue): string {\n // Iteration order in JavaScript is not guaranteed. To ensure that we generate\n // matching canonical IDs for identical maps, we need to sort the keys.\n const sortedKeys = Object.keys(mapValue.fields || {}).sort();\n\n let result = '{';\n let first = true;\n for (const key of sortedKeys) {\n if (!first) {\n result += ',';\n } else {\n first = false;\n }\n result += `${key}:${canonifyValue(mapValue.fields![key])}`;\n }\n return result + '}';\n}\n\nfunction canonifyArray(arrayValue: ArrayValue): string {\n let result = '[';\n let first = true;\n for (const value of arrayValue.values || []) {\n if (!first) {\n result += ',';\n } else {\n first = false;\n }\n result += canonifyValue(value);\n }\n return result + ']';\n}\n\n/**\n * Returns an approximate (and wildly inaccurate) in-memory size for the field\n * value.\n *\n * The memory size takes into account only the actual user data as it resides\n * in memory and ignores object overhead.\n */\nexport function estimateByteSize(value: Value): number {\n switch (typeOrder(value)) {\n case TypeOrder.NullValue:\n return 4;\n case TypeOrder.BooleanValue:\n return 4;\n case TypeOrder.NumberValue:\n return 8;\n case TypeOrder.TimestampValue:\n // Timestamps are made up of two distinct numbers (seconds + nanoseconds)\n return 16;\n case TypeOrder.ServerTimestampValue:\n const previousValue = getPreviousValue(value);\n return previousValue ? 16 + estimateByteSize(previousValue) : 16;\n case TypeOrder.StringValue:\n // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures:\n // \"JavaScript's String type is [...] a set of elements of 16-bit unsigned\n // integer values\"\n return value.stringValue!.length * 2;\n case TypeOrder.BlobValue:\n return normalizeByteString(value.bytesValue!).approximateByteSize();\n case TypeOrder.RefValue:\n return value.referenceValue!.length;\n case TypeOrder.GeoPointValue:\n // GeoPoints are made up of two distinct numbers (latitude + longitude)\n return 16;\n case TypeOrder.ArrayValue:\n return estimateArrayByteSize(value.arrayValue!);\n case TypeOrder.VectorValue:\n case TypeOrder.ObjectValue:\n return estimateMapByteSize(value.mapValue!);\n default:\n throw fail(0x34ae, 'Invalid value type', { value });\n }\n}\n\nfunction estimateMapByteSize(mapValue: MapValue): number {\n let size = 0;\n forEach(mapValue.fields, (key, val) => {\n size += key.length + estimateByteSize(val);\n });\n return size;\n}\n\nfunction estimateArrayByteSize(arrayValue: ArrayValue): number {\n return (arrayValue.values || []).reduce(\n (previousSize, value) => previousSize + estimateByteSize(value),\n 0\n );\n}\n\n/** Returns a reference value for the provided database and key. */\nexport function refValue(databaseId: DatabaseId, key: DocumentKey): Value {\n return {\n referenceValue: `projects/${databaseId.projectId}/databases/${\n databaseId.database\n }/documents/${key.path.canonicalString()}`\n };\n}\n\n/** Returns true if `value` is an IntegerValue . */\nexport function isInteger(\n value?: Value | null\n): value is { integerValue: string | number } {\n return !!value && 'integerValue' in value;\n}\n\n/** Returns true if `value` is a DoubleValue. */\nexport function isDouble(\n value?: Value | null\n): value is { doubleValue: string | number } {\n return !!value && 'doubleValue' in value;\n}\n\n/** Returns true if `value` is either an IntegerValue or a DoubleValue. */\nexport function isNumber(value?: Value | null): boolean {\n return isInteger(value) || isDouble(value);\n}\n\n/** Returns true if `value` is an ArrayValue. */\nexport function isArray(\n value?: Value | null\n): value is { arrayValue: ArrayValue } {\n return !!value && 'arrayValue' in value;\n}\n\n/** Returns true if `value` is a ReferenceValue. */\nexport function isReferenceValue(\n value?: Value | null\n): value is { referenceValue: string } {\n return !!value && 'referenceValue' in value;\n}\n\n/** Returns true if `value` is a NullValue. */\nexport function isNullValue(\n value?: Value | null\n): value is { nullValue: 'NULL_VALUE' } {\n return !!value && 'nullValue' in value;\n}\n\n/** Returns true if `value` is NaN. */\nexport function isNanValue(\n value?: Value | null\n): value is { doubleValue: 'NaN' | number } {\n return !!value && 'doubleValue' in value && isNaN(Number(value.doubleValue));\n}\n\n/** Returns true if `value` is a MapValue. */\nexport function isMapValue(\n value?: Value | null\n): value is { mapValue: MapValue } {\n return !!value && 'mapValue' in value;\n}\n\n/** Returns true if `value` is a VetorValue. */\nexport function isVectorValue(value: ProtoValue | null): boolean {\n const type = (value?.mapValue?.fields || {})[TYPE_KEY]?.stringValue;\n return type === VECTOR_VALUE_SENTINEL;\n}\n\n/** Creates a deep copy of `source`. */\nexport function deepClone(source: Value): Value {\n if (source.geoPointValue) {\n return { geoPointValue: { ...source.geoPointValue } };\n } else if (\n source.timestampValue &&\n typeof source.timestampValue === 'object'\n ) {\n return { timestampValue: { ...source.timestampValue } };\n } else if (source.mapValue) {\n const target: Value = { mapValue: { fields: {} } };\n forEach(\n source.mapValue.fields,\n (key, val) => (target.mapValue!.fields![key] = deepClone(val))\n );\n return target;\n } else if (source.arrayValue) {\n const target: Value = { arrayValue: { values: [] } };\n for (let i = 0; i < (source.arrayValue.values || []).length; ++i) {\n target.arrayValue!.values![i] = deepClone(source.arrayValue.values![i]);\n }\n return target;\n } else {\n return { ...source };\n }\n}\n\n/** Returns true if the Value represents the canonical {@link #MAX_VALUE} . */\nexport function isMaxValue(value: Value): boolean {\n return (\n (((value.mapValue || {}).fields || {})['__type__'] || {}).stringValue ===\n MAX_VALUE_TYPE\n );\n}\n\nexport const MIN_VECTOR_VALUE = {\n mapValue: {\n fields: {\n [TYPE_KEY]: { stringValue: VECTOR_VALUE_SENTINEL },\n [VECTOR_MAP_VECTORS_KEY]: {\n arrayValue: {}\n }\n }\n }\n};\n\n/** Returns the lowest value for the given value type (inclusive). */\nexport function valuesGetLowerBound(value: Value): Value {\n if ('nullValue' in value) {\n return MIN_VALUE;\n } else if ('booleanValue' in value) {\n return { booleanValue: false };\n } else if ('integerValue' in value || 'doubleValue' in value) {\n return { doubleValue: NaN };\n } else if ('timestampValue' in value) {\n return { timestampValue: { seconds: Number.MIN_SAFE_INTEGER } };\n } else if ('stringValue' in value) {\n return { stringValue: '' };\n } else if ('bytesValue' in value) {\n return { bytesValue: '' };\n } else if ('referenceValue' in value) {\n return refValue(DatabaseId.empty(), DocumentKey.empty());\n } else if ('geoPointValue' in value) {\n return { geoPointValue: { latitude: -90, longitude: -180 } };\n } else if ('arrayValue' in value) {\n return { arrayValue: {} };\n } else if ('mapValue' in value) {\n if (isVectorValue(value)) {\n return MIN_VECTOR_VALUE;\n }\n return { mapValue: {} };\n } else {\n return fail(0x8c66, 'Invalid value type', { value });\n }\n}\n\n/** Returns the largest value for the given value type (exclusive). */\nexport function valuesGetUpperBound(value: Value): Value {\n if ('nullValue' in value) {\n return { booleanValue: false };\n } else if ('booleanValue' in value) {\n return { doubleValue: NaN };\n } else if ('integerValue' in value || 'doubleValue' in value) {\n return { timestampValue: { seconds: Number.MIN_SAFE_INTEGER } };\n } else if ('timestampValue' in value) {\n return { stringValue: '' };\n } else if ('stringValue' in value) {\n return { bytesValue: '' };\n } else if ('bytesValue' in value) {\n return refValue(DatabaseId.empty(), DocumentKey.empty());\n } else if ('referenceValue' in value) {\n return { geoPointValue: { latitude: -90, longitude: -180 } };\n } else if ('geoPointValue' in value) {\n return { arrayValue: {} };\n } else if ('arrayValue' in value) {\n return MIN_VECTOR_VALUE;\n } else if ('mapValue' in value) {\n if (isVectorValue(value)) {\n return { mapValue: {} };\n }\n return MAX_VALUE;\n } else {\n return fail(0xf207, 'Invalid value type', { value });\n }\n}\n\nexport function lowerBoundCompare(\n left: { value: Value; inclusive: boolean },\n right: { value: Value; inclusive: boolean }\n): number {\n const cmp = valueCompare(left.value, right.value);\n if (cmp !== 0) {\n return cmp;\n }\n\n if (left.inclusive && !right.inclusive) {\n return -1;\n } else if (!left.inclusive && right.inclusive) {\n return 1;\n }\n\n return 0;\n}\n\nexport function upperBoundCompare(\n left: { value: Value; inclusive: boolean },\n right: { value: Value; inclusive: boolean }\n): number {\n const cmp = valueCompare(left.value, right.value);\n if (cmp !== 0) {\n return cmp;\n }\n\n if (left.inclusive && !right.inclusive) {\n return 1;\n } else if (!left.inclusive && right.inclusive) {\n return -1;\n }\n\n return 0;\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { isReferenceValue, valueCompare, valueEquals } from '../model/values';\nimport { Value as ProtoValue } from '../protos/firestore_proto_api';\nimport { debugAssert } from '../util/assert';\n\nimport { Direction, OrderBy } from './order_by';\n\n/**\n * Represents a bound of a query.\n *\n * The bound is specified with the given components representing a position and\n * whether it's just before or just after the position (relative to whatever the\n * query order is).\n *\n * The position represents a logical index position for a query. It's a prefix\n * of values for the (potentially implicit) order by clauses of a query.\n *\n * Bound provides a function to determine whether a document comes before or\n * after a bound. This is influenced by whether the position is just before or\n * just after the provided values.\n */\nexport class Bound {\n constructor(readonly position: ProtoValue[], readonly inclusive: boolean) {}\n}\n\nfunction boundCompareToDocument(\n bound: Bound,\n orderBy: OrderBy[],\n doc: Document\n): number {\n debugAssert(\n bound.position.length <= orderBy.length,\n \"Bound has more components than query's orderBy\"\n );\n let comparison = 0;\n for (let i = 0; i < bound.position.length; i++) {\n const orderByComponent = orderBy[i];\n const component = bound.position[i];\n if (orderByComponent.field.isKeyField()) {\n debugAssert(\n isReferenceValue(component),\n 'Bound has a non-key value where the key path is being used.'\n );\n comparison = DocumentKey.comparator(\n DocumentKey.fromName(component.referenceValue),\n doc.key\n );\n } else {\n const docValue = doc.data.field(orderByComponent.field);\n debugAssert(\n docValue !== null,\n 'Field should exist since document matched the orderBy already.'\n );\n comparison = valueCompare(component, docValue);\n }\n if (orderByComponent.dir === Direction.DESCENDING) {\n comparison = comparison * -1;\n }\n if (comparison !== 0) {\n break;\n }\n }\n return comparison;\n}\n\n/**\n * Returns true if a document sorts after a bound using the provided sort\n * order.\n */\nexport function boundSortsAfterDocument(\n bound: Bound,\n orderBy: OrderBy[],\n doc: Document\n): boolean {\n const comparison = boundCompareToDocument(bound, orderBy, doc);\n return bound.inclusive ? comparison >= 0 : comparison > 0;\n}\n\n/**\n * Returns true if a document sorts before a bound using the provided sort\n * order.\n */\nexport function boundSortsBeforeDocument(\n bound: Bound,\n orderBy: OrderBy[],\n doc: Document\n): boolean {\n const comparison = boundCompareToDocument(bound, orderBy, doc);\n return bound.inclusive ? comparison <= 0 : comparison < 0;\n}\n\nexport function boundEquals(left: Bound | null, right: Bound | null): boolean {\n if (left === null) {\n return right === null;\n } else if (right === null) {\n return false;\n }\n\n if (\n left.inclusive !== right.inclusive ||\n left.position.length !== right.position.length\n ) {\n return false;\n }\n for (let i = 0; i < left.position.length; i++) {\n const leftPosition = left.position[i];\n const rightPosition = right.position[i];\n if (!valueEquals(leftPosition, rightPosition)) {\n return false;\n }\n }\n return true;\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { FieldPath } from '../model/path';\nimport {\n arrayValueContains,\n canonicalId,\n isArray,\n isReferenceValue,\n typeOrder,\n valueCompare,\n valueEquals\n} from '../model/values';\nimport { Value as ProtoValue } from '../protos/firestore_proto_api';\nimport { debugAssert, fail } from '../util/assert';\n\n// The operator of a FieldFilter\nexport const enum Operator {\n LESS_THAN = '<',\n LESS_THAN_OR_EQUAL = '<=',\n EQUAL = '==',\n NOT_EQUAL = '!=',\n GREATER_THAN = '>',\n GREATER_THAN_OR_EQUAL = '>=',\n ARRAY_CONTAINS = 'array-contains',\n IN = 'in',\n NOT_IN = 'not-in',\n ARRAY_CONTAINS_ANY = 'array-contains-any'\n}\n\n// The operator of a CompositeFilter\nexport const enum CompositeOperator {\n OR = 'or',\n AND = 'and'\n}\n\nexport abstract class Filter {\n abstract matches(doc: Document): boolean;\n\n abstract getFlattenedFilters(): readonly FieldFilter[];\n\n abstract getFilters(): Filter[];\n}\n\nexport class FieldFilter extends Filter {\n protected constructor(\n public readonly field: FieldPath,\n public readonly op: Operator,\n public readonly value: ProtoValue\n ) {\n super();\n }\n\n /**\n * Creates a filter based on the provided arguments.\n */\n static create(\n field: FieldPath,\n op: Operator,\n value: ProtoValue\n ): FieldFilter {\n if (field.isKeyField()) {\n if (op === Operator.IN || op === Operator.NOT_IN) {\n return this.createKeyFieldInFilter(field, op, value);\n } else {\n debugAssert(\n isReferenceValue(value),\n 'Comparing on key, but filter value not a RefValue'\n );\n debugAssert(\n op !== Operator.ARRAY_CONTAINS && op !== Operator.ARRAY_CONTAINS_ANY,\n `'${op.toString()}' queries don't make sense on document keys.`\n );\n return new KeyFieldFilter(field, op, value);\n }\n } else if (op === Operator.ARRAY_CONTAINS) {\n return new ArrayContainsFilter(field, value);\n } else if (op === Operator.IN) {\n debugAssert(\n isArray(value),\n 'IN filter has invalid value: ' + value.toString()\n );\n return new InFilter(field, value);\n } else if (op === Operator.NOT_IN) {\n debugAssert(\n isArray(value),\n 'NOT_IN filter has invalid value: ' + value.toString()\n );\n return new NotInFilter(field, value);\n } else if (op === Operator.ARRAY_CONTAINS_ANY) {\n debugAssert(\n isArray(value),\n 'ARRAY_CONTAINS_ANY filter has invalid value: ' + value.toString()\n );\n return new ArrayContainsAnyFilter(field, value);\n } else {\n return new FieldFilter(field, op, value);\n }\n }\n\n private static createKeyFieldInFilter(\n field: FieldPath,\n op: Operator.IN | Operator.NOT_IN,\n value: ProtoValue\n ): FieldFilter {\n debugAssert(\n isArray(value),\n `Comparing on key with ${op.toString()}` +\n ', but filter value not an ArrayValue'\n );\n debugAssert(\n (value.arrayValue.values || []).every(elem => isReferenceValue(elem)),\n `Comparing on key with ${op.toString()}` +\n ', but an array value was not a RefValue'\n );\n\n return op === Operator.IN\n ? new KeyFieldInFilter(field, value)\n : new KeyFieldNotInFilter(field, value);\n }\n\n matches(doc: Document): boolean {\n const other = doc.data.field(this.field);\n // Types do not have to match in NOT_EQUAL filters.\n if (this.op === Operator.NOT_EQUAL) {\n return (\n other !== null &&\n other.nullValue === undefined &&\n this.matchesComparison(valueCompare(other!, this.value))\n );\n }\n\n // Only compare types with matching backend order (such as double and int).\n return (\n other !== null &&\n typeOrder(this.value) === typeOrder(other) &&\n this.matchesComparison(valueCompare(other, this.value))\n );\n }\n\n protected matchesComparison(comparison: number): boolean {\n switch (this.op) {\n case Operator.LESS_THAN:\n return comparison < 0;\n case Operator.LESS_THAN_OR_EQUAL:\n return comparison <= 0;\n case Operator.EQUAL:\n return comparison === 0;\n case Operator.NOT_EQUAL:\n return comparison !== 0;\n case Operator.GREATER_THAN:\n return comparison > 0;\n case Operator.GREATER_THAN_OR_EQUAL:\n return comparison >= 0;\n default:\n return fail(0xb8a2, 'Unknown FieldFilter operator', {\n operator: this.op\n });\n }\n }\n\n isInequality(): boolean {\n return (\n [\n Operator.LESS_THAN,\n Operator.LESS_THAN_OR_EQUAL,\n Operator.GREATER_THAN,\n Operator.GREATER_THAN_OR_EQUAL,\n Operator.NOT_EQUAL,\n Operator.NOT_IN\n ].indexOf(this.op) >= 0\n );\n }\n\n getFlattenedFilters(): readonly FieldFilter[] {\n return [this];\n }\n\n getFilters(): Filter[] {\n return [this];\n }\n}\n\nexport class CompositeFilter extends Filter {\n private memoizedFlattenedFilters: FieldFilter[] | null = null;\n\n protected constructor(\n public readonly filters: readonly Filter[],\n public readonly op: CompositeOperator\n ) {\n super();\n }\n\n /**\n * Creates a filter based on the provided arguments.\n */\n static create(filters: Filter[], op: CompositeOperator): CompositeFilter {\n return new CompositeFilter(filters, op);\n }\n\n matches(doc: Document): boolean {\n if (compositeFilterIsConjunction(this)) {\n // For conjunctions, all filters must match, so return false if any filter doesn't match.\n return this.filters.find(filter => !filter.matches(doc)) === undefined;\n } else {\n // For disjunctions, at least one filter should match.\n return this.filters.find(filter => filter.matches(doc)) !== undefined;\n }\n }\n\n getFlattenedFilters(): readonly FieldFilter[] {\n if (this.memoizedFlattenedFilters !== null) {\n return this.memoizedFlattenedFilters;\n }\n\n this.memoizedFlattenedFilters = this.filters.reduce((result, subfilter) => {\n return result.concat(subfilter.getFlattenedFilters());\n }, [] as FieldFilter[]);\n\n return this.memoizedFlattenedFilters;\n }\n\n // Returns a mutable copy of `this.filters`\n getFilters(): Filter[] {\n return Object.assign([], this.filters);\n }\n}\n\nexport function compositeFilterIsConjunction(\n compositeFilter: CompositeFilter\n): boolean {\n return compositeFilter.op === CompositeOperator.AND;\n}\n\nexport function compositeFilterIsDisjunction(\n compositeFilter: CompositeFilter\n): boolean {\n return compositeFilter.op === CompositeOperator.OR;\n}\n\n/**\n * Returns true if this filter is a conjunction of field filters only. Returns false otherwise.\n */\nexport function compositeFilterIsFlatConjunction(\n compositeFilter: CompositeFilter\n): boolean {\n return (\n compositeFilterIsFlat(compositeFilter) &&\n compositeFilterIsConjunction(compositeFilter)\n );\n}\n\n/**\n * Returns true if this filter does not contain any composite filters. Returns false otherwise.\n */\nexport function compositeFilterIsFlat(\n compositeFilter: CompositeFilter\n): boolean {\n for (const filter of compositeFilter.filters) {\n if (filter instanceof CompositeFilter) {\n return false;\n }\n }\n return true;\n}\n\nexport function canonifyFilter(filter: Filter): string {\n debugAssert(\n filter instanceof FieldFilter || filter instanceof CompositeFilter,\n 'canonifyFilter() only supports FieldFilters and CompositeFilters'\n );\n\n if (filter instanceof FieldFilter) {\n // TODO(b/29183165): Technically, this won't be unique if two values have\n // the same description, such as the int 3 and the string \"3\". So we should\n // add the types in here somehow, too.\n return (\n filter.field.canonicalString() +\n filter.op.toString() +\n canonicalId(filter.value)\n );\n } else if (compositeFilterIsFlatConjunction(filter)) {\n // Older SDK versions use an implicit AND operation between their filters.\n // In the new SDK versions, the developer may use an explicit AND filter.\n // To stay consistent with the old usages, we add a special case to ensure\n // the canonical ID for these two are the same. For example:\n // `col.whereEquals(\"a\", 1).whereEquals(\"b\", 2)` should have the same\n // canonical ID as `col.where(and(equals(\"a\",1), equals(\"b\",2)))`.\n return filter.filters.map(filter => canonifyFilter(filter)).join(',');\n } else {\n // filter instanceof CompositeFilter\n const canonicalIdsString = filter.filters\n .map(filter => canonifyFilter(filter))\n .join(',');\n return `${filter.op}(${canonicalIdsString})`;\n }\n}\n\nexport function filterEquals(f1: Filter, f2: Filter): boolean {\n if (f1 instanceof FieldFilter) {\n return fieldFilterEquals(f1, f2);\n } else if (f1 instanceof CompositeFilter) {\n return compositeFilterEquals(f1, f2);\n } else {\n fail(0x4bef, 'Only FieldFilters and CompositeFilters can be compared');\n }\n}\n\nexport function fieldFilterEquals(f1: FieldFilter, f2: Filter): boolean {\n return (\n f2 instanceof FieldFilter &&\n f1.op === f2.op &&\n f1.field.isEqual(f2.field) &&\n valueEquals(f1.value, f2.value)\n );\n}\n\nexport function compositeFilterEquals(\n f1: CompositeFilter,\n f2: Filter\n): boolean {\n if (\n f2 instanceof CompositeFilter &&\n f1.op === f2.op &&\n f1.filters.length === f2.filters.length\n ) {\n const subFiltersMatch: boolean = f1.filters.reduce(\n (result: boolean, f1Filter: Filter, index: number): boolean =>\n result && filterEquals(f1Filter, f2.filters[index]),\n true\n );\n\n return subFiltersMatch;\n }\n\n return false;\n}\n\n/**\n * Returns a new composite filter that contains all filter from\n * `compositeFilter` plus all the given filters in `otherFilters`.\n */\nexport function compositeFilterWithAddedFilters(\n compositeFilter: CompositeFilter,\n otherFilters: Filter[]\n): CompositeFilter {\n const mergedFilters = compositeFilter.filters.concat(otherFilters);\n return CompositeFilter.create(mergedFilters, compositeFilter.op);\n}\n\n/** Returns a debug description for `filter`. */\nexport function stringifyFilter(filter: Filter): string {\n debugAssert(\n filter instanceof FieldFilter || filter instanceof CompositeFilter,\n 'stringifyFilter() only supports FieldFilters and CompositeFilters'\n );\n if (filter instanceof FieldFilter) {\n return stringifyFieldFilter(filter);\n } else if (filter instanceof CompositeFilter) {\n return stringifyCompositeFilter(filter);\n } else {\n return 'Filter';\n }\n}\n\nexport function stringifyCompositeFilter(filter: CompositeFilter): string {\n return (\n filter.op.toString() +\n ` {` +\n filter.getFilters().map(stringifyFilter).join(' ,') +\n '}'\n );\n}\n\nexport function stringifyFieldFilter(filter: FieldFilter): string {\n return `${filter.field.canonicalString()} ${filter.op} ${canonicalId(\n filter.value\n )}`;\n}\n\n/** Filter that matches on key fields (i.e. '__name__'). */\nexport class KeyFieldFilter extends FieldFilter {\n private readonly key: DocumentKey;\n\n constructor(field: FieldPath, op: Operator, value: ProtoValue) {\n super(field, op, value);\n debugAssert(\n isReferenceValue(value),\n 'KeyFieldFilter expects a ReferenceValue'\n );\n this.key = DocumentKey.fromName(value.referenceValue);\n }\n\n matches(doc: Document): boolean {\n const comparison = DocumentKey.comparator(doc.key, this.key);\n return this.matchesComparison(comparison);\n }\n}\n\n/** Filter that matches on key fields within an array. */\nexport class KeyFieldInFilter extends FieldFilter {\n private readonly keys: DocumentKey[];\n\n constructor(field: FieldPath, value: ProtoValue) {\n super(field, Operator.IN, value);\n this.keys = extractDocumentKeysFromArrayValue(Operator.IN, value);\n }\n\n matches(doc: Document): boolean {\n return this.keys.some(key => key.isEqual(doc.key));\n }\n}\n\n/** Filter that matches on key fields not present within an array. */\nexport class KeyFieldNotInFilter extends FieldFilter {\n private readonly keys: DocumentKey[];\n\n constructor(field: FieldPath, value: ProtoValue) {\n super(field, Operator.NOT_IN, value);\n this.keys = extractDocumentKeysFromArrayValue(Operator.NOT_IN, value);\n }\n\n matches(doc: Document): boolean {\n return !this.keys.some(key => key.isEqual(doc.key));\n }\n}\n\nfunction extractDocumentKeysFromArrayValue(\n op: Operator.IN | Operator.NOT_IN,\n value: ProtoValue\n): DocumentKey[] {\n debugAssert(\n isArray(value),\n 'KeyFieldInFilter/KeyFieldNotInFilter expects an ArrayValue'\n );\n return (value.arrayValue?.values || []).map(v => {\n debugAssert(\n isReferenceValue(v),\n `Comparing on key with ${op.toString()}, but an array value was not ` +\n `a ReferenceValue`\n );\n return DocumentKey.fromName(v.referenceValue);\n });\n}\n\n/** A Filter that implements the array-contains operator. */\nexport class ArrayContainsFilter extends FieldFilter {\n constructor(field: FieldPath, value: ProtoValue) {\n super(field, Operator.ARRAY_CONTAINS, value);\n }\n\n matches(doc: Document): boolean {\n const other = doc.data.field(this.field);\n return isArray(other) && arrayValueContains(other.arrayValue, this.value);\n }\n}\n\n/** A Filter that implements the IN operator. */\nexport class InFilter extends FieldFilter {\n constructor(field: FieldPath, value: ProtoValue) {\n super(field, Operator.IN, value);\n debugAssert(isArray(value), 'InFilter expects an ArrayValue');\n }\n\n matches(doc: Document): boolean {\n const other = doc.data.field(this.field);\n return other !== null && arrayValueContains(this.value.arrayValue!, other);\n }\n}\n\n/** A Filter that implements the not-in operator. */\nexport class NotInFilter extends FieldFilter {\n constructor(field: FieldPath, value: ProtoValue) {\n super(field, Operator.NOT_IN, value);\n debugAssert(isArray(value), 'NotInFilter expects an ArrayValue');\n }\n\n matches(doc: Document): boolean {\n if (\n arrayValueContains(this.value.arrayValue!, { nullValue: 'NULL_VALUE' })\n ) {\n return false;\n }\n const other = doc.data.field(this.field);\n return (\n other !== null &&\n other.nullValue === undefined &&\n !arrayValueContains(this.value.arrayValue!, other)\n );\n }\n}\n\n/** A Filter that implements the array-contains-any operator. */\nexport class ArrayContainsAnyFilter extends FieldFilter {\n constructor(field: FieldPath, value: ProtoValue) {\n super(field, Operator.ARRAY_CONTAINS_ANY, value);\n debugAssert(isArray(value), 'ArrayContainsAnyFilter expects an ArrayValue');\n }\n\n matches(doc: Document): boolean {\n const other = doc.data.field(this.field);\n if (!isArray(other) || !other.arrayValue.values) {\n return false;\n }\n return other.arrayValue.values.some(val =>\n arrayValueContains(this.value.arrayValue!, val)\n );\n }\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FieldPath } from '../model/path';\n\n/**\n * The direction of sorting in an order by.\n */\nexport const enum Direction {\n ASCENDING = 'asc',\n DESCENDING = 'desc'\n}\n\n/**\n * An ordering on a field, in some Direction. Direction defaults to ASCENDING.\n */\nexport class OrderBy {\n constructor(\n readonly field: FieldPath,\n readonly dir: Direction = Direction.ASCENDING\n ) {}\n}\n\nexport function canonifyOrderBy(orderBy: OrderBy): string {\n // TODO(b/29183165): Make this collision robust.\n return orderBy.field.canonicalString() + orderBy.dir;\n}\n\nexport function stringifyOrderBy(orderBy: OrderBy): string {\n return `${orderBy.field.canonicalString()} (${orderBy.dir})`;\n}\n\nexport function orderByEquals(left: OrderBy, right: OrderBy): boolean {\n return left.dir === right.dir && left.field.isEqual(right.field);\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Timestamp } from '../lite-api/timestamp';\n\n/**\n * A version of a document in Firestore. This corresponds to the version\n * timestamp, such as update_time or read_time.\n */\nexport class SnapshotVersion {\n static fromTimestamp(value: Timestamp): SnapshotVersion {\n return new SnapshotVersion(value);\n }\n\n static min(): SnapshotVersion {\n return new SnapshotVersion(new Timestamp(0, 0));\n }\n\n static max(): SnapshotVersion {\n return new SnapshotVersion(new Timestamp(253402300799, 1e9 - 1));\n }\n\n private constructor(private timestamp: Timestamp) {}\n\n compareTo(other: SnapshotVersion): number {\n return this.timestamp._compareTo(other.timestamp);\n }\n\n isEqual(other: SnapshotVersion): boolean {\n return this.timestamp.isEqual(other.timestamp);\n }\n\n /** Returns a number representation of the version for use in spec tests. */\n toMicroseconds(): number {\n // Convert to microseconds.\n return this.timestamp.seconds * 1e6 + this.timestamp.nanoseconds / 1000;\n }\n\n toString(): string {\n return 'SnapshotVersion(' + this.timestamp.toString() + ')';\n }\n\n toTimestamp(): Timestamp {\n return this.timestamp;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { debugAssert, fail } from './assert';\n\n/*\n * Implementation of an immutable SortedMap using a Left-leaning\n * Red-Black Tree, adapted from the implementation in Mugs\n * (http://mads379.github.com/mugs/) by Mads Hartmann Jensen\n * (mads379@gmail.com).\n *\n * Original paper on Left-leaning Red-Black Trees:\n * http://www.cs.princeton.edu/~rs/talks/LLRB/LLRB.pdf\n *\n * Invariant 1: No red node has a red child\n * Invariant 2: Every leaf path has the same number of black nodes\n * Invariant 3: Only the left child can be red (left leaning)\n */\n\nexport type Comparator = (key1: K, key2: K) => number;\n\nexport interface Entry {\n key: K;\n value: V;\n}\n\n// An immutable sorted map implementation, based on a Left-leaning Red-Black\n// tree.\nexport class SortedMap {\n // visible for testing\n root: LLRBNode | LLRBEmptyNode;\n\n constructor(\n public comparator: Comparator,\n root?: LLRBNode | LLRBEmptyNode\n ) {\n this.root = root ? root : LLRBNode.EMPTY;\n }\n\n // Returns a copy of the map, with the specified key/value added or replaced.\n insert(key: K, value: V): SortedMap {\n return new SortedMap(\n this.comparator,\n this.root\n .insert(key, value, this.comparator)\n .copy(null, null, LLRBNode.BLACK, null, null)\n );\n }\n\n // Returns a copy of the map, with the specified key removed.\n remove(key: K): SortedMap {\n return new SortedMap(\n this.comparator,\n this.root\n .remove(key, this.comparator)\n .copy(null, null, LLRBNode.BLACK, null, null)\n );\n }\n\n // Returns the value of the node with the given key, or null.\n get(key: K): V | null {\n let node = this.root;\n while (!node.isEmpty()) {\n const cmp = this.comparator(key, node.key);\n if (cmp === 0) {\n return node.value;\n } else if (cmp < 0) {\n node = node.left;\n } else if (cmp > 0) {\n node = node.right;\n }\n }\n return null;\n }\n\n // Returns the index of the element in this sorted map, or -1 if it doesn't\n // exist.\n indexOf(key: K): number {\n // Number of nodes that were pruned when descending right\n let prunedNodes = 0;\n let node = this.root;\n while (!node.isEmpty()) {\n const cmp = this.comparator(key, node.key);\n if (cmp === 0) {\n return prunedNodes + node.left.size;\n } else if (cmp < 0) {\n node = node.left;\n } else {\n // Count all nodes left of the node plus the node itself\n prunedNodes += node.left.size + 1;\n node = node.right;\n }\n }\n // Node not found\n return -1;\n }\n\n isEmpty(): boolean {\n return this.root.isEmpty();\n }\n\n // Returns the total number of nodes in the map.\n get size(): number {\n return this.root.size;\n }\n\n // Returns the minimum key in the map.\n minKey(): K | null {\n return this.root.minKey();\n }\n\n // Returns the maximum key in the map.\n maxKey(): K | null {\n return this.root.maxKey();\n }\n\n // Traverses the map in key order and calls the specified action function\n // for each key/value pair. If action returns true, traversal is aborted.\n // Returns the first truthy value returned by action, or the last falsey\n // value returned by action.\n inorderTraversal(action: (k: K, v: V) => T): T {\n return (this.root as LLRBNode).inorderTraversal(action);\n }\n\n forEach(fn: (k: K, v: V) => void): void {\n this.inorderTraversal((k, v) => {\n fn(k, v);\n return false;\n });\n }\n\n toString(): string {\n const descriptions: string[] = [];\n this.inorderTraversal((k, v) => {\n descriptions.push(`${k}:${v}`);\n return false;\n });\n return `{${descriptions.join(', ')}}`;\n }\n\n // Traverses the map in reverse key order and calls the specified action\n // function for each key/value pair. If action returns true, traversal is\n // aborted.\n // Returns the first truthy value returned by action, or the last falsey\n // value returned by action.\n reverseTraversal(action: (k: K, v: V) => T): T {\n return (this.root as LLRBNode).reverseTraversal(action);\n }\n\n // Returns an iterator over the SortedMap.\n getIterator(): SortedMapIterator {\n return new SortedMapIterator(this.root, null, this.comparator, false);\n }\n\n getIteratorFrom(key: K): SortedMapIterator {\n return new SortedMapIterator(this.root, key, this.comparator, false);\n }\n\n getReverseIterator(): SortedMapIterator {\n return new SortedMapIterator(this.root, null, this.comparator, true);\n }\n\n getReverseIteratorFrom(key: K): SortedMapIterator {\n return new SortedMapIterator(this.root, key, this.comparator, true);\n }\n} // end SortedMap\n\n// An iterator over an LLRBNode.\nexport class SortedMapIterator {\n private isReverse: boolean;\n private nodeStack: Array | LLRBEmptyNode>;\n\n constructor(\n node: LLRBNode | LLRBEmptyNode,\n startKey: K | null,\n comparator: Comparator,\n isReverse: boolean\n ) {\n this.isReverse = isReverse;\n this.nodeStack = [];\n\n let cmp = 1;\n while (!node.isEmpty()) {\n cmp = startKey ? comparator(node.key, startKey) : 1;\n // flip the comparison if we're going in reverse\n if (startKey && isReverse) {\n cmp *= -1;\n }\n\n if (cmp < 0) {\n // This node is less than our start key. ignore it\n if (this.isReverse) {\n node = node.left;\n } else {\n node = node.right;\n }\n } else if (cmp === 0) {\n // This node is exactly equal to our start key. Push it on the stack,\n // but stop iterating;\n this.nodeStack.push(node);\n break;\n } else {\n // This node is greater than our start key, add it to the stack and move\n // to the next one\n this.nodeStack.push(node);\n if (this.isReverse) {\n node = node.right;\n } else {\n node = node.left;\n }\n }\n }\n }\n\n getNext(): Entry {\n debugAssert(\n this.nodeStack.length > 0,\n 'getNext() called on iterator when hasNext() is false.'\n );\n\n let node = this.nodeStack.pop()!;\n const result = { key: node.key, value: node.value };\n\n if (this.isReverse) {\n node = node.left;\n while (!node.isEmpty()) {\n this.nodeStack.push(node);\n node = node.right;\n }\n } else {\n node = node.right;\n while (!node.isEmpty()) {\n this.nodeStack.push(node);\n node = node.left;\n }\n }\n\n return result;\n }\n\n hasNext(): boolean {\n return this.nodeStack.length > 0;\n }\n\n peek(): Entry | null {\n if (this.nodeStack.length === 0) {\n return null;\n }\n\n const node = this.nodeStack[this.nodeStack.length - 1];\n return { key: node.key, value: node.value };\n }\n} // end SortedMapIterator\n\n// Represents a node in a Left-leaning Red-Black tree.\nexport class LLRBNode {\n readonly color: boolean;\n readonly left: LLRBNode | LLRBEmptyNode;\n readonly right: LLRBNode | LLRBEmptyNode;\n readonly size: number;\n\n // Empty node is shared between all LLRB trees.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n static EMPTY: LLRBEmptyNode = null as any;\n\n static RED = true;\n static BLACK = false;\n\n constructor(\n public key: K,\n public value: V,\n color?: boolean,\n left?: LLRBNode | LLRBEmptyNode,\n right?: LLRBNode | LLRBEmptyNode\n ) {\n this.color = color != null ? color : LLRBNode.RED;\n this.left = left != null ? left : LLRBNode.EMPTY;\n this.right = right != null ? right : LLRBNode.EMPTY;\n this.size = this.left.size + 1 + this.right.size;\n }\n\n // Returns a copy of the current node, optionally replacing pieces of it.\n copy(\n key: K | null,\n value: V | null,\n color: boolean | null,\n left: LLRBNode | LLRBEmptyNode | null,\n right: LLRBNode | LLRBEmptyNode | null\n ): LLRBNode {\n return new LLRBNode(\n key != null ? key : this.key,\n value != null ? value : this.value,\n color != null ? color : this.color,\n left != null ? left : this.left,\n right != null ? right : this.right\n );\n }\n\n isEmpty(): boolean {\n return false;\n }\n\n // Traverses the tree in key order and calls the specified action function\n // for each node. If action returns true, traversal is aborted.\n // Returns the first truthy value returned by action, or the last falsey\n // value returned by action.\n inorderTraversal(action: (k: K, v: V) => T): T {\n return (\n (this.left as LLRBNode).inorderTraversal(action) ||\n action(this.key, this.value) ||\n (this.right as LLRBNode).inorderTraversal(action)\n );\n }\n\n // Traverses the tree in reverse key order and calls the specified action\n // function for each node. If action returns true, traversal is aborted.\n // Returns the first truthy value returned by action, or the last falsey\n // value returned by action.\n reverseTraversal(action: (k: K, v: V) => T): T {\n return (\n (this.right as LLRBNode).reverseTraversal(action) ||\n action(this.key, this.value) ||\n (this.left as LLRBNode).reverseTraversal(action)\n );\n }\n\n // Returns the minimum node in the tree.\n private min(): LLRBNode {\n if (this.left.isEmpty()) {\n return this;\n } else {\n return (this.left as LLRBNode).min();\n }\n }\n\n // Returns the maximum key in the tree.\n minKey(): K | null {\n return this.min().key;\n }\n\n // Returns the maximum key in the tree.\n maxKey(): K | null {\n if (this.right.isEmpty()) {\n return this.key;\n } else {\n return this.right.maxKey();\n }\n }\n\n // Returns new tree, with the key/value added.\n insert(key: K, value: V, comparator: Comparator): LLRBNode {\n let n: LLRBNode = this;\n const cmp = comparator(key, n.key);\n if (cmp < 0) {\n n = n.copy(null, null, null, n.left.insert(key, value, comparator), null);\n } else if (cmp === 0) {\n n = n.copy(null, value, null, null, null);\n } else {\n n = n.copy(\n null,\n null,\n null,\n null,\n n.right.insert(key, value, comparator)\n );\n }\n return n.fixUp();\n }\n\n private removeMin(): LLRBNode | LLRBEmptyNode {\n if (this.left.isEmpty()) {\n return LLRBNode.EMPTY;\n }\n let n: LLRBNode = this;\n if (!n.left.isRed() && !n.left.left.isRed()) {\n n = n.moveRedLeft();\n }\n n = n.copy(null, null, null, (n.left as LLRBNode).removeMin(), null);\n return n.fixUp();\n }\n\n // Returns new tree, with the specified item removed.\n remove(\n key: K,\n comparator: Comparator\n ): LLRBNode | LLRBEmptyNode {\n let smallest: LLRBNode;\n let n: LLRBNode = this;\n if (comparator(key, n.key) < 0) {\n if (!n.left.isEmpty() && !n.left.isRed() && !n.left.left.isRed()) {\n n = n.moveRedLeft();\n }\n n = n.copy(null, null, null, n.left.remove(key, comparator), null);\n } else {\n if (n.left.isRed()) {\n n = n.rotateRight();\n }\n if (!n.right.isEmpty() && !n.right.isRed() && !n.right.left.isRed()) {\n n = n.moveRedRight();\n }\n if (comparator(key, n.key) === 0) {\n if (n.right.isEmpty()) {\n return LLRBNode.EMPTY;\n } else {\n smallest = (n.right as LLRBNode).min();\n n = n.copy(\n smallest.key,\n smallest.value,\n null,\n null,\n (n.right as LLRBNode).removeMin()\n );\n }\n }\n n = n.copy(null, null, null, null, n.right.remove(key, comparator));\n }\n return n.fixUp();\n }\n\n isRed(): boolean {\n return this.color;\n }\n\n // Returns new tree after performing any needed rotations.\n private fixUp(): LLRBNode {\n let n: LLRBNode = this;\n if (n.right.isRed() && !n.left.isRed()) {\n n = n.rotateLeft();\n }\n if (n.left.isRed() && n.left.left.isRed()) {\n n = n.rotateRight();\n }\n if (n.left.isRed() && n.right.isRed()) {\n n = n.colorFlip();\n }\n return n;\n }\n\n private moveRedLeft(): LLRBNode {\n let n = this.colorFlip();\n if (n.right.left.isRed()) {\n n = n.copy(\n null,\n null,\n null,\n null,\n (n.right as LLRBNode).rotateRight()\n );\n n = n.rotateLeft();\n n = n.colorFlip();\n }\n return n;\n }\n\n private moveRedRight(): LLRBNode {\n let n = this.colorFlip();\n if (n.left.left.isRed()) {\n n = n.rotateRight();\n n = n.colorFlip();\n }\n return n;\n }\n\n private rotateLeft(): LLRBNode {\n const nl = this.copy(null, null, LLRBNode.RED, null, this.right.left);\n return (this.right as LLRBNode).copy(\n null,\n null,\n this.color,\n nl,\n null\n );\n }\n\n private rotateRight(): LLRBNode {\n const nr = this.copy(null, null, LLRBNode.RED, this.left.right, null);\n return (this.left as LLRBNode).copy(null, null, this.color, null, nr);\n }\n\n private colorFlip(): LLRBNode {\n const left = this.left.copy(null, null, !this.left.color, null, null);\n const right = this.right.copy(null, null, !this.right.color, null, null);\n return this.copy(null, null, !this.color, left, right);\n }\n\n // For testing.\n checkMaxDepth(): boolean {\n const blackDepth = this.check();\n if (Math.pow(2.0, blackDepth) <= this.size + 1) {\n return true;\n } else {\n return false;\n }\n }\n\n // In a balanced RB tree, the black-depth (number of black nodes) from root to\n // leaves is equal on both sides. This function verifies that or asserts.\n protected check(): number {\n if (this.isRed() && this.left.isRed()) {\n throw fail(0xaad2, 'Red node has red child', {\n key: this.key,\n value: this.value\n });\n }\n if (this.right.isRed()) {\n throw fail(0x3721, 'Right child of (`key`, `value`) is red', {\n key: this.key,\n value: this.value\n });\n }\n const blackDepth = (this.left as LLRBNode).check();\n if (blackDepth !== (this.right as LLRBNode).check()) {\n throw fail(0x6d2d, 'Black depths differ');\n } else {\n return blackDepth + (this.isRed() ? 0 : 1);\n }\n }\n} // end LLRBNode\n\n// Represents an empty node (a leaf node in the Red-Black Tree).\nexport class LLRBEmptyNode {\n get key(): never {\n throw fail(0xe1a6, 'LLRBEmptyNode has no key.');\n }\n get value(): never {\n throw fail(0x3f0d, 'LLRBEmptyNode has no value.');\n }\n get color(): never {\n throw fail(0x4157, 'LLRBEmptyNode has no color.');\n }\n get left(): never {\n throw fail(0x741e, 'LLRBEmptyNode has no left child.');\n }\n get right(): never {\n throw fail(0x901e, 'LLRBEmptyNode has no right child.');\n }\n size = 0;\n\n // Returns a copy of the current node.\n copy(\n key: K | null,\n value: V | null,\n color: boolean | null,\n left: LLRBNode | LLRBEmptyNode | null,\n right: LLRBNode | LLRBEmptyNode | null\n ): LLRBEmptyNode {\n return this;\n }\n\n // Returns a copy of the tree, with the specified key/value added.\n insert(key: K, value: V, comparator: Comparator): LLRBNode {\n return new LLRBNode(key, value);\n }\n\n // Returns a copy of the tree, with the specified key removed.\n remove(key: K, comparator: Comparator): LLRBEmptyNode {\n return this;\n }\n\n isEmpty(): boolean {\n return true;\n }\n\n inorderTraversal(action: (k: K, v: V) => boolean): boolean {\n return false;\n }\n\n reverseTraversal(action: (k: K, v: V) => boolean): boolean {\n return false;\n }\n\n minKey(): K | null {\n return null;\n }\n\n maxKey(): K | null {\n return null;\n }\n\n isRed(): boolean {\n return false;\n }\n\n // For testing.\n checkMaxDepth(): boolean {\n return true;\n }\n\n protected check(): 0 {\n return 0;\n }\n} // end LLRBEmptyNode\n\nLLRBNode.EMPTY = new LLRBEmptyNode();\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SortedMap, SortedMapIterator } from './sorted_map';\n\n/**\n * SortedSet is an immutable (copy-on-write) collection that holds elements\n * in order specified by the provided comparator.\n *\n * NOTE: if provided comparator returns 0 for two elements, we consider them to\n * be equal!\n */\nexport class SortedSet {\n private data: SortedMap;\n\n constructor(private comparator: (left: T, right: T) => number) {\n this.data = new SortedMap(this.comparator);\n }\n\n has(elem: T): boolean {\n return this.data.get(elem) !== null;\n }\n\n first(): T | null {\n return this.data.minKey();\n }\n\n last(): T | null {\n return this.data.maxKey();\n }\n\n get size(): number {\n return this.data.size;\n }\n\n indexOf(elem: T): number {\n return this.data.indexOf(elem);\n }\n\n /** Iterates elements in order defined by \"comparator\" */\n forEach(cb: (elem: T) => void): void {\n this.data.inorderTraversal((k: T, v: boolean) => {\n cb(k);\n return false;\n });\n }\n\n /** Iterates over `elem`s such that: range[0] <= elem < range[1]. */\n forEachInRange(range: [T, T], cb: (elem: T) => void): void {\n const iter = this.data.getIteratorFrom(range[0]);\n while (iter.hasNext()) {\n const elem = iter.getNext();\n if (this.comparator(elem.key, range[1]) >= 0) {\n return;\n }\n cb(elem.key);\n }\n }\n\n /**\n * Iterates over `elem`s such that: start <= elem until false is returned.\n */\n forEachWhile(cb: (elem: T) => boolean, start?: T): void {\n let iter: SortedMapIterator;\n if (start !== undefined) {\n iter = this.data.getIteratorFrom(start);\n } else {\n iter = this.data.getIterator();\n }\n while (iter.hasNext()) {\n const elem = iter.getNext();\n const result = cb(elem.key);\n if (!result) {\n return;\n }\n }\n }\n\n /** Finds the least element greater than or equal to `elem`. */\n firstAfterOrEqual(elem: T): T | null {\n const iter = this.data.getIteratorFrom(elem);\n return iter.hasNext() ? iter.getNext().key : null;\n }\n\n getIterator(): SortedSetIterator {\n return new SortedSetIterator(this.data.getIterator());\n }\n\n getIteratorFrom(key: T): SortedSetIterator {\n return new SortedSetIterator(this.data.getIteratorFrom(key));\n }\n\n /** Inserts or updates an element */\n add(elem: T): SortedSet {\n return this.copy(this.data.remove(elem).insert(elem, true));\n }\n\n /** Deletes an element */\n delete(elem: T): SortedSet {\n if (!this.has(elem)) {\n return this;\n }\n return this.copy(this.data.remove(elem));\n }\n\n isEmpty(): boolean {\n return this.data.isEmpty();\n }\n\n unionWith(other: SortedSet): SortedSet {\n let result: SortedSet = this;\n\n // Make sure `result` always refers to the larger one of the two sets.\n if (result.size < other.size) {\n result = other;\n other = this;\n }\n\n other.forEach(elem => {\n result = result.add(elem);\n });\n return result;\n }\n\n isEqual(other: SortedSet): boolean {\n if (!(other instanceof SortedSet)) {\n return false;\n }\n if (this.size !== other.size) {\n return false;\n }\n\n const thisIt = this.data.getIterator();\n const otherIt = other.data.getIterator();\n while (thisIt.hasNext()) {\n const thisElem = thisIt.getNext().key;\n const otherElem = otherIt.getNext().key;\n if (this.comparator(thisElem, otherElem) !== 0) {\n return false;\n }\n }\n return true;\n }\n\n toArray(): T[] {\n const res: T[] = [];\n this.forEach(targetId => {\n res.push(targetId);\n });\n return res;\n }\n\n toString(): string {\n const result: T[] = [];\n this.forEach(elem => result.push(elem));\n return 'SortedSet(' + result.toString() + ')';\n }\n\n private copy(data: SortedMap): SortedSet {\n const result = new SortedSet(this.comparator);\n result.data = data;\n return result;\n }\n}\n\nexport class SortedSetIterator {\n constructor(private iter: SortedMapIterator) {}\n\n getNext(): T {\n return this.iter.getNext().key;\n }\n\n hasNext(): boolean {\n return this.iter.hasNext();\n }\n}\n\n/**\n * Compares two sorted sets for equality using their natural ordering. The\n * method computes the intersection and invokes `onAdd` for every element that\n * is in `after` but not `before`. `onRemove` is invoked for every element in\n * `before` but missing from `after`.\n *\n * The method creates a copy of both `before` and `after` and runs in O(n log\n * n), where n is the size of the two lists.\n *\n * @param before - The elements that exist in the original set.\n * @param after - The elements to diff against the original set.\n * @param comparator - The comparator for the elements in before and after.\n * @param onAdd - A function to invoke for every element that is part of `\n * after` but not `before`.\n * @param onRemove - A function to invoke for every element that is part of\n * `before` but not `after`.\n */\nexport function diffSortedSets(\n before: SortedSet,\n after: SortedSet,\n comparator: (l: T, r: T) => number,\n onAdd: (entry: T) => void,\n onRemove: (entry: T) => void\n): void {\n const beforeIt = before.getIterator();\n const afterIt = after.getIterator();\n\n let beforeValue = advanceIterator(beforeIt);\n let afterValue = advanceIterator(afterIt);\n\n // Walk through the two sets at the same time, using the ordering defined by\n // `comparator`.\n while (beforeValue || afterValue) {\n let added = false;\n let removed = false;\n\n if (beforeValue && afterValue) {\n const cmp = comparator(beforeValue, afterValue);\n if (cmp < 0) {\n // The element was removed if the next element in our ordered\n // walkthrough is only in `before`.\n removed = true;\n } else if (cmp > 0) {\n // The element was added if the next element in our ordered walkthrough\n // is only in `after`.\n added = true;\n }\n } else if (beforeValue != null) {\n removed = true;\n } else {\n added = true;\n }\n\n if (added) {\n onAdd(afterValue!);\n afterValue = advanceIterator(afterIt);\n } else if (removed) {\n onRemove(beforeValue!);\n beforeValue = advanceIterator(beforeIt);\n } else {\n beforeValue = advanceIterator(beforeIt);\n afterValue = advanceIterator(afterIt);\n }\n }\n}\n\n/**\n * Returns the next element from the iterator or `undefined` if none available.\n */\nfunction advanceIterator(it: SortedSetIterator): T | undefined {\n return it.hasNext() ? it.getNext() : undefined;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { debugAssert } from '../util/assert';\nimport { arrayEquals } from '../util/misc';\nimport { SortedSet } from '../util/sorted_set';\n\nimport { FieldPath } from './path';\n\n/**\n * Provides a set of fields that can be used to partially patch a document.\n * FieldMask is used in conjunction with ObjectValue.\n * Examples:\n * foo - Overwrites foo entirely with the provided value. If foo is not\n * present in the companion ObjectValue, the field is deleted.\n * foo.bar - Overwrites only the field bar of the object foo.\n * If foo is not an object, foo is replaced with an object\n * containing foo\n */\nexport class FieldMask {\n constructor(readonly fields: FieldPath[]) {\n // TODO(dimond): validation of FieldMask\n // Sort the field mask to support `FieldMask.isEqual()` and assert below.\n fields.sort(FieldPath.comparator);\n debugAssert(\n !fields.some((v, i) => i !== 0 && v.isEqual(fields[i - 1])),\n 'FieldMask contains field that is not unique: ' +\n fields.find((v, i) => i !== 0 && v.isEqual(fields[i - 1]))!\n );\n }\n\n static empty(): FieldMask {\n return new FieldMask([]);\n }\n\n /**\n * Returns a new FieldMask object that is the result of adding all the given\n * fields paths to this field mask.\n */\n unionWith(extraFields: FieldPath[]): FieldMask {\n let mergedMaskSet = new SortedSet(FieldPath.comparator);\n for (const fieldPath of this.fields) {\n mergedMaskSet = mergedMaskSet.add(fieldPath);\n }\n for (const fieldPath of extraFields) {\n mergedMaskSet = mergedMaskSet.add(fieldPath);\n }\n return new FieldMask(mergedMaskSet.toArray());\n }\n\n /**\n * Verifies that `fieldPath` is included by at least one field in this field\n * mask.\n *\n * This is an O(n) operation, where `n` is the size of the field mask.\n */\n covers(fieldPath: FieldPath): boolean {\n for (const fieldMaskPath of this.fields) {\n if (fieldMaskPath.isPrefixOf(fieldPath)) {\n return true;\n }\n }\n return false;\n }\n\n isEqual(other: FieldMask): boolean {\n return arrayEquals(this.fields, other.fields, (l, r) => l.isEqual(r));\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n MapValue as ProtoMapValue,\n Value as ProtoValue\n} from '../protos/firestore_proto_api';\nimport { debugAssert } from '../util/assert';\nimport { forEach } from '../util/obj';\n\nimport { FieldMask } from './field_mask';\nimport { FieldPath } from './path';\nimport { isServerTimestamp } from './server_timestamps';\nimport { deepClone, isMapValue, valueEquals } from './values';\n\nexport interface JsonObject {\n [name: string]: T;\n}\n/**\n * An ObjectValue represents a MapValue in the Firestore Proto and offers the\n * ability to add and remove fields (via the ObjectValueBuilder).\n */\nexport class ObjectValue {\n constructor(readonly value: { mapValue: ProtoMapValue }) {\n debugAssert(\n !isServerTimestamp(value),\n 'ServerTimestamps should be converted to ServerTimestampValue'\n );\n }\n\n static empty(): ObjectValue {\n return new ObjectValue({ mapValue: {} });\n }\n\n /**\n * Returns the value at the given path or null.\n *\n * @param path - the path to search\n * @returns The value at the path or null if the path is not set.\n */\n field(path: FieldPath): ProtoValue | null {\n if (path.isEmpty()) {\n return this.value;\n } else {\n let currentLevel: ProtoValue = this.value;\n for (let i = 0; i < path.length - 1; ++i) {\n currentLevel = (currentLevel.mapValue!.fields || {})[path.get(i)];\n if (!isMapValue(currentLevel)) {\n return null;\n }\n }\n currentLevel = (currentLevel.mapValue!.fields! || {})[path.lastSegment()];\n return currentLevel || null;\n }\n }\n\n /**\n * Sets the field to the provided value.\n *\n * @param path - The field path to set.\n * @param value - The value to set.\n */\n set(path: FieldPath, value: ProtoValue): void {\n debugAssert(\n !path.isEmpty(),\n 'Cannot set field for empty path on ObjectValue'\n );\n const fieldsMap = this.getFieldsMap(path.popLast());\n fieldsMap[path.lastSegment()] = deepClone(value);\n }\n\n /**\n * Sets the provided fields to the provided values.\n *\n * @param data - A map of fields to values (or null for deletes).\n */\n setAll(data: Map): void {\n let parent = FieldPath.emptyPath();\n\n let upserts: { [key: string]: ProtoValue } = {};\n let deletes: string[] = [];\n\n data.forEach((value, path) => {\n if (!parent.isImmediateParentOf(path)) {\n // Insert the accumulated changes at this parent location\n const fieldsMap = this.getFieldsMap(parent);\n this.applyChanges(fieldsMap, upserts, deletes);\n upserts = {};\n deletes = [];\n parent = path.popLast();\n }\n\n if (value) {\n upserts[path.lastSegment()] = deepClone(value);\n } else {\n deletes.push(path.lastSegment());\n }\n });\n\n const fieldsMap = this.getFieldsMap(parent);\n this.applyChanges(fieldsMap, upserts, deletes);\n }\n\n /**\n * Removes the field at the specified path. If there is no field at the\n * specified path, nothing is changed.\n *\n * @param path - The field path to remove.\n */\n delete(path: FieldPath): void {\n debugAssert(\n !path.isEmpty(),\n 'Cannot delete field for empty path on ObjectValue'\n );\n const nestedValue = this.field(path.popLast());\n if (isMapValue(nestedValue) && nestedValue.mapValue.fields) {\n delete nestedValue.mapValue.fields[path.lastSegment()];\n }\n }\n\n isEqual(other: ObjectValue): boolean {\n return valueEquals(this.value, other.value);\n }\n\n /**\n * Returns the map that contains the leaf element of `path`. If the parent\n * entry does not yet exist, or if it is not a map, a new map will be created.\n */\n private getFieldsMap(path: FieldPath): Record {\n let current = this.value;\n\n if (!current.mapValue!.fields) {\n current.mapValue = { fields: {} };\n }\n\n for (let i = 0; i < path.length; ++i) {\n let next = current.mapValue!.fields![path.get(i)];\n if (!isMapValue(next) || !next.mapValue.fields) {\n next = { mapValue: { fields: {} } };\n current.mapValue!.fields![path.get(i)] = next;\n }\n current = next as { mapValue: ProtoMapValue };\n }\n\n return current.mapValue!.fields!;\n }\n\n /**\n * Modifies `fieldsMap` by adding, replacing or deleting the specified\n * entries.\n */\n private applyChanges(\n fieldsMap: Record,\n inserts: { [key: string]: ProtoValue },\n deletes: string[]\n ): void {\n forEach(inserts, (key, val) => (fieldsMap[key] = val));\n for (const field of deletes) {\n delete fieldsMap[field];\n }\n }\n\n clone(): ObjectValue {\n return new ObjectValue(\n deepClone(this.value) as { mapValue: ProtoMapValue }\n );\n }\n}\n\n/**\n * Returns a FieldMask built from all fields in a MapValue.\n */\nexport function extractFieldMask(value: ProtoMapValue): FieldMask {\n const fields: FieldPath[] = [];\n forEach(value!.fields, (key, value) => {\n const currentPath = new FieldPath([key]);\n if (isMapValue(value)) {\n const nestedMask = extractFieldMask(value.mapValue!);\n const nestedFields = nestedMask.fields;\n if (nestedFields.length === 0) {\n // Preserve the empty map by adding it to the FieldMask.\n fields.push(currentPath);\n } else {\n // For nested and non-empty ObjectValues, add the FieldPath of the\n // leaf nodes.\n for (const nestedPath of nestedFields) {\n fields.push(currentPath.child(nestedPath));\n }\n }\n } else {\n // For nested and non-empty ObjectValues, add the FieldPath of the leaf\n // nodes.\n fields.push(currentPath);\n }\n });\n return new FieldMask(fields);\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { debugAssert, fail } from '../util/assert';\n\nimport { DocumentKey } from './document_key';\nimport { ObjectValue } from './object_value';\nimport { FieldPath } from './path';\nimport { valueCompare } from './values';\n\n/**\n * Whether the document represents an existing document, a document that is\n * known to exist or a document whose state or existence is unknown.\n */\nconst enum DocumentType {\n /**\n * Represents the initial state of a MutableDocument when only the document\n * key is known. Invalid documents transition to other states as mutations are\n * applied. If a document remains invalid after applying mutations, it should\n * be discarded.\n *\n * Invalid documents can have neither local nor committed mutations.\n */\n INVALID,\n /**\n * Represents a document in Firestore with a key, version, data and whether\n * the data has local mutations applied to it.\n *\n * Found documents can be synced or have or committed mutations applied.\n */\n FOUND_DOCUMENT,\n /**\n * Represents that no documents exists for the key at the given version.\n *\n * Documents that are deleted based on a local mutation do not raise snapshots\n * with `hasPendingWrites`. As such, deleted documents never have\n * `HAS_LOCAL_MUTATIONS` set. Once a delete is committed, we store them with\n * `HAS_COMMITTED_MUTATIONS` until we received the delete from the Watch\n * stream.\n */\n NO_DOCUMENT,\n /**\n * Represents an existing document whose data is unknown (e.g. a document that\n * was updated without a known base document).\n *\n * An unknown document always has `HAS_COMMITTED_MUTATIONS` set, since unknown\n * documents can only be generated by applying a patch mutation from a write\n * acknowledgement.\n */\n UNKNOWN_DOCUMENT\n}\n\n/** Describes whether a document has latency-compensated edits applied. */\nconst enum DocumentState {\n /** No mutations applied. Document was sent to us by Watch. */\n SYNCED,\n /**\n * Local mutations applied via the mutation queue. Document is potentially\n * inconsistent.\n */\n HAS_LOCAL_MUTATIONS,\n /**\n * Mutations applied based on a write acknowledgment. Document is potentially\n * inconsistent.\n */\n HAS_COMMITTED_MUTATIONS\n}\n\n/**\n * Represents a document in Firestore with a key, version, data and whether the\n * data has local mutations applied to it.\n */\nexport interface Document {\n /** The key for this document */\n readonly key: DocumentKey;\n\n /**\n * The version of this document if it exists or a version at which this\n * document was guaranteed to not exist.\n */\n readonly version: SnapshotVersion;\n\n /**\n * The timestamp at which this document was read from the remote server. Uses\n * `SnapshotVersion.min()` for documents created by the user.\n */\n readonly readTime: SnapshotVersion;\n\n /**\n * The timestamp at which the document was created. This value increases\n * monotonically when a document is deleted then recreated. It can also be\n * compared to `createTime` of other documents and the `readTime` of a query.\n */\n readonly createTime: SnapshotVersion;\n\n /** The underlying data of this document or an empty value if no data exists. */\n readonly data: ObjectValue;\n\n /** Returns whether local mutations were applied via the mutation queue. */\n readonly hasLocalMutations: boolean;\n\n /** Returns whether mutations were applied based on a write acknowledgment. */\n readonly hasCommittedMutations: boolean;\n\n /**\n * Whether this document had a local mutation applied that has not yet been\n * acknowledged by Watch.\n */\n readonly hasPendingWrites: boolean;\n\n /**\n * Returns whether this document is valid (i.e. it is an entry in the\n * RemoteDocumentCache, was created by a mutation or read from the backend).\n */\n isValidDocument(): boolean;\n\n /**\n * Returns whether the document exists and its data is known at the current\n * version.\n */\n isFoundDocument(): boolean;\n\n /**\n * Returns whether the document is known to not exist at the current version.\n */\n isNoDocument(): boolean;\n\n /**\n * Returns whether the document exists and its data is unknown at the current\n * version.\n */\n isUnknownDocument(): boolean;\n\n isEqual(other: Document | null | undefined): boolean;\n\n /** Creates a mutable copy of this document. */\n mutableCopy(): MutableDocument;\n\n toString(): string;\n}\n\n/**\n * Represents a document in Firestore with a key, version, data and whether it\n * has local mutations applied to it.\n *\n * Documents can transition between states via `convertToFoundDocument()`,\n * `convertToNoDocument()` and `convertToUnknownDocument()`. If a document does\n * not transition to one of these states even after all mutations have been\n * applied, `isValidDocument()` returns false and the document should be removed\n * from all views.\n */\nexport class MutableDocument implements Document {\n private constructor(\n readonly key: DocumentKey,\n private documentType: DocumentType,\n public version: SnapshotVersion,\n public readTime: SnapshotVersion,\n public createTime: SnapshotVersion,\n public data: ObjectValue,\n private documentState: DocumentState\n ) {}\n\n /**\n * Creates a document with no known version or data, but which can serve as\n * base document for mutations.\n */\n static newInvalidDocument(documentKey: DocumentKey): MutableDocument {\n return new MutableDocument(\n documentKey,\n DocumentType.INVALID,\n /* version */ SnapshotVersion.min(),\n /* readTime */ SnapshotVersion.min(),\n /* createTime */ SnapshotVersion.min(),\n ObjectValue.empty(),\n DocumentState.SYNCED\n );\n }\n\n /**\n * Creates a new document that is known to exist with the given data at the\n * given version.\n */\n static newFoundDocument(\n documentKey: DocumentKey,\n version: SnapshotVersion,\n createTime: SnapshotVersion,\n value: ObjectValue\n ): MutableDocument {\n return new MutableDocument(\n documentKey,\n DocumentType.FOUND_DOCUMENT,\n /* version */ version,\n /* readTime */ SnapshotVersion.min(),\n /* createTime */ createTime,\n value,\n DocumentState.SYNCED\n );\n }\n\n /** Creates a new document that is known to not exist at the given version. */\n static newNoDocument(\n documentKey: DocumentKey,\n version: SnapshotVersion\n ): MutableDocument {\n return new MutableDocument(\n documentKey,\n DocumentType.NO_DOCUMENT,\n /* version */ version,\n /* readTime */ SnapshotVersion.min(),\n /* createTime */ SnapshotVersion.min(),\n ObjectValue.empty(),\n DocumentState.SYNCED\n );\n }\n\n /**\n * Creates a new document that is known to exist at the given version but\n * whose data is not known (e.g. a document that was updated without a known\n * base document).\n */\n static newUnknownDocument(\n documentKey: DocumentKey,\n version: SnapshotVersion\n ): MutableDocument {\n return new MutableDocument(\n documentKey,\n DocumentType.UNKNOWN_DOCUMENT,\n /* version */ version,\n /* readTime */ SnapshotVersion.min(),\n /* createTime */ SnapshotVersion.min(),\n ObjectValue.empty(),\n DocumentState.HAS_COMMITTED_MUTATIONS\n );\n }\n\n /**\n * Changes the document type to indicate that it exists and that its version\n * and data are known.\n */\n convertToFoundDocument(\n version: SnapshotVersion,\n value: ObjectValue\n ): MutableDocument {\n // If a document is switching state from being an invalid or deleted\n // document to a valid (FOUND_DOCUMENT) document, either due to receiving an\n // update from Watch or due to applying a local set mutation on top\n // of a deleted document, our best guess about its createTime would be the\n // version at which the document transitioned to a FOUND_DOCUMENT.\n if (\n this.createTime.isEqual(SnapshotVersion.min()) &&\n (this.documentType === DocumentType.NO_DOCUMENT ||\n this.documentType === DocumentType.INVALID)\n ) {\n this.createTime = version;\n }\n this.version = version;\n this.documentType = DocumentType.FOUND_DOCUMENT;\n this.data = value;\n this.documentState = DocumentState.SYNCED;\n return this;\n }\n\n /**\n * Changes the document type to indicate that it doesn't exist at the given\n * version.\n */\n convertToNoDocument(version: SnapshotVersion): MutableDocument {\n this.version = version;\n this.documentType = DocumentType.NO_DOCUMENT;\n this.data = ObjectValue.empty();\n this.documentState = DocumentState.SYNCED;\n return this;\n }\n\n /**\n * Changes the document type to indicate that it exists at a given version but\n * that its data is not known (e.g. a document that was updated without a known\n * base document).\n */\n convertToUnknownDocument(version: SnapshotVersion): MutableDocument {\n this.version = version;\n this.documentType = DocumentType.UNKNOWN_DOCUMENT;\n this.data = ObjectValue.empty();\n this.documentState = DocumentState.HAS_COMMITTED_MUTATIONS;\n return this;\n }\n\n setHasCommittedMutations(): MutableDocument {\n debugAssert(\n this.isValidDocument(),\n 'Invalid documents cannot have committed mutations'\n );\n this.documentState = DocumentState.HAS_COMMITTED_MUTATIONS;\n return this;\n }\n\n setHasLocalMutations(): MutableDocument {\n this.documentState = DocumentState.HAS_LOCAL_MUTATIONS;\n this.version = SnapshotVersion.min();\n return this;\n }\n\n setReadTime(readTime: SnapshotVersion): MutableDocument {\n this.readTime = readTime;\n return this;\n }\n\n get hasLocalMutations(): boolean {\n return this.documentState === DocumentState.HAS_LOCAL_MUTATIONS;\n }\n\n get hasCommittedMutations(): boolean {\n return this.documentState === DocumentState.HAS_COMMITTED_MUTATIONS;\n }\n\n get hasPendingWrites(): boolean {\n return this.hasLocalMutations || this.hasCommittedMutations;\n }\n\n isValidDocument(): boolean {\n return this.documentType !== DocumentType.INVALID;\n }\n\n isFoundDocument(): boolean {\n return this.documentType === DocumentType.FOUND_DOCUMENT;\n }\n\n isNoDocument(): boolean {\n return this.documentType === DocumentType.NO_DOCUMENT;\n }\n\n isUnknownDocument(): boolean {\n return this.documentType === DocumentType.UNKNOWN_DOCUMENT;\n }\n\n isEqual(other: Document | null | undefined): boolean {\n return (\n other instanceof MutableDocument &&\n this.key.isEqual(other.key) &&\n this.version.isEqual(other.version) &&\n this.documentType === other.documentType &&\n this.documentState === other.documentState &&\n this.data.isEqual(other.data)\n );\n }\n\n mutableCopy(): MutableDocument {\n return new MutableDocument(\n this.key,\n this.documentType,\n this.version,\n this.readTime,\n this.createTime,\n this.data.clone(),\n this.documentState\n );\n }\n\n toString(): string {\n return (\n `Document(${this.key}, ${this.version}, ${JSON.stringify(\n this.data.value\n )}, ` +\n `{createTime: ${this.createTime}}), ` +\n `{documentType: ${this.documentType}}), ` +\n `{documentState: ${this.documentState}})`\n );\n }\n}\n\n/**\n * Compares the value for field `field` in the provided documents. Throws if\n * the field does not exist in both documents.\n */\nexport function compareDocumentsByField(\n field: FieldPath,\n d1: Document,\n d2: Document\n): number {\n const v1 = d1.data.field(field);\n const v2 = d2.data.field(field);\n if (v1 !== null && v2 !== null) {\n return valueCompare(v1, v2);\n } else {\n return fail(\n 0xa786,\n \"Trying to compare documents on fields that don't exist\"\n );\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DocumentKey } from '../model/document_key';\nimport {\n FieldIndex,\n fieldIndexGetArraySegment,\n fieldIndexGetDirectionalSegments,\n IndexKind\n} from '../model/field_index';\nimport { FieldPath, ResourcePath } from '../model/path';\nimport {\n canonicalId,\n MAX_VALUE,\n MIN_VALUE,\n lowerBoundCompare,\n upperBoundCompare,\n valuesGetLowerBound,\n valuesGetUpperBound\n} from '../model/values';\nimport { Value as ProtoValue } from '../protos/firestore_proto_api';\nimport { debugCast } from '../util/assert';\nimport { SortedSet } from '../util/sorted_set';\nimport { isNullOrUndefined } from '../util/types';\n\nimport { Bound, boundEquals } from './bound';\nimport {\n Filter,\n FieldFilter,\n canonifyFilter,\n stringifyFilter,\n filterEquals,\n Operator\n} from './filter';\nimport {\n canonifyOrderBy,\n OrderBy,\n orderByEquals,\n stringifyOrderBy\n} from './order_by';\n\n/**\n * A Target represents the WatchTarget representation of a Query, which is used\n * by the LocalStore and the RemoteStore to keep track of and to execute\n * backend queries. While a Query can represent multiple Targets, each Targets\n * maps to a single WatchTarget in RemoteStore and a single TargetData entry\n * in persistence.\n */\nexport interface Target {\n readonly path: ResourcePath;\n readonly collectionGroup: string | null;\n readonly orderBy: OrderBy[];\n readonly filters: Filter[];\n readonly limit: number | null;\n readonly startAt: Bound | null;\n readonly endAt: Bound | null;\n}\n\n// Visible for testing\nexport class TargetImpl implements Target {\n memoizedCanonicalId: string | null = null;\n constructor(\n readonly path: ResourcePath,\n readonly collectionGroup: string | null = null,\n readonly orderBy: OrderBy[] = [],\n readonly filters: Filter[] = [],\n readonly limit: number | null = null,\n readonly startAt: Bound | null = null,\n readonly endAt: Bound | null = null\n ) {}\n}\n\n/**\n * Initializes a Target with a path and optional additional query constraints.\n * Path must currently be empty if this is a collection group query.\n *\n * NOTE: you should always construct `Target` from `Query.toTarget` instead of\n * using this factory method, because `Query` provides an implicit `orderBy`\n * property.\n */\nexport function newTarget(\n path: ResourcePath,\n collectionGroup: string | null = null,\n orderBy: OrderBy[] = [],\n filters: Filter[] = [],\n limit: number | null = null,\n startAt: Bound | null = null,\n endAt: Bound | null = null\n): Target {\n return new TargetImpl(\n path,\n collectionGroup,\n orderBy,\n filters,\n limit,\n startAt,\n endAt\n );\n}\n\nexport function canonifyTarget(target: Target): string {\n const targetImpl = debugCast(target, TargetImpl);\n\n if (targetImpl.memoizedCanonicalId === null) {\n let str = targetImpl.path.canonicalString();\n if (targetImpl.collectionGroup !== null) {\n str += '|cg:' + targetImpl.collectionGroup;\n }\n str += '|f:';\n str += targetImpl.filters.map(f => canonifyFilter(f)).join(',');\n str += '|ob:';\n str += targetImpl.orderBy.map(o => canonifyOrderBy(o)).join(',');\n\n if (!isNullOrUndefined(targetImpl.limit)) {\n str += '|l:';\n str += targetImpl.limit!;\n }\n if (targetImpl.startAt) {\n str += '|lb:';\n str += targetImpl.startAt.inclusive ? 'b:' : 'a:';\n str += targetImpl.startAt.position.map(p => canonicalId(p)).join(',');\n }\n if (targetImpl.endAt) {\n str += '|ub:';\n str += targetImpl.endAt.inclusive ? 'a:' : 'b:';\n str += targetImpl.endAt.position.map(p => canonicalId(p)).join(',');\n }\n targetImpl.memoizedCanonicalId = str;\n }\n return targetImpl.memoizedCanonicalId;\n}\n\nexport function stringifyTarget(target: Target): string {\n let str = target.path.canonicalString();\n if (target.collectionGroup !== null) {\n str += ' collectionGroup=' + target.collectionGroup;\n }\n if (target.filters.length > 0) {\n str += `, filters: [${target.filters\n .map(f => stringifyFilter(f))\n .join(', ')}]`;\n }\n if (!isNullOrUndefined(target.limit)) {\n str += ', limit: ' + target.limit;\n }\n if (target.orderBy.length > 0) {\n str += `, orderBy: [${target.orderBy\n .map(o => stringifyOrderBy(o))\n .join(', ')}]`;\n }\n if (target.startAt) {\n str += ', startAt: ';\n str += target.startAt.inclusive ? 'b:' : 'a:';\n str += target.startAt.position.map(p => canonicalId(p)).join(',');\n }\n if (target.endAt) {\n str += ', endAt: ';\n str += target.endAt.inclusive ? 'a:' : 'b:';\n str += target.endAt.position.map(p => canonicalId(p)).join(',');\n }\n return `Target(${str})`;\n}\n\nexport function targetEquals(left: Target, right: Target): boolean {\n if (left.limit !== right.limit) {\n return false;\n }\n\n if (left.orderBy.length !== right.orderBy.length) {\n return false;\n }\n\n for (let i = 0; i < left.orderBy.length; i++) {\n if (!orderByEquals(left.orderBy[i], right.orderBy[i])) {\n return false;\n }\n }\n\n if (left.filters.length !== right.filters.length) {\n return false;\n }\n\n for (let i = 0; i < left.filters.length; i++) {\n if (!filterEquals(left.filters[i], right.filters[i])) {\n return false;\n }\n }\n\n if (left.collectionGroup !== right.collectionGroup) {\n return false;\n }\n\n if (!left.path.isEqual(right.path)) {\n return false;\n }\n\n if (!boundEquals(left.startAt, right.startAt)) {\n return false;\n }\n\n return boundEquals(left.endAt, right.endAt);\n}\n\nexport function targetIsDocumentTarget(target: Target): boolean {\n return (\n DocumentKey.isDocumentKey(target.path) &&\n target.collectionGroup === null &&\n target.filters.length === 0\n );\n}\n\n/** Returns the field filters that target the given field path. */\nexport function targetGetFieldFiltersForPath(\n target: Target,\n path: FieldPath\n): FieldFilter[] {\n return target.filters.filter(\n f => f instanceof FieldFilter && f.field.isEqual(path)\n ) as FieldFilter[];\n}\n\n/**\n * Returns the values that are used in ARRAY_CONTAINS or ARRAY_CONTAINS_ANY\n * filters. Returns `null` if there are no such filters.\n */\nexport function targetGetArrayValues(\n target: Target,\n fieldIndex: FieldIndex\n): ProtoValue[] | null {\n const segment = fieldIndexGetArraySegment(fieldIndex);\n if (segment === undefined) {\n return null;\n }\n\n for (const fieldFilter of targetGetFieldFiltersForPath(\n target,\n segment.fieldPath\n )) {\n switch (fieldFilter.op) {\n case Operator.ARRAY_CONTAINS_ANY:\n return fieldFilter.value.arrayValue!.values || [];\n case Operator.ARRAY_CONTAINS:\n return [fieldFilter.value];\n default:\n // Remaining filters are not array filters.\n }\n }\n return null;\n}\n\n/**\n * Returns the list of values that are used in != or NOT_IN filters. Returns\n * `null` if there are no such filters.\n */\nexport function targetGetNotInValues(\n target: Target,\n fieldIndex: FieldIndex\n): ProtoValue[] | null {\n const values = new Map();\n\n for (const segment of fieldIndexGetDirectionalSegments(fieldIndex)) {\n for (const fieldFilter of targetGetFieldFiltersForPath(\n target,\n segment.fieldPath\n )) {\n switch (fieldFilter.op) {\n case Operator.EQUAL:\n case Operator.IN:\n // Encode equality prefix, which is encoded in the index value before\n // the inequality (e.g. `a == 'a' && b != 'b'` is encoded to\n // `value != 'ab'`).\n values.set(segment.fieldPath.canonicalString(), fieldFilter.value);\n break;\n case Operator.NOT_IN:\n case Operator.NOT_EQUAL:\n // NotIn/NotEqual is always a suffix. There cannot be any remaining\n // segments and hence we can return early here.\n values.set(segment.fieldPath.canonicalString(), fieldFilter.value);\n return Array.from(values.values());\n default:\n // Remaining filters cannot be used as notIn bounds.\n }\n }\n }\n\n return null;\n}\n\n/**\n * Returns a lower bound of field values that can be used as a starting point to\n * scan the index defined by `fieldIndex`. Returns `MIN_VALUE` if no lower bound\n * exists.\n */\nexport function targetGetLowerBound(\n target: Target,\n fieldIndex: FieldIndex\n): Bound {\n const values: ProtoValue[] = [];\n let inclusive = true;\n\n // For each segment, retrieve a lower bound if there is a suitable filter or\n // startAt.\n for (const segment of fieldIndexGetDirectionalSegments(fieldIndex)) {\n const segmentBound =\n segment.kind === IndexKind.ASCENDING\n ? targetGetAscendingBound(target, segment.fieldPath, target.startAt)\n : targetGetDescendingBound(target, segment.fieldPath, target.startAt);\n\n values.push(segmentBound.value);\n inclusive &&= segmentBound.inclusive;\n }\n return new Bound(values, inclusive);\n}\n\n/**\n * Returns an upper bound of field values that can be used as an ending point\n * when scanning the index defined by `fieldIndex`. Returns `MAX_VALUE` if no\n * upper bound exists.\n */\nexport function targetGetUpperBound(\n target: Target,\n fieldIndex: FieldIndex\n): Bound {\n const values: ProtoValue[] = [];\n let inclusive = true;\n\n // For each segment, retrieve an upper bound if there is a suitable filter or\n // endAt.\n for (const segment of fieldIndexGetDirectionalSegments(fieldIndex)) {\n const segmentBound =\n segment.kind === IndexKind.ASCENDING\n ? targetGetDescendingBound(target, segment.fieldPath, target.endAt)\n : targetGetAscendingBound(target, segment.fieldPath, target.endAt);\n\n values.push(segmentBound.value);\n inclusive &&= segmentBound.inclusive;\n }\n\n return new Bound(values, inclusive);\n}\n\n/**\n * Returns the value to use as the lower bound for ascending index segment at\n * the provided `fieldPath` (or the upper bound for an descending segment).\n */\nfunction targetGetAscendingBound(\n target: Target,\n fieldPath: FieldPath,\n bound: Bound | null\n): { value: ProtoValue; inclusive: boolean } {\n let value: ProtoValue = MIN_VALUE;\n\n let inclusive = true;\n\n // Process all filters to find a value for the current field segment\n for (const fieldFilter of targetGetFieldFiltersForPath(target, fieldPath)) {\n let filterValue: ProtoValue = MIN_VALUE;\n let filterInclusive = true;\n\n switch (fieldFilter.op) {\n case Operator.LESS_THAN:\n case Operator.LESS_THAN_OR_EQUAL:\n filterValue = valuesGetLowerBound(fieldFilter.value);\n break;\n case Operator.EQUAL:\n case Operator.IN:\n case Operator.GREATER_THAN_OR_EQUAL:\n filterValue = fieldFilter.value;\n break;\n case Operator.GREATER_THAN:\n filterValue = fieldFilter.value;\n filterInclusive = false;\n break;\n case Operator.NOT_EQUAL:\n case Operator.NOT_IN:\n filterValue = MIN_VALUE;\n break;\n default:\n // Remaining filters cannot be used as lower bounds.\n }\n\n if (\n lowerBoundCompare(\n { value, inclusive },\n { value: filterValue, inclusive: filterInclusive }\n ) < 0\n ) {\n value = filterValue;\n inclusive = filterInclusive;\n }\n }\n\n // If there is an additional bound, compare the values against the existing\n // range to see if we can narrow the scope.\n if (bound !== null) {\n for (let i = 0; i < target.orderBy.length; ++i) {\n const orderBy = target.orderBy[i];\n if (orderBy.field.isEqual(fieldPath)) {\n const cursorValue = bound.position[i];\n if (\n lowerBoundCompare(\n { value, inclusive },\n { value: cursorValue, inclusive: bound.inclusive }\n ) < 0\n ) {\n value = cursorValue;\n inclusive = bound.inclusive;\n }\n break;\n }\n }\n }\n\n return { value, inclusive };\n}\n\n/**\n * Returns the value to use as the upper bound for ascending index segment at\n * the provided `fieldPath` (or the lower bound for a descending segment).\n */\nfunction targetGetDescendingBound(\n target: Target,\n fieldPath: FieldPath,\n bound: Bound | null\n): { value: ProtoValue; inclusive: boolean } {\n let value: ProtoValue = MAX_VALUE;\n let inclusive = true;\n\n // Process all filters to find a value for the current field segment\n for (const fieldFilter of targetGetFieldFiltersForPath(target, fieldPath)) {\n let filterValue: ProtoValue = MAX_VALUE;\n let filterInclusive = true;\n\n switch (fieldFilter.op) {\n case Operator.GREATER_THAN_OR_EQUAL:\n case Operator.GREATER_THAN:\n filterValue = valuesGetUpperBound(fieldFilter.value);\n filterInclusive = false;\n break;\n case Operator.EQUAL:\n case Operator.IN:\n case Operator.LESS_THAN_OR_EQUAL:\n filterValue = fieldFilter.value;\n break;\n case Operator.LESS_THAN:\n filterValue = fieldFilter.value;\n filterInclusive = false;\n break;\n case Operator.NOT_EQUAL:\n case Operator.NOT_IN:\n filterValue = MAX_VALUE;\n break;\n default:\n // Remaining filters cannot be used as upper bounds.\n }\n\n if (\n upperBoundCompare(\n { value, inclusive },\n { value: filterValue, inclusive: filterInclusive }\n ) > 0\n ) {\n value = filterValue;\n inclusive = filterInclusive;\n }\n }\n\n // If there is an additional bound, compare the values against the existing\n // range to see if we can narrow the scope.\n if (bound !== null) {\n for (let i = 0; i < target.orderBy.length; ++i) {\n const orderBy = target.orderBy[i];\n if (orderBy.field.isEqual(fieldPath)) {\n const cursorValue = bound.position[i];\n if (\n upperBoundCompare(\n { value, inclusive },\n { value: cursorValue, inclusive: bound.inclusive }\n ) > 0\n ) {\n value = cursorValue;\n inclusive = bound.inclusive;\n }\n break;\n }\n }\n }\n\n return { value, inclusive };\n}\n\n/** Returns the number of segments of a perfect index for this target. */\nexport function targetGetSegmentCount(target: Target): number {\n let fields = new SortedSet(FieldPath.comparator);\n let hasArraySegment = false;\n\n for (const filter of target.filters) {\n for (const subFilter of filter.getFlattenedFilters()) {\n // __name__ is not an explicit segment of any index, so we don't need to\n // count it.\n if (subFilter.field.isKeyField()) {\n continue;\n }\n\n // ARRAY_CONTAINS or ARRAY_CONTAINS_ANY filters must be counted separately.\n // For instance, it is possible to have an index for \"a ARRAY a ASC\". Even\n // though these are on the same field, they should be counted as two\n // separate segments in an index.\n if (\n subFilter.op === Operator.ARRAY_CONTAINS ||\n subFilter.op === Operator.ARRAY_CONTAINS_ANY\n ) {\n hasArraySegment = true;\n } else {\n fields = fields.add(subFilter.field);\n }\n }\n }\n\n for (const orderBy of target.orderBy) {\n // __name__ is not an explicit segment of any index, so we don't need to\n // count it.\n if (!orderBy.field.isKeyField()) {\n fields = fields.add(orderBy.field);\n }\n }\n\n return fields.size + (hasArraySegment ? 1 : 0);\n}\n\nexport function targetHasLimit(target: Target): boolean {\n return target.limit !== null;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { compareDocumentsByField, Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { FieldPath, ResourcePath } from '../model/path';\nimport { debugAssert, debugCast, fail } from '../util/assert';\nimport { SortedSet } from '../util/sorted_set';\n\nimport {\n Bound,\n boundSortsAfterDocument,\n boundSortsBeforeDocument\n} from './bound';\nimport { FieldFilter, Filter } from './filter';\nimport { Direction, OrderBy } from './order_by';\nimport {\n canonifyTarget,\n newTarget,\n stringifyTarget,\n Target,\n targetEquals\n} from './target';\n\nexport const enum LimitType {\n First = 'F',\n Last = 'L'\n}\n\n/**\n * The Query interface defines all external properties of a query.\n *\n * QueryImpl implements this interface to provide memoization for `queryNormalizedOrderBy`\n * and `queryToTarget`.\n */\nexport interface Query {\n readonly path: ResourcePath;\n readonly collectionGroup: string | null;\n readonly explicitOrderBy: OrderBy[];\n readonly filters: Filter[];\n readonly limit: number | null;\n readonly limitType: LimitType;\n readonly startAt: Bound | null;\n readonly endAt: Bound | null;\n}\n\n/**\n * Query encapsulates all the query attributes we support in the SDK. It can\n * be run against the LocalStore, as well as be converted to a `Target` to\n * query the RemoteStore results.\n *\n * Visible for testing.\n */\nexport class QueryImpl implements Query {\n memoizedNormalizedOrderBy: OrderBy[] | null = null;\n\n // The corresponding `Target` of this `Query` instance, for use with\n // non-aggregate queries.\n memoizedTarget: Target | null = null;\n\n // The corresponding `Target` of this `Query` instance, for use with\n // aggregate queries. Unlike targets for non-aggregate queries,\n // aggregate query targets do not contain normalized order-bys, they only\n // contain explicit order-bys.\n memoizedAggregateTarget: Target | null = null;\n\n /**\n * Initializes a Query with a path and optional additional query constraints.\n * Path must currently be empty if this is a collection group query.\n */\n constructor(\n readonly path: ResourcePath,\n readonly collectionGroup: string | null = null,\n readonly explicitOrderBy: OrderBy[] = [],\n readonly filters: Filter[] = [],\n readonly limit: number | null = null,\n readonly limitType: LimitType = LimitType.First,\n readonly startAt: Bound | null = null,\n readonly endAt: Bound | null = null\n ) {\n if (this.startAt) {\n debugAssert(\n this.startAt.position.length <= queryNormalizedOrderBy(this).length,\n 'Bound is longer than orderBy'\n );\n }\n if (this.endAt) {\n debugAssert(\n this.endAt.position.length <= queryNormalizedOrderBy(this).length,\n 'Bound is longer than orderBy'\n );\n }\n }\n}\n\n/** Creates a new Query instance with the options provided. */\nexport function newQuery(\n path: ResourcePath,\n collectionGroup: string | null,\n explicitOrderBy: OrderBy[],\n filters: Filter[],\n limit: number | null,\n limitType: LimitType,\n startAt: Bound | null,\n endAt: Bound | null\n): Query {\n return new QueryImpl(\n path,\n collectionGroup,\n explicitOrderBy,\n filters,\n limit,\n limitType,\n startAt,\n endAt\n );\n}\n\n/** Creates a new Query for a query that matches all documents at `path` */\nexport function newQueryForPath(path: ResourcePath): Query {\n return new QueryImpl(path);\n}\n\n/**\n * Helper to convert a collection group query into a collection query at a\n * specific path. This is used when executing collection group queries, since\n * we have to split the query into a set of collection queries at multiple\n * paths.\n */\nexport function asCollectionQueryAtPath(\n query: Query,\n path: ResourcePath\n): Query {\n return new QueryImpl(\n path,\n /*collectionGroup=*/ null,\n query.explicitOrderBy.slice(),\n query.filters.slice(),\n query.limit,\n query.limitType,\n query.startAt,\n query.endAt\n );\n}\n\n/**\n * Returns true if this query does not specify any query constraints that\n * could remove results.\n */\nexport function queryMatchesAllDocuments(query: Query): boolean {\n return (\n query.filters.length === 0 &&\n query.limit === null &&\n query.startAt == null &&\n query.endAt == null &&\n (query.explicitOrderBy.length === 0 ||\n (query.explicitOrderBy.length === 1 &&\n query.explicitOrderBy[0].field.isKeyField()))\n );\n}\n\n// Returns the sorted set of inequality filter fields used in this query.\nexport function getInequalityFilterFields(query: Query): SortedSet {\n let result = new SortedSet(FieldPath.comparator);\n query.filters.forEach((filter: Filter) => {\n const subFilters = filter.getFlattenedFilters();\n subFilters.forEach((filter: FieldFilter) => {\n if (filter.isInequality()) {\n result = result.add(filter.field);\n }\n });\n });\n return result;\n}\n\n/**\n * Creates a new Query for a collection group query that matches all documents\n * within the provided collection group.\n */\nexport function newQueryForCollectionGroup(collectionId: string): Query {\n return new QueryImpl(ResourcePath.emptyPath(), collectionId);\n}\n\n/**\n * Returns whether the query matches a single document by path (rather than a\n * collection).\n */\nexport function isDocumentQuery(query: Query): boolean {\n return (\n DocumentKey.isDocumentKey(query.path) &&\n query.collectionGroup === null &&\n query.filters.length === 0\n );\n}\n\n/**\n * Returns whether the query matches a collection group rather than a specific\n * collection.\n */\nexport function isCollectionGroupQuery(query: Query): boolean {\n return query.collectionGroup !== null;\n}\n\n/**\n * Returns the normalized order-by constraint that is used to execute the Query,\n * which can be different from the order-by constraints the user provided (e.g.\n * the SDK and backend always orders by `__name__`). The normalized order-by\n * includes implicit order-bys in addition to the explicit user provided\n * order-bys.\n */\nexport function queryNormalizedOrderBy(query: Query): OrderBy[] {\n const queryImpl = debugCast(query, QueryImpl);\n if (queryImpl.memoizedNormalizedOrderBy === null) {\n queryImpl.memoizedNormalizedOrderBy = [];\n const fieldsNormalized = new Set();\n\n // Any explicit order by fields should be added as is.\n for (const orderBy of queryImpl.explicitOrderBy) {\n queryImpl.memoizedNormalizedOrderBy.push(orderBy);\n fieldsNormalized.add(orderBy.field.canonicalString());\n }\n\n // The order of the implicit ordering always matches the last explicit order by.\n const lastDirection =\n queryImpl.explicitOrderBy.length > 0\n ? queryImpl.explicitOrderBy[queryImpl.explicitOrderBy.length - 1].dir\n : Direction.ASCENDING;\n\n // Any inequality fields not explicitly ordered should be implicitly ordered in a lexicographical\n // order. When there are multiple inequality filters on the same field, the field should be added\n // only once.\n // Note: `SortedSet` sorts the key field before other fields. However, we want the key\n // field to be sorted last.\n const inequalityFields: SortedSet =\n getInequalityFilterFields(queryImpl);\n inequalityFields.forEach(field => {\n if (\n !fieldsNormalized.has(field.canonicalString()) &&\n !field.isKeyField()\n ) {\n queryImpl.memoizedNormalizedOrderBy!.push(\n new OrderBy(field, lastDirection)\n );\n }\n });\n\n // Add the document key field to the last if it is not explicitly ordered.\n if (!fieldsNormalized.has(FieldPath.keyField().canonicalString())) {\n queryImpl.memoizedNormalizedOrderBy.push(\n new OrderBy(FieldPath.keyField(), lastDirection)\n );\n }\n }\n return queryImpl.memoizedNormalizedOrderBy;\n}\n\n/**\n * Converts this `Query` instance to its corresponding `Target` representation.\n */\nexport function queryToTarget(query: Query): Target {\n const queryImpl = debugCast(query, QueryImpl);\n if (!queryImpl.memoizedTarget) {\n queryImpl.memoizedTarget = _queryToTarget(\n queryImpl,\n queryNormalizedOrderBy(query)\n );\n }\n\n return queryImpl.memoizedTarget;\n}\n\n/**\n * Converts this `Query` instance to its corresponding `Target` representation,\n * for use within an aggregate query. Unlike targets for non-aggregate queries,\n * aggregate query targets do not contain normalized order-bys, they only\n * contain explicit order-bys.\n */\nexport function queryToAggregateTarget(query: Query): Target {\n const queryImpl = debugCast(query, QueryImpl);\n\n if (!queryImpl.memoizedAggregateTarget) {\n // Do not include implicit order-bys for aggregate queries.\n queryImpl.memoizedAggregateTarget = _queryToTarget(\n queryImpl,\n query.explicitOrderBy\n );\n }\n\n return queryImpl.memoizedAggregateTarget;\n}\n\nfunction _queryToTarget(queryImpl: QueryImpl, orderBys: OrderBy[]): Target {\n if (queryImpl.limitType === LimitType.First) {\n return newTarget(\n queryImpl.path,\n queryImpl.collectionGroup,\n orderBys,\n queryImpl.filters,\n queryImpl.limit,\n queryImpl.startAt,\n queryImpl.endAt\n );\n } else {\n // Flip the orderBy directions since we want the last results\n orderBys = orderBys.map(orderBy => {\n const dir =\n orderBy.dir === Direction.DESCENDING\n ? Direction.ASCENDING\n : Direction.DESCENDING;\n return new OrderBy(orderBy.field, dir);\n });\n\n // We need to swap the cursors to match the now-flipped query ordering.\n const startAt = queryImpl.endAt\n ? new Bound(queryImpl.endAt.position, queryImpl.endAt.inclusive)\n : null;\n const endAt = queryImpl.startAt\n ? new Bound(queryImpl.startAt.position, queryImpl.startAt.inclusive)\n : null;\n\n // Now return as a LimitType.First query.\n return newTarget(\n queryImpl.path,\n queryImpl.collectionGroup,\n orderBys,\n queryImpl.filters,\n queryImpl.limit,\n startAt,\n endAt\n );\n }\n}\n\nexport function queryWithAddedFilter(query: Query, filter: Filter): Query {\n debugAssert(\n !isDocumentQuery(query),\n 'No filtering allowed for document query'\n );\n\n const newFilters = query.filters.concat([filter]);\n return new QueryImpl(\n query.path,\n query.collectionGroup,\n query.explicitOrderBy.slice(),\n newFilters,\n query.limit,\n query.limitType,\n query.startAt,\n query.endAt\n );\n}\n\nexport function queryWithAddedOrderBy(query: Query, orderBy: OrderBy): Query {\n debugAssert(\n !query.startAt && !query.endAt,\n 'Bounds must be set after orderBy'\n );\n // TODO(dimond): validate that orderBy does not list the same key twice.\n const newOrderBy = query.explicitOrderBy.concat([orderBy]);\n return new QueryImpl(\n query.path,\n query.collectionGroup,\n newOrderBy,\n query.filters.slice(),\n query.limit,\n query.limitType,\n query.startAt,\n query.endAt\n );\n}\n\nexport function queryWithLimit(\n query: Query,\n limit: number | null,\n limitType: LimitType\n): Query {\n return new QueryImpl(\n query.path,\n query.collectionGroup,\n query.explicitOrderBy.slice(),\n query.filters.slice(),\n limit,\n limitType,\n query.startAt,\n query.endAt\n );\n}\n\nexport function queryWithStartAt(query: Query, bound: Bound): Query {\n return new QueryImpl(\n query.path,\n query.collectionGroup,\n query.explicitOrderBy.slice(),\n query.filters.slice(),\n query.limit,\n query.limitType,\n bound,\n query.endAt\n );\n}\n\nexport function queryWithEndAt(query: Query, bound: Bound): Query {\n return new QueryImpl(\n query.path,\n query.collectionGroup,\n query.explicitOrderBy.slice(),\n query.filters.slice(),\n query.limit,\n query.limitType,\n query.startAt,\n bound\n );\n}\n\nexport function queryEquals(left: Query, right: Query): boolean {\n return (\n targetEquals(queryToTarget(left), queryToTarget(right)) &&\n left.limitType === right.limitType\n );\n}\n\n// TODO(b/29183165): This is used to get a unique string from a query to, for\n// example, use as a dictionary key, but the implementation is subject to\n// collisions. Make it collision-free.\nexport function canonifyQuery(query: Query): string {\n return `${canonifyTarget(queryToTarget(query))}|lt:${query.limitType}`;\n}\n\nexport function stringifyQuery(query: Query): string {\n return `Query(target=${stringifyTarget(queryToTarget(query))}; limitType=${\n query.limitType\n })`;\n}\n\n/** Returns whether `doc` matches the constraints of `query`. */\nexport function queryMatches(query: Query, doc: Document): boolean {\n return (\n doc.isFoundDocument() &&\n queryMatchesPathAndCollectionGroup(query, doc) &&\n queryMatchesOrderBy(query, doc) &&\n queryMatchesFilters(query, doc) &&\n queryMatchesBounds(query, doc)\n );\n}\n\nfunction queryMatchesPathAndCollectionGroup(\n query: Query,\n doc: Document\n): boolean {\n const docPath = doc.key.path;\n if (query.collectionGroup !== null) {\n // NOTE: this.path is currently always empty since we don't expose Collection\n // Group queries rooted at a document path yet.\n return (\n doc.key.hasCollectionId(query.collectionGroup) &&\n query.path.isPrefixOf(docPath)\n );\n } else if (DocumentKey.isDocumentKey(query.path)) {\n // exact match for document queries\n return query.path.isEqual(docPath);\n } else {\n // shallow ancestor queries by default\n return query.path.isImmediateParentOf(docPath);\n }\n}\n\n/**\n * A document must have a value for every ordering clause in order to show up\n * in the results.\n */\nfunction queryMatchesOrderBy(query: Query, doc: Document): boolean {\n // We must use `queryNormalizedOrderBy()` to get the list of all orderBys (both implicit and explicit).\n // Note that for OR queries, orderBy applies to all disjunction terms and implicit orderBys must\n // be taken into account. For example, the query \"a > 1 || b==1\" has an implicit \"orderBy a\" due\n // to the inequality, and is evaluated as \"a > 1 orderBy a || b==1 orderBy a\".\n // A document with content of {b:1} matches the filters, but does not match the orderBy because\n // it's missing the field 'a'.\n for (const orderBy of queryNormalizedOrderBy(query)) {\n // order-by key always matches\n if (!orderBy.field.isKeyField() && doc.data.field(orderBy.field) === null) {\n return false;\n }\n }\n return true;\n}\n\nfunction queryMatchesFilters(query: Query, doc: Document): boolean {\n for (const filter of query.filters) {\n if (!filter.matches(doc)) {\n return false;\n }\n }\n return true;\n}\n\n/** Makes sure a document is within the bounds, if provided. */\nfunction queryMatchesBounds(query: Query, doc: Document): boolean {\n if (\n query.startAt &&\n !boundSortsBeforeDocument(query.startAt, queryNormalizedOrderBy(query), doc)\n ) {\n return false;\n }\n if (\n query.endAt &&\n !boundSortsAfterDocument(query.endAt, queryNormalizedOrderBy(query), doc)\n ) {\n return false;\n }\n return true;\n}\n\n/**\n * Returns the collection group that this query targets.\n *\n * PORTING NOTE: This is only used in the Web SDK to facilitate multi-tab\n * synchronization for query results.\n */\nexport function queryCollectionGroup(query: Query): string {\n return (\n query.collectionGroup ||\n (query.path.length % 2 === 1\n ? query.path.lastSegment()\n : query.path.get(query.path.length - 2))\n );\n}\n\n/**\n * Returns a new comparator function that can be used to compare two documents\n * based on the Query's ordering constraint.\n */\nexport function newQueryComparator(\n query: Query\n): (d1: Document, d2: Document) => number {\n return (d1: Document, d2: Document): number => {\n let comparedOnKeyField = false;\n for (const orderBy of queryNormalizedOrderBy(query)) {\n const comp = compareDocs(orderBy, d1, d2);\n if (comp !== 0) {\n return comp;\n }\n comparedOnKeyField = comparedOnKeyField || orderBy.field.isKeyField();\n }\n // Assert that we actually compared by key\n debugAssert(\n comparedOnKeyField,\n \"orderBy used that doesn't compare on key field\"\n );\n return 0;\n };\n}\n\nexport function compareDocs(\n orderBy: OrderBy,\n d1: Document,\n d2: Document\n): number {\n const comparison = orderBy.field.isKeyField()\n ? DocumentKey.comparator(d1.key, d2.key)\n : compareDocumentsByField(orderBy.field, d1, d2);\n switch (orderBy.dir) {\n case Direction.ASCENDING:\n return comparison;\n case Direction.DESCENDING:\n return -1 * comparison;\n default:\n return fail(0x4d4e, 'Unknown direction', { direction: orderBy.dir });\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Value as ProtoValue } from '../protos/firestore_proto_api';\nimport { isNegativeZero, isSafeInteger } from '../util/types';\n\n/** Base interface for the Serializer implementation. */\nexport interface Serializer {\n readonly useProto3Json: boolean;\n}\n\n/**\n * Returns an DoubleValue for `value` that is encoded based the serializer's\n * `useProto3Json` setting.\n */\nexport function toDouble(serializer: Serializer, value: number): ProtoValue {\n if (serializer.useProto3Json) {\n if (isNaN(value)) {\n return { doubleValue: 'NaN' };\n } else if (value === Infinity) {\n return { doubleValue: 'Infinity' };\n } else if (value === -Infinity) {\n return { doubleValue: '-Infinity' };\n }\n }\n return { doubleValue: isNegativeZero(value) ? '-0' : value };\n}\n\n/**\n * Returns an IntegerValue for `value`.\n */\nexport function toInteger(value: number): ProtoValue {\n return { integerValue: '' + value };\n}\n\n/**\n * Returns a value for a number that's appropriate to put into a proto.\n * The return value is an IntegerValue if it can safely represent the value,\n * otherwise a DoubleValue is returned.\n */\nexport function toNumber(serializer: Serializer, value: number): ProtoValue {\n return isSafeInteger(value) ? toInteger(value) : toDouble(serializer, value);\n}\n","/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Timestamp } from '../lite-api/timestamp';\nimport { Value as ProtoValue } from '../protos/firestore_proto_api';\nimport { Serializer, toDouble, toInteger } from '../remote/number_serializer';\nimport { debugAssert } from '../util/assert';\nimport { arrayEquals } from '../util/misc';\n\nimport { normalizeNumber } from './normalize';\nimport { serverTimestamp } from './server_timestamps';\nimport { isArray, isInteger, isNumber, valueEquals } from './values';\n\n/** Used to represent a field transform on a mutation. */\nexport class TransformOperation {\n // Make sure that the structural type of `TransformOperation` is unique.\n // See https://github.com/microsoft/TypeScript/issues/5451\n private _ = undefined;\n}\n\n/**\n * Computes the local transform result against the provided `previousValue`,\n * optionally using the provided localWriteTime.\n */\nexport function applyTransformOperationToLocalView(\n transform: TransformOperation,\n previousValue: ProtoValue | null,\n localWriteTime: Timestamp\n): ProtoValue {\n if (transform instanceof ServerTimestampTransform) {\n return serverTimestamp(localWriteTime, previousValue);\n } else if (transform instanceof ArrayUnionTransformOperation) {\n return applyArrayUnionTransformOperation(transform, previousValue);\n } else if (transform instanceof ArrayRemoveTransformOperation) {\n return applyArrayRemoveTransformOperation(transform, previousValue);\n } else {\n debugAssert(\n transform instanceof NumericIncrementTransformOperation,\n 'Expected NumericIncrementTransformOperation but was: ' + transform\n );\n return applyNumericIncrementTransformOperationToLocalView(\n transform,\n previousValue\n );\n }\n}\n\n/**\n * Computes a final transform result after the transform has been acknowledged\n * by the server, potentially using the server-provided transformResult.\n */\nexport function applyTransformOperationToRemoteDocument(\n transform: TransformOperation,\n previousValue: ProtoValue | null,\n transformResult: ProtoValue | null\n): ProtoValue {\n // The server just sends null as the transform result for array operations,\n // so we have to calculate a result the same as we do for local\n // applications.\n if (transform instanceof ArrayUnionTransformOperation) {\n return applyArrayUnionTransformOperation(transform, previousValue);\n } else if (transform instanceof ArrayRemoveTransformOperation) {\n return applyArrayRemoveTransformOperation(transform, previousValue);\n }\n\n debugAssert(\n transformResult !== null,\n \"Didn't receive transformResult for non-array transform\"\n );\n return transformResult;\n}\n\n/**\n * If this transform operation is not idempotent, returns the base value to\n * persist for this transform. If a base value is returned, the transform\n * operation is always applied to this base value, even if document has\n * already been updated.\n *\n * Base values provide consistent behavior for non-idempotent transforms and\n * allow us to return the same latency-compensated value even if the backend\n * has already applied the transform operation. The base value is null for\n * idempotent transforms, as they can be re-played even if the backend has\n * already applied them.\n *\n * @returns a base value to store along with the mutation, or null for\n * idempotent transforms.\n */\nexport function computeTransformOperationBaseValue(\n transform: TransformOperation,\n previousValue: ProtoValue | null\n): ProtoValue | null {\n if (transform instanceof NumericIncrementTransformOperation) {\n return isNumber(previousValue) ? previousValue! : { integerValue: 0 };\n }\n return null;\n}\n\nexport function transformOperationEquals(\n left: TransformOperation,\n right: TransformOperation\n): boolean {\n if (\n left instanceof ArrayUnionTransformOperation &&\n right instanceof ArrayUnionTransformOperation\n ) {\n return arrayEquals(left.elements, right.elements, valueEquals);\n } else if (\n left instanceof ArrayRemoveTransformOperation &&\n right instanceof ArrayRemoveTransformOperation\n ) {\n return arrayEquals(left.elements, right.elements, valueEquals);\n } else if (\n left instanceof NumericIncrementTransformOperation &&\n right instanceof NumericIncrementTransformOperation\n ) {\n return valueEquals(left.operand, right.operand);\n }\n\n return (\n left instanceof ServerTimestampTransform &&\n right instanceof ServerTimestampTransform\n );\n}\n\n/** Transforms a value into a server-generated timestamp. */\nexport class ServerTimestampTransform extends TransformOperation {}\n\n/** Transforms an array value via a union operation. */\nexport class ArrayUnionTransformOperation extends TransformOperation {\n constructor(readonly elements: ProtoValue[]) {\n super();\n }\n}\n\nfunction applyArrayUnionTransformOperation(\n transform: ArrayUnionTransformOperation,\n previousValue: ProtoValue | null\n): ProtoValue {\n const values = coercedFieldValuesArray(previousValue);\n for (const toUnion of transform.elements) {\n if (!values.some(element => valueEquals(element, toUnion))) {\n values.push(toUnion);\n }\n }\n return { arrayValue: { values } };\n}\n\n/** Transforms an array value via a remove operation. */\nexport class ArrayRemoveTransformOperation extends TransformOperation {\n constructor(readonly elements: ProtoValue[]) {\n super();\n }\n}\n\nfunction applyArrayRemoveTransformOperation(\n transform: ArrayRemoveTransformOperation,\n previousValue: ProtoValue | null\n): ProtoValue {\n let values = coercedFieldValuesArray(previousValue);\n for (const toRemove of transform.elements) {\n values = values.filter(element => !valueEquals(element, toRemove));\n }\n return { arrayValue: { values } };\n}\n\n/**\n * Implements the backend semantics for locally computed NUMERIC_ADD (increment)\n * transforms. Converts all field values to integers or doubles, but unlike the\n * backend does not cap integer values at 2^63. Instead, JavaScript number\n * arithmetic is used and precision loss can occur for values greater than 2^53.\n */\nexport class NumericIncrementTransformOperation extends TransformOperation {\n constructor(readonly serializer: Serializer, readonly operand: ProtoValue) {\n super();\n debugAssert(\n isNumber(operand),\n 'NumericIncrementTransform transform requires a NumberValue'\n );\n }\n}\n\nexport function applyNumericIncrementTransformOperationToLocalView(\n transform: NumericIncrementTransformOperation,\n previousValue: ProtoValue | null\n): ProtoValue {\n // PORTING NOTE: Since JavaScript's integer arithmetic is limited to 53 bit\n // precision and resolves overflows by reducing precision, we do not\n // manually cap overflows at 2^63.\n const baseValue = computeTransformOperationBaseValue(\n transform,\n previousValue\n )!;\n const sum = asNumber(baseValue) + asNumber(transform.operand);\n if (isInteger(baseValue) && isInteger(transform.operand)) {\n return toInteger(sum);\n } else {\n return toDouble(transform.serializer, sum);\n }\n}\n\nfunction asNumber(value: ProtoValue): number {\n return normalizeNumber(value.integerValue || value.doubleValue);\n}\n\nfunction coercedFieldValuesArray(value: ProtoValue | null): ProtoValue[] {\n return isArray(value) && value.arrayValue.values\n ? value.arrayValue.values.slice()\n : [];\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { Timestamp } from '../lite-api/timestamp';\nimport { Value as ProtoValue } from '../protos/firestore_proto_api';\nimport { debugAssert, hardAssert } from '../util/assert';\nimport { arrayEquals } from '../util/misc';\nimport { SortedSet } from '../util/sorted_set';\n\nimport { Document, MutableDocument } from './document';\nimport { DocumentKey } from './document_key';\nimport { FieldMask } from './field_mask';\nimport { ObjectValue } from './object_value';\nimport { FieldPath } from './path';\nimport {\n applyTransformOperationToLocalView,\n applyTransformOperationToRemoteDocument,\n computeTransformOperationBaseValue,\n TransformOperation,\n transformOperationEquals\n} from './transform_operation';\n\n/** A field path and the TransformOperation to perform upon it. */\nexport class FieldTransform {\n constructor(\n readonly field: FieldPath,\n readonly transform: TransformOperation\n ) {}\n}\n\nexport function fieldTransformEquals(\n left: FieldTransform,\n right: FieldTransform\n): boolean {\n return (\n left.field.isEqual(right.field) &&\n transformOperationEquals(left.transform, right.transform)\n );\n}\n\nexport function fieldTransformsAreEqual(\n left?: FieldTransform[],\n right?: FieldTransform[]\n): boolean {\n if (left === undefined && right === undefined) {\n return true;\n }\n\n if (left && right) {\n return arrayEquals(left, right, (l, r) => fieldTransformEquals(l, r));\n }\n\n return false;\n}\n\n/** The result of successfully applying a mutation to the backend. */\nexport class MutationResult {\n constructor(\n /**\n * The version at which the mutation was committed:\n *\n * - For most operations, this is the updateTime in the WriteResult.\n * - For deletes, the commitTime of the WriteResponse (because deletes are\n * not stored and have no updateTime).\n *\n * Note that these versions can be different: No-op writes will not change\n * the updateTime even though the commitTime advances.\n */\n readonly version: SnapshotVersion,\n /**\n * The resulting fields returned from the backend after a mutation\n * containing field transforms has been committed. Contains one FieldValue\n * for each FieldTransform that was in the mutation.\n *\n * Will be empty if the mutation did not contain any field transforms.\n */\n readonly transformResults: Array\n ) {}\n}\n\nexport const enum MutationType {\n Set,\n Patch,\n Delete,\n Verify\n}\n\n/**\n * Encodes a precondition for a mutation. This follows the model that the\n * backend accepts with the special case of an explicit \"empty\" precondition\n * (meaning no precondition).\n */\nexport class Precondition {\n private constructor(\n readonly updateTime?: SnapshotVersion,\n readonly exists?: boolean\n ) {\n debugAssert(\n updateTime === undefined || exists === undefined,\n 'Precondition can specify \"exists\" or \"updateTime\" but not both'\n );\n }\n\n /** Creates a new empty Precondition. */\n static none(): Precondition {\n return new Precondition();\n }\n\n /** Creates a new Precondition with an exists flag. */\n static exists(exists: boolean): Precondition {\n return new Precondition(undefined, exists);\n }\n\n /** Creates a new Precondition based on a version a document exists at. */\n static updateTime(version: SnapshotVersion): Precondition {\n return new Precondition(version);\n }\n\n /** Returns whether this Precondition is empty. */\n get isNone(): boolean {\n return this.updateTime === undefined && this.exists === undefined;\n }\n\n isEqual(other: Precondition): boolean {\n return (\n this.exists === other.exists &&\n (this.updateTime\n ? !!other.updateTime && this.updateTime.isEqual(other.updateTime)\n : !other.updateTime)\n );\n }\n}\n\n/** Returns true if the preconditions is valid for the given document. */\nexport function preconditionIsValidForDocument(\n precondition: Precondition,\n document: MutableDocument\n): boolean {\n if (precondition.updateTime !== undefined) {\n return (\n document.isFoundDocument() &&\n document.version.isEqual(precondition.updateTime)\n );\n } else if (precondition.exists !== undefined) {\n return precondition.exists === document.isFoundDocument();\n } else {\n debugAssert(precondition.isNone, 'Precondition should be empty');\n return true;\n }\n}\n\n/**\n * A mutation describes a self-contained change to a document. Mutations can\n * create, replace, delete, and update subsets of documents.\n *\n * Mutations not only act on the value of the document but also its version.\n *\n * For local mutations (mutations that haven't been committed yet), we preserve\n * the existing version for Set and Patch mutations. For Delete mutations, we\n * reset the version to 0.\n *\n * Here's the expected transition table.\n *\n * MUTATION APPLIED TO RESULTS IN\n *\n * SetMutation Document(v3) Document(v3)\n * SetMutation NoDocument(v3) Document(v0)\n * SetMutation InvalidDocument(v0) Document(v0)\n * PatchMutation Document(v3) Document(v3)\n * PatchMutation NoDocument(v3) NoDocument(v3)\n * PatchMutation InvalidDocument(v0) UnknownDocument(v3)\n * DeleteMutation Document(v3) NoDocument(v0)\n * DeleteMutation NoDocument(v3) NoDocument(v0)\n * DeleteMutation InvalidDocument(v0) NoDocument(v0)\n *\n * For acknowledged mutations, we use the updateTime of the WriteResponse as\n * the resulting version for Set and Patch mutations. As deletes have no\n * explicit update time, we use the commitTime of the WriteResponse for\n * Delete mutations.\n *\n * If a mutation is acknowledged by the backend but fails the precondition check\n * locally, we transition to an `UnknownDocument` and rely on Watch to send us\n * the updated version.\n *\n * Field transforms are used only with Patch and Set Mutations. We use the\n * `updateTransforms` message to store transforms, rather than the `transforms`s\n * messages.\n *\n * ## Subclassing Notes\n *\n * Every type of mutation needs to implement its own applyToRemoteDocument() and\n * applyToLocalView() to implement the actual behavior of applying the mutation\n * to some source document (see `setMutationApplyToRemoteDocument()` for an\n * example).\n */\nexport abstract class Mutation {\n abstract readonly type: MutationType;\n abstract readonly key: DocumentKey;\n abstract readonly precondition: Precondition;\n abstract readonly fieldTransforms: FieldTransform[];\n /**\n * Returns a `FieldMask` representing the fields that will be changed by\n * applying this mutation. Returns `null` if the mutation will overwrite the\n * entire document.\n */\n abstract getFieldMask(): FieldMask | null;\n}\n\n/**\n * A utility method to calculate a `Mutation` representing the overlay from the\n * final state of the document, and a `FieldMask` representing the fields that\n * are mutated by the local mutations.\n */\nexport function calculateOverlayMutation(\n doc: MutableDocument,\n mask: FieldMask | null\n): Mutation | null {\n if (!doc.hasLocalMutations || (mask && mask!.fields.length === 0)) {\n return null;\n }\n\n // mask is null when sets or deletes are applied to the current document.\n if (mask === null) {\n if (doc.isNoDocument()) {\n return new DeleteMutation(doc.key, Precondition.none());\n } else {\n return new SetMutation(doc.key, doc.data, Precondition.none());\n }\n } else {\n const docValue = doc.data;\n const patchValue = ObjectValue.empty();\n let maskSet = new SortedSet(FieldPath.comparator);\n for (let path of mask.fields) {\n if (!maskSet.has(path)) {\n let value = docValue.field(path);\n // If we are deleting a nested field, we take the immediate parent as\n // the mask used to construct the resulting mutation.\n // Justification: Nested fields can create parent fields implicitly. If\n // only a leaf entry is deleted in later mutations, the parent field\n // should still remain, but we may have lost this information.\n // Consider mutation (foo.bar 1), then mutation (foo.bar delete()).\n // This leaves the final result (foo, {}). Despite the fact that `doc`\n // has the correct result, `foo` is not in `mask`, and the resulting\n // mutation would miss `foo`.\n if (value === null && path.length > 1) {\n path = path.popLast();\n value = docValue.field(path);\n }\n if (value === null) {\n patchValue.delete(path);\n } else {\n patchValue.set(path, value);\n }\n maskSet = maskSet.add(path);\n }\n }\n return new PatchMutation(\n doc.key,\n patchValue,\n new FieldMask(maskSet.toArray()),\n Precondition.none()\n );\n }\n}\n\n/**\n * Applies this mutation to the given document for the purposes of computing a\n * new remote document. If the input document doesn't match the expected state\n * (e.g. it is invalid or outdated), the document type may transition to\n * unknown.\n *\n * @param mutation - The mutation to apply.\n * @param document - The document to mutate. The input document can be an\n * invalid document if the client has no knowledge of the pre-mutation state\n * of the document.\n * @param mutationResult - The result of applying the mutation from the backend.\n */\nexport function mutationApplyToRemoteDocument(\n mutation: Mutation,\n document: MutableDocument,\n mutationResult: MutationResult\n): void {\n mutationVerifyKeyMatches(mutation, document);\n if (mutation instanceof SetMutation) {\n setMutationApplyToRemoteDocument(mutation, document, mutationResult);\n } else if (mutation instanceof PatchMutation) {\n patchMutationApplyToRemoteDocument(mutation, document, mutationResult);\n } else {\n debugAssert(\n mutation instanceof DeleteMutation,\n 'Unexpected mutation type: ' + mutation\n );\n deleteMutationApplyToRemoteDocument(mutation, document, mutationResult);\n }\n}\n\n/**\n * Applies this mutation to the given document for the purposes of computing\n * the new local view of a document. If the input document doesn't match the\n * expected state, the document is not modified.\n *\n * @param mutation - The mutation to apply.\n * @param document - The document to mutate. The input document can be an\n * invalid document if the client has no knowledge of the pre-mutation state\n * of the document.\n * @param previousMask - The fields that have been updated before applying this mutation.\n * @param localWriteTime - A timestamp indicating the local write time of the\n * batch this mutation is a part of.\n * @returns A `FieldMask` representing the fields that are changed by applying this mutation.\n */\nexport function mutationApplyToLocalView(\n mutation: Mutation,\n document: MutableDocument,\n previousMask: FieldMask | null,\n localWriteTime: Timestamp\n): FieldMask | null {\n mutationVerifyKeyMatches(mutation, document);\n\n if (mutation instanceof SetMutation) {\n return setMutationApplyToLocalView(\n mutation,\n document,\n previousMask,\n localWriteTime\n );\n } else if (mutation instanceof PatchMutation) {\n return patchMutationApplyToLocalView(\n mutation,\n document,\n previousMask,\n localWriteTime\n );\n } else {\n debugAssert(\n mutation instanceof DeleteMutation,\n 'Unexpected mutation type: ' + mutation\n );\n return deleteMutationApplyToLocalView(mutation, document, previousMask);\n }\n}\n\n/**\n * If this mutation is not idempotent, returns the base value to persist with\n * this mutation. If a base value is returned, the mutation is always applied\n * to this base value, even if document has already been updated.\n *\n * The base value is a sparse object that consists of only the document\n * fields for which this mutation contains a non-idempotent transformation\n * (e.g. a numeric increment). The provided value guarantees consistent\n * behavior for non-idempotent transforms and allow us to return the same\n * latency-compensated value even if the backend has already applied the\n * mutation. The base value is null for idempotent mutations, as they can be\n * re-played even if the backend has already applied them.\n *\n * @returns a base value to store along with the mutation, or null for\n * idempotent mutations.\n */\nexport function mutationExtractBaseValue(\n mutation: Mutation,\n document: Document\n): ObjectValue | null {\n let baseObject: ObjectValue | null = null;\n for (const fieldTransform of mutation.fieldTransforms) {\n const existingValue = document.data.field(fieldTransform.field);\n const coercedValue = computeTransformOperationBaseValue(\n fieldTransform.transform,\n existingValue || null\n );\n\n if (coercedValue != null) {\n if (baseObject === null) {\n baseObject = ObjectValue.empty();\n }\n baseObject.set(fieldTransform.field, coercedValue);\n }\n }\n return baseObject ? baseObject : null;\n}\n\nexport function mutationEquals(left: Mutation, right: Mutation): boolean {\n if (left.type !== right.type) {\n return false;\n }\n\n if (!left.key.isEqual(right.key)) {\n return false;\n }\n\n if (!left.precondition.isEqual(right.precondition)) {\n return false;\n }\n\n if (!fieldTransformsAreEqual(left.fieldTransforms, right.fieldTransforms)) {\n return false;\n }\n\n if (left.type === MutationType.Set) {\n return (left as SetMutation).value.isEqual((right as SetMutation).value);\n }\n\n if (left.type === MutationType.Patch) {\n return (\n (left as PatchMutation).data.isEqual((right as PatchMutation).data) &&\n (left as PatchMutation).fieldMask.isEqual(\n (right as PatchMutation).fieldMask\n )\n );\n }\n\n return true;\n}\n\nfunction mutationVerifyKeyMatches(\n mutation: Mutation,\n document: MutableDocument\n): void {\n debugAssert(\n document.key.isEqual(mutation.key),\n 'Can only apply a mutation to a document with the same key'\n );\n}\n\n/**\n * A mutation that creates or replaces the document at the given key with the\n * object value contents.\n */\nexport class SetMutation extends Mutation {\n constructor(\n readonly key: DocumentKey,\n readonly value: ObjectValue,\n readonly precondition: Precondition,\n readonly fieldTransforms: FieldTransform[] = []\n ) {\n super();\n }\n\n readonly type: MutationType = MutationType.Set;\n\n getFieldMask(): FieldMask | null {\n return null;\n }\n}\n\nfunction setMutationApplyToRemoteDocument(\n mutation: SetMutation,\n document: MutableDocument,\n mutationResult: MutationResult\n): void {\n // Unlike setMutationApplyToLocalView, if we're applying a mutation to a\n // remote document the server has accepted the mutation so the precondition\n // must have held.\n const newData = mutation.value.clone();\n const transformResults = serverTransformResults(\n mutation.fieldTransforms,\n document,\n mutationResult.transformResults\n );\n newData.setAll(transformResults);\n document\n .convertToFoundDocument(mutationResult.version, newData)\n .setHasCommittedMutations();\n}\n\nfunction setMutationApplyToLocalView(\n mutation: SetMutation,\n document: MutableDocument,\n previousMask: FieldMask | null,\n localWriteTime: Timestamp\n): FieldMask | null {\n if (!preconditionIsValidForDocument(mutation.precondition, document)) {\n // The mutation failed to apply (e.g. a document ID created with add()\n // caused a name collision).\n return previousMask;\n }\n\n const newData = mutation.value.clone();\n const transformResults = localTransformResults(\n mutation.fieldTransforms,\n localWriteTime,\n document\n );\n newData.setAll(transformResults);\n document\n .convertToFoundDocument(document.version, newData)\n .setHasLocalMutations();\n return null; // SetMutation overwrites all fields.\n}\n\n/**\n * A mutation that modifies fields of the document at the given key with the\n * given values. The values are applied through a field mask:\n *\n * * When a field is in both the mask and the values, the corresponding field\n * is updated.\n * * When a field is in neither the mask nor the values, the corresponding\n * field is unmodified.\n * * When a field is in the mask but not in the values, the corresponding field\n * is deleted.\n * * When a field is not in the mask but is in the values, the values map is\n * ignored.\n */\nexport class PatchMutation extends Mutation {\n constructor(\n readonly key: DocumentKey,\n readonly data: ObjectValue,\n readonly fieldMask: FieldMask,\n readonly precondition: Precondition,\n readonly fieldTransforms: FieldTransform[] = []\n ) {\n super();\n }\n\n readonly type: MutationType = MutationType.Patch;\n\n getFieldMask(): FieldMask | null {\n return this.fieldMask;\n }\n}\n\nfunction patchMutationApplyToRemoteDocument(\n mutation: PatchMutation,\n document: MutableDocument,\n mutationResult: MutationResult\n): void {\n if (!preconditionIsValidForDocument(mutation.precondition, document)) {\n // Since the mutation was not rejected, we know that the precondition\n // matched on the backend. We therefore must not have the expected version\n // of the document in our cache and convert to an UnknownDocument with a\n // known updateTime.\n document.convertToUnknownDocument(mutationResult.version);\n return;\n }\n\n const transformResults = serverTransformResults(\n mutation.fieldTransforms,\n document,\n mutationResult.transformResults\n );\n const newData = document.data;\n newData.setAll(getPatch(mutation));\n newData.setAll(transformResults);\n document\n .convertToFoundDocument(mutationResult.version, newData)\n .setHasCommittedMutations();\n}\n\nfunction patchMutationApplyToLocalView(\n mutation: PatchMutation,\n document: MutableDocument,\n previousMask: FieldMask | null,\n localWriteTime: Timestamp\n): FieldMask | null {\n if (!preconditionIsValidForDocument(mutation.precondition, document)) {\n return previousMask;\n }\n\n const transformResults = localTransformResults(\n mutation.fieldTransforms,\n localWriteTime,\n document\n );\n const newData = document.data;\n newData.setAll(getPatch(mutation));\n newData.setAll(transformResults);\n document\n .convertToFoundDocument(document.version, newData)\n .setHasLocalMutations();\n\n if (previousMask === null) {\n return null;\n }\n\n return previousMask\n .unionWith(mutation.fieldMask.fields)\n .unionWith(mutation.fieldTransforms.map(transform => transform.field));\n}\n\n/**\n * Returns a FieldPath/Value map with the content of the PatchMutation.\n */\nfunction getPatch(mutation: PatchMutation): Map {\n const result = new Map();\n mutation.fieldMask.fields.forEach(fieldPath => {\n if (!fieldPath.isEmpty()) {\n const newValue = mutation.data.field(fieldPath);\n result.set(fieldPath, newValue);\n }\n });\n return result;\n}\n\n/**\n * Creates a list of \"transform results\" (a transform result is a field value\n * representing the result of applying a transform) for use after a mutation\n * containing transforms has been acknowledged by the server.\n *\n * @param fieldTransforms - The field transforms to apply the result to.\n * @param mutableDocument - The current state of the document after applying all\n * previous mutations.\n * @param serverTransformResults - The transform results received by the server.\n * @returns The transform results list.\n */\nfunction serverTransformResults(\n fieldTransforms: FieldTransform[],\n mutableDocument: MutableDocument,\n serverTransformResults: Array\n): Map {\n const transformResults = new Map();\n hardAssert(\n fieldTransforms.length === serverTransformResults.length,\n 0x7f90,\n 'server transform result count should match field transform count',\n {\n serverTransformResultCount: serverTransformResults.length,\n fieldTransformCount: fieldTransforms.length\n }\n );\n\n for (let i = 0; i < serverTransformResults.length; i++) {\n const fieldTransform = fieldTransforms[i];\n const transform = fieldTransform.transform;\n const previousValue = mutableDocument.data.field(fieldTransform.field);\n transformResults.set(\n fieldTransform.field,\n applyTransformOperationToRemoteDocument(\n transform,\n previousValue,\n serverTransformResults[i]\n )\n );\n }\n return transformResults;\n}\n\n/**\n * Creates a list of \"transform results\" (a transform result is a field value\n * representing the result of applying a transform) for use when applying a\n * transform locally.\n *\n * @param fieldTransforms - The field transforms to apply the result to.\n * @param localWriteTime - The local time of the mutation (used to\n * generate ServerTimestampValues).\n * @param mutableDocument - The document to apply transforms on.\n * @returns The transform results list.\n */\nfunction localTransformResults(\n fieldTransforms: FieldTransform[],\n localWriteTime: Timestamp,\n mutableDocument: MutableDocument\n): Map {\n const transformResults = new Map();\n for (const fieldTransform of fieldTransforms) {\n const transform = fieldTransform.transform;\n\n const previousValue = mutableDocument.data.field(fieldTransform.field);\n transformResults.set(\n fieldTransform.field,\n applyTransformOperationToLocalView(\n transform,\n previousValue,\n localWriteTime\n )\n );\n }\n return transformResults;\n}\n\n/** A mutation that deletes the document at the given key. */\nexport class DeleteMutation extends Mutation {\n constructor(readonly key: DocumentKey, readonly precondition: Precondition) {\n super();\n }\n\n readonly type: MutationType = MutationType.Delete;\n readonly fieldTransforms: FieldTransform[] = [];\n\n getFieldMask(): FieldMask | null {\n return null;\n }\n}\n\nfunction deleteMutationApplyToRemoteDocument(\n mutation: DeleteMutation,\n document: MutableDocument,\n mutationResult: MutationResult\n): void {\n debugAssert(\n mutationResult.transformResults.length === 0,\n 'Transform results received by DeleteMutation.'\n );\n\n // Unlike applyToLocalView, if we're applying a mutation to a remote\n // document the server has accepted the mutation so the precondition must\n // have held.\n document\n .convertToNoDocument(mutationResult.version)\n .setHasCommittedMutations();\n}\n\nfunction deleteMutationApplyToLocalView(\n mutation: DeleteMutation,\n document: MutableDocument,\n previousMask: FieldMask | null\n): FieldMask | null {\n debugAssert(\n document.key.isEqual(mutation.key),\n 'Can only apply mutation to document with same key'\n );\n if (preconditionIsValidForDocument(mutation.precondition, document)) {\n document.convertToNoDocument(document.version).setHasLocalMutations();\n return null;\n }\n return previousMask;\n}\n\n/**\n * A mutation that verifies the existence of the document at the given key with\n * the provided precondition.\n *\n * The `verify` operation is only used in Transactions, and this class serves\n * primarily to facilitate serialization into protos.\n */\nexport class VerifyMutation extends Mutation {\n constructor(readonly key: DocumentKey, readonly precondition: Precondition) {\n super();\n }\n\n readonly type: MutationType = MutationType.Verify;\n readonly fieldTransforms: FieldTransform[] = [];\n\n getFieldMask(): FieldMask | null {\n return null;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Aggregate } from '../core/aggregate';\nimport { Bound } from '../core/bound';\nimport { DatabaseId } from '../core/database_info';\nimport {\n CompositeFilter,\n compositeFilterIsFlatConjunction,\n CompositeOperator,\n FieldFilter,\n Filter,\n Operator\n} from '../core/filter';\nimport { Direction, OrderBy } from '../core/order_by';\nimport {\n LimitType,\n newQuery,\n newQueryForPath,\n Query,\n queryToTarget\n} from '../core/query';\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { targetIsDocumentTarget, Target } from '../core/target';\nimport { TargetId } from '../core/types';\nimport { Timestamp } from '../lite-api/timestamp';\nimport { TargetData, TargetPurpose } from '../local/target_data';\nimport { MutableDocument } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { FieldMask } from '../model/field_mask';\nimport {\n DeleteMutation,\n FieldTransform,\n Mutation,\n MutationResult,\n PatchMutation,\n Precondition,\n SetMutation,\n VerifyMutation\n} from '../model/mutation';\nimport { normalizeTimestamp } from '../model/normalize';\nimport { ObjectValue } from '../model/object_value';\nimport { FieldPath, ResourcePath } from '../model/path';\nimport {\n ArrayRemoveTransformOperation,\n ArrayUnionTransformOperation,\n NumericIncrementTransformOperation,\n ServerTimestampTransform,\n TransformOperation\n} from '../model/transform_operation';\nimport { isNanValue, isNullValue } from '../model/values';\nimport {\n ApiClientObjectMap as ProtoApiClientObjectMap,\n BatchGetDocumentsResponse as ProtoBatchGetDocumentsResponse,\n CompositeFilterOp as ProtoCompositeFilterOp,\n Cursor as ProtoCursor,\n Document as ProtoDocument,\n DocumentMask as ProtoDocumentMask,\n DocumentsTarget as ProtoDocumentsTarget,\n FieldFilterOp as ProtoFieldFilterOp,\n FieldReference as ProtoFieldReference,\n FieldTransform as ProtoFieldTransform,\n Filter as ProtoFilter,\n ListenResponse as ProtoListenResponse,\n Order as ProtoOrder,\n OrderDirection as ProtoOrderDirection,\n Precondition as ProtoPrecondition,\n QueryTarget as ProtoQueryTarget,\n RunAggregationQueryRequest as ProtoRunAggregationQueryRequest,\n Aggregation as ProtoAggregation,\n Status as ProtoStatus,\n Target as ProtoTarget,\n TargetChangeTargetChangeType as ProtoTargetChangeTargetChangeType,\n Timestamp as ProtoTimestamp,\n Write as ProtoWrite,\n WriteResult as ProtoWriteResult\n} from '../protos/firestore_proto_api';\nimport { debugAssert, fail, hardAssert } from '../util/assert';\nimport { ByteString } from '../util/byte_string';\nimport { Code, FirestoreError } from '../util/error';\nimport { isNullOrUndefined } from '../util/types';\n\nimport { ExistenceFilter } from './existence_filter';\nimport { Serializer } from './number_serializer';\nimport { mapCodeFromRpcCode } from './rpc_error';\nimport {\n DocumentWatchChange,\n ExistenceFilterChange,\n WatchChange,\n WatchTargetChange,\n WatchTargetChangeState\n} from './watch_change';\n\nconst DIRECTIONS = (() => {\n const dirs: { [dir: string]: ProtoOrderDirection } = {};\n dirs[Direction.ASCENDING] = 'ASCENDING';\n dirs[Direction.DESCENDING] = 'DESCENDING';\n return dirs;\n})();\n\nconst OPERATORS = (() => {\n const ops: { [op: string]: ProtoFieldFilterOp } = {};\n ops[Operator.LESS_THAN] = 'LESS_THAN';\n ops[Operator.LESS_THAN_OR_EQUAL] = 'LESS_THAN_OR_EQUAL';\n ops[Operator.GREATER_THAN] = 'GREATER_THAN';\n ops[Operator.GREATER_THAN_OR_EQUAL] = 'GREATER_THAN_OR_EQUAL';\n ops[Operator.EQUAL] = 'EQUAL';\n ops[Operator.NOT_EQUAL] = 'NOT_EQUAL';\n ops[Operator.ARRAY_CONTAINS] = 'ARRAY_CONTAINS';\n ops[Operator.IN] = 'IN';\n ops[Operator.NOT_IN] = 'NOT_IN';\n ops[Operator.ARRAY_CONTAINS_ANY] = 'ARRAY_CONTAINS_ANY';\n return ops;\n})();\n\nconst COMPOSITE_OPERATORS = (() => {\n const ops: { [op: string]: ProtoCompositeFilterOp } = {};\n ops[CompositeOperator.AND] = 'AND';\n ops[CompositeOperator.OR] = 'OR';\n return ops;\n})();\n\nfunction assertPresent(value: unknown, description: string): asserts value {\n debugAssert(!isNullOrUndefined(value), description + ' is missing');\n}\n\n/**\n * This class generates JsonObject values for the Datastore API suitable for\n * sending to either GRPC stub methods or via the JSON/HTTP REST API.\n *\n * The serializer supports both Protobuf.js and Proto3 JSON formats. By\n * setting `useProto3Json` to true, the serializer will use the Proto3 JSON\n * format.\n *\n * For a description of the Proto3 JSON format check\n * https://developers.google.com/protocol-buffers/docs/proto3#json\n *\n * TODO(klimt): We can remove the databaseId argument if we keep the full\n * resource name in documents.\n */\nexport class JsonProtoSerializer implements Serializer {\n constructor(\n readonly databaseId: DatabaseId,\n readonly useProto3Json: boolean\n ) {}\n}\n\nfunction fromRpcStatus(status: ProtoStatus): FirestoreError {\n const code =\n status.code === undefined ? Code.UNKNOWN : mapCodeFromRpcCode(status.code);\n return new FirestoreError(code, status.message || '');\n}\n\n/**\n * Returns a value for a number (or null) that's appropriate to put into\n * a google.protobuf.Int32Value proto.\n * DO NOT USE THIS FOR ANYTHING ELSE.\n * This method cheats. It's typed as returning \"number\" because that's what\n * our generated proto interfaces say Int32Value must be. But GRPC actually\n * expects a { value: } struct.\n */\nfunction toInt32Proto(\n serializer: JsonProtoSerializer,\n val: number | null\n): number | { value: number } | null {\n if (serializer.useProto3Json || isNullOrUndefined(val)) {\n return val;\n } else {\n return { value: val };\n }\n}\n\n/**\n * Returns a number (or null) from a google.protobuf.Int32Value proto.\n */\nfunction fromInt32Proto(\n val: number | { value: number } | undefined\n): number | null {\n let result;\n if (typeof val === 'object') {\n result = val.value;\n } else {\n result = val;\n }\n return isNullOrUndefined(result) ? null : result;\n}\n\n/**\n * Returns a value for a Date that's appropriate to put into a proto.\n */\nexport function toTimestamp(\n serializer: JsonProtoSerializer,\n timestamp: Timestamp\n): ProtoTimestamp {\n if (serializer.useProto3Json) {\n // Serialize to ISO-8601 date format, but with full nano resolution.\n // Since JS Date has only millis, let's only use it for the seconds and\n // then manually add the fractions to the end.\n const jsDateStr = new Date(timestamp.seconds * 1000).toISOString();\n // Remove .xxx frac part and Z in the end.\n const strUntilSeconds = jsDateStr.replace(/\\.\\d*/, '').replace('Z', '');\n // Pad the fraction out to 9 digits (nanos).\n const nanoStr = ('000000000' + timestamp.nanoseconds).slice(-9);\n\n return `${strUntilSeconds}.${nanoStr}Z`;\n } else {\n return {\n seconds: '' + timestamp.seconds,\n nanos: timestamp.nanoseconds\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } as any;\n }\n}\n\n/**\n * Returns a Timestamp typed object given protobuf timestamp value.\n */\nexport function fromTimestamp(date: ProtoTimestamp): Timestamp {\n const timestamp = normalizeTimestamp(date);\n return new Timestamp(timestamp.seconds, timestamp.nanos);\n}\n\n/**\n * Returns a value for bytes that's appropriate to put in a proto.\n *\n * Visible for testing.\n */\nexport function toBytes(\n serializer: JsonProtoSerializer,\n bytes: ByteString\n): string | Uint8Array {\n if (serializer.useProto3Json) {\n return bytes.toBase64();\n } else {\n return bytes.toUint8Array();\n }\n}\n\n/**\n * Returns a ByteString based on the proto string value.\n */\nexport function fromBytes(\n serializer: JsonProtoSerializer,\n value: string | Uint8Array | undefined\n): ByteString {\n if (serializer.useProto3Json) {\n hardAssert(\n value === undefined || typeof value === 'string',\n 0xe30b,\n 'value must be undefined or a string when using proto3 Json'\n );\n return ByteString.fromBase64String(value ? value : '');\n } else {\n hardAssert(\n value === undefined ||\n // Check if the value is an instance of both Buffer and Uint8Array,\n // despite the fact that Buffer extends Uint8Array. In some\n // environments, such as jsdom, the prototype chain of Buffer\n // does not indicate that it extends Uint8Array.\n value instanceof Buffer ||\n value instanceof Uint8Array,\n 0x3f41,\n 'value must be undefined, Buffer, or Uint8Array'\n );\n return ByteString.fromUint8Array(value ? value : new Uint8Array());\n }\n}\n\nexport function toVersion(\n serializer: JsonProtoSerializer,\n version: SnapshotVersion\n): ProtoTimestamp {\n return toTimestamp(serializer, version.toTimestamp());\n}\n\nexport function fromVersion(version: ProtoTimestamp): SnapshotVersion {\n hardAssert(!!version, 0xc050, \"Trying to deserialize version that isn't set\");\n return SnapshotVersion.fromTimestamp(fromTimestamp(version));\n}\n\nexport function toResourceName(\n databaseId: DatabaseId,\n path: ResourcePath\n): string {\n return toResourcePath(databaseId, path).canonicalString();\n}\n\nexport function toResourcePath(\n databaseId: DatabaseId,\n path?: ResourcePath\n): ResourcePath {\n const resourcePath = fullyQualifiedPrefixPath(databaseId).child('documents');\n return path === undefined ? resourcePath : resourcePath.child(path);\n}\n\nfunction fromResourceName(name: string): ResourcePath {\n const resource = ResourcePath.fromString(name);\n hardAssert(\n isValidResourceName(resource),\n 0x27ce,\n 'Tried to deserialize invalid key',\n { key: resource.toString() }\n );\n return resource;\n}\n\nexport function toName(\n serializer: JsonProtoSerializer,\n key: DocumentKey\n): string {\n return toResourceName(serializer.databaseId, key.path);\n}\n\nexport function fromName(\n serializer: JsonProtoSerializer,\n name: string\n): DocumentKey {\n const resource = fromResourceName(name);\n\n if (resource.get(1) !== serializer.databaseId.projectId) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Tried to deserialize key from different project: ' +\n resource.get(1) +\n ' vs ' +\n serializer.databaseId.projectId\n );\n }\n\n if (resource.get(3) !== serializer.databaseId.database) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Tried to deserialize key from different database: ' +\n resource.get(3) +\n ' vs ' +\n serializer.databaseId.database\n );\n }\n return new DocumentKey(extractLocalPathFromResourceName(resource));\n}\n\nfunction toQueryPath(\n serializer: JsonProtoSerializer,\n path: ResourcePath\n): string {\n return toResourceName(serializer.databaseId, path);\n}\n\nfunction fromQueryPath(name: string): ResourcePath {\n const resourceName = fromResourceName(name);\n // In v1beta1 queries for collections at the root did not have a trailing\n // \"/documents\". In v1 all resource paths contain \"/documents\". Preserve the\n // ability to read the v1beta1 form for compatibility with queries persisted\n // in the local target cache.\n if (resourceName.length === 4) {\n return ResourcePath.emptyPath();\n }\n return extractLocalPathFromResourceName(resourceName);\n}\n\nexport function getEncodedDatabaseId(serializer: JsonProtoSerializer): string {\n const path = new ResourcePath([\n 'projects',\n serializer.databaseId.projectId,\n 'databases',\n serializer.databaseId.database\n ]);\n return path.canonicalString();\n}\n\nfunction fullyQualifiedPrefixPath(databaseId: DatabaseId): ResourcePath {\n return new ResourcePath([\n 'projects',\n databaseId.projectId,\n 'databases',\n databaseId.database\n ]);\n}\n\nfunction extractLocalPathFromResourceName(\n resourceName: ResourcePath\n): ResourcePath {\n hardAssert(\n resourceName.length > 4 && resourceName.get(4) === 'documents',\n 0x71a3,\n 'tried to deserialize invalid key',\n { key: resourceName.toString() }\n );\n return resourceName.popFirst(5);\n}\n\n/** Creates a Document proto from key and fields (but no create/update time) */\nexport function toMutationDocument(\n serializer: JsonProtoSerializer,\n key: DocumentKey,\n fields: ObjectValue\n): ProtoDocument {\n return {\n name: toName(serializer, key),\n fields: fields.value.mapValue.fields\n };\n}\n\nexport function toDocument(\n serializer: JsonProtoSerializer,\n document: MutableDocument\n): ProtoDocument {\n debugAssert(\n !document.hasLocalMutations,\n \"Can't serialize documents with mutations.\"\n );\n return {\n name: toName(serializer, document.key),\n fields: document.data.value.mapValue.fields,\n updateTime: toTimestamp(serializer, document.version.toTimestamp()),\n createTime: toTimestamp(serializer, document.createTime.toTimestamp())\n };\n}\n\nexport function fromDocument(\n serializer: JsonProtoSerializer,\n document: ProtoDocument,\n hasCommittedMutations?: boolean\n): MutableDocument {\n const key = fromName(serializer, document.name!);\n const version = fromVersion(document.updateTime!);\n // If we read a document from persistence that is missing createTime, it's due\n // to older SDK versions not storing this information. In such cases, we'll\n // set the createTime to zero. This can be removed in the long term.\n const createTime = document.createTime\n ? fromVersion(document.createTime)\n : SnapshotVersion.min();\n const data = new ObjectValue({ mapValue: { fields: document.fields } });\n const result = MutableDocument.newFoundDocument(\n key,\n version,\n createTime,\n data\n );\n if (hasCommittedMutations) {\n result.setHasCommittedMutations();\n }\n return hasCommittedMutations ? result.setHasCommittedMutations() : result;\n}\n\nfunction fromFound(\n serializer: JsonProtoSerializer,\n doc: ProtoBatchGetDocumentsResponse\n): MutableDocument {\n hardAssert(\n !!doc.found,\n 0xaa33,\n 'Tried to deserialize a found document from a missing document.'\n );\n assertPresent(doc.found.name, 'doc.found.name');\n assertPresent(doc.found.updateTime, 'doc.found.updateTime');\n const key = fromName(serializer, doc.found.name);\n const version = fromVersion(doc.found.updateTime);\n const createTime = doc.found.createTime\n ? fromVersion(doc.found.createTime)\n : SnapshotVersion.min();\n const data = new ObjectValue({ mapValue: { fields: doc.found.fields } });\n return MutableDocument.newFoundDocument(key, version, createTime, data);\n}\n\nfunction fromMissing(\n serializer: JsonProtoSerializer,\n result: ProtoBatchGetDocumentsResponse\n): MutableDocument {\n hardAssert(\n !!result.missing,\n 0x0f36,\n 'Tried to deserialize a missing document from a found document.'\n );\n hardAssert(\n !!result.readTime,\n 0x5995,\n 'Tried to deserialize a missing document without a read time.'\n );\n const key = fromName(serializer, result.missing);\n const version = fromVersion(result.readTime);\n return MutableDocument.newNoDocument(key, version);\n}\n\nexport function fromBatchGetDocumentsResponse(\n serializer: JsonProtoSerializer,\n result: ProtoBatchGetDocumentsResponse\n): MutableDocument {\n if ('found' in result) {\n return fromFound(serializer, result);\n } else if ('missing' in result) {\n return fromMissing(serializer, result);\n }\n return fail(0x1c42, 'invalid batch get response', { result });\n}\n\nexport function fromWatchChange(\n serializer: JsonProtoSerializer,\n change: ProtoListenResponse\n): WatchChange {\n let watchChange: WatchChange;\n if ('targetChange' in change) {\n assertPresent(change.targetChange, 'targetChange');\n // proto3 default value is unset in JSON (undefined), so use 'NO_CHANGE'\n // if unset\n const state = fromWatchTargetChangeState(\n change.targetChange.targetChangeType || 'NO_CHANGE'\n );\n const targetIds: TargetId[] = change.targetChange.targetIds || [];\n\n const resumeToken = fromBytes(serializer, change.targetChange.resumeToken);\n const causeProto = change.targetChange!.cause;\n const cause = causeProto && fromRpcStatus(causeProto);\n watchChange = new WatchTargetChange(\n state,\n targetIds,\n resumeToken,\n cause || null\n );\n } else if ('documentChange' in change) {\n assertPresent(change.documentChange, 'documentChange');\n const entityChange = change.documentChange;\n assertPresent(entityChange.document, 'documentChange.name');\n assertPresent(entityChange.document.name, 'documentChange.document.name');\n assertPresent(\n entityChange.document.updateTime,\n 'documentChange.document.updateTime'\n );\n const key = fromName(serializer, entityChange.document.name);\n const version = fromVersion(entityChange.document.updateTime);\n const createTime = entityChange.document.createTime\n ? fromVersion(entityChange.document.createTime)\n : SnapshotVersion.min();\n const data = new ObjectValue({\n mapValue: { fields: entityChange.document.fields }\n });\n const doc = MutableDocument.newFoundDocument(\n key,\n version,\n createTime,\n data\n );\n const updatedTargetIds = entityChange.targetIds || [];\n const removedTargetIds = entityChange.removedTargetIds || [];\n watchChange = new DocumentWatchChange(\n updatedTargetIds,\n removedTargetIds,\n doc.key,\n doc\n );\n } else if ('documentDelete' in change) {\n assertPresent(change.documentDelete, 'documentDelete');\n const docDelete = change.documentDelete;\n assertPresent(docDelete.document, 'documentDelete.document');\n const key = fromName(serializer, docDelete.document);\n const version = docDelete.readTime\n ? fromVersion(docDelete.readTime)\n : SnapshotVersion.min();\n const doc = MutableDocument.newNoDocument(key, version);\n const removedTargetIds = docDelete.removedTargetIds || [];\n watchChange = new DocumentWatchChange([], removedTargetIds, doc.key, doc);\n } else if ('documentRemove' in change) {\n assertPresent(change.documentRemove, 'documentRemove');\n const docRemove = change.documentRemove;\n assertPresent(docRemove.document, 'documentRemove');\n const key = fromName(serializer, docRemove.document);\n const removedTargetIds = docRemove.removedTargetIds || [];\n watchChange = new DocumentWatchChange([], removedTargetIds, key, null);\n } else if ('filter' in change) {\n // TODO(dimond): implement existence filter parsing with strategy.\n assertPresent(change.filter, 'filter');\n const filter = change.filter;\n assertPresent(filter.targetId, 'filter.targetId');\n const { count = 0, unchangedNames } = filter;\n const existenceFilter = new ExistenceFilter(count, unchangedNames);\n const targetId = filter.targetId;\n watchChange = new ExistenceFilterChange(targetId, existenceFilter);\n } else {\n return fail(0x2d51, 'Unknown change type', { change });\n }\n return watchChange;\n}\n\nfunction fromWatchTargetChangeState(\n state: ProtoTargetChangeTargetChangeType\n): WatchTargetChangeState {\n if (state === 'NO_CHANGE') {\n return WatchTargetChangeState.NoChange;\n } else if (state === 'ADD') {\n return WatchTargetChangeState.Added;\n } else if (state === 'REMOVE') {\n return WatchTargetChangeState.Removed;\n } else if (state === 'CURRENT') {\n return WatchTargetChangeState.Current;\n } else if (state === 'RESET') {\n return WatchTargetChangeState.Reset;\n } else {\n return fail(0x9991, 'Got unexpected TargetChange.state', { state });\n }\n}\n\nexport function versionFromListenResponse(\n change: ProtoListenResponse\n): SnapshotVersion {\n // We have only reached a consistent snapshot for the entire stream if there\n // is a read_time set and it applies to all targets (i.e. the list of\n // targets is empty). The backend is guaranteed to send such responses.\n if (!('targetChange' in change)) {\n return SnapshotVersion.min();\n }\n const targetChange = change.targetChange!;\n if (targetChange.targetIds && targetChange.targetIds.length) {\n return SnapshotVersion.min();\n }\n if (!targetChange.readTime) {\n return SnapshotVersion.min();\n }\n return fromVersion(targetChange.readTime);\n}\n\nexport function toMutation(\n serializer: JsonProtoSerializer,\n mutation: Mutation\n): ProtoWrite {\n let result: ProtoWrite;\n if (mutation instanceof SetMutation) {\n result = {\n update: toMutationDocument(serializer, mutation.key, mutation.value)\n };\n } else if (mutation instanceof DeleteMutation) {\n result = { delete: toName(serializer, mutation.key) };\n } else if (mutation instanceof PatchMutation) {\n result = {\n update: toMutationDocument(serializer, mutation.key, mutation.data),\n updateMask: toDocumentMask(mutation.fieldMask)\n };\n } else if (mutation instanceof VerifyMutation) {\n result = {\n verify: toName(serializer, mutation.key)\n };\n } else {\n return fail(0x40d7, 'Unknown mutation type', {\n mutationType: mutation.type\n });\n }\n\n if (mutation.fieldTransforms.length > 0) {\n result.updateTransforms = mutation.fieldTransforms.map(transform =>\n toFieldTransform(serializer, transform)\n );\n }\n\n if (!mutation.precondition.isNone) {\n result.currentDocument = toPrecondition(serializer, mutation.precondition);\n }\n\n return result;\n}\n\nexport function fromMutation(\n serializer: JsonProtoSerializer,\n proto: ProtoWrite\n): Mutation {\n const precondition = proto.currentDocument\n ? fromPrecondition(proto.currentDocument)\n : Precondition.none();\n\n const fieldTransforms = proto.updateTransforms\n ? proto.updateTransforms.map(transform =>\n fromFieldTransform(serializer, transform)\n )\n : [];\n\n if (proto.update) {\n assertPresent(proto.update.name, 'name');\n const key = fromName(serializer, proto.update.name);\n const value = new ObjectValue({\n mapValue: { fields: proto.update.fields }\n });\n\n if (proto.updateMask) {\n const fieldMask = fromDocumentMask(proto.updateMask);\n return new PatchMutation(\n key,\n value,\n fieldMask,\n precondition,\n fieldTransforms\n );\n } else {\n return new SetMutation(key, value, precondition, fieldTransforms);\n }\n } else if (proto.delete) {\n const key = fromName(serializer, proto.delete);\n return new DeleteMutation(key, precondition);\n } else if (proto.verify) {\n const key = fromName(serializer, proto.verify);\n return new VerifyMutation(key, precondition);\n } else {\n return fail(0x05b7, 'unknown mutation proto', { proto });\n }\n}\n\nfunction toPrecondition(\n serializer: JsonProtoSerializer,\n precondition: Precondition\n): ProtoPrecondition {\n debugAssert(!precondition.isNone, \"Can't serialize an empty precondition\");\n if (precondition.updateTime !== undefined) {\n return {\n updateTime: toVersion(serializer, precondition.updateTime)\n };\n } else if (precondition.exists !== undefined) {\n return { exists: precondition.exists };\n } else {\n return fail(0x6b69, 'Unknown precondition');\n }\n}\n\nfunction fromPrecondition(precondition: ProtoPrecondition): Precondition {\n if (precondition.updateTime !== undefined) {\n return Precondition.updateTime(fromVersion(precondition.updateTime));\n } else if (precondition.exists !== undefined) {\n return Precondition.exists(precondition.exists);\n } else {\n return Precondition.none();\n }\n}\n\nfunction fromWriteResult(\n proto: ProtoWriteResult,\n commitTime: ProtoTimestamp\n): MutationResult {\n // NOTE: Deletes don't have an updateTime.\n let version = proto.updateTime\n ? fromVersion(proto.updateTime)\n : fromVersion(commitTime);\n\n if (version.isEqual(SnapshotVersion.min())) {\n // The Firestore Emulator currently returns an update time of 0 for\n // deletes of non-existing documents (rather than null). This breaks the\n // test \"get deleted doc while offline with source=cache\" as NoDocuments\n // with version 0 are filtered by IndexedDb's RemoteDocumentCache.\n // TODO(#2149): Remove this when Emulator is fixed\n version = fromVersion(commitTime);\n }\n\n return new MutationResult(version, proto.transformResults || []);\n}\n\nexport function fromWriteResults(\n protos: ProtoWriteResult[] | undefined,\n commitTime?: ProtoTimestamp\n): MutationResult[] {\n if (protos && protos.length > 0) {\n hardAssert(\n commitTime !== undefined,\n 0x3811,\n 'Received a write result without a commit time'\n );\n return protos.map(proto => fromWriteResult(proto, commitTime));\n } else {\n return [];\n }\n}\n\nfunction toFieldTransform(\n serializer: JsonProtoSerializer,\n fieldTransform: FieldTransform\n): ProtoFieldTransform {\n const transform = fieldTransform.transform;\n if (transform instanceof ServerTimestampTransform) {\n return {\n fieldPath: fieldTransform.field.canonicalString(),\n setToServerValue: 'REQUEST_TIME'\n };\n } else if (transform instanceof ArrayUnionTransformOperation) {\n return {\n fieldPath: fieldTransform.field.canonicalString(),\n appendMissingElements: {\n values: transform.elements\n }\n };\n } else if (transform instanceof ArrayRemoveTransformOperation) {\n return {\n fieldPath: fieldTransform.field.canonicalString(),\n removeAllFromArray: {\n values: transform.elements\n }\n };\n } else if (transform instanceof NumericIncrementTransformOperation) {\n return {\n fieldPath: fieldTransform.field.canonicalString(),\n increment: transform.operand\n };\n } else {\n throw fail(0x51c2, 'Unknown transform', {\n transform: fieldTransform.transform\n });\n }\n}\n\nfunction fromFieldTransform(\n serializer: JsonProtoSerializer,\n proto: ProtoFieldTransform\n): FieldTransform {\n let transform: TransformOperation | null = null;\n if ('setToServerValue' in proto) {\n hardAssert(\n proto.setToServerValue === 'REQUEST_TIME',\n 0x40f6,\n 'Unknown server value transform proto',\n { proto }\n );\n transform = new ServerTimestampTransform();\n } else if ('appendMissingElements' in proto) {\n const values = proto.appendMissingElements!.values || [];\n transform = new ArrayUnionTransformOperation(values);\n } else if ('removeAllFromArray' in proto) {\n const values = proto.removeAllFromArray!.values || [];\n transform = new ArrayRemoveTransformOperation(values);\n } else if ('increment' in proto) {\n transform = new NumericIncrementTransformOperation(\n serializer,\n proto.increment!\n );\n } else {\n fail(0x40c8, 'Unknown transform proto', { proto });\n }\n const fieldPath = FieldPath.fromServerFormat(proto.fieldPath!);\n return new FieldTransform(fieldPath, transform!);\n}\n\nexport function toDocumentsTarget(\n serializer: JsonProtoSerializer,\n target: Target\n): ProtoDocumentsTarget {\n return { documents: [toQueryPath(serializer, target.path)] };\n}\n\nexport function fromDocumentsTarget(\n documentsTarget: ProtoDocumentsTarget\n): Target {\n const count = documentsTarget.documents!.length;\n hardAssert(\n count === 1,\n 0x07ae,\n 'DocumentsTarget contained other than 1 document',\n {\n count\n }\n );\n const name = documentsTarget.documents![0];\n return queryToTarget(newQueryForPath(fromQueryPath(name)));\n}\n\nexport function toQueryTarget(\n serializer: JsonProtoSerializer,\n target: Target\n): { queryTarget: ProtoQueryTarget; parent: ResourcePath } {\n // Dissect the path into parent, collectionId, and optional key filter.\n const queryTarget: ProtoQueryTarget = { structuredQuery: {} };\n const path = target.path;\n let parent: ResourcePath;\n if (target.collectionGroup !== null) {\n debugAssert(\n path.length % 2 === 0,\n 'Collection Group queries should be within a document path or root.'\n );\n parent = path;\n queryTarget.structuredQuery!.from = [\n {\n collectionId: target.collectionGroup,\n allDescendants: true\n }\n ];\n } else {\n debugAssert(\n path.length % 2 !== 0,\n 'Document queries with filters are not supported.'\n );\n parent = path.popLast();\n queryTarget.structuredQuery!.from = [{ collectionId: path.lastSegment() }];\n }\n queryTarget.parent = toQueryPath(serializer, parent);\n\n const where = toFilters(target.filters);\n if (where) {\n queryTarget.structuredQuery!.where = where;\n }\n\n const orderBy = toOrder(target.orderBy);\n if (orderBy) {\n queryTarget.structuredQuery!.orderBy = orderBy;\n }\n\n const limit = toInt32Proto(serializer, target.limit);\n if (limit !== null) {\n queryTarget.structuredQuery!.limit = limit;\n }\n\n if (target.startAt) {\n queryTarget.structuredQuery!.startAt = toStartAtCursor(target.startAt);\n }\n if (target.endAt) {\n queryTarget.structuredQuery!.endAt = toEndAtCursor(target.endAt);\n }\n\n return { queryTarget, parent };\n}\n\nexport function toRunAggregationQueryRequest(\n serializer: JsonProtoSerializer,\n target: Target,\n aggregates: Aggregate[],\n skipAliasing?: boolean\n): {\n request: ProtoRunAggregationQueryRequest;\n aliasMap: Record;\n parent: ResourcePath;\n} {\n const { queryTarget, parent } = toQueryTarget(serializer, target);\n const aliasMap: Record = {};\n\n const aggregations: ProtoAggregation[] = [];\n let aggregationNum = 0;\n\n aggregates.forEach(aggregate => {\n // Map all client-side aliases to a unique short-form\n // alias. This avoids issues with client-side aliases that\n // exceed the 1500-byte string size limit.\n const serverAlias = skipAliasing\n ? aggregate.alias\n : `aggregate_${aggregationNum++}`;\n aliasMap[serverAlias] = aggregate.alias;\n\n if (aggregate.aggregateType === 'count') {\n aggregations.push({\n alias: serverAlias,\n count: {}\n });\n } else if (aggregate.aggregateType === 'avg') {\n aggregations.push({\n alias: serverAlias,\n avg: {\n field: toFieldPathReference(aggregate.fieldPath!)\n }\n });\n } else if (aggregate.aggregateType === 'sum') {\n aggregations.push({\n alias: serverAlias,\n sum: {\n field: toFieldPathReference(aggregate.fieldPath!)\n }\n });\n }\n });\n\n return {\n request: {\n structuredAggregationQuery: {\n aggregations,\n structuredQuery: queryTarget.structuredQuery\n },\n parent: queryTarget.parent\n },\n aliasMap,\n parent\n };\n}\n\nexport function convertQueryTargetToQuery(target: ProtoQueryTarget): Query {\n let path = fromQueryPath(target.parent!);\n\n const query = target.structuredQuery!;\n const fromCount = query.from ? query.from.length : 0;\n let collectionGroup: string | null = null;\n if (fromCount > 0) {\n hardAssert(\n fromCount === 1,\n 0xfe26,\n 'StructuredQuery.from with more than one collection is not supported.'\n );\n const from = query.from![0];\n if (from.allDescendants) {\n collectionGroup = from.collectionId!;\n } else {\n path = path.child(from.collectionId!);\n }\n }\n\n let filterBy: Filter[] = [];\n if (query.where) {\n filterBy = fromFilters(query.where);\n }\n\n let orderBy: OrderBy[] = [];\n if (query.orderBy) {\n orderBy = fromOrder(query.orderBy);\n }\n\n let limit: number | null = null;\n if (query.limit) {\n limit = fromInt32Proto(query.limit);\n }\n\n let startAt: Bound | null = null;\n if (query.startAt) {\n startAt = fromStartAtCursor(query.startAt);\n }\n\n let endAt: Bound | null = null;\n if (query.endAt) {\n endAt = fromEndAtCursor(query.endAt);\n }\n\n return newQuery(\n path,\n collectionGroup,\n orderBy,\n filterBy,\n limit,\n LimitType.First,\n startAt,\n endAt\n );\n}\n\nexport function fromQueryTarget(target: ProtoQueryTarget): Target {\n return queryToTarget(convertQueryTargetToQuery(target));\n}\n\nexport function toListenRequestLabels(\n serializer: JsonProtoSerializer,\n targetData: TargetData\n): ProtoApiClientObjectMap | null {\n const value = toLabel(targetData.purpose);\n if (value == null) {\n return null;\n } else {\n return {\n 'goog-listen-tags': value\n };\n }\n}\n\nexport function toLabel(purpose: TargetPurpose): string | null {\n switch (purpose) {\n case TargetPurpose.Listen:\n return null;\n case TargetPurpose.ExistenceFilterMismatch:\n return 'existence-filter-mismatch';\n case TargetPurpose.ExistenceFilterMismatchBloom:\n return 'existence-filter-mismatch-bloom';\n case TargetPurpose.LimboResolution:\n return 'limbo-document';\n default:\n return fail(0x713b, 'Unrecognized query purpose', { purpose });\n }\n}\n\nexport function toTarget(\n serializer: JsonProtoSerializer,\n targetData: TargetData\n): ProtoTarget {\n let result: ProtoTarget;\n const target = targetData.target;\n\n if (targetIsDocumentTarget(target)) {\n result = { documents: toDocumentsTarget(serializer, target) };\n } else {\n result = { query: toQueryTarget(serializer, target).queryTarget };\n }\n\n result.targetId = targetData.targetId;\n\n if (targetData.resumeToken.approximateByteSize() > 0) {\n result.resumeToken = toBytes(serializer, targetData.resumeToken);\n const expectedCount = toInt32Proto(serializer, targetData.expectedCount);\n if (expectedCount !== null) {\n result.expectedCount = expectedCount;\n }\n } else if (targetData.snapshotVersion.compareTo(SnapshotVersion.min()) > 0) {\n // TODO(wuandy): Consider removing above check because it is most likely true.\n // Right now, many tests depend on this behaviour though (leaving min() out\n // of serialization).\n result.readTime = toTimestamp(\n serializer,\n targetData.snapshotVersion.toTimestamp()\n );\n const expectedCount = toInt32Proto(serializer, targetData.expectedCount);\n if (expectedCount !== null) {\n result.expectedCount = expectedCount;\n }\n }\n\n return result;\n}\n\nfunction toFilters(filters: Filter[]): ProtoFilter | undefined {\n if (filters.length === 0) {\n return;\n }\n\n return toFilter(CompositeFilter.create(filters, CompositeOperator.AND));\n}\n\nfunction fromFilters(filter: ProtoFilter): Filter[] {\n const result = fromFilter(filter);\n\n if (\n result instanceof CompositeFilter &&\n compositeFilterIsFlatConjunction(result)\n ) {\n return result.getFilters();\n }\n\n return [result];\n}\n\nfunction fromFilter(filter: ProtoFilter): Filter {\n if (filter.unaryFilter !== undefined) {\n return fromUnaryFilter(filter);\n } else if (filter.fieldFilter !== undefined) {\n return fromFieldFilter(filter);\n } else if (filter.compositeFilter !== undefined) {\n return fromCompositeFilter(filter);\n } else {\n return fail(0x7591, 'Unknown filter', { filter });\n }\n}\n\nfunction toOrder(orderBys: OrderBy[]): ProtoOrder[] | undefined {\n if (orderBys.length === 0) {\n return;\n }\n return orderBys.map(order => toPropertyOrder(order));\n}\n\nfunction fromOrder(orderBys: ProtoOrder[]): OrderBy[] {\n return orderBys.map(order => fromPropertyOrder(order));\n}\n\nfunction toStartAtCursor(cursor: Bound): ProtoCursor {\n return {\n before: cursor.inclusive,\n values: cursor.position\n };\n}\n\nfunction toEndAtCursor(cursor: Bound): ProtoCursor {\n return {\n before: !cursor.inclusive,\n values: cursor.position\n };\n}\n\nfunction fromStartAtCursor(cursor: ProtoCursor): Bound {\n const inclusive = !!cursor.before;\n const position = cursor.values || [];\n return new Bound(position, inclusive);\n}\n\nfunction fromEndAtCursor(cursor: ProtoCursor): Bound {\n const inclusive = !cursor.before;\n const position = cursor.values || [];\n return new Bound(position, inclusive);\n}\n\n// visible for testing\nexport function toDirection(dir: Direction): ProtoOrderDirection {\n return DIRECTIONS[dir];\n}\n\n// visible for testing\nexport function fromDirection(\n dir: ProtoOrderDirection | undefined\n): Direction | undefined {\n switch (dir) {\n case 'ASCENDING':\n return Direction.ASCENDING;\n case 'DESCENDING':\n return Direction.DESCENDING;\n default:\n return undefined;\n }\n}\n\n// visible for testing\nexport function toOperatorName(op: Operator): ProtoFieldFilterOp {\n return OPERATORS[op];\n}\n\nexport function toCompositeOperatorName(\n op: CompositeOperator\n): ProtoCompositeFilterOp {\n return COMPOSITE_OPERATORS[op];\n}\n\nexport function fromOperatorName(op: ProtoFieldFilterOp): Operator {\n switch (op) {\n case 'EQUAL':\n return Operator.EQUAL;\n case 'NOT_EQUAL':\n return Operator.NOT_EQUAL;\n case 'GREATER_THAN':\n return Operator.GREATER_THAN;\n case 'GREATER_THAN_OR_EQUAL':\n return Operator.GREATER_THAN_OR_EQUAL;\n case 'LESS_THAN':\n return Operator.LESS_THAN;\n case 'LESS_THAN_OR_EQUAL':\n return Operator.LESS_THAN_OR_EQUAL;\n case 'ARRAY_CONTAINS':\n return Operator.ARRAY_CONTAINS;\n case 'IN':\n return Operator.IN;\n case 'NOT_IN':\n return Operator.NOT_IN;\n case 'ARRAY_CONTAINS_ANY':\n return Operator.ARRAY_CONTAINS_ANY;\n case 'OPERATOR_UNSPECIFIED':\n return fail(0xe2fe, 'Unspecified operator');\n default:\n return fail(0xc54a, 'Unknown operator');\n }\n}\n\nexport function fromCompositeOperatorName(\n op: ProtoCompositeFilterOp\n): CompositeOperator {\n switch (op) {\n case 'AND':\n return CompositeOperator.AND;\n case 'OR':\n return CompositeOperator.OR;\n default:\n return fail(0x0402, 'Unknown operator');\n }\n}\n\nexport function toFieldPathReference(path: FieldPath): ProtoFieldReference {\n return { fieldPath: path.canonicalString() };\n}\n\nexport function fromFieldPathReference(\n fieldReference: ProtoFieldReference\n): FieldPath {\n return FieldPath.fromServerFormat(fieldReference.fieldPath!);\n}\n\n// visible for testing\nexport function toPropertyOrder(orderBy: OrderBy): ProtoOrder {\n return {\n field: toFieldPathReference(orderBy.field),\n direction: toDirection(orderBy.dir)\n };\n}\n\nexport function fromPropertyOrder(orderBy: ProtoOrder): OrderBy {\n return new OrderBy(\n fromFieldPathReference(orderBy.field!),\n fromDirection(orderBy.direction)\n );\n}\n\n// visible for testing\nexport function toFilter(filter: Filter): ProtoFilter {\n if (filter instanceof FieldFilter) {\n return toUnaryOrFieldFilter(filter);\n } else if (filter instanceof CompositeFilter) {\n return toCompositeFilter(filter);\n } else {\n return fail(0xd65d, 'Unrecognized filter type', { filter });\n }\n}\n\nexport function toCompositeFilter(filter: CompositeFilter): ProtoFilter {\n const protos = filter.getFilters().map(filter => toFilter(filter));\n\n if (protos.length === 1) {\n return protos[0];\n }\n\n return {\n compositeFilter: {\n op: toCompositeOperatorName(filter.op),\n filters: protos\n }\n };\n}\n\nexport function toUnaryOrFieldFilter(filter: FieldFilter): ProtoFilter {\n if (filter.op === Operator.EQUAL) {\n if (isNanValue(filter.value)) {\n return {\n unaryFilter: {\n field: toFieldPathReference(filter.field),\n op: 'IS_NAN'\n }\n };\n } else if (isNullValue(filter.value)) {\n return {\n unaryFilter: {\n field: toFieldPathReference(filter.field),\n op: 'IS_NULL'\n }\n };\n }\n } else if (filter.op === Operator.NOT_EQUAL) {\n if (isNanValue(filter.value)) {\n return {\n unaryFilter: {\n field: toFieldPathReference(filter.field),\n op: 'IS_NOT_NAN'\n }\n };\n } else if (isNullValue(filter.value)) {\n return {\n unaryFilter: {\n field: toFieldPathReference(filter.field),\n op: 'IS_NOT_NULL'\n }\n };\n }\n }\n return {\n fieldFilter: {\n field: toFieldPathReference(filter.field),\n op: toOperatorName(filter.op),\n value: filter.value\n }\n };\n}\n\nexport function fromUnaryFilter(filter: ProtoFilter): Filter {\n switch (filter.unaryFilter!.op!) {\n case 'IS_NAN':\n const nanField = fromFieldPathReference(filter.unaryFilter!.field!);\n return FieldFilter.create(nanField, Operator.EQUAL, {\n doubleValue: NaN\n });\n case 'IS_NULL':\n const nullField = fromFieldPathReference(filter.unaryFilter!.field!);\n return FieldFilter.create(nullField, Operator.EQUAL, {\n nullValue: 'NULL_VALUE'\n });\n case 'IS_NOT_NAN':\n const notNanField = fromFieldPathReference(filter.unaryFilter!.field!);\n return FieldFilter.create(notNanField, Operator.NOT_EQUAL, {\n doubleValue: NaN\n });\n case 'IS_NOT_NULL':\n const notNullField = fromFieldPathReference(filter.unaryFilter!.field!);\n return FieldFilter.create(notNullField, Operator.NOT_EQUAL, {\n nullValue: 'NULL_VALUE'\n });\n case 'OPERATOR_UNSPECIFIED':\n return fail(0xef81, 'Unspecified filter');\n default:\n return fail(0xed36, 'Unknown filter');\n }\n}\n\nexport function fromFieldFilter(filter: ProtoFilter): FieldFilter {\n return FieldFilter.create(\n fromFieldPathReference(filter.fieldFilter!.field!),\n fromOperatorName(filter.fieldFilter!.op!),\n filter.fieldFilter!.value!\n );\n}\n\nexport function fromCompositeFilter(filter: ProtoFilter): CompositeFilter {\n return CompositeFilter.create(\n filter.compositeFilter!.filters!.map(filter => fromFilter(filter)),\n fromCompositeOperatorName(filter.compositeFilter!.op!)\n );\n}\n\nexport function toDocumentMask(fieldMask: FieldMask): ProtoDocumentMask {\n const canonicalFields: string[] = [];\n fieldMask.fields.forEach(field =>\n canonicalFields.push(field.canonicalString())\n );\n return {\n fieldPaths: canonicalFields\n };\n}\n\nexport function fromDocumentMask(proto: ProtoDocumentMask): FieldMask {\n const paths = proto.fieldPaths || [];\n return new FieldMask(paths.map(path => FieldPath.fromServerFormat(path)));\n}\n\nexport function isValidResourceName(path: ResourcePath): boolean {\n // Resource names have at least 4 components (project ID, database ID)\n return (\n path.length >= 4 &&\n path.get(0) === 'projects' &&\n path.get(2) === 'databases'\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** Return the Platform-specific serializer monitor. */\nimport { DatabaseId } from '../../core/database_info';\nimport { JsonProtoSerializer } from '../../remote/serializer';\n\nexport function newSerializer(databaseId: DatabaseId): JsonProtoSerializer {\n return new JsonProtoSerializer(databaseId, /* useProto3Json= */ true);\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { AsyncQueue, DelayedOperation, TimerId } from '../util/async_queue';\nimport { logDebug } from '../util/log';\n\nconst LOG_TAG = 'ExponentialBackoff';\n\n/**\n * Initial backoff time in milliseconds after an error.\n * Set to 1s according to https://cloud.google.com/apis/design/errors.\n */\nconst DEFAULT_BACKOFF_INITIAL_DELAY_MS = 1000;\n\nconst DEFAULT_BACKOFF_FACTOR = 1.5;\n\n/** Maximum backoff time in milliseconds */\nconst DEFAULT_BACKOFF_MAX_DELAY_MS = 60 * 1000;\n\n/**\n * A helper for running delayed tasks following an exponential backoff curve\n * between attempts.\n *\n * Each delay is made up of a \"base\" delay which follows the exponential\n * backoff curve, and a +/- 50% \"jitter\" that is calculated and added to the\n * base delay. This prevents clients from accidentally synchronizing their\n * delays causing spikes of load to the backend.\n */\nexport class ExponentialBackoff {\n private currentBaseMs: number = 0;\n private timerPromise: DelayedOperation | null = null;\n /** The last backoff attempt, as epoch milliseconds. */\n private lastAttemptTime = Date.now();\n\n constructor(\n /**\n * The AsyncQueue to run backoff operations on.\n */\n private readonly queue: AsyncQueue,\n /**\n * The ID to use when scheduling backoff operations on the AsyncQueue.\n */\n private readonly timerId: TimerId,\n /**\n * The initial delay (used as the base delay on the first retry attempt).\n * Note that jitter will still be applied, so the actual delay could be as\n * little as 0.5*initialDelayMs.\n */\n private readonly initialDelayMs: number = DEFAULT_BACKOFF_INITIAL_DELAY_MS,\n /**\n * The multiplier to use to determine the extended base delay after each\n * attempt.\n */\n private readonly backoffFactor: number = DEFAULT_BACKOFF_FACTOR,\n /**\n * The maximum base delay after which no further backoff is performed.\n * Note that jitter will still be applied, so the actual delay could be as\n * much as 1.5*maxDelayMs.\n */\n private readonly maxDelayMs: number = DEFAULT_BACKOFF_MAX_DELAY_MS\n ) {\n this.reset();\n }\n\n /**\n * Resets the backoff delay.\n *\n * The very next backoffAndWait() will have no delay. If it is called again\n * (i.e. due to an error), initialDelayMs (plus jitter) will be used, and\n * subsequent ones will increase according to the backoffFactor.\n */\n reset(): void {\n this.currentBaseMs = 0;\n }\n\n /**\n * Resets the backoff delay to the maximum delay (e.g. for use after a\n * RESOURCE_EXHAUSTED error).\n */\n resetToMax(): void {\n this.currentBaseMs = this.maxDelayMs;\n }\n\n /**\n * Returns a promise that resolves after currentDelayMs, and increases the\n * delay for any subsequent attempts. If there was a pending backoff operation\n * already, it will be canceled.\n */\n backoffAndRun(op: () => Promise): void {\n // Cancel any pending backoff operation.\n this.cancel();\n\n // First schedule using the current base (which may be 0 and should be\n // honored as such).\n const desiredDelayWithJitterMs = Math.floor(\n this.currentBaseMs + this.jitterDelayMs()\n );\n\n // Guard against lastAttemptTime being in the future due to a clock change.\n const delaySoFarMs = Math.max(0, Date.now() - this.lastAttemptTime);\n\n // Guard against the backoff delay already being past.\n const remainingDelayMs = Math.max(\n 0,\n desiredDelayWithJitterMs - delaySoFarMs\n );\n\n if (remainingDelayMs > 0) {\n logDebug(\n LOG_TAG,\n `Backing off for ${remainingDelayMs} ms ` +\n `(base delay: ${this.currentBaseMs} ms, ` +\n `delay with jitter: ${desiredDelayWithJitterMs} ms, ` +\n `last attempt: ${delaySoFarMs} ms ago)`\n );\n }\n\n this.timerPromise = this.queue.enqueueAfterDelay(\n this.timerId,\n remainingDelayMs,\n () => {\n this.lastAttemptTime = Date.now();\n return op();\n }\n );\n\n // Apply backoff factor to determine next delay and ensure it is within\n // bounds.\n this.currentBaseMs *= this.backoffFactor;\n if (this.currentBaseMs < this.initialDelayMs) {\n this.currentBaseMs = this.initialDelayMs;\n }\n if (this.currentBaseMs > this.maxDelayMs) {\n this.currentBaseMs = this.maxDelayMs;\n }\n }\n\n skipBackoff(): void {\n if (this.timerPromise !== null) {\n this.timerPromise.skipDelay();\n this.timerPromise = null;\n }\n }\n\n cancel(): void {\n if (this.timerPromise !== null) {\n this.timerPromise.cancel();\n this.timerPromise = null;\n }\n }\n\n /** Returns a random value in the range [-currentBaseMs/2, currentBaseMs/2] */\n private jitterDelayMs(): number {\n return (Math.random() - 0.5) * this.currentBaseMs;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { CredentialsProvider } from '../api/credentials';\nimport { User } from '../auth/user';\nimport { Aggregate } from '../core/aggregate';\nimport { DatabaseId } from '../core/database_info';\nimport { queryToAggregateTarget, Query, queryToTarget } from '../core/query';\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { Mutation } from '../model/mutation';\nimport { ResourcePath } from '../model/path';\nimport {\n ApiClientObjectMap,\n BatchGetDocumentsRequest as ProtoBatchGetDocumentsRequest,\n BatchGetDocumentsResponse as ProtoBatchGetDocumentsResponse,\n RunAggregationQueryRequest as ProtoRunAggregationQueryRequest,\n RunAggregationQueryResponse as ProtoRunAggregationQueryResponse,\n RunQueryRequest as ProtoRunQueryRequest,\n RunQueryResponse as ProtoRunQueryResponse,\n Value\n} from '../protos/firestore_proto_api';\nimport { debugAssert, debugCast, hardAssert } from '../util/assert';\nimport { AsyncQueue } from '../util/async_queue';\nimport { Code, FirestoreError } from '../util/error';\nimport { isNullOrUndefined } from '../util/types';\n\nimport { Connection } from './connection';\nimport {\n PersistentListenStream,\n PersistentWriteStream,\n WatchStreamListener,\n WriteStreamListener\n} from './persistent_stream';\nimport {\n fromDocument,\n fromBatchGetDocumentsResponse,\n JsonProtoSerializer,\n toMutation,\n toName,\n toQueryTarget,\n toResourcePath,\n toRunAggregationQueryRequest\n} from './serializer';\n\n/**\n * Datastore and its related methods are a wrapper around the external Google\n * Cloud Datastore grpc API, which provides an interface that is more convenient\n * for the rest of the client SDK architecture to consume.\n */\nexport abstract class Datastore {\n abstract terminate(): void;\n abstract serializer: JsonProtoSerializer;\n}\n\n/**\n * An implementation of Datastore that exposes additional state for internal\n * consumption.\n */\nclass DatastoreImpl extends Datastore {\n terminated = false;\n\n constructor(\n readonly authCredentials: CredentialsProvider,\n readonly appCheckCredentials: CredentialsProvider,\n readonly connection: Connection,\n readonly serializer: JsonProtoSerializer\n ) {\n super();\n }\n\n verifyInitialized(): void {\n debugAssert(!!this.connection, 'Datastore.start() not called');\n if (this.terminated) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'The client has already been terminated.'\n );\n }\n }\n\n /** Invokes the provided RPC with auth and AppCheck tokens. */\n invokeRPC(\n rpcName: string,\n databaseId: DatabaseId,\n resourcePath: ResourcePath,\n request: Req\n ): Promise {\n this.verifyInitialized();\n return Promise.all([\n this.authCredentials.getToken(),\n this.appCheckCredentials.getToken()\n ])\n .then(([authToken, appCheckToken]) => {\n return this.connection.invokeRPC(\n rpcName,\n toResourcePath(databaseId, resourcePath),\n request,\n authToken,\n appCheckToken\n );\n })\n .catch((error: FirestoreError) => {\n if (error.name === 'FirebaseError') {\n if (error.code === Code.UNAUTHENTICATED) {\n this.authCredentials.invalidateToken();\n this.appCheckCredentials.invalidateToken();\n }\n throw error;\n } else {\n throw new FirestoreError(Code.UNKNOWN, error.toString());\n }\n });\n }\n\n /** Invokes the provided RPC with streamed results with auth and AppCheck tokens. */\n invokeStreamingRPC(\n rpcName: string,\n databaseId: DatabaseId,\n resourcePath: ResourcePath,\n request: Req,\n expectedResponseCount?: number\n ): Promise {\n this.verifyInitialized();\n return Promise.all([\n this.authCredentials.getToken(),\n this.appCheckCredentials.getToken()\n ])\n .then(([authToken, appCheckToken]) => {\n return this.connection.invokeStreamingRPC(\n rpcName,\n toResourcePath(databaseId, resourcePath),\n request,\n authToken,\n appCheckToken,\n expectedResponseCount\n );\n })\n .catch((error: FirestoreError) => {\n if (error.name === 'FirebaseError') {\n if (error.code === Code.UNAUTHENTICATED) {\n this.authCredentials.invalidateToken();\n this.appCheckCredentials.invalidateToken();\n }\n throw error;\n } else {\n throw new FirestoreError(Code.UNKNOWN, error.toString());\n }\n });\n }\n\n terminate(): void {\n this.terminated = true;\n this.connection.terminate();\n }\n}\n\n// TODO(firestorexp): Make sure there is only one Datastore instance per\n// firestore-exp client.\nexport function newDatastore(\n authCredentials: CredentialsProvider,\n appCheckCredentials: CredentialsProvider,\n connection: Connection,\n serializer: JsonProtoSerializer\n): Datastore {\n return new DatastoreImpl(\n authCredentials,\n appCheckCredentials,\n connection,\n serializer\n );\n}\n\nexport async function invokeCommitRpc(\n datastore: Datastore,\n mutations: Mutation[]\n): Promise {\n const datastoreImpl = debugCast(datastore, DatastoreImpl);\n const request = {\n writes: mutations.map(m => toMutation(datastoreImpl.serializer, m))\n };\n await datastoreImpl.invokeRPC(\n 'Commit',\n datastoreImpl.serializer.databaseId,\n ResourcePath.emptyPath(),\n request\n );\n}\n\nexport async function invokeBatchGetDocumentsRpc(\n datastore: Datastore,\n keys: DocumentKey[]\n): Promise {\n const datastoreImpl = debugCast(datastore, DatastoreImpl);\n const request = {\n documents: keys.map(k => toName(datastoreImpl.serializer, k))\n };\n const response = await datastoreImpl.invokeStreamingRPC<\n ProtoBatchGetDocumentsRequest,\n ProtoBatchGetDocumentsResponse\n >(\n 'BatchGetDocuments',\n datastoreImpl.serializer.databaseId,\n ResourcePath.emptyPath(),\n request,\n keys.length\n );\n\n const docs = new Map();\n response.forEach(proto => {\n const doc = fromBatchGetDocumentsResponse(datastoreImpl.serializer, proto);\n docs.set(doc.key.toString(), doc);\n });\n const result: Document[] = [];\n keys.forEach(key => {\n const doc = docs.get(key.toString());\n hardAssert(!!doc, 0xd7c2, 'Missing entity in write response for `key`', {\n key\n });\n result.push(doc);\n });\n return result;\n}\n\nexport async function invokeRunQueryRpc(\n datastore: Datastore,\n query: Query\n): Promise {\n const datastoreImpl = debugCast(datastore, DatastoreImpl);\n const { queryTarget, parent } = toQueryTarget(\n datastoreImpl.serializer,\n queryToTarget(query)\n );\n const response = await datastoreImpl.invokeStreamingRPC<\n ProtoRunQueryRequest,\n ProtoRunQueryResponse\n >('RunQuery', datastoreImpl.serializer.databaseId, parent, {\n structuredQuery: queryTarget.structuredQuery\n });\n return (\n response\n // Omit RunQueryResponses that only contain readTimes.\n .filter(proto => !!proto.document)\n .map(proto =>\n fromDocument(datastoreImpl.serializer, proto.document!, undefined)\n )\n );\n}\n\nexport async function invokeRunAggregationQueryRpc(\n datastore: Datastore,\n query: Query,\n aggregates: Aggregate[]\n): Promise> {\n const datastoreImpl = debugCast(datastore, DatastoreImpl);\n const { request, aliasMap, parent } = toRunAggregationQueryRequest(\n datastoreImpl.serializer,\n queryToAggregateTarget(query),\n aggregates\n );\n\n if (!datastoreImpl.connection.shouldResourcePathBeIncludedInRequest) {\n delete request.parent;\n }\n const response = await datastoreImpl.invokeStreamingRPC<\n ProtoRunAggregationQueryRequest,\n ProtoRunAggregationQueryResponse\n >(\n 'RunAggregationQuery',\n datastoreImpl.serializer.databaseId,\n parent,\n request,\n /*expectedResponseCount=*/ 1\n );\n\n // Omit RunAggregationQueryResponse that only contain readTimes.\n const filteredResult = response.filter(proto => !!proto.result);\n\n hardAssert(\n filteredResult.length === 1,\n 0xfcd7,\n 'Aggregation fields are missing from result.'\n );\n debugAssert(\n !isNullOrUndefined(filteredResult[0].result),\n 'aggregationQueryResponse.result'\n );\n debugAssert(\n !isNullOrUndefined(filteredResult[0].result.aggregateFields),\n 'aggregationQueryResponse.result.aggregateFields'\n );\n\n // Remap the short-form aliases that were sent to the server\n // to the client-side aliases. Users will access the results\n // using the client-side alias.\n const unmappedAggregateFields = filteredResult[0].result?.aggregateFields;\n const remappedFields = Object.keys(unmappedAggregateFields).reduce<\n ApiClientObjectMap\n >((accumulator, key) => {\n debugAssert(\n !isNullOrUndefined(aliasMap[key]),\n `'${key}' not present in aliasMap result`\n );\n accumulator[aliasMap[key]] = unmappedAggregateFields[key]!;\n return accumulator;\n }, {});\n\n return remappedFields;\n}\n\nexport function newPersistentWriteStream(\n datastore: Datastore,\n queue: AsyncQueue,\n listener: WriteStreamListener\n): PersistentWriteStream {\n const datastoreImpl = debugCast(datastore, DatastoreImpl);\n datastoreImpl.verifyInitialized();\n return new PersistentWriteStream(\n queue,\n datastoreImpl.connection,\n datastoreImpl.authCredentials,\n datastoreImpl.appCheckCredentials,\n datastoreImpl.serializer,\n listener\n );\n}\n\nexport function newPersistentWatchStream(\n datastore: Datastore,\n queue: AsyncQueue,\n listener: WatchStreamListener\n): PersistentListenStream {\n const datastoreImpl = debugCast(datastore, DatastoreImpl);\n datastoreImpl.verifyInitialized();\n return new PersistentListenStream(\n queue,\n datastoreImpl.connection,\n datastoreImpl.authCredentials,\n datastoreImpl.appCheckCredentials,\n datastoreImpl.serializer,\n listener\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport { _FirebaseService } from '@firebase/app';\n\nimport { CredentialsProvider } from '../api/credentials';\nimport { cloneLongPollingOptions } from '../api/long_polling_options';\nimport { User } from '../auth/user';\nimport { DatabaseId, DatabaseInfo } from '../core/database_info';\nimport { newConnection } from '../platform/connection';\nimport { newSerializer } from '../platform/serializer';\nimport { Datastore, newDatastore } from '../remote/datastore';\nimport { Code, FirestoreError } from '../util/error';\nimport { logDebug } from '../util/log';\n\nimport { FirestoreSettingsImpl } from './settings';\n\nexport const LOG_TAG = 'ComponentProvider';\n\n// The components module manages the lifetime of dependencies of the Firestore\n// client. Dependencies can be lazily constructed and only one exists per\n// Firestore instance.\n\n/**\n * An interface implemented by FirebaseFirestore that provides compatibility\n * with the usage in this file.\n *\n * This interface mainly exists to remove a cyclic dependency.\n */\nexport interface FirestoreService extends _FirebaseService {\n _authCredentials: CredentialsProvider;\n _appCheckCredentials: CredentialsProvider;\n _persistenceKey: string;\n _databaseId: DatabaseId;\n _terminated: boolean;\n\n _freezeSettings(): FirestoreSettingsImpl;\n}\n/**\n * An instance map that ensures only one Datastore exists per Firestore\n * instance.\n */\nconst datastoreInstances = new Map();\n\n/**\n * Returns an initialized and started Datastore for the given Firestore\n * instance. Callers must invoke removeComponents() when the Firestore\n * instance is terminated.\n */\nexport function getDatastore(firestore: FirestoreService): Datastore {\n if (firestore._terminated) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'The client has already been terminated.'\n );\n }\n if (!datastoreInstances.has(firestore)) {\n logDebug(LOG_TAG, 'Initializing Datastore');\n const databaseInfo = makeDatabaseInfo(\n firestore._databaseId,\n firestore.app.options.appId || '',\n firestore._persistenceKey,\n firestore._freezeSettings()\n );\n const connection = newConnection(databaseInfo);\n const serializer = newSerializer(firestore._databaseId);\n const datastore = newDatastore(\n firestore._authCredentials,\n firestore._appCheckCredentials,\n connection,\n serializer\n );\n\n datastoreInstances.set(firestore, datastore);\n }\n return datastoreInstances.get(firestore)!;\n}\n\n/**\n * Removes all components associated with the provided instance. Must be called\n * when the `Firestore` instance is terminated.\n */\nexport function removeComponents(firestore: FirestoreService): void {\n const datastore = datastoreInstances.get(firestore);\n if (datastore) {\n logDebug(LOG_TAG, 'Removing Datastore');\n datastoreInstances.delete(firestore);\n datastore.terminate();\n }\n}\n\nexport function makeDatabaseInfo(\n databaseId: DatabaseId,\n appId: string,\n persistenceKey: string,\n settings: FirestoreSettingsImpl\n): DatabaseInfo {\n return new DatabaseInfo(\n databaseId,\n appId,\n persistenceKey,\n settings.host,\n settings.ssl,\n settings.experimentalForceLongPolling,\n settings.experimentalAutoDetectLongPolling,\n cloneLongPollingOptions(settings.experimentalLongPollingOptions),\n settings.useFetchStreams,\n settings.isUsingEmulator\n );\n}\n","/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ListenSequenceNumber, TargetId } from '../core/types';\nimport { SortedMap } from '../util/sorted_map';\n\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { TargetData } from './target_data';\n\n/**\n * Describes a map whose keys are active target ids. We do not care about the type of the\n * values.\n */\nexport type ActiveTargets = SortedMap;\n\nexport const GC_DID_NOT_RUN: LruResults = {\n didRun: false,\n sequenceNumbersCollected: 0,\n targetsRemoved: 0,\n documentsRemoved: 0\n};\n\nexport const LRU_COLLECTION_DISABLED = -1;\nexport const LRU_DEFAULT_CACHE_SIZE_BYTES = 40 * 1024 * 1024;\n\nexport class LruParams {\n private static readonly DEFAULT_COLLECTION_PERCENTILE = 10;\n private static readonly DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT = 1000;\n\n static withCacheSize(cacheSize: number): LruParams {\n return new LruParams(\n cacheSize,\n LruParams.DEFAULT_COLLECTION_PERCENTILE,\n LruParams.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT\n );\n }\n\n static readonly DEFAULT: LruParams = new LruParams(\n LRU_DEFAULT_CACHE_SIZE_BYTES,\n LruParams.DEFAULT_COLLECTION_PERCENTILE,\n LruParams.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT\n );\n\n static readonly DISABLED: LruParams = new LruParams(\n LRU_COLLECTION_DISABLED,\n 0,\n 0\n );\n\n constructor(\n // When we attempt to collect, we will only do so if the cache size is greater than this\n // threshold. Passing `COLLECTION_DISABLED` here will cause collection to always be skipped.\n readonly cacheSizeCollectionThreshold: number,\n // The percentage of sequence numbers that we will attempt to collect\n readonly percentileToCollect: number,\n // A cap on the total number of sequence numbers that will be collected. This prevents\n // us from collecting a huge number of sequence numbers if the cache has grown very large.\n readonly maximumSequenceNumbersToCollect: number\n ) {}\n}\n\nexport interface LruGarbageCollector {\n readonly params: LruParams;\n\n collect(\n txn: PersistenceTransaction,\n activeTargetIds: ActiveTargets\n ): PersistencePromise;\n\n /** Given a percentile of target to collect, returns the number of targets to collect. */\n calculateTargetCount(\n txn: PersistenceTransaction,\n percentile: number\n ): PersistencePromise;\n\n /** Returns the nth sequence number, counting in order from the smallest. */\n nthSequenceNumber(\n txn: PersistenceTransaction,\n n: number\n ): PersistencePromise;\n\n /**\n * Removes documents that have a sequence number equal to or less than the\n * upper bound and are not otherwise pinned.\n */\n removeOrphanedDocuments(\n txn: PersistenceTransaction,\n upperBound: ListenSequenceNumber\n ): PersistencePromise;\n\n getCacheSize(txn: PersistenceTransaction): PersistencePromise;\n\n /**\n * Removes targets with a sequence number equal to or less than the given\n * upper bound, and removes document associations with those targets.\n */\n removeTargets(\n txn: PersistenceTransaction,\n upperBound: ListenSequenceNumber,\n activeTargetIds: ActiveTargets\n ): PersistencePromise;\n}\n\n/**\n * Describes the results of a garbage collection run. `didRun` will be set to\n * `false` if collection was skipped (either it is disabled or the cache size\n * has not hit the threshold). If collection ran, the other fields will be\n * filled in with the details of the results.\n */\nexport interface LruResults {\n readonly didRun: boolean;\n readonly sequenceNumbersCollected: number;\n readonly targetsRemoved: number;\n readonly documentsRemoved: number;\n}\n\n/**\n * Persistence layers intending to use LRU Garbage collection should have\n * reference delegates that implement this interface. This interface defines the\n * operations that the LRU garbage collector needs from the persistence layer.\n */\nexport interface LruDelegate {\n readonly garbageCollector: LruGarbageCollector;\n\n /** Enumerates all the targets in the TargetCache. */\n forEachTarget(\n txn: PersistenceTransaction,\n f: (target: TargetData) => void\n ): PersistencePromise;\n\n getSequenceNumberCount(\n txn: PersistenceTransaction\n ): PersistencePromise;\n\n /**\n * Enumerates sequence numbers for documents not associated with a target.\n * Note that this may include duplicate sequence numbers.\n */\n forEachOrphanedDocumentSequenceNumber(\n txn: PersistenceTransaction,\n f: (sequenceNumber: ListenSequenceNumber) => void\n ): PersistencePromise;\n\n /**\n * Removes all targets that have a sequence number less than or equal to\n * `upperBound`, and are not present in the `activeTargetIds` set.\n *\n * @returns the number of targets removed.\n */\n removeTargets(\n txn: PersistenceTransaction,\n upperBound: ListenSequenceNumber,\n activeTargetIds: ActiveTargets\n ): PersistencePromise;\n\n /**\n * Removes all unreferenced documents from the cache that have a sequence\n * number less than or equal to the given `upperBound`.\n *\n * @returns the number of documents removed.\n */\n removeOrphanedDocuments(\n txn: PersistenceTransaction,\n upperBound: ListenSequenceNumber\n ): PersistencePromise;\n\n getCacheSize(txn: PersistenceTransaction): PersistencePromise;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getGlobal, getUA, isIndexedDBAvailable } from '@firebase/util';\n\nimport { debugAssert } from '../util/assert';\nimport { Code, FirestoreError } from '../util/error';\nimport { logDebug, logError } from '../util/log';\nimport { Deferred } from '../util/promise';\n\nimport { PersistencePromise } from './persistence_promise';\n\n// References to `indexedDB` are guarded by SimpleDb.isAvailable() and getGlobal()\n/* eslint-disable no-restricted-globals */\n\nconst LOG_TAG = 'SimpleDb';\n\n/**\n * The maximum number of retry attempts for an IndexedDb transaction that fails\n * with a DOMException.\n */\nconst TRANSACTION_RETRY_COUNT = 3;\n\n// The different modes supported by `SimpleDb.runTransaction()`\ntype SimpleDbTransactionMode = 'readonly' | 'readwrite';\n\nexport interface SimpleDbSchemaConverter {\n createOrUpgrade(\n db: IDBDatabase,\n txn: IDBTransaction,\n fromVersion: number,\n toVersion: number\n ): PersistencePromise;\n}\n\n/**\n * Wraps an IDBTransaction and exposes a store() method to get a handle to a\n * specific object store.\n */\nexport class SimpleDbTransaction {\n private aborted = false;\n\n /**\n * A `Promise` that resolves with the result of the IndexedDb transaction.\n */\n private readonly completionDeferred = new Deferred();\n\n static open(\n db: IDBDatabase,\n action: string,\n mode: IDBTransactionMode,\n objectStoreNames: string[]\n ): SimpleDbTransaction {\n try {\n return new SimpleDbTransaction(\n action,\n db.transaction(objectStoreNames, mode)\n );\n } catch (e) {\n throw new IndexedDbTransactionError(action, e as Error);\n }\n }\n\n constructor(\n private readonly action: string,\n private readonly transaction: IDBTransaction\n ) {\n this.transaction.oncomplete = () => {\n this.completionDeferred.resolve();\n };\n this.transaction.onabort = () => {\n if (transaction.error) {\n this.completionDeferred.reject(\n new IndexedDbTransactionError(action, transaction.error)\n );\n } else {\n this.completionDeferred.resolve();\n }\n };\n this.transaction.onerror = (event: Event) => {\n const error = checkForAndReportiOSError(\n (event.target as IDBRequest).error!\n );\n this.completionDeferred.reject(\n new IndexedDbTransactionError(action, error)\n );\n };\n }\n\n get completionPromise(): Promise {\n return this.completionDeferred.promise;\n }\n\n abort(error?: Error): void {\n if (error) {\n this.completionDeferred.reject(error);\n }\n\n if (!this.aborted) {\n logDebug(\n LOG_TAG,\n 'Aborting transaction:',\n error ? error.message : 'Client-initiated abort'\n );\n this.aborted = true;\n this.transaction.abort();\n }\n }\n\n maybeCommit(): void {\n // If the browser supports V3 IndexedDB, we invoke commit() explicitly to\n // speed up index DB processing if the event loop remains blocks.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const maybeV3IndexedDb = this.transaction as any;\n if (!this.aborted && typeof maybeV3IndexedDb.commit === 'function') {\n maybeV3IndexedDb.commit();\n }\n }\n\n /**\n * Returns a SimpleDbStore for the specified store. All\n * operations performed on the SimpleDbStore happen within the context of this\n * transaction and it cannot be used anymore once the transaction is\n * completed.\n *\n * Note that we can't actually enforce that the KeyType and ValueType are\n * correct, but they allow type safety through the rest of the consuming code.\n */\n store(\n storeName: string\n ): SimpleDbStore {\n const store = this.transaction.objectStore(storeName);\n debugAssert(!!store, 'Object store not part of transaction: ' + storeName);\n return new SimpleDbStore(store);\n }\n}\n\n/**\n * Provides a wrapper around IndexedDb with a simplified interface that uses\n * Promise-like return values to chain operations. Real promises cannot be used\n * since .then() continuations are executed asynchronously (e.g. via\n * .setImmediate), which would cause IndexedDB to end the transaction.\n * See PersistencePromise for more details.\n */\nexport class SimpleDb {\n private db?: IDBDatabase;\n private lastClosedDbVersion: number | null = null;\n private versionchangelistener?: (event: IDBVersionChangeEvent) => void;\n\n /** Deletes the specified database. */\n static delete(name: string): Promise {\n logDebug(LOG_TAG, 'Removing database:', name);\n const globals = getGlobal();\n return wrapRequest(\n globals.indexedDB.deleteDatabase(name)\n ).toPromise();\n }\n\n /** Returns true if IndexedDB is available in the current environment. */\n static isAvailable(): boolean {\n if (!isIndexedDBAvailable()) {\n return false;\n }\n\n if (SimpleDb.isMockPersistence()) {\n return true;\n }\n\n // We extensively use indexed array values and compound keys,\n // which IE and Edge do not support. However, they still have indexedDB\n // defined on the window, so we need to check for them here and make sure\n // to return that persistence is not enabled for those browsers.\n // For tracking support of this feature, see here:\n // https://developer.microsoft.com/en-us/microsoft-edge/platform/status/indexeddbarraysandmultientrysupport/\n\n // Check the UA string to find out the browser.\n const ua = getUA();\n\n // IE 10\n // ua = 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)';\n\n // IE 11\n // ua = 'Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko';\n\n // Edge\n // ua = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML,\n // like Gecko) Chrome/39.0.2171.71 Safari/537.36 Edge/12.0';\n\n // iOS Safari: Disable for users running iOS version < 10.\n const iOSVersion = SimpleDb.getIOSVersion(ua);\n const isUnsupportedIOS = 0 < iOSVersion && iOSVersion < 10;\n\n // Android browser: Disable for users running version < 4.5.\n const androidVersion = getAndroidVersion(ua);\n const isUnsupportedAndroid = 0 < androidVersion && androidVersion < 4.5;\n\n if (\n ua.indexOf('MSIE ') > 0 ||\n ua.indexOf('Trident/') > 0 ||\n ua.indexOf('Edge/') > 0 ||\n isUnsupportedIOS ||\n isUnsupportedAndroid\n ) {\n return false;\n } else {\n return true;\n }\n }\n\n /**\n * Returns true if the backing IndexedDB store is the Node IndexedDBShim\n * (see https://github.com/axemclion/IndexedDBShim).\n */\n static isMockPersistence(): boolean {\n return (\n typeof process !== 'undefined' &&\n process.env?.USE_MOCK_PERSISTENCE === 'YES'\n );\n }\n\n /** Helper to get a typed SimpleDbStore from a transaction. */\n static getStore(\n txn: SimpleDbTransaction,\n store: string\n ): SimpleDbStore {\n return txn.store(store);\n }\n\n // visible for testing\n /** Parse User Agent to determine iOS version. Returns -1 if not found. */\n static getIOSVersion(ua: string): number {\n const iOSVersionRegex = ua.match(/i(?:phone|pad|pod) os ([\\d_]+)/i);\n const version = iOSVersionRegex\n ? iOSVersionRegex[1].split('_').slice(0, 2).join('.')\n : '-1';\n return Number(version);\n }\n\n /*\n * Creates a new SimpleDb wrapper for IndexedDb database `name`.\n *\n * Note that `version` must not be a downgrade. IndexedDB does not support\n * downgrading the schema version. We currently do not support any way to do\n * versioning outside of IndexedDB's versioning mechanism, as only\n * version-upgrade transactions are allowed to do things like create\n * objectstores.\n */\n constructor(\n private readonly name: string,\n private readonly version: number,\n private readonly schemaConverter: SimpleDbSchemaConverter\n ) {\n debugAssert(\n SimpleDb.isAvailable(),\n 'IndexedDB not supported in current environment.'\n );\n\n const iOSVersion = SimpleDb.getIOSVersion(getUA());\n // NOTE: According to https://bugs.webkit.org/show_bug.cgi?id=197050, the\n // bug we're checking for should exist in iOS >= 12.2 and < 13, but for\n // whatever reason it's much harder to hit after 12.2 so we only proactively\n // log on 12.2.\n if (iOSVersion === 12.2) {\n logError(\n 'Firestore persistence suffers from a bug in iOS 12.2 ' +\n 'Safari that may cause your app to stop working. See ' +\n 'https://stackoverflow.com/q/56496296/110915 for details ' +\n 'and a potential workaround.'\n );\n }\n }\n\n /**\n * Opens the specified database, creating or upgrading it if necessary.\n */\n async ensureDb(action: string): Promise {\n if (!this.db) {\n logDebug(LOG_TAG, 'Opening database:', this.name);\n this.db = await new Promise((resolve, reject) => {\n // TODO(mikelehen): Investigate browser compatibility.\n // https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API/Using_IndexedDB\n // suggests IE9 and older WebKit browsers handle upgrade\n // differently. They expect setVersion, as described here:\n // https://developer.mozilla.org/en-US/docs/Web/API/IDBVersionChangeRequest/setVersion\n const request = indexedDB.open(this.name, this.version);\n\n request.onsuccess = (event: Event) => {\n const db = (event.target as IDBOpenDBRequest).result;\n resolve(db);\n };\n\n request.onblocked = () => {\n reject(\n new IndexedDbTransactionError(\n action,\n 'Cannot upgrade IndexedDB schema while another tab is open. ' +\n 'Close all tabs that access Firestore and reload this page to proceed.'\n )\n );\n };\n\n request.onerror = (event: Event) => {\n const error: DOMException = (event.target as IDBOpenDBRequest).error!;\n if (error.name === 'VersionError') {\n reject(\n new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'A newer version of the Firestore SDK was previously used and so the persisted ' +\n 'data is not compatible with the version of the SDK you are now using. The SDK ' +\n 'will operate with persistence disabled. If you need persistence, please ' +\n 're-upgrade to a newer version of the SDK or else clear the persisted IndexedDB ' +\n 'data for your app to start fresh.'\n )\n );\n } else if (error.name === 'InvalidStateError') {\n reject(\n new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'Unable to open an IndexedDB connection. This could be due to running in a ' +\n 'private browsing session on a browser whose private browsing sessions do not ' +\n 'support IndexedDB: ' +\n error\n )\n );\n } else {\n reject(new IndexedDbTransactionError(action, error));\n }\n };\n\n request.onupgradeneeded = (event: IDBVersionChangeEvent) => {\n logDebug(\n LOG_TAG,\n 'Database \"' + this.name + '\" requires upgrade from version:',\n event.oldVersion\n );\n const db = (event.target as IDBOpenDBRequest).result;\n this.schemaConverter\n .createOrUpgrade(\n db,\n request.transaction!,\n event.oldVersion,\n this.version\n )\n .next(() => {\n logDebug(\n LOG_TAG,\n 'Database upgrade to version ' + this.version + ' complete'\n );\n });\n };\n });\n }\n\n if (this.versionchangelistener) {\n this.db.onversionchange = event => this.versionchangelistener!(event);\n }\n\n return this.db;\n }\n\n setVersionChangeListener(\n versionChangeListener: (event: IDBVersionChangeEvent) => void\n ): void {\n this.versionchangelistener = versionChangeListener;\n if (this.db) {\n this.db.onversionchange = (event: IDBVersionChangeEvent) => {\n return versionChangeListener(event);\n };\n }\n }\n\n async runTransaction(\n action: string,\n mode: SimpleDbTransactionMode,\n objectStores: string[],\n transactionFn: (transaction: SimpleDbTransaction) => PersistencePromise\n ): Promise {\n const readonly = mode === 'readonly';\n let attemptNumber = 0;\n\n while (true) {\n ++attemptNumber;\n\n try {\n this.db = await this.ensureDb(action);\n\n const transaction = SimpleDbTransaction.open(\n this.db,\n action,\n readonly ? 'readonly' : 'readwrite',\n objectStores\n );\n const transactionFnResult = transactionFn(transaction)\n .next(result => {\n transaction.maybeCommit();\n return result;\n })\n .catch(error => {\n // Abort the transaction if there was an error.\n transaction.abort(error);\n // We cannot actually recover, and calling `abort()` will cause the transaction's\n // completion promise to be rejected. This in turn means that we won't use\n // `transactionFnResult` below. We return a rejection here so that we don't add the\n // possibility of returning `void` to the type of `transactionFnResult`.\n return PersistencePromise.reject(error);\n })\n .toPromise();\n\n // As noted above, errors are propagated by aborting the transaction. So\n // we swallow any error here to avoid the browser logging it as unhandled.\n transactionFnResult.catch(() => {});\n\n // Wait for the transaction to complete (i.e. IndexedDb's onsuccess event to\n // fire), but still return the original transactionFnResult back to the\n // caller.\n await transaction.completionPromise;\n return transactionFnResult;\n } catch (e) {\n const error = e as Error;\n // TODO(schmidt-sebastian): We could probably be smarter about this and\n // not retry exceptions that are likely unrecoverable (such as quota\n // exceeded errors).\n\n // Note: We cannot use an instanceof check for FirestoreException, since the\n // exception is wrapped in a generic error by our async/await handling.\n const retryable =\n error.name !== 'FirebaseError' &&\n attemptNumber < TRANSACTION_RETRY_COUNT;\n logDebug(\n LOG_TAG,\n 'Transaction failed with error:',\n error.message,\n 'Retrying:',\n retryable\n );\n\n this.close();\n\n if (!retryable) {\n return Promise.reject(error);\n }\n }\n }\n }\n\n close(): void {\n if (this.db) {\n this.db.close();\n }\n this.db = undefined;\n }\n}\n\n/** Parse User Agent to determine Android version. Returns -1 if not found. */\nexport function getAndroidVersion(ua: string): number {\n const androidVersionRegex = ua.match(/Android ([\\d.]+)/i);\n const version = androidVersionRegex\n ? androidVersionRegex[1].split('.').slice(0, 2).join('.')\n : '-1';\n return Number(version);\n}\n\n/**\n * A controller for iterating over a key range or index. It allows an iterate\n * callback to delete the currently-referenced object, or jump to a new key\n * within the key range or index.\n */\nexport class IterationController {\n private shouldStop = false;\n private nextKey: IDBValidKey | null = null;\n\n constructor(private dbCursor: IDBCursorWithValue) {}\n\n get isDone(): boolean {\n return this.shouldStop;\n }\n\n get skipToKey(): IDBValidKey | null {\n return this.nextKey;\n }\n\n set cursor(value: IDBCursorWithValue) {\n this.dbCursor = value;\n }\n\n /**\n * This function can be called to stop iteration at any point.\n */\n done(): void {\n this.shouldStop = true;\n }\n\n /**\n * This function can be called to skip to that next key, which could be\n * an index or a primary key.\n */\n skip(key: IDBValidKey): void {\n this.nextKey = key;\n }\n\n /**\n * Delete the current cursor value from the object store.\n *\n * NOTE: You CANNOT do this with a keysOnly query.\n */\n delete(): PersistencePromise {\n return wrapRequest(this.dbCursor.delete());\n }\n}\n\n/**\n * Callback used with iterate() method.\n */\nexport type IterateCallback = (\n key: KeyType,\n value: ValueType,\n control: IterationController\n) => void | PersistencePromise;\n\n/** Options available to the iterate() method. */\nexport interface IterateOptions {\n /** Index to iterate over (else primary keys will be iterated) */\n index?: string;\n\n /** IndexedDB Range to iterate over (else entire store will be iterated) */\n range?: IDBKeyRange;\n\n /** If true, values aren't read while iterating. */\n keysOnly?: boolean;\n\n /** If true, iterate over the store in reverse. */\n reverse?: boolean;\n}\n\n/** An error that wraps exceptions that thrown during IndexedDB execution. */\nexport class IndexedDbTransactionError extends FirestoreError {\n name = 'IndexedDbTransactionError';\n\n constructor(actionName: string, cause: Error | string) {\n super(\n Code.UNAVAILABLE,\n `IndexedDB transaction '${actionName}' failed: ${cause}`\n );\n }\n}\n\n/** Verifies whether `e` is an IndexedDbTransactionError. */\nexport function isIndexedDbTransactionError(e: Error): boolean {\n // Use name equality, as instanceof checks on errors don't work with errors\n // that wrap other errors.\n return e.name === 'IndexedDbTransactionError';\n}\n\n/**\n * A wrapper around an IDBObjectStore providing an API that:\n *\n * 1) Has generic KeyType / ValueType parameters to provide strongly-typed\n * methods for acting against the object store.\n * 2) Deals with IndexedDB's onsuccess / onerror event callbacks, making every\n * method return a PersistencePromise instead.\n * 3) Provides a higher-level API to avoid needing to do excessive wrapping of\n * intermediate IndexedDB types (IDBCursorWithValue, etc.)\n */\nexport class SimpleDbStore<\n KeyType extends IDBValidKey,\n ValueType extends unknown\n> {\n constructor(private store: IDBObjectStore) {}\n\n /**\n * Writes a value into the Object Store.\n *\n * @param key - Optional explicit key to use when writing the object, else the\n * key will be auto-assigned (e.g. via the defined keyPath for the store).\n * @param value - The object to write.\n */\n put(value: ValueType): PersistencePromise;\n put(key: KeyType, value: ValueType): PersistencePromise;\n put(\n keyOrValue: KeyType | ValueType,\n value?: ValueType\n ): PersistencePromise {\n let request;\n if (value !== undefined) {\n logDebug(LOG_TAG, 'PUT', this.store.name, keyOrValue, value);\n request = this.store.put(value, keyOrValue as KeyType);\n } else {\n logDebug(LOG_TAG, 'PUT', this.store.name, '', keyOrValue);\n request = this.store.put(keyOrValue as ValueType);\n }\n return wrapRequest(request);\n }\n\n /**\n * Adds a new value into an Object Store and returns the new key. Similar to\n * IndexedDb's `add()`, this method will fail on primary key collisions.\n *\n * @param value - The object to write.\n * @returns The key of the value to add.\n */\n add(value: ValueType): PersistencePromise {\n logDebug(LOG_TAG, 'ADD', this.store.name, value, value);\n const request = this.store.add(value as ValueType);\n return wrapRequest(request);\n }\n\n /**\n * Gets the object with the specified key from the specified store, or null\n * if no object exists with the specified key.\n *\n * @key The key of the object to get.\n * @returns The object with the specified key or null if no object exists.\n */\n get(key: KeyType): PersistencePromise {\n const request = this.store.get(key);\n // We're doing an unsafe cast to ValueType.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return wrapRequest(request).next(result => {\n // Normalize nonexistence to null.\n if (result === undefined) {\n result = null;\n }\n logDebug(LOG_TAG, 'GET', this.store.name, key, result);\n return result;\n });\n }\n\n delete(key: KeyType | IDBKeyRange): PersistencePromise {\n logDebug(LOG_TAG, 'DELETE', this.store.name, key);\n const request = this.store.delete(key);\n return wrapRequest(request);\n }\n\n /**\n * If we ever need more of the count variants, we can add overloads. For now,\n * all we need is to count everything in a store.\n *\n * Returns the number of rows in the store.\n */\n count(): PersistencePromise {\n logDebug(LOG_TAG, 'COUNT', this.store.name);\n const request = this.store.count();\n return wrapRequest(request);\n }\n\n /** Loads all elements from the object store. */\n loadAll(): PersistencePromise;\n /** Loads all elements for the index range from the object store. */\n loadAll(range: IDBKeyRange): PersistencePromise;\n /** Loads all elements ordered by the given index. */\n loadAll(index: string): PersistencePromise;\n /**\n * Loads all elements from the object store that fall into the provided in the\n * index range for the given index.\n */\n loadAll(index: string, range: IDBKeyRange): PersistencePromise;\n loadAll(\n indexOrRange?: string | IDBKeyRange,\n range?: IDBKeyRange\n ): PersistencePromise {\n const iterateOptions = this.options(indexOrRange, range);\n // Use `getAll()` if the browser supports IndexedDB v3, as it is roughly\n // 20% faster.\n const store = iterateOptions.index\n ? this.store.index(iterateOptions.index)\n : this.store;\n if (typeof store.getAll === 'function') {\n const request = store.getAll(iterateOptions.range);\n return new PersistencePromise((resolve, reject) => {\n request.onerror = (event: Event) => {\n reject((event.target as IDBRequest).error!);\n };\n request.onsuccess = (event: Event) => {\n resolve((event.target as IDBRequest).result);\n };\n });\n } else {\n const cursor = this.cursor(iterateOptions);\n const results: ValueType[] = [];\n return this.iterateCursor(cursor, (key, value) => {\n results.push(value);\n }).next(() => {\n return results;\n });\n }\n }\n\n /**\n * Loads the first `count` elements from the provided index range. Loads all\n * elements if no limit is provided.\n */\n loadFirst(\n range: IDBKeyRange,\n count: number | null\n ): PersistencePromise {\n const request = this.store.getAll(\n range,\n count === null ? undefined : count\n );\n return new PersistencePromise((resolve, reject) => {\n request.onerror = (event: Event) => {\n reject((event.target as IDBRequest).error!);\n };\n request.onsuccess = (event: Event) => {\n resolve((event.target as IDBRequest).result);\n };\n });\n }\n\n deleteAll(): PersistencePromise;\n deleteAll(range: IDBKeyRange): PersistencePromise;\n deleteAll(index: string, range: IDBKeyRange): PersistencePromise;\n deleteAll(\n indexOrRange?: string | IDBKeyRange,\n range?: IDBKeyRange\n ): PersistencePromise {\n logDebug(LOG_TAG, 'DELETE ALL', this.store.name);\n const options = this.options(indexOrRange, range);\n options.keysOnly = false;\n const cursor = this.cursor(options);\n return this.iterateCursor(cursor, (key, value, control) => {\n // NOTE: Calling delete() on a cursor is documented as more efficient than\n // calling delete() on an object store with a single key\n // (https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/delete),\n // however, this requires us *not* to use a keysOnly cursor\n // (https://developer.mozilla.org/en-US/docs/Web/API/IDBCursor/delete). We\n // may want to compare the performance of each method.\n return control.delete();\n });\n }\n\n /**\n * Iterates over keys and values in an object store.\n *\n * @param options - Options specifying how to iterate the objects in the\n * store.\n * @param callback - will be called for each iterated object. Iteration can be\n * canceled at any point by calling the doneFn passed to the callback.\n * The callback can return a PersistencePromise if it performs async\n * operations but note that iteration will continue without waiting for them\n * to complete.\n * @returns A PersistencePromise that resolves once all PersistencePromises\n * returned by callbacks resolve.\n */\n iterate(\n callback: IterateCallback\n ): PersistencePromise;\n iterate(\n options: IterateOptions,\n callback: IterateCallback\n ): PersistencePromise;\n iterate(\n optionsOrCallback: IterateOptions | IterateCallback,\n callback?: IterateCallback\n ): PersistencePromise {\n let options;\n if (!callback) {\n options = {};\n callback = optionsOrCallback as IterateCallback;\n } else {\n options = optionsOrCallback as IterateOptions;\n }\n const cursor = this.cursor(options);\n return this.iterateCursor(cursor, callback);\n }\n\n /**\n * Iterates over a store, but waits for the given callback to complete for\n * each entry before iterating the next entry. This allows the callback to do\n * asynchronous work to determine if this iteration should continue.\n *\n * The provided callback should return `true` to continue iteration, and\n * `false` otherwise.\n */\n iterateSerial(\n callback: (k: KeyType, v: ValueType) => PersistencePromise\n ): PersistencePromise {\n const cursorRequest = this.cursor({});\n return new PersistencePromise((resolve, reject) => {\n cursorRequest.onerror = (event: Event) => {\n const error = checkForAndReportiOSError(\n (event.target as IDBRequest).error!\n );\n reject(error);\n };\n cursorRequest.onsuccess = (event: Event) => {\n const cursor: IDBCursorWithValue = (event.target as IDBRequest).result;\n if (!cursor) {\n resolve();\n return;\n }\n\n callback(cursor.primaryKey as KeyType, cursor.value).next(\n shouldContinue => {\n if (shouldContinue) {\n cursor.continue();\n } else {\n resolve();\n }\n }\n );\n };\n });\n }\n\n private iterateCursor(\n cursorRequest: IDBRequest,\n fn: IterateCallback\n ): PersistencePromise {\n const results: Array> = [];\n return new PersistencePromise((resolve, reject) => {\n cursorRequest.onerror = (event: Event) => {\n reject((event.target as IDBRequest).error!);\n };\n cursorRequest.onsuccess = (event: Event) => {\n const cursor: IDBCursorWithValue = (event.target as IDBRequest).result;\n if (!cursor) {\n resolve();\n return;\n }\n const controller = new IterationController(cursor);\n const userResult = fn(\n cursor.primaryKey as KeyType,\n cursor.value,\n controller\n );\n if (userResult instanceof PersistencePromise) {\n const userPromise: PersistencePromise = userResult.catch(\n err => {\n controller.done();\n return PersistencePromise.reject(err);\n }\n );\n results.push(userPromise);\n }\n if (controller.isDone) {\n resolve();\n } else if (controller.skipToKey === null) {\n cursor.continue();\n } else {\n cursor.continue(controller.skipToKey);\n }\n };\n }).next(() => PersistencePromise.waitFor(results));\n }\n\n private options(\n indexOrRange?: string | IDBKeyRange,\n range?: IDBKeyRange\n ): IterateOptions {\n let indexName: string | undefined = undefined;\n if (indexOrRange !== undefined) {\n if (typeof indexOrRange === 'string') {\n indexName = indexOrRange;\n } else {\n debugAssert(\n range === undefined,\n '3rd argument must not be defined if 2nd is a range.'\n );\n range = indexOrRange;\n }\n }\n return { index: indexName, range };\n }\n\n private cursor(options: IterateOptions): IDBRequest {\n let direction: IDBCursorDirection = 'next';\n if (options.reverse) {\n direction = 'prev';\n }\n if (options.index) {\n const index = this.store.index(options.index);\n if (options.keysOnly) {\n return index.openKeyCursor(options.range, direction);\n } else {\n return index.openCursor(options.range, direction);\n }\n } else {\n return this.store.openCursor(options.range, direction);\n }\n }\n}\n\n/**\n * Wraps an IDBRequest in a PersistencePromise, using the onsuccess / onerror\n * handlers to resolve / reject the PersistencePromise as appropriate.\n */\nfunction wrapRequest(request: IDBRequest): PersistencePromise {\n return new PersistencePromise((resolve, reject) => {\n request.onsuccess = (event: Event) => {\n const result = (event.target as IDBRequest).result;\n resolve(result);\n };\n\n request.onerror = (event: Event) => {\n const error = checkForAndReportiOSError(\n (event.target as IDBRequest).error!\n );\n reject(error);\n };\n });\n}\n\n// Guard so we only report the error once.\nlet reportedIOSError = false;\nfunction checkForAndReportiOSError(error: DOMException): Error {\n const iOSVersion = SimpleDb.getIOSVersion(getUA());\n if (iOSVersion >= 12.2 && iOSVersion < 13) {\n const IOS_ERROR =\n 'An internal error was encountered in the Indexed Database server';\n if (error.message.indexOf(IOS_ERROR) >= 0) {\n // Wrap error in a more descriptive one.\n const newError = new FirestoreError(\n 'internal',\n `IOS_INDEXEDDB_BUG1: IndexedDb has thrown '${IOS_ERROR}'. This is likely ` +\n `due to an unavoidable bug in iOS. See https://stackoverflow.com/q/56496296/110915 ` +\n `for details and a potential workaround.`\n );\n if (!reportedIOSError) {\n reportedIOSError = true;\n // Throw a global exception outside of this promise chain, for the user to\n // potentially catch.\n setTimeout(() => {\n throw newError;\n }, 0);\n }\n return newError;\n }\n }\n return error;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirestoreError } from '../api';\nimport { ListenSequence } from '../core/listen_sequence';\nimport { ListenSequenceNumber } from '../core/types';\nimport { debugAssert } from '../util/assert';\nimport { AsyncQueue, DelayedOperation, TimerId } from '../util/async_queue';\nimport { getLogLevel, logDebug, LogLevel } from '../util/log';\nimport { primitiveComparator } from '../util/misc';\nimport { SortedSet } from '../util/sorted_set';\n\nimport { ignoreIfPrimaryLeaseLoss, LocalStore } from './local_store';\nimport {\n ActiveTargets,\n GC_DID_NOT_RUN,\n LRU_COLLECTION_DISABLED,\n LruDelegate,\n LruGarbageCollector,\n LruParams,\n LruResults\n} from './lru_garbage_collector';\nimport { Scheduler } from './persistence';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { isIndexedDbTransactionError } from './simple_db';\n\nconst LOG_TAG = 'LruGarbageCollector';\n\nexport const LRU_MINIMUM_CACHE_SIZE_BYTES = 1 * 1024 * 1024;\n\n/** How long we wait to try running LRU GC after SDK initialization. */\nconst INITIAL_GC_DELAY_MS = 1 * 60 * 1000;\n/** Minimum amount of time between GC checks, after the first one. */\nconst REGULAR_GC_DELAY_MS = 5 * 60 * 1000;\n\n// The type and comparator for the items contained in the SortedSet used in\n// place of a priority queue for the RollingSequenceNumberBuffer.\ntype BufferEntry = [ListenSequenceNumber, number];\n\nfunction bufferEntryComparator(\n [aSequence, aIndex]: BufferEntry,\n [bSequence, bIndex]: BufferEntry\n): number {\n const seqCmp = primitiveComparator(aSequence, bSequence);\n if (seqCmp === 0) {\n // This order doesn't matter, but we can bias against churn by sorting\n // entries created earlier as less than newer entries.\n return primitiveComparator(aIndex, bIndex);\n } else {\n return seqCmp;\n }\n}\n\n/**\n * Used to calculate the nth sequence number. Keeps a rolling buffer of the\n * lowest n values passed to `addElement`, and finally reports the largest of\n * them in `maxValue`.\n */\nclass RollingSequenceNumberBuffer {\n private buffer: SortedSet = new SortedSet(\n bufferEntryComparator\n );\n\n private previousIndex = 0;\n\n constructor(private readonly maxElements: number) {}\n\n private nextIndex(): number {\n return ++this.previousIndex;\n }\n\n addElement(sequenceNumber: ListenSequenceNumber): void {\n const entry: BufferEntry = [sequenceNumber, this.nextIndex()];\n if (this.buffer.size < this.maxElements) {\n this.buffer = this.buffer.add(entry);\n } else {\n const highestValue = this.buffer.last()!;\n if (bufferEntryComparator(entry, highestValue) < 0) {\n this.buffer = this.buffer.delete(highestValue).add(entry);\n }\n }\n }\n\n get maxValue(): ListenSequenceNumber {\n // Guaranteed to be non-empty. If we decide we are not collecting any\n // sequence numbers, nthSequenceNumber below short-circuits. If we have\n // decided that we are collecting n sequence numbers, it's because n is some\n // percentage of the existing sequence numbers. That means we should never\n // be in a situation where we are collecting sequence numbers but don't\n // actually have any.\n return this.buffer.last()![0];\n }\n}\n\n/**\n * This class is responsible for the scheduling of LRU garbage collection. It handles checking\n * whether or not GC is enabled, as well as which delay to use before the next run.\n */\nexport class LruScheduler implements Scheduler {\n private gcTask: DelayedOperation | null;\n\n constructor(\n private readonly garbageCollector: LruGarbageCollector,\n private readonly asyncQueue: AsyncQueue,\n private readonly localStore: LocalStore\n ) {\n this.gcTask = null;\n }\n\n start(): void {\n debugAssert(\n this.gcTask === null,\n 'Cannot start an already started LruScheduler'\n );\n if (\n this.garbageCollector.params.cacheSizeCollectionThreshold !==\n LRU_COLLECTION_DISABLED\n ) {\n this.scheduleGC(INITIAL_GC_DELAY_MS);\n }\n }\n\n stop(): void {\n if (this.gcTask) {\n this.gcTask.cancel();\n this.gcTask = null;\n }\n }\n\n get started(): boolean {\n return this.gcTask !== null;\n }\n\n private scheduleGC(delay: number): void {\n debugAssert(\n this.gcTask === null,\n 'Cannot schedule GC while a task is pending'\n );\n logDebug(LOG_TAG, `Garbage collection scheduled in ${delay}ms`);\n this.gcTask = this.asyncQueue.enqueueAfterDelay(\n TimerId.LruGarbageCollection,\n delay,\n async () => {\n this.gcTask = null;\n try {\n await this.localStore.collectGarbage(this.garbageCollector);\n } catch (e) {\n if (isIndexedDbTransactionError(e as Error)) {\n logDebug(\n LOG_TAG,\n 'Ignoring IndexedDB error during garbage collection: ',\n e\n );\n } else {\n await ignoreIfPrimaryLeaseLoss(e as FirestoreError);\n }\n }\n await this.scheduleGC(REGULAR_GC_DELAY_MS);\n }\n );\n }\n}\n\n/**\n * Implements the steps for LRU garbage collection.\n */\nclass LruGarbageCollectorImpl implements LruGarbageCollector {\n constructor(\n private readonly delegate: LruDelegate,\n readonly params: LruParams\n ) {}\n\n calculateTargetCount(\n txn: PersistenceTransaction,\n percentile: number\n ): PersistencePromise {\n return this.delegate.getSequenceNumberCount(txn).next(targetCount => {\n return Math.floor((percentile / 100.0) * targetCount);\n });\n }\n\n nthSequenceNumber(\n txn: PersistenceTransaction,\n n: number\n ): PersistencePromise {\n if (n === 0) {\n return PersistencePromise.resolve(ListenSequence.INVALID);\n }\n\n const buffer = new RollingSequenceNumberBuffer(n);\n return this.delegate\n .forEachTarget(txn, target => buffer.addElement(target.sequenceNumber))\n .next(() => {\n return this.delegate.forEachOrphanedDocumentSequenceNumber(\n txn,\n sequenceNumber => buffer.addElement(sequenceNumber)\n );\n })\n .next(() => buffer.maxValue);\n }\n\n removeTargets(\n txn: PersistenceTransaction,\n upperBound: ListenSequenceNumber,\n activeTargetIds: ActiveTargets\n ): PersistencePromise {\n return this.delegate.removeTargets(txn, upperBound, activeTargetIds);\n }\n\n removeOrphanedDocuments(\n txn: PersistenceTransaction,\n upperBound: ListenSequenceNumber\n ): PersistencePromise {\n return this.delegate.removeOrphanedDocuments(txn, upperBound);\n }\n\n collect(\n txn: PersistenceTransaction,\n activeTargetIds: ActiveTargets\n ): PersistencePromise {\n if (this.params.cacheSizeCollectionThreshold === LRU_COLLECTION_DISABLED) {\n logDebug('LruGarbageCollector', 'Garbage collection skipped; disabled');\n return PersistencePromise.resolve(GC_DID_NOT_RUN);\n }\n\n return this.getCacheSize(txn).next(cacheSize => {\n if (cacheSize < this.params.cacheSizeCollectionThreshold) {\n logDebug(\n 'LruGarbageCollector',\n `Garbage collection skipped; Cache size ${cacheSize} ` +\n `is lower than threshold ${this.params.cacheSizeCollectionThreshold}`\n );\n return GC_DID_NOT_RUN;\n } else {\n return this.runGarbageCollection(txn, activeTargetIds);\n }\n });\n }\n\n getCacheSize(txn: PersistenceTransaction): PersistencePromise {\n return this.delegate.getCacheSize(txn);\n }\n\n private runGarbageCollection(\n txn: PersistenceTransaction,\n activeTargetIds: ActiveTargets\n ): PersistencePromise {\n let upperBoundSequenceNumber: number;\n let sequenceNumbersToCollect: number, targetsRemoved: number;\n // Timestamps for various pieces of the process\n let countedTargetsTs: number,\n foundUpperBoundTs: number,\n removedTargetsTs: number,\n removedDocumentsTs: number;\n const startTs = Date.now();\n return this.calculateTargetCount(txn, this.params.percentileToCollect)\n .next(sequenceNumbers => {\n // Cap at the configured max\n if (sequenceNumbers > this.params.maximumSequenceNumbersToCollect) {\n logDebug(\n 'LruGarbageCollector',\n 'Capping sequence numbers to collect down ' +\n `to the maximum of ${this.params.maximumSequenceNumbersToCollect} ` +\n `from ${sequenceNumbers}`\n );\n sequenceNumbersToCollect =\n this.params.maximumSequenceNumbersToCollect;\n } else {\n sequenceNumbersToCollect = sequenceNumbers;\n }\n countedTargetsTs = Date.now();\n\n return this.nthSequenceNumber(txn, sequenceNumbersToCollect);\n })\n .next(upperBound => {\n upperBoundSequenceNumber = upperBound;\n foundUpperBoundTs = Date.now();\n\n return this.removeTargets(\n txn,\n upperBoundSequenceNumber,\n activeTargetIds\n );\n })\n .next(numTargetsRemoved => {\n targetsRemoved = numTargetsRemoved;\n removedTargetsTs = Date.now();\n\n return this.removeOrphanedDocuments(txn, upperBoundSequenceNumber);\n })\n .next(documentsRemoved => {\n removedDocumentsTs = Date.now();\n\n if (getLogLevel() <= LogLevel.DEBUG) {\n const desc =\n 'LRU Garbage Collection\\n' +\n `\\tCounted targets in ${countedTargetsTs - startTs}ms\\n` +\n `\\tDetermined least recently used ${sequenceNumbersToCollect} in ` +\n `${foundUpperBoundTs - countedTargetsTs}ms\\n` +\n `\\tRemoved ${targetsRemoved} targets in ` +\n `${removedTargetsTs - foundUpperBoundTs}ms\\n` +\n `\\tRemoved ${documentsRemoved} documents in ` +\n `${removedDocumentsTs - removedTargetsTs}ms\\n` +\n `Total Duration: ${removedDocumentsTs - startTs}ms`;\n logDebug('LruGarbageCollector', desc);\n }\n\n return PersistencePromise.resolve({\n didRun: true,\n sequenceNumbersCollected: sequenceNumbersToCollect,\n targetsRemoved,\n documentsRemoved\n });\n });\n }\n}\n\nexport function newLruGarbageCollector(\n delegate: LruDelegate,\n params: LruParams\n): LruGarbageCollector {\n return new LruGarbageCollectorImpl(delegate, params);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { EmulatorMockTokenOptions } from '@firebase/util';\n\nimport { FirestoreLocalCache } from '../api/cache_config';\nimport { CredentialsSettings } from '../api/credentials';\nimport {\n ExperimentalLongPollingOptions,\n cloneLongPollingOptions,\n longPollingOptionsEqual\n} from '../api/long_polling_options';\nimport {\n LRU_COLLECTION_DISABLED,\n LRU_DEFAULT_CACHE_SIZE_BYTES\n} from '../local/lru_garbage_collector';\nimport { LRU_MINIMUM_CACHE_SIZE_BYTES } from '../local/lru_garbage_collector_impl';\nimport { Code, FirestoreError } from '../util/error';\nimport { validateIsNotUsedTogether } from '../util/input_validation';\n\n// settings() defaults:\nexport const DEFAULT_HOST = 'firestore.googleapis.com';\nexport const DEFAULT_SSL = true;\n\n// The minimum long-polling timeout is hardcoded on the server. The value here\n// should be kept in sync with the value used by the server, as the server will\n// silently ignore a value below the minimum and fall back to the default.\n// Googlers see b/266868871 for relevant discussion.\nconst MIN_LONG_POLLING_TIMEOUT_SECONDS = 5;\n\n// No maximum long-polling timeout is configured in the server, and defaults to\n// 30 seconds, which is what Watch appears to use.\n// Googlers see b/266868871 for relevant discussion.\nconst MAX_LONG_POLLING_TIMEOUT_SECONDS = 30;\n\n// Whether long-polling auto-detected is enabled by default.\nconst DEFAULT_AUTO_DETECT_LONG_POLLING = true;\n\n/**\n * Specifies custom configurations for your Cloud Firestore instance.\n * You must set these before invoking any other methods.\n */\nexport interface FirestoreSettings {\n /** The hostname to connect to. */\n host?: string;\n\n /** Whether to use SSL when connecting. */\n ssl?: boolean;\n\n /**\n * Whether to skip nested properties that are set to `undefined` during\n * object serialization. If set to `true`, these properties are skipped\n * and not written to Firestore. If set to `false` or omitted, the SDK\n * throws an exception when it encounters properties of type `undefined`.\n */\n ignoreUndefinedProperties?: boolean;\n}\n\n/**\n * @internal\n * Undocumented, private additional settings not exposed in our public API.\n */\nexport interface PrivateSettings extends FirestoreSettings {\n // Can be a google-auth-library or gapi client.\n credentials?: CredentialsSettings;\n cacheSizeBytes?: number;\n experimentalForceLongPolling?: boolean;\n experimentalAutoDetectLongPolling?: boolean;\n experimentalLongPollingOptions?: ExperimentalLongPollingOptions;\n useFetchStreams?: boolean;\n emulatorOptions?: { mockUserToken?: EmulatorMockTokenOptions | string };\n\n localCache?: FirestoreLocalCache;\n}\n\n/**\n * A concrete type describing all the values that can be applied via a\n * user-supplied `FirestoreSettings` object. This is a separate type so that\n * defaults can be supplied and the value can be checked for equality.\n */\nexport class FirestoreSettingsImpl {\n /** The hostname to connect to. */\n readonly host: string;\n\n /** Whether to use SSL when connecting. */\n readonly ssl: boolean;\n\n readonly cacheSizeBytes: number;\n\n readonly experimentalForceLongPolling: boolean;\n\n readonly experimentalAutoDetectLongPolling: boolean;\n\n readonly experimentalLongPollingOptions: ExperimentalLongPollingOptions;\n\n readonly ignoreUndefinedProperties: boolean;\n\n readonly useFetchStreams: boolean;\n readonly localCache?: FirestoreLocalCache;\n\n readonly isUsingEmulator: boolean;\n\n // Can be a google-auth-library or gapi client.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n credentials?: any;\n\n constructor(settings: PrivateSettings) {\n if (settings.host === undefined) {\n if (settings.ssl !== undefined) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n \"Can't provide ssl option if host option is not set\"\n );\n }\n this.host = DEFAULT_HOST;\n this.ssl = DEFAULT_SSL;\n } else {\n this.host = settings.host;\n this.ssl = settings.ssl ?? DEFAULT_SSL;\n }\n this.isUsingEmulator = settings.emulatorOptions !== undefined;\n\n this.credentials = settings.credentials;\n this.ignoreUndefinedProperties = !!settings.ignoreUndefinedProperties;\n this.localCache = settings.localCache;\n\n if (settings.cacheSizeBytes === undefined) {\n this.cacheSizeBytes = LRU_DEFAULT_CACHE_SIZE_BYTES;\n } else {\n if (\n settings.cacheSizeBytes !== LRU_COLLECTION_DISABLED &&\n settings.cacheSizeBytes < LRU_MINIMUM_CACHE_SIZE_BYTES\n ) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `cacheSizeBytes must be at least ${LRU_MINIMUM_CACHE_SIZE_BYTES}`\n );\n } else {\n this.cacheSizeBytes = settings.cacheSizeBytes;\n }\n }\n\n validateIsNotUsedTogether(\n 'experimentalForceLongPolling',\n settings.experimentalForceLongPolling,\n 'experimentalAutoDetectLongPolling',\n settings.experimentalAutoDetectLongPolling\n );\n\n this.experimentalForceLongPolling = !!settings.experimentalForceLongPolling;\n\n if (this.experimentalForceLongPolling) {\n this.experimentalAutoDetectLongPolling = false;\n } else if (settings.experimentalAutoDetectLongPolling === undefined) {\n this.experimentalAutoDetectLongPolling = DEFAULT_AUTO_DETECT_LONG_POLLING;\n } else {\n // For backwards compatibility, coerce the value to boolean even though\n // the TypeScript compiler has narrowed the type to boolean already.\n // noinspection PointlessBooleanExpressionJS\n this.experimentalAutoDetectLongPolling =\n !!settings.experimentalAutoDetectLongPolling;\n }\n\n this.experimentalLongPollingOptions = cloneLongPollingOptions(\n settings.experimentalLongPollingOptions ?? {}\n );\n validateLongPollingOptions(this.experimentalLongPollingOptions);\n\n this.useFetchStreams = !!settings.useFetchStreams;\n }\n\n isEqual(other: FirestoreSettingsImpl): boolean {\n return (\n this.host === other.host &&\n this.ssl === other.ssl &&\n this.credentials === other.credentials &&\n this.cacheSizeBytes === other.cacheSizeBytes &&\n this.experimentalForceLongPolling ===\n other.experimentalForceLongPolling &&\n this.experimentalAutoDetectLongPolling ===\n other.experimentalAutoDetectLongPolling &&\n longPollingOptionsEqual(\n this.experimentalLongPollingOptions,\n other.experimentalLongPollingOptions\n ) &&\n this.ignoreUndefinedProperties === other.ignoreUndefinedProperties &&\n this.useFetchStreams === other.useFetchStreams\n );\n }\n}\n\nfunction validateLongPollingOptions(\n options: ExperimentalLongPollingOptions\n): void {\n if (options.timeoutSeconds !== undefined) {\n if (isNaN(options.timeoutSeconds)) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `invalid long polling timeout: ` +\n `${options.timeoutSeconds} (must not be NaN)`\n );\n }\n if (options.timeoutSeconds < MIN_LONG_POLLING_TIMEOUT_SECONDS) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `invalid long polling timeout: ${options.timeoutSeconds} ` +\n `(minimum allowed value is ${MIN_LONG_POLLING_TIMEOUT_SECONDS})`\n );\n }\n if (options.timeoutSeconds > MAX_LONG_POLLING_TIMEOUT_SECONDS) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `invalid long polling timeout: ${options.timeoutSeconds} ` +\n `(maximum allowed value is ${MAX_LONG_POLLING_TIMEOUT_SECONDS})`\n );\n }\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport {\n _getProvider,\n _removeServiceInstance,\n FirebaseApp,\n getApp\n} from '@firebase/app';\nimport {\n createMockUserToken,\n deepEqual,\n EmulatorMockTokenOptions,\n getDefaultEmulatorHostnameAndPort,\n isCloudWorkstation,\n pingServer,\n updateEmulatorBanner\n} from '@firebase/util';\n\nimport {\n CredentialsProvider,\n EmulatorAuthCredentialsProvider,\n makeAuthCredentialsProvider,\n OAuthToken\n} from '../api/credentials';\nimport { User } from '../auth/user';\nimport { DatabaseId, DEFAULT_DATABASE_NAME } from '../core/database_info';\nimport { Code, FirestoreError } from '../util/error';\nimport { cast } from '../util/input_validation';\nimport { logWarn } from '../util/log';\n\nimport { FirestoreService, removeComponents } from './components';\nimport {\n DEFAULT_HOST,\n FirestoreSettingsImpl,\n PrivateSettings,\n FirestoreSettings\n} from './settings';\n\nexport { EmulatorMockTokenOptions } from '@firebase/util';\n\ndeclare module '@firebase/component' {\n interface NameServiceMapping {\n 'firestore/lite': Firestore;\n }\n}\n\n/**\n * The Cloud Firestore service interface.\n *\n * Do not call this constructor directly. Instead, use {@link (getFirestore:1)}.\n */\nexport class Firestore implements FirestoreService {\n /**\n * Whether it's a Firestore or Firestore Lite instance.\n */\n type: 'firestore-lite' | 'firestore' = 'firestore-lite';\n\n readonly _persistenceKey: string = '(lite)';\n\n private _settings = new FirestoreSettingsImpl({});\n private _settingsFrozen = false;\n private _emulatorOptions: {\n mockUserToken?: EmulatorMockTokenOptions | string;\n } = {};\n\n // A task that is assigned when the terminate() is invoked and resolved when\n // all components have shut down. Otherwise, Firestore is not terminated,\n // which can mean either the FirestoreClient is in the process of starting,\n // or restarting.\n private _terminateTask: Promise | 'notTerminated' = 'notTerminated';\n\n /** @hideconstructor */\n constructor(\n public _authCredentials: CredentialsProvider,\n public _appCheckCredentials: CredentialsProvider,\n readonly _databaseId: DatabaseId,\n readonly _app?: FirebaseApp\n ) {}\n\n /**\n * The {@link @firebase/app#FirebaseApp} associated with this `Firestore` service\n * instance.\n */\n get app(): FirebaseApp {\n if (!this._app) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n \"Firestore was not initialized using the Firebase SDK. 'app' is \" +\n 'not available'\n );\n }\n return this._app;\n }\n\n get _initialized(): boolean {\n return this._settingsFrozen;\n }\n\n get _terminated(): boolean {\n return this._terminateTask !== 'notTerminated';\n }\n\n _setSettings(settings: PrivateSettings): void {\n if (this._settingsFrozen) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'Firestore has already been started and its settings can no longer ' +\n 'be changed. You can only modify settings before calling any other ' +\n 'methods on a Firestore object.'\n );\n }\n this._settings = new FirestoreSettingsImpl(settings);\n this._emulatorOptions = settings.emulatorOptions || {};\n\n if (settings.credentials !== undefined) {\n this._authCredentials = makeAuthCredentialsProvider(settings.credentials);\n }\n }\n\n _getSettings(): FirestoreSettingsImpl {\n return this._settings;\n }\n\n _getEmulatorOptions(): { mockUserToken?: EmulatorMockTokenOptions | string } {\n return this._emulatorOptions;\n }\n\n _freezeSettings(): FirestoreSettingsImpl {\n this._settingsFrozen = true;\n return this._settings;\n }\n\n _delete(): Promise {\n // The `_terminateTask` must be assigned future that completes when\n // terminate is complete. The existence of this future puts SDK in state\n // that will not accept further API interaction.\n if (this._terminateTask === 'notTerminated') {\n this._terminateTask = this._terminate();\n }\n return this._terminateTask;\n }\n\n async _restart(): Promise {\n // The `_terminateTask` must equal 'notTerminated' after restart to\n // signal that client is in a state that accepts API calls.\n if (this._terminateTask === 'notTerminated') {\n await this._terminate();\n } else {\n this._terminateTask = 'notTerminated';\n }\n }\n\n /** Returns a JSON-serializable representation of this `Firestore` instance. */\n toJSON(): object {\n return {\n app: this._app,\n databaseId: this._databaseId,\n settings: this._settings\n };\n }\n\n /**\n * Terminates all components used by this client. Subclasses can override\n * this method to clean up their own dependencies, but must also call this\n * method.\n *\n * Only ever called once.\n */\n protected _terminate(): Promise {\n removeComponents(this);\n return Promise.resolve();\n }\n}\n\n/**\n * Initializes a new instance of Cloud Firestore with the provided settings.\n * Can only be called before any other functions, including\n * {@link (getFirestore:1)}. If the custom settings are empty, this function is\n * equivalent to calling {@link (getFirestore:1)}.\n *\n * @param app - The {@link @firebase/app#FirebaseApp} with which the `Firestore` instance will\n * be associated.\n * @param settings - A settings object to configure the `Firestore` instance.\n * @returns A newly initialized `Firestore` instance.\n */\nexport function initializeFirestore(\n app: FirebaseApp,\n settings: FirestoreSettings\n): Firestore;\n/**\n * Initializes a new instance of Cloud Firestore with the provided settings.\n * Can only be called before any other functions, including\n * {@link (getFirestore:1)}. If the custom settings are empty, this function is\n * equivalent to calling {@link (getFirestore:1)}.\n *\n * @param app - The {@link @firebase/app#FirebaseApp} with which the `Firestore` instance will\n * be associated.\n * @param settings - A settings object to configure the `Firestore` instance.\n * @param databaseId - The name of the database.\n * @returns A newly initialized `Firestore` instance.\n * @beta\n */\nexport function initializeFirestore(\n app: FirebaseApp,\n settings: FirestoreSettings,\n databaseId?: string\n): Firestore;\nexport function initializeFirestore(\n app: FirebaseApp,\n settings: FirestoreSettings,\n databaseId?: string\n): Firestore {\n if (!databaseId) {\n databaseId = DEFAULT_DATABASE_NAME;\n }\n const provider = _getProvider(app, 'firestore/lite');\n\n if (provider.isInitialized(databaseId)) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'Firestore can only be initialized once per app.'\n );\n }\n\n return provider.initialize({\n options: settings,\n instanceIdentifier: databaseId\n });\n}\n\n/**\n * Returns the existing default {@link Firestore} instance that is associated with the\n * default {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new\n * instance with default settings.\n *\n * @returns The {@link Firestore} instance of the provided app.\n */\nexport function getFirestore(): Firestore;\n/**\n * Returns the existing default {@link Firestore} instance that is associated with the\n * provided {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new\n * instance with default settings.\n *\n * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned {@link Firestore}\n * instance is associated with.\n * @returns The {@link Firestore} instance of the provided app.\n */\nexport function getFirestore(app: FirebaseApp): Firestore;\n/**\n * Returns the existing {@link Firestore} instance that is associated with the\n * default {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new\n * instance with default settings.\n *\n * @param databaseId - The name of the database.\n * @returns The {@link Firestore} instance of the provided app.\n * @beta\n */\nexport function getFirestore(databaseId: string): Firestore;\n/**\n * Returns the existing {@link Firestore} instance that is associated with the\n * provided {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new\n * instance with default settings.\n *\n * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned {@link Firestore}\n * instance is associated with.\n * @param databaseId - The name of the database.\n * @returns The {@link Firestore} instance of the provided app.\n * @beta\n */\nexport function getFirestore(app: FirebaseApp, databaseId: string): Firestore;\nexport function getFirestore(\n appOrDatabaseId?: FirebaseApp | string,\n optionalDatabaseId?: string\n): Firestore {\n const app: FirebaseApp =\n typeof appOrDatabaseId === 'object' ? appOrDatabaseId : getApp();\n const databaseId =\n typeof appOrDatabaseId === 'string'\n ? appOrDatabaseId\n : optionalDatabaseId || '(default)';\n const db = _getProvider(app, 'firestore/lite').getImmediate({\n identifier: databaseId\n }) as Firestore;\n if (!db._initialized) {\n const emulator = getDefaultEmulatorHostnameAndPort('firestore');\n if (emulator) {\n connectFirestoreEmulator(db, ...emulator);\n }\n }\n return db;\n}\n\n/**\n * Modify this instance to communicate with the Cloud Firestore emulator.\n *\n * Note: This must be called before this instance has been used to do any\n * operations.\n *\n * @param firestore - The `Firestore` instance to configure to connect to the\n * emulator.\n * @param host - the emulator host (ex: localhost).\n * @param port - the emulator port (ex: 9000).\n * @param options.mockUserToken - the mock auth token to use for unit testing\n * Security Rules.\n */\nexport function connectFirestoreEmulator(\n firestore: Firestore,\n host: string,\n port: number,\n options: {\n mockUserToken?: EmulatorMockTokenOptions | string;\n } = {}\n): void {\n firestore = cast(firestore, Firestore);\n const useSsl = isCloudWorkstation(host);\n const settings = firestore._getSettings();\n const existingConfig = {\n ...settings,\n emulatorOptions: firestore._getEmulatorOptions()\n };\n const newHostSetting = `${host}:${port}`;\n if (useSsl) {\n void pingServer(`https://${newHostSetting}`);\n updateEmulatorBanner('Firestore', true);\n }\n if (settings.host !== DEFAULT_HOST && settings.host !== newHostSetting) {\n logWarn(\n 'Host has been set in both settings() and connectFirestoreEmulator(), emulator host ' +\n 'will be used.'\n );\n }\n const newConfig = {\n ...settings,\n host: newHostSetting,\n ssl: useSsl,\n emulatorOptions: options\n };\n // No-op if the new configuration matches the current configuration. This supports SSR\n // enviornments which might call `connectFirestoreEmulator` multiple times as a standard practice.\n if (deepEqual(newConfig, existingConfig)) {\n return;\n }\n\n firestore._setSettings(newConfig);\n\n if (options.mockUserToken) {\n let token: string;\n let user: User;\n if (typeof options.mockUserToken === 'string') {\n token = options.mockUserToken;\n user = User.MOCK_USER;\n } else {\n // Let createMockUserToken validate first (catches common mistakes like\n // invalid field \"uid\" and missing field \"sub\" / \"user_id\".)\n token = createMockUserToken(\n options.mockUserToken,\n firestore._app?.options.projectId\n );\n const uid = options.mockUserToken.sub || options.mockUserToken.user_id;\n if (!uid) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n \"mockUserToken must contain 'sub' or 'user_id' field!\"\n );\n }\n user = new User(uid);\n }\n\n firestore._authCredentials = new EmulatorAuthCredentialsProvider(\n new OAuthToken(token, user)\n );\n }\n}\n\n/**\n * Terminates the provided `Firestore` instance.\n *\n * After calling `terminate()` only the `clearIndexedDbPersistence()` functions\n * may be used. Any other function will throw a `FirestoreError`. Termination\n * does not cancel any pending writes, and any promises that are awaiting a\n * response from the server will not be resolved.\n *\n * To restart after termination, create a new instance of `Firestore` with\n * {@link (getFirestore:1)}.\n *\n * Note: Under normal circumstances, calling `terminate()` is not required. This\n * function is useful only when you want to force this instance to release all of\n * its resources or in combination with {@link clearIndexedDbPersistence} to\n * ensure that all local state is destroyed between test runs.\n *\n * @param firestore - The `Firestore` instance to terminate.\n * @returns A `Promise` that is resolved when the instance has been successfully\n * terminated.\n */\nexport function terminate(firestore: Firestore): Promise {\n firestore = cast(firestore, Firestore);\n _removeServiceInstance(firestore.app, 'firestore/lite');\n return firestore._delete();\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n _registerComponent,\n registerVersion,\n SDK_VERSION\n} from '@firebase/app';\nimport { Component, ComponentType } from '@firebase/component';\n\nimport { version } from '../package.json';\nimport {\n LiteAppCheckTokenProvider,\n LiteAuthCredentialsProvider\n} from '../src/api/credentials';\nimport { databaseIdFromApp } from '../src/core/database_info';\nimport { setSDKVersion } from '../src/core/version';\nimport { Firestore } from '../src/lite-api/database';\n\ndeclare module '@firebase/component' {\n interface NameServiceMapping {\n 'firestore/lite': Firestore;\n }\n}\n\nexport function registerFirestore(): void {\n setSDKVersion(`${SDK_VERSION}_lite`);\n _registerComponent(\n new Component(\n 'firestore/lite',\n (container, { instanceIdentifier: databaseId, options: settings }) => {\n const app = container.getProvider('app').getImmediate()!;\n const firestoreInstance = new Firestore(\n new LiteAuthCredentialsProvider(\n container.getProvider('auth-internal')\n ),\n new LiteAppCheckTokenProvider(\n app,\n container.getProvider('app-check-internal')\n ),\n databaseIdFromApp(app, databaseId),\n app\n );\n if (settings) {\n firestoreInstance._setSettings(settings);\n }\n return firestoreInstance;\n },\n 'PUBLIC' as ComponentType.PUBLIC\n ).setMultipleInstances(true)\n );\n // RUNTIME_ENV and BUILD_TARGET are replaced by real values during the compilation\n registerVersion('firestore-lite', version, '__RUNTIME_ENV__');\n registerVersion('firestore-lite', version, '__BUILD_TARGET__');\n}\n","/**\n * @license\n * Copyright 2023 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FieldPath } from '../model/path';\n\n/**\n * Union type representing the aggregate type to be performed.\n */\nexport type AggregateType = 'count' | 'avg' | 'sum';\n\n/**\n * Represents an Aggregate to be performed over a query result set.\n */\nexport interface Aggregate {\n readonly fieldPath?: FieldPath;\n readonly alias: string;\n readonly aggregateType: AggregateType;\n}\n\n/**\n * Concrete implementation of the Aggregate type.\n */\nexport class AggregateImpl implements Aggregate {\n constructor(\n readonly alias: string,\n readonly aggregateType: AggregateType,\n readonly fieldPath?: FieldPath\n ) {}\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { AggregateType } from '../core/aggregate';\nimport { FieldPath as InternalFieldPath } from '../model/path';\nimport { ApiClientObjectMap, Value } from '../protos/firestore_proto_api';\n\nimport { average, count, sum } from './aggregate';\nimport { DocumentData, Query } from './reference';\nimport { AbstractUserDataWriter } from './user_data_writer';\n\nexport { AggregateType };\n\n/**\n * Represents an aggregation that can be performed by Firestore.\n */\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport class AggregateField {\n /** A type string to uniquely identify instances of this class. */\n readonly type = 'AggregateField';\n\n /** Indicates the aggregation operation of this AggregateField. */\n readonly aggregateType: AggregateType;\n\n /**\n * Create a new AggregateField\n * @param aggregateType Specifies the type of aggregation operation to perform.\n * @param _internalFieldPath Optionally specifies the field that is aggregated.\n * @internal\n */\n constructor(\n aggregateType: AggregateType = 'count',\n readonly _internalFieldPath?: InternalFieldPath\n ) {\n this.aggregateType = aggregateType;\n }\n}\n\n/**\n * The union of all `AggregateField` types that are supported by Firestore.\n */\nexport type AggregateFieldType =\n | ReturnType\n | ReturnType\n | ReturnType;\n\n/**\n * Specifies a set of aggregations and their aliases.\n */\nexport interface AggregateSpec {\n [field: string]: AggregateFieldType;\n}\n\n/**\n * A type whose keys are taken from an `AggregateSpec`, and whose values are the\n * result of the aggregation performed by the corresponding `AggregateField`\n * from the input `AggregateSpec`.\n */\nexport type AggregateSpecData = {\n [P in keyof T]: T[P] extends AggregateField ? U : never;\n};\n\n/**\n * The results of executing an aggregation query.\n */\nexport class AggregateQuerySnapshot<\n AggregateSpecType extends AggregateSpec,\n AppModelType = DocumentData,\n DbModelType extends DocumentData = DocumentData\n> {\n /** A type string to uniquely identify instances of this class. */\n readonly type = 'AggregateQuerySnapshot';\n\n /**\n * The underlying query over which the aggregations recorded in this\n * `AggregateQuerySnapshot` were performed.\n */\n readonly query: Query;\n\n /** @hideconstructor */\n constructor(\n query: Query,\n private readonly _userDataWriter: AbstractUserDataWriter,\n private readonly _data: ApiClientObjectMap\n ) {\n this.query = query;\n }\n\n /**\n * Returns the results of the aggregations performed over the underlying\n * query.\n *\n * The keys of the returned object will be the same as those of the\n * `AggregateSpec` object specified to the aggregation method, and the values\n * will be the corresponding aggregation result.\n *\n * @returns The results of the aggregations performed over the underlying\n * query.\n */\n data(): AggregateSpecData {\n return this._userDataWriter.convertObjectMap(\n this._data\n ) as AggregateSpecData;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getModularInstance } from '@firebase/util';\n\nimport {\n newQueryForCollectionGroup,\n newQueryForPath,\n Query as InternalQuery,\n queryEquals\n} from '../core/query';\nimport { DocumentKey } from '../model/document_key';\nimport { ResourcePath } from '../model/path';\nimport { Code, FirestoreError } from '../util/error';\nimport {\n cast,\n validateCollectionPath,\n validateDocumentPath,\n validateNonEmptyArgument\n} from '../util/input_validation';\n// API extractor fails importing property unless we also explicitly import Property.\n// eslint-disable-next-line @typescript-eslint/no-unused-vars, unused-imports/no-unused-imports-ts\nimport { Property, property, validateJSON } from '../util/json_validation';\nimport { AutoId } from '../util/misc';\n\nimport { Firestore } from './database';\nimport { FieldPath } from './field_path';\nimport { FieldValue } from './field_value';\nimport { FirestoreDataConverter } from './snapshot';\nimport { NestedUpdateFields, Primitive } from './types';\n\n/**\n * Document data (for use with {@link @firebase/firestore/lite#(setDoc:1)}) consists of fields mapped to\n * values.\n */\nexport interface DocumentData {\n /** A mapping between a field and its value. */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [field: string]: any;\n}\n\n/**\n * Similar to TypeScript's `Partial`, but allows nested fields to be\n * omitted and FieldValues to be passed in as property values.\n */\nexport type PartialWithFieldValue =\n | Partial\n | (T extends Primitive\n ? T\n : T extends {}\n ? { [K in keyof T]?: PartialWithFieldValue | FieldValue }\n : never);\n\n/**\n * Allows FieldValues to be passed in as a property value while maintaining\n * type safety.\n */\nexport type WithFieldValue =\n | T\n | (T extends Primitive\n ? T\n : T extends {}\n ? { [K in keyof T]: WithFieldValue | FieldValue }\n : never);\n\n/**\n * Update data (for use with {@link (updateDoc:1)}) that consists of field paths\n * (e.g. 'foo' or 'foo.baz') mapped to values. Fields that contain dots\n * reference nested fields within the document. FieldValues can be passed in\n * as property values.\n */\nexport type UpdateData = T extends Primitive\n ? T\n : T extends {}\n ? { [K in keyof T]?: UpdateData | FieldValue } & NestedUpdateFields\n : Partial;\n/**\n * An options object that configures the behavior of {@link @firebase/firestore/lite#(setDoc:1)}, {@link\n * @firebase/firestore/lite#(WriteBatch.set:1)} and {@link @firebase/firestore/lite#(Transaction.set:1)} calls. These calls can be\n * configured to perform granular merges instead of overwriting the target\n * documents in their entirety by providing a `SetOptions` with `merge: true`.\n *\n * @param merge - Changes the behavior of a `setDoc()` call to only replace the\n * values specified in its data argument. Fields omitted from the `setDoc()`\n * call remain untouched. If your input sets any field to an empty map, all\n * nested fields are overwritten.\n * @param mergeFields - Changes the behavior of `setDoc()` calls to only replace\n * the specified field paths. Any field path that is not specified is ignored\n * and remains untouched. If your input sets any field to an empty map, all\n * nested fields are overwritten.\n */\nexport type SetOptions =\n | {\n readonly merge?: boolean;\n }\n | {\n readonly mergeFields?: Array;\n };\n\n/**\n * A `Query` refers to a query which you can read or listen to. You can also\n * construct refined `Query` objects by adding filters and ordering.\n */\nexport class Query<\n AppModelType = DocumentData,\n DbModelType extends DocumentData = DocumentData\n> {\n /** The type of this Firestore reference. */\n readonly type: 'query' | 'collection' = 'query';\n\n /**\n * The `Firestore` instance for the Firestore database (useful for performing\n * transactions, etc.).\n */\n readonly firestore: Firestore;\n\n // This is the lite version of the Query class in the main SDK.\n\n /** @hideconstructor protected */\n constructor(\n firestore: Firestore,\n /**\n * If provided, the `FirestoreDataConverter` associated with this instance.\n */\n readonly converter: FirestoreDataConverter<\n AppModelType,\n DbModelType\n > | null,\n readonly _query: InternalQuery\n ) {\n this.firestore = firestore;\n }\n\n /**\n * Removes the current converter.\n *\n * @param converter - `null` removes the current converter.\n * @returns A `Query` that does not use a\n * converter.\n */\n withConverter(converter: null): Query;\n /**\n * Applies a custom data converter to this query, allowing you to use your own\n * custom model objects with Firestore. When you call {@link getDocs} with\n * the returned query, the provided converter will convert between Firestore\n * data of type `NewDbModelType` and your custom type `NewAppModelType`.\n *\n * @param converter - Converts objects to and from Firestore.\n * @returns A `Query` that uses the provided converter.\n */\n withConverter<\n NewAppModelType,\n NewDbModelType extends DocumentData = DocumentData\n >(\n converter: FirestoreDataConverter\n ): Query;\n withConverter<\n NewAppModelType,\n NewDbModelType extends DocumentData = DocumentData\n >(\n converter: FirestoreDataConverter | null\n ): Query {\n return new Query(\n this.firestore,\n converter,\n this._query\n );\n }\n}\n\n/**\n * A `DocumentReference` refers to a document location in a Firestore database\n * and can be used to write, read, or listen to the location. The document at\n * the referenced location may or may not exist.\n */\nexport class DocumentReference<\n AppModelType = DocumentData,\n DbModelType extends DocumentData = DocumentData\n> {\n /** The type of this Firestore reference. */\n readonly type = 'document';\n\n /**\n * The {@link Firestore} instance the document is in.\n * This is useful for performing transactions, for example.\n */\n readonly firestore: Firestore;\n\n /** @hideconstructor */\n constructor(\n firestore: Firestore,\n /**\n * If provided, the `FirestoreDataConverter` associated with this instance.\n */\n readonly converter: FirestoreDataConverter<\n AppModelType,\n DbModelType\n > | null,\n readonly _key: DocumentKey\n ) {\n this.firestore = firestore;\n }\n\n get _path(): ResourcePath {\n return this._key.path;\n }\n\n /**\n * The document's identifier within its collection.\n */\n get id(): string {\n return this._key.path.lastSegment();\n }\n\n /**\n * A string representing the path of the referenced document (relative\n * to the root of the database).\n */\n get path(): string {\n return this._key.path.canonicalString();\n }\n\n /**\n * The collection this `DocumentReference` belongs to.\n */\n get parent(): CollectionReference {\n return new CollectionReference(\n this.firestore,\n this.converter,\n this._key.path.popLast()\n );\n }\n\n /**\n * Applies a custom data converter to this `DocumentReference`, allowing you\n * to use your own custom model objects with Firestore. When you call {@link\n * @firebase/firestore/lite#(setDoc:1)}, {@link @firebase/firestore/lite#getDoc}, etc. with the returned `DocumentReference`\n * instance, the provided converter will convert between Firestore data of\n * type `NewDbModelType` and your custom type `NewAppModelType`.\n *\n * @param converter - Converts objects to and from Firestore.\n * @returns A `DocumentReference` that uses the provided converter.\n */\n withConverter<\n NewAppModelType,\n NewDbModelType extends DocumentData = DocumentData\n >(\n converter: FirestoreDataConverter\n ): DocumentReference;\n /**\n * Removes the current converter.\n *\n * @param converter - `null` removes the current converter.\n * @returns A `DocumentReference` that does not\n * use a converter.\n */\n withConverter(converter: null): DocumentReference;\n withConverter<\n NewAppModelType,\n NewDbModelType extends DocumentData = DocumentData\n >(\n converter: FirestoreDataConverter | null\n ): DocumentReference {\n return new DocumentReference(\n this.firestore,\n converter,\n this._key\n );\n }\n\n static _jsonSchemaVersion: string = 'firestore/documentReference/1.0';\n static _jsonSchema = {\n type: property('string', DocumentReference._jsonSchemaVersion),\n referencePath: property('string')\n };\n\n /**\n * Returns a JSON-serializable representation of this `DocumentReference` instance.\n *\n * @returns a JSON representation of this object.\n */\n toJSON(): object {\n return {\n type: DocumentReference._jsonSchemaVersion,\n referencePath: this._key.toString()\n };\n }\n\n /**\n * Builds a `DocumentReference` instance from a JSON object created by\n * {@link DocumentReference.toJSON}.\n *\n * @param firestore - The {@link Firestore} instance the snapshot should be loaded for.\n * @param json a JSON object represention of a `DocumentReference` instance\n * @returns an instance of {@link DocumentReference} if the JSON object could be parsed. Throws a\n * {@link FirestoreError} if an error occurs.\n */\n static fromJSON(firestore: Firestore, json: object): DocumentReference;\n /**\n * Builds a `DocumentReference` instance from a JSON object created by\n * {@link DocumentReference.toJSON}.\n *\n * @param firestore - The {@link Firestore} instance the snapshot should be loaded for.\n * @param json a JSON object represention of a `DocumentReference` instance\n * @param converter - Converts objects to and from Firestore.\n * @returns an instance of {@link DocumentReference} if the JSON object could be parsed. Throws a\n * {@link FirestoreError} if an error occurs.\n */\n static fromJSON<\n NewAppModelType = DocumentData,\n NewDbModelType extends DocumentData = DocumentData\n >(\n firestore: Firestore,\n json: object,\n converter: FirestoreDataConverter\n ): DocumentReference;\n static fromJSON<\n NewAppModelType = DocumentData,\n NewDbModelType extends DocumentData = DocumentData\n >(\n firestore: Firestore,\n json: object,\n converter?: FirestoreDataConverter\n ): DocumentReference {\n if (validateJSON(json, DocumentReference._jsonSchema)) {\n return new DocumentReference(\n firestore,\n converter ? converter : null,\n new DocumentKey(ResourcePath.fromString(json.referencePath))\n );\n }\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Unexpected error creating Bytes from JSON.'\n );\n }\n}\n\n/**\n * A `CollectionReference` object can be used for adding documents, getting\n * document references, and querying for documents (using {@link (query:1)}).\n */\nexport class CollectionReference<\n AppModelType = DocumentData,\n DbModelType extends DocumentData = DocumentData\n> extends Query {\n /** The type of this Firestore reference. */\n readonly type = 'collection';\n\n /** @hideconstructor */\n constructor(\n firestore: Firestore,\n converter: FirestoreDataConverter | null,\n readonly _path: ResourcePath\n ) {\n super(firestore, converter, newQueryForPath(_path));\n }\n\n /** The collection's identifier. */\n get id(): string {\n return this._query.path.lastSegment();\n }\n\n /**\n * A string representing the path of the referenced collection (relative\n * to the root of the database).\n */\n get path(): string {\n return this._query.path.canonicalString();\n }\n\n /**\n * A reference to the containing `DocumentReference` if this is a\n * subcollection. If this isn't a subcollection, the reference is null.\n */\n get parent(): DocumentReference | null {\n const parentPath = this._path.popLast();\n if (parentPath.isEmpty()) {\n return null;\n } else {\n return new DocumentReference(\n this.firestore,\n /* converter= */ null,\n new DocumentKey(parentPath)\n );\n }\n }\n\n /**\n * Applies a custom data converter to this `CollectionReference`, allowing you\n * to use your own custom model objects with Firestore. When you call {@link\n * addDoc} with the returned `CollectionReference` instance, the provided\n * converter will convert between Firestore data of type `NewDbModelType` and\n * your custom type `NewAppModelType`.\n *\n * @param converter - Converts objects to and from Firestore.\n * @returns A `CollectionReference` that uses the provided converter.\n */\n withConverter<\n NewAppModelType,\n NewDbModelType extends DocumentData = DocumentData\n >(\n converter: FirestoreDataConverter\n ): CollectionReference;\n /**\n * Removes the current converter.\n *\n * @param converter - `null` removes the current converter.\n * @returns A `CollectionReference` that does not\n * use a converter.\n */\n withConverter(\n converter: null\n ): CollectionReference;\n withConverter<\n NewAppModelType,\n NewDbModelType extends DocumentData = DocumentData\n >(\n converter: FirestoreDataConverter | null\n ): CollectionReference {\n return new CollectionReference(\n this.firestore,\n converter,\n this._path\n );\n }\n}\n\n/**\n * Gets a `CollectionReference` instance that refers to the collection at\n * the specified absolute path.\n *\n * @param firestore - A reference to the root `Firestore` instance.\n * @param path - A slash-separated path to a collection.\n * @param pathSegments - Additional path segments to apply relative to the first\n * argument.\n * @throws If the final path has an even number of segments and does not point\n * to a collection.\n * @returns The `CollectionReference` instance.\n */\nexport function collection(\n firestore: Firestore,\n path: string,\n ...pathSegments: string[]\n): CollectionReference;\n/**\n * Gets a `CollectionReference` instance that refers to a subcollection of\n * `reference` at the specified relative path.\n *\n * @param reference - A reference to a collection.\n * @param path - A slash-separated path to a collection.\n * @param pathSegments - Additional path segments to apply relative to the first\n * argument.\n * @throws If the final path has an even number of segments and does not point\n * to a collection.\n * @returns The `CollectionReference` instance.\n */\nexport function collection(\n reference: CollectionReference,\n path: string,\n ...pathSegments: string[]\n): CollectionReference;\n/**\n * Gets a `CollectionReference` instance that refers to a subcollection of\n * `reference` at the specified relative path.\n *\n * @param reference - A reference to a Firestore document.\n * @param path - A slash-separated path to a collection.\n * @param pathSegments - Additional path segments that will be applied relative\n * to the first argument.\n * @throws If the final path has an even number of segments and does not point\n * to a collection.\n * @returns The `CollectionReference` instance.\n */\nexport function collection(\n reference: DocumentReference,\n path: string,\n ...pathSegments: string[]\n): CollectionReference;\nexport function collection(\n parent:\n | Firestore\n | DocumentReference\n | CollectionReference,\n path: string,\n ...pathSegments: string[]\n): CollectionReference {\n parent = getModularInstance(parent);\n\n validateNonEmptyArgument('collection', 'path', path);\n if (parent instanceof Firestore) {\n const absolutePath = ResourcePath.fromString(path, ...pathSegments);\n validateCollectionPath(absolutePath);\n return new CollectionReference(parent, /* converter= */ null, absolutePath);\n } else {\n if (\n !(parent instanceof DocumentReference) &&\n !(parent instanceof CollectionReference)\n ) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Expected first argument to collection() to be a CollectionReference, ' +\n 'a DocumentReference or FirebaseFirestore'\n );\n }\n const absolutePath = parent._path.child(\n ResourcePath.fromString(path, ...pathSegments)\n );\n validateCollectionPath(absolutePath);\n return new CollectionReference(\n parent.firestore,\n /* converter= */ null,\n absolutePath\n );\n }\n}\n\n// TODO(firestorelite): Consider using ErrorFactory -\n// https://github.com/firebase/firebase-js-sdk/blob/0131e1f/packages/util/src/errors.ts#L106\n\n/**\n * Creates and returns a new `Query` instance that includes all documents in the\n * database that are contained in a collection or subcollection with the\n * given `collectionId`.\n *\n * @param firestore - A reference to the root `Firestore` instance.\n * @param collectionId - Identifies the collections to query over. Every\n * collection or subcollection with this ID as the last segment of its path\n * will be included. Cannot contain a slash.\n * @returns The created `Query`.\n */\nexport function collectionGroup(\n firestore: Firestore,\n collectionId: string\n): Query {\n firestore = cast(firestore, Firestore);\n\n validateNonEmptyArgument('collectionGroup', 'collection id', collectionId);\n if (collectionId.indexOf('/') >= 0) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid collection ID '${collectionId}' passed to function ` +\n `collectionGroup(). Collection IDs must not contain '/'.`\n );\n }\n\n return new Query(\n firestore,\n /* converter= */ null,\n newQueryForCollectionGroup(collectionId)\n );\n}\n\n/**\n * Gets a `DocumentReference` instance that refers to the document at the\n * specified absolute path.\n *\n * @param firestore - A reference to the root `Firestore` instance.\n * @param path - A slash-separated path to a document.\n * @param pathSegments - Additional path segments that will be applied relative\n * to the first argument.\n * @throws If the final path has an odd number of segments and does not point to\n * a document.\n * @returns The `DocumentReference` instance.\n */\nexport function doc(\n firestore: Firestore,\n path: string,\n ...pathSegments: string[]\n): DocumentReference;\n/**\n * Gets a `DocumentReference` instance that refers to a document within\n * `reference` at the specified relative path. If no path is specified, an\n * automatically-generated unique ID will be used for the returned\n * `DocumentReference`.\n *\n * @param reference - A reference to a collection.\n * @param path - A slash-separated path to a document. Has to be omitted to use\n * auto-generated IDs.\n * @param pathSegments - Additional path segments that will be applied relative\n * to the first argument.\n * @throws If the final path has an odd number of segments and does not point to\n * a document.\n * @returns The `DocumentReference` instance.\n */\nexport function doc(\n reference: CollectionReference,\n path?: string,\n ...pathSegments: string[]\n): DocumentReference;\n/**\n * Gets a `DocumentReference` instance that refers to a document within\n * `reference` at the specified relative path.\n *\n * @param reference - A reference to a Firestore document.\n * @param path - A slash-separated path to a document.\n * @param pathSegments - Additional path segments that will be applied relative\n * to the first argument.\n * @throws If the final path has an odd number of segments and does not point to\n * a document.\n * @returns The `DocumentReference` instance.\n */\nexport function doc(\n reference: DocumentReference,\n path: string,\n ...pathSegments: string[]\n): DocumentReference;\nexport function doc(\n parent:\n | Firestore\n | CollectionReference\n | DocumentReference,\n path?: string,\n ...pathSegments: string[]\n): DocumentReference {\n parent = getModularInstance(parent);\n\n // We allow omission of 'pathString' but explicitly prohibit passing in both\n // 'undefined' and 'null'.\n if (arguments.length === 1) {\n path = AutoId.newId();\n }\n validateNonEmptyArgument('doc', 'path', path);\n\n if (parent instanceof Firestore) {\n const absolutePath = ResourcePath.fromString(path, ...pathSegments);\n validateDocumentPath(absolutePath);\n return new DocumentReference(\n parent,\n /* converter= */ null,\n new DocumentKey(absolutePath)\n );\n } else {\n if (\n !(parent instanceof DocumentReference) &&\n !(parent instanceof CollectionReference)\n ) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Expected first argument to collection() to be a CollectionReference, ' +\n 'a DocumentReference or FirebaseFirestore'\n );\n }\n const absolutePath = parent._path.child(\n ResourcePath.fromString(path, ...pathSegments)\n );\n validateDocumentPath(absolutePath);\n return new DocumentReference(\n parent.firestore,\n parent instanceof CollectionReference ? parent.converter : null,\n new DocumentKey(absolutePath)\n );\n }\n}\n\n/**\n * Returns true if the provided references are equal.\n *\n * @param left - A reference to compare.\n * @param right - A reference to compare.\n * @returns true if the references point to the same location in the same\n * Firestore database.\n */\nexport function refEqual(\n left:\n | DocumentReference\n | CollectionReference,\n right:\n | DocumentReference\n | CollectionReference\n): boolean {\n left = getModularInstance(left);\n right = getModularInstance(right);\n\n if (\n (left instanceof DocumentReference ||\n left instanceof CollectionReference) &&\n (right instanceof DocumentReference || right instanceof CollectionReference)\n ) {\n return (\n left.firestore === right.firestore &&\n left.path === right.path &&\n left.converter === right.converter\n );\n }\n return false;\n}\n\n/**\n * Returns true if the provided queries point to the same collection and apply\n * the same constraints.\n *\n * @param left - A `Query` to compare.\n * @param right - A `Query` to compare.\n * @returns true if the references point to the same location in the same\n * Firestore database.\n */\nexport function queryEqual(\n left: Query,\n right: Query\n): boolean {\n left = getModularInstance(left);\n right = getModularInstance(right);\n\n if (left instanceof Query && right instanceof Query) {\n return (\n left.firestore === right.firestore &&\n queryEquals(left._query, right._query) &&\n left.converter === right.converter\n );\n }\n return false;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ByteString } from '../util/byte_string';\nimport { Code, FirestoreError } from '../util/error';\n// API extractor fails importing property unless we also explicitly import Property.\n// eslint-disable-next-line @typescript-eslint/no-unused-vars, unused-imports/no-unused-imports-ts\nimport { Property, property, validateJSON } from '../util/json_validation';\n\n/**\n * An immutable object representing an array of bytes.\n */\nexport class Bytes {\n _byteString: ByteString;\n\n /** @hideconstructor */\n constructor(byteString: ByteString) {\n this._byteString = byteString;\n }\n\n /**\n * Creates a new `Bytes` object from the given Base64 string, converting it to\n * bytes.\n *\n * @param base64 - The Base64 string used to create the `Bytes` object.\n */\n static fromBase64String(base64: string): Bytes {\n try {\n return new Bytes(ByteString.fromBase64String(base64));\n } catch (e) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Failed to construct data from Base64 string: ' + e\n );\n }\n }\n\n /**\n * Creates a new `Bytes` object from the given Uint8Array.\n *\n * @param array - The Uint8Array used to create the `Bytes` object.\n */\n static fromUint8Array(array: Uint8Array): Bytes {\n return new Bytes(ByteString.fromUint8Array(array));\n }\n\n /**\n * Returns the underlying bytes as a Base64-encoded string.\n *\n * @returns The Base64-encoded string created from the `Bytes` object.\n */\n toBase64(): string {\n return this._byteString.toBase64();\n }\n\n /**\n * Returns the underlying bytes in a new `Uint8Array`.\n *\n * @returns The Uint8Array created from the `Bytes` object.\n */\n toUint8Array(): Uint8Array {\n return this._byteString.toUint8Array();\n }\n\n /**\n * Returns a string representation of the `Bytes` object.\n *\n * @returns A string representation of the `Bytes` object.\n */\n toString(): string {\n return 'Bytes(base64: ' + this.toBase64() + ')';\n }\n\n /**\n * Returns true if this `Bytes` object is equal to the provided one.\n *\n * @param other - The `Bytes` object to compare against.\n * @returns true if this `Bytes` object is equal to the provided one.\n */\n isEqual(other: Bytes): boolean {\n return this._byteString.isEqual(other._byteString);\n }\n\n static _jsonSchemaVersion: string = 'firestore/bytes/1.0';\n static _jsonSchema = {\n type: property('string', Bytes._jsonSchemaVersion),\n bytes: property('string')\n };\n\n /**\n * Returns a JSON-serializable representation of this `Bytes` instance.\n *\n * @returns a JSON representation of this object.\n */\n toJSON(): object {\n return {\n type: Bytes._jsonSchemaVersion,\n bytes: this.toBase64()\n };\n }\n\n /**\n * Builds a `Bytes` instance from a JSON object created by {@link Bytes.toJSON}.\n *\n * @param json a JSON object represention of a `Bytes` instance\n * @returns an instance of {@link Bytes} if the JSON object could be parsed. Throws a\n * {@link FirestoreError} if an error occurs.\n */\n static fromJSON(json: object): Bytes {\n if (validateJSON(json, Bytes._jsonSchema)) {\n return Bytes.fromBase64String(json.bytes);\n }\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Unexpected error creating Bytes from JSON.'\n );\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n DOCUMENT_KEY_NAME,\n FieldPath as InternalFieldPath\n} from '../model/path';\nimport { Code, FirestoreError } from '../util/error';\n\n/**\n * A `FieldPath` refers to a field in a document. The path may consist of a\n * single field name (referring to a top-level field in the document), or a\n * list of field names (referring to a nested field in the document).\n *\n * Create a `FieldPath` by providing field names. If more than one field\n * name is provided, the path will point to a nested field in a document.\n */\nexport class FieldPath {\n /** Internal representation of a Firestore field path. */\n readonly _internalPath: InternalFieldPath;\n\n /**\n * Creates a `FieldPath` from the provided field names. If more than one field\n * name is provided, the path will point to a nested field in a document.\n *\n * @param fieldNames - A list of field names.\n */\n constructor(...fieldNames: string[]) {\n for (let i = 0; i < fieldNames.length; ++i) {\n if (fieldNames[i].length === 0) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid field name at argument $(i + 1). ` +\n 'Field names must not be empty.'\n );\n }\n }\n\n this._internalPath = new InternalFieldPath(fieldNames);\n }\n\n /**\n * Returns true if this `FieldPath` is equal to the provided one.\n *\n * @param other - The `FieldPath` to compare against.\n * @returns true if this `FieldPath` is equal to the provided one.\n */\n isEqual(other: FieldPath): boolean {\n return this._internalPath.isEqual(other._internalPath);\n }\n}\n\n/**\n * Returns a special sentinel `FieldPath` to refer to the ID of a document.\n * It can be used in queries to sort or filter by the document ID.\n */\nexport function documentId(): FieldPath {\n return new FieldPath(DOCUMENT_KEY_NAME);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ParseContext } from '../api/parse_context';\nimport { FieldTransform } from '../model/mutation';\n\n/**\n * Sentinel values that can be used when writing document fields with `set()`\n * or `update()`.\n */\nexport abstract class FieldValue {\n /**\n * @param _methodName - The public API endpoint that returns this class.\n * @hideconstructor\n */\n constructor(public _methodName: string) {}\n\n /** Compares `FieldValue`s for equality. */\n abstract isEqual(other: FieldValue): boolean;\n abstract _toFieldTransform(context: ParseContext): FieldTransform | null;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Code, FirestoreError } from '../util/error';\n// API extractor fails importing 'property' unless we also explicitly import 'Property'.\n// eslint-disable-next-line @typescript-eslint/no-unused-vars, unused-imports/no-unused-imports-ts\nimport { Property, property, validateJSON } from '../util/json_validation';\nimport { primitiveComparator } from '../util/misc';\n\n/**\n * An immutable object representing a geographic location in Firestore. The\n * location is represented as latitude/longitude pair.\n *\n * Latitude values are in the range of [-90, 90].\n * Longitude values are in the range of [-180, 180].\n */\nexport class GeoPoint {\n // Prefix with underscore to signal this is a private variable in JS and\n // prevent it showing up for autocompletion when typing latitude or longitude.\n private _lat: number;\n private _long: number;\n\n /**\n * Creates a new immutable `GeoPoint` object with the provided latitude and\n * longitude values.\n * @param latitude - The latitude as number between -90 and 90.\n * @param longitude - The longitude as number between -180 and 180.\n */\n constructor(latitude: number, longitude: number) {\n if (!isFinite(latitude) || latitude < -90 || latitude > 90) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Latitude must be a number between -90 and 90, but was: ' + latitude\n );\n }\n if (!isFinite(longitude) || longitude < -180 || longitude > 180) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Longitude must be a number between -180 and 180, but was: ' + longitude\n );\n }\n\n this._lat = latitude;\n this._long = longitude;\n }\n\n /**\n * The latitude of this `GeoPoint` instance.\n */\n get latitude(): number {\n return this._lat;\n }\n\n /**\n * The longitude of this `GeoPoint` instance.\n */\n get longitude(): number {\n return this._long;\n }\n\n /**\n * Returns true if this `GeoPoint` is equal to the provided one.\n *\n * @param other - The `GeoPoint` to compare against.\n * @returns true if this `GeoPoint` is equal to the provided one.\n */\n isEqual(other: GeoPoint): boolean {\n return this._lat === other._lat && this._long === other._long;\n }\n\n /**\n * Actually private to JS consumers of our API, so this function is prefixed\n * with an underscore.\n */\n _compareTo(other: GeoPoint): number {\n return (\n primitiveComparator(this._lat, other._lat) ||\n primitiveComparator(this._long, other._long)\n );\n }\n\n static _jsonSchemaVersion: string = 'firestore/geoPoint/1.0';\n static _jsonSchema = {\n type: property('string', GeoPoint._jsonSchemaVersion),\n latitude: property('number'),\n longitude: property('number')\n };\n\n /**\n * Returns a JSON-serializable representation of this `GeoPoint` instance.\n *\n * @returns a JSON representation of this object.\n */\n toJSON(): { latitude: number; longitude: number; type: string } {\n return {\n latitude: this._lat,\n longitude: this._long,\n type: GeoPoint._jsonSchemaVersion\n };\n }\n\n /**\n * Builds a `GeoPoint` instance from a JSON object created by {@link GeoPoint.toJSON}.\n *\n * @param json a JSON object represention of a `GeoPoint` instance\n * @returns an instance of {@link GeoPoint} if the JSON object could be parsed. Throws a\n * {@link FirestoreError} if an error occurs.\n */\n static fromJSON(json: object): GeoPoint {\n if (validateJSON(json, GeoPoint._jsonSchema)) {\n return new GeoPoint(json.latitude, json.longitude);\n }\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Unexpected error creating GeoPoint from JSON.'\n );\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Returns true iff the array contains the value using strong equality.\n */\nexport function includes(array: T[], value: T): boolean {\n for (let i = 0; i < array.length; i++) {\n if (array[i] === value) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * Returns true iff the array contains any value matching the predicate\n */\nexport function some(array: T[], predicate: (t: T) => boolean): boolean {\n for (let i = 0; i < array.length; i++) {\n if (predicate(array[i])) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * Calls predicate function for each item in the array until the predicate\n * returns true, at which point the index of that item is returned. If the\n * predicate does not return true for any item, null is returned.\n */\nexport function findIndex
(\n array: A[],\n predicate: (value: A) => boolean\n): number | null {\n for (let i = 0; i < array.length; i++) {\n if (predicate(array[i])) {\n return i;\n }\n }\n return null;\n}\n\n/**\n * Compares two array for equality using comparator. The method computes the\n * intersection and invokes `onAdd` for every element that is in `after` but not\n * `before`. `onRemove` is invoked for every element in `before` but missing\n * from `after`.\n *\n * The method creates a copy of both `before` and `after` and runs in O(n log\n * n), where n is the size of the two lists.\n *\n * @param before - The elements that exist in the original array.\n * @param after - The elements to diff against the original array.\n * @param comparator - The comparator for the elements in before and after.\n * @param onAdd - A function to invoke for every element that is part of `\n * after` but not `before`.\n * @param onRemove - A function to invoke for every element that is part of\n * `before` but not `after`.\n */\nexport function diffArrays(\n before: T[],\n after: T[],\n comparator: (l: T, r: T) => number,\n onAdd: (entry: T) => void,\n onRemove: (entry: T) => void\n): void {\n before = [...before];\n after = [...after];\n before.sort(comparator);\n after.sort(comparator);\n\n const bLen = before.length;\n const aLen = after.length;\n let a = 0;\n let b = 0;\n while (a < aLen && b < bLen) {\n const cmp = comparator(before[b], after[a]);\n if (cmp < 0) {\n // The element was removed if the next element in our ordered\n // walkthrough is only in `before`.\n onRemove(before[b++]);\n } else if (cmp > 0) {\n // The element was added if the next element in our ordered walkthrough\n // is only in `after`.\n onAdd(after[a++]);\n } else {\n a++;\n b++;\n }\n }\n while (a < aLen) {\n onAdd(after[a++]);\n }\n while (b < bLen) {\n onRemove(before[b++]);\n }\n}\n\n/**\n * Verifies equality for an array of objects using the `isEqual` interface.\n *\n * @private\n * @internal\n * @param left Array of objects supporting `isEqual`.\n * @param right Array of objects supporting `isEqual`.\n * @return True if arrays are equal.\n */\nexport function isArrayEqual boolean }>(\n left: T[],\n right: T[]\n): boolean {\n if (left.length !== right.length) {\n return false;\n }\n\n for (let i = 0; i < left.length; ++i) {\n if (!left[i].isEqual(right[i])) {\n return false;\n }\n }\n\n return true;\n}\n\n/**\n * Verifies equality for an array of primitives.\n *\n * @private\n * @internal\n * @param left Array of primitives.\n * @param right Array of primitives.\n * @return True if arrays are equal.\n */\nexport function isPrimitiveArrayEqual(\n left: T[],\n right: T[]\n): boolean {\n if (left.length !== right.length) {\n return false;\n }\n\n for (let i = 0; i < left.length; ++i) {\n if (left[i] !== right[i]) {\n return false;\n }\n }\n\n return true;\n}\n","/**\n * @license\n * Copyright 2024 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isPrimitiveArrayEqual } from '../util/array';\nimport { Code, FirestoreError } from '../util/error';\n// API extractor fails importing 'property' unless we also explicitly import 'Property'.\n// eslint-disable-next-line @typescript-eslint/no-unused-vars, unused-imports/no-unused-imports-ts\nimport { Property, property, validateJSON } from '../util/json_validation';\n\n/**\n * Represents a vector type in Firestore documents.\n * Create an instance with {@link vector}.\n *\n * @class VectorValue\n */\nexport class VectorValue {\n private readonly _values: number[];\n\n /**\n * @private\n * @internal\n */\n constructor(values: number[] | undefined) {\n // Making a copy of the parameter.\n this._values = (values || []).map(n => n);\n }\n\n /**\n * Returns a copy of the raw number array form of the vector.\n */\n toArray(): number[] {\n return this._values.map(n => n);\n }\n\n /**\n * Returns `true` if the two `VectorValue` values have the same raw number arrays, returns `false` otherwise.\n */\n isEqual(other: VectorValue): boolean {\n return isPrimitiveArrayEqual(this._values, other._values);\n }\n\n static _jsonSchemaVersion: string = 'firestore/vectorValue/1.0';\n static _jsonSchema = {\n type: property('string', VectorValue._jsonSchemaVersion),\n vectorValues: property('object')\n };\n\n /**\n * Returns a JSON-serializable representation of this `VectorValue` instance.\n *\n * @returns a JSON representation of this object.\n */\n toJSON(): object {\n return {\n type: VectorValue._jsonSchemaVersion,\n vectorValues: this._values\n };\n }\n\n /**\n * Builds a `VectorValue` instance from a JSON object created by {@link VectorValue.toJSON}.\n *\n * @param json a JSON object represention of a `VectorValue` instance.\n * @returns an instance of {@link VectorValue} if the JSON object could be parsed. Throws a\n * {@link FirestoreError} if an error occurs.\n */\n static fromJSON(json: object): VectorValue {\n if (validateJSON(json, VectorValue._jsonSchema)) {\n if (\n Array.isArray(json.vectorValues) &&\n json.vectorValues.every(element => typeof element === 'number')\n ) {\n return new VectorValue(json.vectorValues);\n }\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n \"Expected 'vectorValues' field to be a number array\"\n );\n }\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Unexpected error creating Timestamp from JSON.'\n );\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n DocumentData,\n FieldPath as PublicFieldPath,\n SetOptions\n} from '@firebase/firestore-types';\nimport { Compat, deepEqual, getModularInstance } from '@firebase/util';\n\nimport { ParseContext } from '../api/parse_context';\nimport { DatabaseId } from '../core/database_info';\nimport { DocumentKey } from '../model/document_key';\nimport { FieldMask } from '../model/field_mask';\nimport {\n FieldTransform,\n Mutation,\n PatchMutation,\n Precondition,\n SetMutation\n} from '../model/mutation';\nimport { ObjectValue } from '../model/object_value';\nimport { FieldPath as InternalFieldPath } from '../model/path';\nimport {\n ArrayRemoveTransformOperation,\n ArrayUnionTransformOperation,\n NumericIncrementTransformOperation,\n ServerTimestampTransform\n} from '../model/transform_operation';\nimport {\n TYPE_KEY,\n VECTOR_MAP_VECTORS_KEY,\n VECTOR_VALUE_SENTINEL\n} from '../model/values';\nimport { newSerializer } from '../platform/serializer';\nimport {\n MapValue as ProtoMapValue,\n Value as ProtoValue\n} from '../protos/firestore_proto_api';\nimport { toDouble, toNumber } from '../remote/number_serializer';\nimport {\n JsonProtoSerializer,\n toBytes,\n toResourceName,\n toTimestamp\n} from '../remote/serializer';\nimport { debugAssert, fail } from '../util/assert';\nimport { Code, FirestoreError } from '../util/error';\nimport { isPlainObject, valueDescription } from '../util/input_validation';\nimport { Dict, forEach, isEmpty } from '../util/obj';\n\nimport { Bytes } from './bytes';\nimport { Firestore } from './database';\nimport { FieldPath } from './field_path';\nimport { FieldValue } from './field_value';\nimport { GeoPoint } from './geo_point';\nimport {\n DocumentReference,\n PartialWithFieldValue,\n WithFieldValue\n} from './reference';\nimport { Timestamp } from './timestamp';\nimport { VectorValue } from './vector_value';\n\nconst RESERVED_FIELD_REGEX = /^__.*__$/;\n\n/**\n * An untyped Firestore Data Converter interface that is shared between the\n * lite, firestore-exp and classic SDK.\n */\nexport interface UntypedFirestoreDataConverter<\n AppModelType,\n DbModelType extends DocumentData = DocumentData\n> {\n toFirestore(\n modelObject: WithFieldValue\n ): WithFieldValue;\n toFirestore(\n modelObject: PartialWithFieldValue,\n options: SetOptions\n ): PartialWithFieldValue;\n fromFirestore(snapshot: unknown, options?: unknown): AppModelType;\n}\n\n/** The result of parsing document data (e.g. for a setData call). */\nexport class ParsedSetData {\n constructor(\n readonly data: ObjectValue,\n readonly fieldMask: FieldMask | null,\n readonly fieldTransforms: FieldTransform[]\n ) {}\n\n toMutation(key: DocumentKey, precondition: Precondition): Mutation {\n if (this.fieldMask !== null) {\n return new PatchMutation(\n key,\n this.data,\n this.fieldMask,\n precondition,\n this.fieldTransforms\n );\n } else {\n return new SetMutation(\n key,\n this.data,\n precondition,\n this.fieldTransforms\n );\n }\n }\n}\n\n/** The result of parsing \"update\" data (i.e. for an updateData call). */\nexport class ParsedUpdateData {\n constructor(\n readonly data: ObjectValue,\n // The fieldMask does not include document transforms.\n readonly fieldMask: FieldMask,\n readonly fieldTransforms: FieldTransform[]\n ) {}\n\n toMutation(key: DocumentKey, precondition: Precondition): Mutation {\n return new PatchMutation(\n key,\n this.data,\n this.fieldMask,\n precondition,\n this.fieldTransforms\n );\n }\n}\n\n/*\n * Represents what type of API method provided the data being parsed; useful\n * for determining which error conditions apply during parsing and providing\n * better error messages.\n */\nexport const enum UserDataSource {\n Set,\n Update,\n MergeSet,\n /**\n * Indicates the source is a where clause, cursor bound, arrayUnion()\n * element, etc. Of note, isWrite(source) will return false.\n */\n Argument,\n /**\n * Indicates that the source is an Argument that may directly contain nested\n * arrays (e.g. the operand of an `in` query).\n */\n ArrayArgument\n}\n\nfunction isWrite(dataSource: UserDataSource): boolean {\n switch (dataSource) {\n case UserDataSource.Set: // fall through\n case UserDataSource.MergeSet: // fall through\n case UserDataSource.Update:\n return true;\n case UserDataSource.Argument:\n case UserDataSource.ArrayArgument:\n return false;\n default:\n throw fail(0x9c4b, 'Unexpected case for UserDataSource', {\n dataSource\n });\n }\n}\n\n/** Contains the settings that are mutated as we parse user data. */\ninterface ContextSettings {\n /** Indicates what kind of API method this data came from. */\n readonly dataSource: UserDataSource;\n /** The name of the method the user called to create the ParseContext. */\n readonly methodName: string;\n /** The document the user is attempting to modify, if that applies. */\n readonly targetDoc?: DocumentKey;\n /**\n * A path within the object being parsed. This could be an empty path (in\n * which case the context represents the root of the data being parsed), or a\n * nonempty path (indicating the context represents a nested location within\n * the data).\n */\n readonly path?: InternalFieldPath;\n /**\n * Whether or not this context corresponds to an element of an array.\n * If not set, elements are treated as if they were outside of arrays.\n */\n readonly arrayElement?: boolean;\n /**\n * Whether or not a converter was specified in this context. If true, error\n * messages will reference the converter when invalid data is provided.\n */\n readonly hasConverter?: boolean;\n}\n\n/** A \"context\" object passed around while parsing user data. */\nclass ParseContextImpl implements ParseContext {\n readonly fieldTransforms: FieldTransform[];\n readonly fieldMask: InternalFieldPath[];\n /**\n * Initializes a ParseContext with the given source and path.\n *\n * @param settings - The settings for the parser.\n * @param databaseId - The database ID of the Firestore instance.\n * @param serializer - The serializer to use to generate the Value proto.\n * @param ignoreUndefinedProperties - Whether to ignore undefined properties\n * rather than throw.\n * @param fieldTransforms - A mutable list of field transforms encountered\n * while parsing the data.\n * @param fieldMask - A mutable list of field paths encountered while parsing\n * the data.\n *\n * TODO(b/34871131): We don't support array paths right now, so path can be\n * null to indicate the context represents any location within an array (in\n * which case certain features will not work and errors will be somewhat\n * compromised).\n */\n constructor(\n readonly settings: ContextSettings,\n readonly databaseId: DatabaseId,\n readonly serializer: JsonProtoSerializer,\n readonly ignoreUndefinedProperties: boolean,\n fieldTransforms?: FieldTransform[],\n fieldMask?: InternalFieldPath[]\n ) {\n // Minor hack: If fieldTransforms is undefined, we assume this is an\n // external call and we need to validate the entire path.\n if (fieldTransforms === undefined) {\n this.validatePath();\n }\n this.fieldTransforms = fieldTransforms || [];\n this.fieldMask = fieldMask || [];\n }\n\n get path(): InternalFieldPath | undefined {\n return this.settings.path;\n }\n\n get dataSource(): UserDataSource {\n return this.settings.dataSource;\n }\n\n /** Returns a new context with the specified settings overwritten. */\n contextWith(configuration: Partial): ParseContextImpl {\n return new ParseContextImpl(\n { ...this.settings, ...configuration },\n this.databaseId,\n this.serializer,\n this.ignoreUndefinedProperties,\n this.fieldTransforms,\n this.fieldMask\n );\n }\n\n childContextForField(field: string): ParseContextImpl {\n const childPath = this.path?.child(field);\n const context = this.contextWith({ path: childPath, arrayElement: false });\n context.validatePathSegment(field);\n return context;\n }\n\n childContextForFieldPath(field: InternalFieldPath): ParseContextImpl {\n const childPath = this.path?.child(field);\n const context = this.contextWith({ path: childPath, arrayElement: false });\n context.validatePath();\n return context;\n }\n\n childContextForArray(index: number): ParseContextImpl {\n // TODO(b/34871131): We don't support array paths right now; so make path\n // undefined.\n return this.contextWith({ path: undefined, arrayElement: true });\n }\n\n createError(reason: string): FirestoreError {\n return createError(\n reason,\n this.settings.methodName,\n this.settings.hasConverter || false,\n this.path,\n this.settings.targetDoc\n );\n }\n\n /** Returns 'true' if 'fieldPath' was traversed when creating this context. */\n contains(fieldPath: InternalFieldPath): boolean {\n return (\n this.fieldMask.find(field => fieldPath.isPrefixOf(field)) !== undefined ||\n this.fieldTransforms.find(transform =>\n fieldPath.isPrefixOf(transform.field)\n ) !== undefined\n );\n }\n\n private validatePath(): void {\n // TODO(b/34871131): Remove null check once we have proper paths for fields\n // within arrays.\n if (!this.path) {\n return;\n }\n for (let i = 0; i < this.path.length; i++) {\n this.validatePathSegment(this.path.get(i));\n }\n }\n\n private validatePathSegment(segment: string): void {\n if (segment.length === 0) {\n throw this.createError('Document fields must not be empty');\n }\n if (isWrite(this.dataSource) && RESERVED_FIELD_REGEX.test(segment)) {\n throw this.createError('Document fields cannot begin and end with \"__\"');\n }\n }\n}\n\n/**\n * Helper for parsing raw user input (provided via the API) into internal model\n * classes.\n */\nexport class UserDataReader {\n private readonly serializer: JsonProtoSerializer;\n\n constructor(\n private readonly databaseId: DatabaseId,\n private readonly ignoreUndefinedProperties: boolean,\n serializer?: JsonProtoSerializer\n ) {\n this.serializer = serializer || newSerializer(databaseId);\n }\n\n /** Creates a new top-level parse context. */\n createContext(\n dataSource: UserDataSource,\n methodName: string,\n targetDoc?: DocumentKey,\n hasConverter = false\n ): ParseContextImpl {\n return new ParseContextImpl(\n {\n dataSource,\n methodName,\n targetDoc,\n path: InternalFieldPath.emptyPath(),\n arrayElement: false,\n hasConverter\n },\n this.databaseId,\n this.serializer,\n this.ignoreUndefinedProperties\n );\n }\n}\n\nexport function newUserDataReader(firestore: Firestore): UserDataReader {\n const settings = firestore._freezeSettings();\n const serializer = newSerializer(firestore._databaseId);\n return new UserDataReader(\n firestore._databaseId,\n !!settings.ignoreUndefinedProperties,\n serializer\n );\n}\n\n/** Parse document data from a set() call. */\nexport function parseSetData(\n userDataReader: UserDataReader,\n methodName: string,\n targetDoc: DocumentKey,\n input: unknown,\n hasConverter: boolean,\n options: SetOptions = {}\n): ParsedSetData {\n const context = userDataReader.createContext(\n options.merge || options.mergeFields\n ? UserDataSource.MergeSet\n : UserDataSource.Set,\n methodName,\n targetDoc,\n hasConverter\n );\n validatePlainObject('Data must be an object, but it was:', context, input);\n const updateData = parseObject(input, context)!;\n\n let fieldMask: FieldMask | null;\n let fieldTransforms: FieldTransform[];\n\n if (options.merge) {\n fieldMask = new FieldMask(context.fieldMask);\n fieldTransforms = context.fieldTransforms;\n } else if (options.mergeFields) {\n const validatedFieldPaths: InternalFieldPath[] = [];\n\n for (const stringOrFieldPath of options.mergeFields) {\n const fieldPath = fieldPathFromArgument(\n methodName,\n stringOrFieldPath,\n targetDoc\n );\n if (!context.contains(fieldPath)) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Field '${fieldPath}' is specified in your field mask but missing from your input data.`\n );\n }\n\n if (!fieldMaskContains(validatedFieldPaths, fieldPath)) {\n validatedFieldPaths.push(fieldPath);\n }\n }\n\n fieldMask = new FieldMask(validatedFieldPaths);\n fieldTransforms = context.fieldTransforms.filter(transform =>\n fieldMask!.covers(transform.field)\n );\n } else {\n fieldMask = null;\n fieldTransforms = context.fieldTransforms;\n }\n\n return new ParsedSetData(\n new ObjectValue(updateData),\n fieldMask,\n fieldTransforms\n );\n}\n\nexport class DeleteFieldValueImpl extends FieldValue {\n _toFieldTransform(context: ParseContextImpl): null {\n if (context.dataSource === UserDataSource.MergeSet) {\n // No transform to add for a delete, but we need to add it to our\n // fieldMask so it gets deleted.\n context.fieldMask.push(context.path!);\n } else if (context.dataSource === UserDataSource.Update) {\n debugAssert(\n context.path!.length > 0,\n `${this._methodName}() at the top level should have already ` +\n 'been handled.'\n );\n throw context.createError(\n `${this._methodName}() can only appear at the top level ` +\n 'of your update data'\n );\n } else {\n // We shouldn't encounter delete sentinels for queries or non-merge set() calls.\n throw context.createError(\n `${this._methodName}() cannot be used with set() unless you pass ` +\n '{merge:true}'\n );\n }\n return null;\n }\n\n isEqual(other: FieldValue): boolean {\n return other instanceof DeleteFieldValueImpl;\n }\n}\n\n/**\n * Creates a child context for parsing SerializableFieldValues.\n *\n * This is different than calling `ParseContext.contextWith` because it keeps\n * the fieldTransforms and fieldMask separate.\n *\n * The created context has its `dataSource` set to `UserDataSource.Argument`.\n * Although these values are used with writes, any elements in these FieldValues\n * are not considered writes since they cannot contain any FieldValue sentinels,\n * etc.\n *\n * @param fieldValue - The sentinel FieldValue for which to create a child\n * context.\n * @param context - The parent context.\n * @param arrayElement - Whether or not the FieldValue has an array.\n */\nfunction createSentinelChildContext(\n fieldValue: FieldValue,\n context: ParseContextImpl,\n arrayElement: boolean\n): ParseContextImpl {\n return new ParseContextImpl(\n {\n dataSource: UserDataSource.Argument,\n targetDoc: context.settings.targetDoc,\n methodName: fieldValue._methodName,\n arrayElement\n },\n context.databaseId,\n context.serializer,\n context.ignoreUndefinedProperties\n );\n}\n\nexport class ServerTimestampFieldValueImpl extends FieldValue {\n _toFieldTransform(context: ParseContextImpl): FieldTransform {\n return new FieldTransform(context.path!, new ServerTimestampTransform());\n }\n\n isEqual(other: FieldValue): boolean {\n return other instanceof ServerTimestampFieldValueImpl;\n }\n}\n\nexport class ArrayUnionFieldValueImpl extends FieldValue {\n constructor(methodName: string, private readonly _elements: unknown[]) {\n super(methodName);\n }\n\n _toFieldTransform(context: ParseContextImpl): FieldTransform {\n const parseContext = createSentinelChildContext(\n this,\n context,\n /*array=*/ true\n );\n const parsedElements = this._elements.map(\n element => parseData(element, parseContext)!\n );\n const arrayUnion = new ArrayUnionTransformOperation(parsedElements);\n return new FieldTransform(context.path!, arrayUnion);\n }\n\n isEqual(other: FieldValue): boolean {\n return (\n other instanceof ArrayUnionFieldValueImpl &&\n deepEqual(this._elements, other._elements)\n );\n }\n}\n\nexport class ArrayRemoveFieldValueImpl extends FieldValue {\n constructor(methodName: string, private readonly _elements: unknown[]) {\n super(methodName);\n }\n\n _toFieldTransform(context: ParseContextImpl): FieldTransform {\n const parseContext = createSentinelChildContext(\n this,\n context,\n /*array=*/ true\n );\n const parsedElements = this._elements.map(\n element => parseData(element, parseContext)!\n );\n const arrayUnion = new ArrayRemoveTransformOperation(parsedElements);\n return new FieldTransform(context.path!, arrayUnion);\n }\n\n isEqual(other: FieldValue): boolean {\n return (\n other instanceof ArrayRemoveFieldValueImpl &&\n deepEqual(this._elements, other._elements)\n );\n }\n}\n\nexport class NumericIncrementFieldValueImpl extends FieldValue {\n constructor(methodName: string, private readonly _operand: number) {\n super(methodName);\n }\n\n _toFieldTransform(context: ParseContextImpl): FieldTransform {\n const numericIncrement = new NumericIncrementTransformOperation(\n context.serializer,\n toNumber(context.serializer, this._operand)\n );\n return new FieldTransform(context.path!, numericIncrement);\n }\n\n isEqual(other: FieldValue): boolean {\n return (\n other instanceof NumericIncrementFieldValueImpl &&\n this._operand === other._operand\n );\n }\n}\n\n/** Parse update data from an update() call. */\nexport function parseUpdateData(\n userDataReader: UserDataReader,\n methodName: string,\n targetDoc: DocumentKey,\n input: unknown\n): ParsedUpdateData {\n const context = userDataReader.createContext(\n UserDataSource.Update,\n methodName,\n targetDoc\n );\n validatePlainObject('Data must be an object, but it was:', context, input);\n\n const fieldMaskPaths: InternalFieldPath[] = [];\n const updateData = ObjectValue.empty();\n forEach(input as Dict, (key, value) => {\n const path = fieldPathFromDotSeparatedString(methodName, key, targetDoc);\n\n // For Compat types, we have to \"extract\" the underlying types before\n // performing validation.\n value = getModularInstance(value);\n\n const childContext = context.childContextForFieldPath(path);\n if (value instanceof DeleteFieldValueImpl) {\n // Add it to the field mask, but don't add anything to updateData.\n fieldMaskPaths.push(path);\n } else {\n const parsedValue = parseData(value, childContext);\n if (parsedValue != null) {\n fieldMaskPaths.push(path);\n updateData.set(path, parsedValue);\n }\n }\n });\n\n const mask = new FieldMask(fieldMaskPaths);\n return new ParsedUpdateData(updateData, mask, context.fieldTransforms);\n}\n\n/** Parse update data from a list of field/value arguments. */\nexport function parseUpdateVarargs(\n userDataReader: UserDataReader,\n methodName: string,\n targetDoc: DocumentKey,\n field: string | PublicFieldPath | Compat,\n value: unknown,\n moreFieldsAndValues: unknown[]\n): ParsedUpdateData {\n const context = userDataReader.createContext(\n UserDataSource.Update,\n methodName,\n targetDoc\n );\n const keys = [fieldPathFromArgument(methodName, field, targetDoc)];\n const values = [value];\n\n if (moreFieldsAndValues.length % 2 !== 0) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Function ${methodName}() needs to be called with an even number ` +\n 'of arguments that alternate between field names and values.'\n );\n }\n\n for (let i = 0; i < moreFieldsAndValues.length; i += 2) {\n keys.push(\n fieldPathFromArgument(\n methodName,\n moreFieldsAndValues[i] as string | PublicFieldPath\n )\n );\n values.push(moreFieldsAndValues[i + 1]);\n }\n\n const fieldMaskPaths: InternalFieldPath[] = [];\n const updateData = ObjectValue.empty();\n\n // We iterate in reverse order to pick the last value for a field if the\n // user specified the field multiple times.\n for (let i = keys.length - 1; i >= 0; --i) {\n if (!fieldMaskContains(fieldMaskPaths, keys[i])) {\n const path = keys[i];\n let value = values[i];\n\n // For Compat types, we have to \"extract\" the underlying types before\n // performing validation.\n value = getModularInstance(value);\n\n const childContext = context.childContextForFieldPath(path);\n if (value instanceof DeleteFieldValueImpl) {\n // Add it to the field mask, but don't add anything to updateData.\n fieldMaskPaths.push(path);\n } else {\n const parsedValue = parseData(value, childContext);\n if (parsedValue != null) {\n fieldMaskPaths.push(path);\n updateData.set(path, parsedValue);\n }\n }\n }\n }\n\n const mask = new FieldMask(fieldMaskPaths);\n return new ParsedUpdateData(updateData, mask, context.fieldTransforms);\n}\n\n/**\n * Parse a \"query value\" (e.g. value in a where filter or a value in a cursor\n * bound).\n *\n * @param allowArrays - Whether the query value is an array that may directly\n * contain additional arrays (e.g. the operand of an `in` query).\n */\nexport function parseQueryValue(\n userDataReader: UserDataReader,\n methodName: string,\n input: unknown,\n allowArrays = false\n): ProtoValue {\n const context = userDataReader.createContext(\n allowArrays ? UserDataSource.ArrayArgument : UserDataSource.Argument,\n methodName\n );\n const parsed = parseData(input, context);\n debugAssert(parsed != null, 'Parsed data should not be null.');\n debugAssert(\n context.fieldTransforms.length === 0,\n 'Field transforms should have been disallowed.'\n );\n return parsed;\n}\n\n/**\n * Parses user data to Protobuf Values.\n *\n * @param input - Data to be parsed.\n * @param context - A context object representing the current path being parsed,\n * the source of the data being parsed, etc.\n * @returns The parsed value, or null if the value was a FieldValue sentinel\n * that should not be included in the resulting parsed data.\n */\nexport function parseData(\n input: unknown,\n context: ParseContextImpl\n): ProtoValue | null {\n // Unwrap the API type from the Compat SDK. This will return the API type\n // from firestore-exp.\n input = getModularInstance(input);\n\n if (looksLikeJsonObject(input)) {\n validatePlainObject('Unsupported field value:', context, input);\n return parseObject(input, context);\n } else if (input instanceof FieldValue) {\n // FieldValues usually parse into transforms (except deleteField())\n // in which case we do not want to include this field in our parsed data\n // (as doing so will overwrite the field directly prior to the transform\n // trying to transform it). So we don't add this location to\n // context.fieldMask and we return null as our parsing result.\n parseSentinelFieldValue(input, context);\n return null;\n } else if (input === undefined && context.ignoreUndefinedProperties) {\n // If the input is undefined it can never participate in the fieldMask, so\n // don't handle this below. If `ignoreUndefinedProperties` is false,\n // `parseScalarValue` will reject an undefined value.\n return null;\n } else {\n // If context.path is null we are inside an array and we don't support\n // field mask paths more granular than the top-level array.\n if (context.path) {\n context.fieldMask.push(context.path);\n }\n\n if (input instanceof Array) {\n // TODO(b/34871131): Include the path containing the array in the error\n // message.\n // In the case of IN queries, the parsed data is an array (representing\n // the set of values to be included for the IN query) that may directly\n // contain additional arrays (each representing an individual field\n // value), so we disable this validation.\n if (\n context.settings.arrayElement &&\n context.dataSource !== UserDataSource.ArrayArgument\n ) {\n throw context.createError('Nested arrays are not supported');\n }\n return parseArray(input as unknown[], context);\n } else {\n return parseScalarValue(input, context);\n }\n }\n}\n\nexport function parseObject(\n obj: Dict,\n context: ParseContextImpl\n): { mapValue: ProtoMapValue } {\n const fields: Dict = {};\n\n if (isEmpty(obj)) {\n // If we encounter an empty object, we explicitly add it to the update\n // mask to ensure that the server creates a map entry.\n if (context.path && context.path.length > 0) {\n context.fieldMask.push(context.path);\n }\n } else {\n forEach(obj, (key: string, val: unknown) => {\n const parsedValue = parseData(val, context.childContextForField(key));\n if (parsedValue != null) {\n fields[key] = parsedValue;\n }\n });\n }\n\n return { mapValue: { fields } };\n}\n\nfunction parseArray(array: unknown[], context: ParseContextImpl): ProtoValue {\n const values: ProtoValue[] = [];\n let entryIndex = 0;\n for (const entry of array) {\n let parsedEntry = parseData(\n entry,\n context.childContextForArray(entryIndex)\n );\n if (parsedEntry == null) {\n // Just include nulls in the array for fields being replaced with a\n // sentinel.\n parsedEntry = { nullValue: 'NULL_VALUE' };\n }\n values.push(parsedEntry);\n entryIndex++;\n }\n return { arrayValue: { values } };\n}\n\n/**\n * \"Parses\" the provided FieldValueImpl, adding any necessary transforms to\n * context.fieldTransforms.\n */\nfunction parseSentinelFieldValue(\n value: FieldValue,\n context: ParseContextImpl\n): void {\n // Sentinels are only supported with writes, and not within arrays.\n if (!isWrite(context.dataSource)) {\n throw context.createError(\n `${value._methodName}() can only be used with update() and set()`\n );\n }\n if (!context.path) {\n throw context.createError(\n `${value._methodName}() is not currently supported inside arrays`\n );\n }\n\n const fieldTransform = value._toFieldTransform(context);\n if (fieldTransform) {\n context.fieldTransforms.push(fieldTransform);\n }\n}\n\n/**\n * Helper to parse a scalar value (i.e. not an Object, Array, or FieldValue)\n *\n * @returns The parsed value\n */\nfunction parseScalarValue(\n value: unknown,\n context: ParseContextImpl\n): ProtoValue | null {\n value = getModularInstance(value);\n\n if (value === null) {\n return { nullValue: 'NULL_VALUE' };\n } else if (typeof value === 'number') {\n return toNumber(context.serializer, value);\n } else if (typeof value === 'boolean') {\n return { booleanValue: value };\n } else if (typeof value === 'string') {\n return { stringValue: value };\n } else if (value instanceof Date) {\n const timestamp = Timestamp.fromDate(value);\n return {\n timestampValue: toTimestamp(context.serializer, timestamp)\n };\n } else if (value instanceof Timestamp) {\n // Firestore backend truncates precision down to microseconds. To ensure\n // offline mode works the same with regards to truncation, perform the\n // truncation immediately without waiting for the backend to do that.\n const timestamp = new Timestamp(\n value.seconds,\n Math.floor(value.nanoseconds / 1000) * 1000\n );\n return {\n timestampValue: toTimestamp(context.serializer, timestamp)\n };\n } else if (value instanceof GeoPoint) {\n return {\n geoPointValue: {\n latitude: value.latitude,\n longitude: value.longitude\n }\n };\n } else if (value instanceof Bytes) {\n return { bytesValue: toBytes(context.serializer, value._byteString) };\n } else if (value instanceof DocumentReference) {\n const thisDb = context.databaseId;\n const otherDb = value.firestore._databaseId;\n if (!otherDb.isEqual(thisDb)) {\n throw context.createError(\n 'Document reference is for database ' +\n `${otherDb.projectId}/${otherDb.database} but should be ` +\n `for database ${thisDb.projectId}/${thisDb.database}`\n );\n }\n return {\n referenceValue: toResourceName(\n value.firestore._databaseId || context.databaseId,\n value._key.path\n )\n };\n } else if (value instanceof VectorValue) {\n return parseVectorValue(value, context);\n } else {\n throw context.createError(\n `Unsupported field value: ${valueDescription(value)}`\n );\n }\n}\n\n/**\n * Creates a new VectorValue proto value (using the internal format).\n */\nexport function parseVectorValue(\n value: VectorValue,\n context: ParseContextImpl\n): ProtoValue {\n const mapValue: ProtoMapValue = {\n fields: {\n [TYPE_KEY]: {\n stringValue: VECTOR_VALUE_SENTINEL\n },\n [VECTOR_MAP_VECTORS_KEY]: {\n arrayValue: {\n values: value.toArray().map(value => {\n if (typeof value !== 'number') {\n throw context.createError(\n 'VectorValues must only contain numeric values.'\n );\n }\n\n return toDouble(context.serializer, value);\n })\n }\n }\n }\n };\n\n return { mapValue };\n}\n\n/**\n * Checks whether an object looks like a JSON object that should be converted\n * into a struct. Normal class/prototype instances are considered to look like\n * JSON objects since they should be converted to a struct value. Arrays, Dates,\n * GeoPoints, etc. are not considered to look like JSON objects since they map\n * to specific FieldValue types other than ObjectValue.\n */\nfunction looksLikeJsonObject(input: unknown): boolean {\n return (\n typeof input === 'object' &&\n input !== null &&\n !(input instanceof Array) &&\n !(input instanceof Date) &&\n !(input instanceof Timestamp) &&\n !(input instanceof GeoPoint) &&\n !(input instanceof Bytes) &&\n !(input instanceof DocumentReference) &&\n !(input instanceof FieldValue) &&\n !(input instanceof VectorValue)\n );\n}\n\nfunction validatePlainObject(\n message: string,\n context: ParseContextImpl,\n input: unknown\n): asserts input is Dict {\n if (!looksLikeJsonObject(input) || !isPlainObject(input)) {\n const description = valueDescription(input);\n if (description === 'an object') {\n // Massage the error if it was an object.\n throw context.createError(message + ' a custom object');\n } else {\n throw context.createError(message + ' ' + description);\n }\n }\n}\n\n/**\n * Helper that calls fromDotSeparatedString() but wraps any error thrown.\n */\nexport function fieldPathFromArgument(\n methodName: string,\n path: string | PublicFieldPath | Compat,\n targetDoc?: DocumentKey\n): InternalFieldPath {\n // If required, replace the FieldPath Compat class with the firestore-exp\n // FieldPath.\n path = getModularInstance(path);\n\n if (path instanceof FieldPath) {\n return path._internalPath;\n } else if (typeof path === 'string') {\n return fieldPathFromDotSeparatedString(methodName, path);\n } else {\n const message = 'Field path arguments must be of type string or ';\n throw createError(\n message,\n methodName,\n /* hasConverter= */ false,\n /* path= */ undefined,\n targetDoc\n );\n }\n}\n\n/**\n * Matches any characters in a field path string that are reserved.\n */\nconst FIELD_PATH_RESERVED = new RegExp('[~\\\\*/\\\\[\\\\]]');\n\n/**\n * Wraps fromDotSeparatedString with an error message about the method that\n * was thrown.\n * @param methodName - The publicly visible method name\n * @param path - The dot-separated string form of a field path which will be\n * split on dots.\n * @param targetDoc - The document against which the field path will be\n * evaluated.\n */\nexport function fieldPathFromDotSeparatedString(\n methodName: string,\n path: string,\n targetDoc?: DocumentKey\n): InternalFieldPath {\n const found = path.search(FIELD_PATH_RESERVED);\n if (found >= 0) {\n throw createError(\n `Invalid field path (${path}). Paths must not contain ` +\n `'~', '*', '/', '[', or ']'`,\n methodName,\n /* hasConverter= */ false,\n /* path= */ undefined,\n targetDoc\n );\n }\n\n try {\n return new FieldPath(...path.split('.'))._internalPath;\n } catch (e) {\n throw createError(\n `Invalid field path (${path}). Paths must not be empty, ` +\n `begin with '.', end with '.', or contain '..'`,\n methodName,\n /* hasConverter= */ false,\n /* path= */ undefined,\n targetDoc\n );\n }\n}\n\nfunction createError(\n reason: string,\n methodName: string,\n hasConverter: boolean,\n path?: InternalFieldPath,\n targetDoc?: DocumentKey\n): FirestoreError {\n const hasPath = path && !path.isEmpty();\n const hasDocument = targetDoc !== undefined;\n let message = `Function ${methodName}() called with invalid data`;\n if (hasConverter) {\n message += ' (via `toFirestore()`)';\n }\n message += '. ';\n\n let description = '';\n if (hasPath || hasDocument) {\n description += ' (found';\n\n if (hasPath) {\n description += ` in field ${path}`;\n }\n if (hasDocument) {\n description += ` in document ${targetDoc}`;\n }\n description += ')';\n }\n\n return new FirestoreError(\n Code.INVALID_ARGUMENT,\n message + reason + description\n );\n}\n\n/** Checks `haystack` if FieldPath `needle` is present. Runs in O(n). */\nfunction fieldMaskContains(\n haystack: InternalFieldPath[],\n needle: InternalFieldPath\n): boolean {\n return haystack.some(v => v.isEqual(needle));\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Compat, getModularInstance } from '@firebase/util';\n\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { FieldPath as InternalFieldPath } from '../model/path';\nimport { arrayEquals } from '../util/misc';\n\nimport { Firestore } from './database';\nimport { FieldPath } from './field_path';\nimport {\n DocumentData,\n DocumentReference,\n PartialWithFieldValue,\n Query,\n queryEqual,\n SetOptions,\n WithFieldValue\n} from './reference';\nimport {\n fieldPathFromDotSeparatedString,\n UntypedFirestoreDataConverter\n} from './user_data_reader';\nimport { AbstractUserDataWriter } from './user_data_writer';\n\n/**\n * Converter used by `withConverter()` to transform user objects of type\n * `AppModelType` into Firestore data of type `DbModelType`.\n *\n * Using the converter allows you to specify generic type arguments when\n * storing and retrieving objects from Firestore.\n *\n * In this context, an \"AppModel\" is a class that is used in an application to\n * package together related information and functionality. Such a class could,\n * for example, have properties with complex, nested data types, properties used\n * for memoization, properties of types not supported by Firestore (such as\n * `symbol` and `bigint`), and helper functions that perform compound\n * operations. Such classes are not suitable and/or possible to store into a\n * Firestore database. Instead, instances of such classes need to be converted\n * to \"plain old JavaScript objects\" (POJOs) with exclusively primitive\n * properties, potentially nested inside other POJOs or arrays of POJOs. In this\n * context, this type is referred to as the \"DbModel\" and would be an object\n * suitable for persisting into Firestore. For convenience, applications can\n * implement `FirestoreDataConverter` and register the converter with Firestore\n * objects, such as `DocumentReference` or `Query`, to automatically convert\n * `AppModel` to `DbModel` when storing into Firestore, and convert `DbModel`\n * to `AppModel` when retrieving from Firestore.\n *\n * @example\n *\n * Simple Example\n *\n * ```typescript\n * const numberConverter = {\n * toFirestore(value: WithFieldValue) {\n * return { value };\n * },\n * fromFirestore(snapshot: QueryDocumentSnapshot, options: SnapshotOptions) {\n * return snapshot.data(options).value as number;\n * }\n * };\n *\n * async function simpleDemo(db: Firestore): Promise {\n * const documentRef = doc(db, 'values/value123').withConverter(numberConverter);\n *\n * // converters are used with `setDoc`, `addDoc`, and `getDoc`\n * await setDoc(documentRef, 42);\n * const snapshot1 = await getDoc(documentRef);\n * assertEqual(snapshot1.data(), 42);\n *\n * // converters are not used when writing data with `updateDoc`\n * await updateDoc(documentRef, { value: 999 });\n * const snapshot2 = await getDoc(documentRef);\n * assertEqual(snapshot2.data(), 999);\n * }\n * ```\n *\n * Advanced Example\n *\n * ```typescript\n * // The Post class is a model that is used by our application.\n * // This class may have properties and methods that are specific\n * // to our application execution, which do not need to be persisted\n * // to Firestore.\n * class Post {\n * constructor(\n * readonly title: string,\n * readonly author: string,\n * readonly lastUpdatedMillis: number\n * ) {}\n * toString(): string {\n * return `${this.title} by ${this.author}`;\n * }\n * }\n *\n * // The PostDbModel represents how we want our posts to be stored\n * // in Firestore. This DbModel has different properties (`ttl`,\n * // `aut`, and `lut`) from the Post class we use in our application.\n * interface PostDbModel {\n * ttl: string;\n * aut: { firstName: string; lastName: string };\n * lut: Timestamp;\n * }\n *\n * // The `PostConverter` implements `FirestoreDataConverter` and specifies\n * // how the Firestore SDK can convert `Post` objects to `PostDbModel`\n * // objects and vice versa.\n * class PostConverter implements FirestoreDataConverter {\n * toFirestore(post: WithFieldValue): WithFieldValue {\n * return {\n * ttl: post.title,\n * aut: this._autFromAuthor(post.author),\n * lut: this._lutFromLastUpdatedMillis(post.lastUpdatedMillis)\n * };\n * }\n *\n * fromFirestore(snapshot: QueryDocumentSnapshot, options: SnapshotOptions): Post {\n * const data = snapshot.data(options) as PostDbModel;\n * const author = `${data.aut.firstName} ${data.aut.lastName}`;\n * return new Post(data.ttl, author, data.lut.toMillis());\n * }\n *\n * _autFromAuthor(\n * author: string | FieldValue\n * ): { firstName: string; lastName: string } | FieldValue {\n * if (typeof author !== 'string') {\n * // `author` is a FieldValue, so just return it.\n * return author;\n * }\n * const [firstName, lastName] = author.split(' ');\n * return {firstName, lastName};\n * }\n *\n * _lutFromLastUpdatedMillis(\n * lastUpdatedMillis: number | FieldValue\n * ): Timestamp | FieldValue {\n * if (typeof lastUpdatedMillis !== 'number') {\n * // `lastUpdatedMillis` must be a FieldValue, so just return it.\n * return lastUpdatedMillis;\n * }\n * return Timestamp.fromMillis(lastUpdatedMillis);\n * }\n * }\n *\n * async function advancedDemo(db: Firestore): Promise {\n * // Create a `DocumentReference` with a `FirestoreDataConverter`.\n * const documentRef = doc(db, 'posts/post123').withConverter(new PostConverter());\n *\n * // The `data` argument specified to `setDoc()` is type checked by the\n * // TypeScript compiler to be compatible with `Post`. Since the `data`\n * // argument is typed as `WithFieldValue` rather than just `Post`,\n * // this allows properties of the `data` argument to also be special\n * // Firestore values that perform server-side mutations, such as\n * // `arrayRemove()`, `deleteField()`, and `serverTimestamp()`.\n * await setDoc(documentRef, {\n * title: 'My Life',\n * author: 'Foo Bar',\n * lastUpdatedMillis: serverTimestamp()\n * });\n *\n * // The TypeScript compiler will fail to compile if the `data` argument to\n * // `setDoc()` is _not_ compatible with `WithFieldValue`. This\n * // type checking prevents the caller from specifying objects with incorrect\n * // properties or property values.\n * // @ts-expect-error \"Argument of type { ttl: string; } is not assignable\n * // to parameter of type WithFieldValue\"\n * await setDoc(documentRef, { ttl: 'The Title' });\n *\n * // When retrieving a document with `getDoc()` the `DocumentSnapshot`\n * // object's `data()` method returns a `Post`, rather than a generic object,\n * // which would have been returned if the `DocumentReference` did _not_ have a\n * // `FirestoreDataConverter` attached to it.\n * const snapshot1: DocumentSnapshot = await getDoc(documentRef);\n * const post1: Post = snapshot1.data()!;\n * if (post1) {\n * assertEqual(post1.title, 'My Life');\n * assertEqual(post1.author, 'Foo Bar');\n * }\n *\n * // The `data` argument specified to `updateDoc()` is type checked by the\n * // TypeScript compiler to be compatible with `PostDbModel`. Note that\n * // unlike `setDoc()`, whose `data` argument must be compatible with `Post`,\n * // the `data` argument to `updateDoc()` must be compatible with\n * // `PostDbModel`. Similar to `setDoc()`, since the `data` argument is typed\n * // as `WithFieldValue` rather than just `PostDbModel`, this\n * // allows properties of the `data` argument to also be those special\n * // Firestore values, like `arrayRemove()`, `deleteField()`, and\n * // `serverTimestamp()`.\n * await updateDoc(documentRef, {\n * 'aut.firstName': 'NewFirstName',\n * lut: serverTimestamp()\n * });\n *\n * // The TypeScript compiler will fail to compile if the `data` argument to\n * // `updateDoc()` is _not_ compatible with `WithFieldValue`.\n * // This type checking prevents the caller from specifying objects with\n * // incorrect properties or property values.\n * // @ts-expect-error \"Argument of type { title: string; } is not assignable\n * // to parameter of type WithFieldValue\"\n * await updateDoc(documentRef, { title: 'New Title' });\n * const snapshot2: DocumentSnapshot = await getDoc(documentRef);\n * const post2: Post = snapshot2.data()!;\n * if (post2) {\n * assertEqual(post2.title, 'My Life');\n * assertEqual(post2.author, 'NewFirstName Bar');\n * }\n * }\n * ```\n */\nexport interface FirestoreDataConverter<\n AppModelType,\n DbModelType extends DocumentData = DocumentData\n> {\n /**\n * Called by the Firestore SDK to convert a custom model object of type\n * `AppModelType` into a plain JavaScript object (suitable for writing\n * directly to the Firestore database) of type `DbModelType`. Used with\n * {@link @firebase/firestore/lite#(setDoc:1)},\n * {@link @firebase/firestore/lite#(WriteBatch.set:1)} and\n * {@link @firebase/firestore/lite#(Transaction.set:1)}.\n *\n * The `WithFieldValue` type extends `T` to also allow FieldValues such as\n * {@link (deleteField:1)} to be used as property values.\n */\n toFirestore(\n modelObject: WithFieldValue\n ): WithFieldValue;\n\n /**\n * Called by the Firestore SDK to convert a custom model object of type\n * `AppModelType` into a plain JavaScript object (suitable for writing\n * directly to the Firestore database) of type `DbModelType`. Used with\n * {@link @firebase/firestore/lite#(setDoc:1)},\n * {@link @firebase/firestore/lite#(WriteBatch.set:1)} and\n * {@link @firebase/firestore/lite#(Transaction.set:1)} with `merge:true`\n * or `mergeFields`.\n *\n * The `PartialWithFieldValue` type extends `Partial` to allow\n * FieldValues such as {@link (arrayUnion:1)} to be used as property values.\n * It also supports nested `Partial` by allowing nested fields to be\n * omitted.\n */\n toFirestore(\n modelObject: PartialWithFieldValue,\n options: SetOptions\n ): PartialWithFieldValue;\n\n /**\n * Called by the Firestore SDK to convert Firestore data into an object of\n * type `AppModelType`. You can access your data by calling:\n * `snapshot.data()`.\n *\n *\n * Generally, the data returned from `snapshot.data()` can be cast to\n * `DbModelType`; however, this is not guaranteed because Firestore does not\n * enforce a schema on the database. For example, writes from a previous\n * version of the application or writes from another client that did not use a\n * type converter could have written data with different properties and/or\n * property types. The implementation will need to choose whether to\n * gracefully recover from non-conforming data or throw an error.\n *\n * @param snapshot - A `QueryDocumentSnapshot` containing your data and\n * metadata.\n */\n fromFirestore(\n snapshot: QueryDocumentSnapshot\n ): AppModelType;\n}\n\n/**\n * A `DocumentSnapshot` contains data read from a document in your Firestore\n * database. The data can be extracted with `.data()` or `.get()` to\n * get a specific field.\n *\n * For a `DocumentSnapshot` that points to a non-existing document, any data\n * access will return 'undefined'. You can use the `exists()` method to\n * explicitly verify a document's existence.\n */\nexport class DocumentSnapshot<\n AppModelType = DocumentData,\n DbModelType extends DocumentData = DocumentData\n> {\n // Note: This class is stripped down version of the DocumentSnapshot in\n // the legacy SDK. The changes are:\n // - No support for SnapshotMetadata.\n // - No support for SnapshotOptions.\n\n /** @hideconstructor protected */\n constructor(\n public _firestore: Firestore,\n public _userDataWriter: AbstractUserDataWriter,\n public _key: DocumentKey,\n public _document: Document | null,\n public _converter: UntypedFirestoreDataConverter<\n AppModelType,\n DbModelType\n > | null\n ) {}\n\n /** Property of the `DocumentSnapshot` that provides the document's ID. */\n get id(): string {\n return this._key.path.lastSegment();\n }\n\n /**\n * The `DocumentReference` for the document included in the `DocumentSnapshot`.\n */\n get ref(): DocumentReference {\n return new DocumentReference(\n this._firestore,\n this._converter,\n this._key\n );\n }\n\n /**\n * Signals whether or not the document at the snapshot's location exists.\n *\n * @returns true if the document exists.\n */\n exists(): this is QueryDocumentSnapshot {\n return this._document !== null;\n }\n\n /**\n * Retrieves all fields in the document as an `Object`. Returns `undefined` if\n * the document doesn't exist.\n *\n * @returns An `Object` containing all fields in the document or `undefined`\n * if the document doesn't exist.\n */\n data(): AppModelType | undefined {\n if (!this._document) {\n return undefined;\n } else if (this._converter) {\n // We only want to use the converter and create a new DocumentSnapshot\n // if a converter has been provided.\n const snapshot = new QueryDocumentSnapshot(\n this._firestore,\n this._userDataWriter,\n this._key,\n this._document,\n /* converter= */ null\n );\n return this._converter.fromFirestore(snapshot);\n } else {\n return this._userDataWriter.convertValue(\n this._document.data.value\n ) as AppModelType;\n }\n }\n\n /**\n * Retrieves the field specified by `fieldPath`. Returns `undefined` if the\n * document or field doesn't exist.\n *\n * @param fieldPath - The path (for example 'foo' or 'foo.bar') to a specific\n * field.\n * @returns The data at the specified field location or undefined if no such\n * field exists in the document.\n */\n // We are using `any` here to avoid an explicit cast by our users.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n get(fieldPath: string | FieldPath): any {\n if (this._document) {\n const value = this._document.data.field(\n fieldPathFromArgument('DocumentSnapshot.get', fieldPath)\n );\n if (value !== null) {\n return this._userDataWriter.convertValue(value);\n }\n }\n return undefined;\n }\n}\n\n/**\n * A `QueryDocumentSnapshot` contains data read from a document in your\n * Firestore database as part of a query. The document is guaranteed to exist\n * and its data can be extracted with `.data()` or `.get()` to get a\n * specific field.\n *\n * A `QueryDocumentSnapshot` offers the same API surface as a\n * `DocumentSnapshot`. Since query results contain only existing documents, the\n * `exists` property will always be true and `data()` will never return\n * 'undefined'.\n */\nexport class QueryDocumentSnapshot<\n AppModelType = DocumentData,\n DbModelType extends DocumentData = DocumentData\n> extends DocumentSnapshot {\n /**\n * Retrieves all fields in the document as an `Object`.\n *\n * @override\n * @returns An `Object` containing all fields in the document.\n */\n data(): AppModelType {\n return super.data() as AppModelType;\n }\n}\n\n/**\n * A `QuerySnapshot` contains zero or more `DocumentSnapshot` objects\n * representing the results of a query. The documents can be accessed as an\n * array via the `docs` property or enumerated using the `forEach` method. The\n * number of documents can be determined via the `empty` and `size`\n * properties.\n */\nexport class QuerySnapshot<\n AppModelType = DocumentData,\n DbModelType extends DocumentData = DocumentData\n> {\n /**\n * The query on which you called {@link getDocs} in order to get this\n * `QuerySnapshot`.\n */\n readonly query: Query;\n\n /** @hideconstructor */\n constructor(\n _query: Query,\n readonly _docs: Array>\n ) {\n this.query = _query;\n }\n\n /** An array of all the documents in the `QuerySnapshot`. */\n get docs(): Array> {\n return [...this._docs];\n }\n\n /** The number of documents in the `QuerySnapshot`. */\n get size(): number {\n return this.docs.length;\n }\n\n /** True if there are no documents in the `QuerySnapshot`. */\n get empty(): boolean {\n return this.docs.length === 0;\n }\n\n /**\n * Enumerates all of the documents in the `QuerySnapshot`.\n *\n * @param callback - A callback to be called with a `QueryDocumentSnapshot` for\n * each document in the snapshot.\n * @param thisArg - The `this` binding for the callback.\n */\n forEach(\n callback: (\n result: QueryDocumentSnapshot\n ) => void,\n thisArg?: unknown\n ): void {\n this._docs.forEach(callback, thisArg);\n }\n}\n\n/**\n * Returns true if the provided snapshots are equal.\n *\n * @param left - A snapshot to compare.\n * @param right - A snapshot to compare.\n * @returns true if the snapshots are equal.\n */\nexport function snapshotEqual(\n left:\n | DocumentSnapshot\n | QuerySnapshot,\n right:\n | DocumentSnapshot\n | QuerySnapshot\n): boolean {\n left = getModularInstance(left);\n right = getModularInstance(right);\n\n if (left instanceof DocumentSnapshot && right instanceof DocumentSnapshot) {\n return (\n left._firestore === right._firestore &&\n left._key.isEqual(right._key) &&\n (left._document === null\n ? right._document === null\n : left._document.isEqual(right._document)) &&\n left._converter === right._converter\n );\n } else if (left instanceof QuerySnapshot && right instanceof QuerySnapshot) {\n return (\n queryEqual(left.query, right.query) &&\n arrayEquals(left.docs, right.docs, snapshotEqual)\n );\n }\n\n return false;\n}\n\n/**\n * Helper that calls `fromDotSeparatedString()` but wraps any error thrown.\n */\nexport function fieldPathFromArgument(\n methodName: string,\n arg: string | FieldPath | Compat\n): InternalFieldPath {\n if (typeof arg === 'string') {\n return fieldPathFromDotSeparatedString(methodName, arg);\n } else if (arg instanceof FieldPath) {\n return arg._internalPath;\n } else {\n return arg._delegate._internalPath;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getModularInstance } from '@firebase/util';\n\nimport { Bound } from '../core/bound';\nimport { DatabaseId } from '../core/database_info';\nimport {\n CompositeFilter,\n CompositeOperator,\n FieldFilter,\n Filter,\n Operator\n} from '../core/filter';\nimport { Direction, OrderBy } from '../core/order_by';\nimport {\n isCollectionGroupQuery,\n LimitType,\n Query as InternalQuery,\n queryNormalizedOrderBy,\n queryWithAddedFilter,\n queryWithAddedOrderBy,\n queryWithEndAt,\n queryWithLimit,\n queryWithStartAt\n} from '../core/query';\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { FieldPath as InternalFieldPath, ResourcePath } from '../model/path';\nimport { isServerTimestamp } from '../model/server_timestamps';\nimport { refValue } from '../model/values';\nimport { Value as ProtoValue } from '../protos/firestore_proto_api';\nimport { Code, FirestoreError } from '../util/error';\nimport {\n validatePositiveNumber,\n valueDescription\n} from '../util/input_validation';\n\nimport { FieldPath } from './field_path';\nimport { DocumentData, DocumentReference, Query } from './reference';\nimport { DocumentSnapshot, fieldPathFromArgument } from './snapshot';\nimport {\n newUserDataReader,\n parseQueryValue,\n UserDataReader\n} from './user_data_reader';\n\nexport function validateHasExplicitOrderByForLimitToLast(\n query: InternalQuery\n): void {\n if (\n query.limitType === LimitType.Last &&\n query.explicitOrderBy.length === 0\n ) {\n throw new FirestoreError(\n Code.UNIMPLEMENTED,\n 'limitToLast() queries require specifying at least one orderBy() clause'\n );\n }\n}\n\n/** Describes the different query constraints available in this SDK. */\nexport type QueryConstraintType =\n | 'where'\n | 'orderBy'\n | 'limit'\n | 'limitToLast'\n | 'startAt'\n | 'startAfter'\n | 'endAt'\n | 'endBefore';\n\n/**\n * An `AppliableConstraint` is an abstraction of a constraint that can be applied\n * to a Firestore query.\n */\nexport abstract class AppliableConstraint {\n /**\n * Takes the provided {@link Query} and returns a copy of the {@link Query} with this\n * {@link AppliableConstraint} applied.\n */\n abstract _apply(\n query: Query\n ): Query;\n}\n\n/**\n * A `QueryConstraint` is used to narrow the set of documents returned by a\n * Firestore query. `QueryConstraint`s are created by invoking {@link where},\n * {@link orderBy}, {@link (startAt:1)}, {@link (startAfter:1)}, {@link\n * (endBefore:1)}, {@link (endAt:1)}, {@link limit}, {@link limitToLast} and\n * can then be passed to {@link (query:1)} to create a new query instance that\n * also contains this `QueryConstraint`.\n */\nexport abstract class QueryConstraint extends AppliableConstraint {\n /** The type of this query constraint */\n abstract readonly type: QueryConstraintType;\n\n /**\n * Takes the provided {@link Query} and returns a copy of the {@link Query} with this\n * {@link AppliableConstraint} applied.\n */\n abstract _apply(\n query: Query\n ): Query;\n}\n\n/**\n * Creates a new immutable instance of {@link Query} that is extended to also\n * include additional query constraints.\n *\n * @param query - The {@link Query} instance to use as a base for the new\n * constraints.\n * @param compositeFilter - The {@link QueryCompositeFilterConstraint} to\n * apply. Create {@link QueryCompositeFilterConstraint} using {@link and} or\n * {@link or}.\n * @param queryConstraints - Additional {@link QueryNonFilterConstraint}s to\n * apply (e.g. {@link orderBy}, {@link limit}).\n * @throws if any of the provided query constraints cannot be combined with the\n * existing or new constraints.\n */\nexport function query(\n query: Query,\n compositeFilter: QueryCompositeFilterConstraint,\n ...queryConstraints: QueryNonFilterConstraint[]\n): Query;\n\n/**\n * Creates a new immutable instance of {@link Query} that is extended to also\n * include additional query constraints.\n *\n * @param query - The {@link Query} instance to use as a base for the new\n * constraints.\n * @param queryConstraints - The list of {@link QueryConstraint}s to apply.\n * @throws if any of the provided query constraints cannot be combined with the\n * existing or new constraints.\n */\nexport function query(\n query: Query,\n ...queryConstraints: QueryConstraint[]\n): Query;\n\nexport function query(\n query: Query,\n queryConstraint: QueryCompositeFilterConstraint | QueryConstraint | undefined,\n ...additionalQueryConstraints: Array<\n QueryConstraint | QueryNonFilterConstraint\n >\n): Query {\n let queryConstraints: AppliableConstraint[] = [];\n\n if (queryConstraint instanceof AppliableConstraint) {\n queryConstraints.push(queryConstraint);\n }\n\n queryConstraints = queryConstraints.concat(additionalQueryConstraints);\n\n validateQueryConstraintArray(queryConstraints);\n\n for (const constraint of queryConstraints) {\n query = constraint._apply(query);\n }\n return query;\n}\n\n/**\n * A `QueryFieldFilterConstraint` is used to narrow the set of documents returned by\n * a Firestore query by filtering on one or more document fields.\n * `QueryFieldFilterConstraint`s are created by invoking {@link where} and can then\n * be passed to {@link (query:1)} to create a new query instance that also contains\n * this `QueryFieldFilterConstraint`.\n */\nexport class QueryFieldFilterConstraint extends QueryConstraint {\n /** The type of this query constraint */\n readonly type = 'where';\n\n /**\n * @internal\n */\n protected constructor(\n private readonly _field: InternalFieldPath,\n private _op: Operator,\n private _value: unknown\n ) {\n super();\n }\n\n static _create(\n _field: InternalFieldPath,\n _op: Operator,\n _value: unknown\n ): QueryFieldFilterConstraint {\n return new QueryFieldFilterConstraint(_field, _op, _value);\n }\n\n _apply(\n query: Query\n ): Query {\n const filter = this._parse(query);\n validateNewFieldFilter(query._query, filter);\n return new Query(\n query.firestore,\n query.converter,\n queryWithAddedFilter(query._query, filter)\n );\n }\n\n _parse(\n query: Query\n ): FieldFilter {\n const reader = newUserDataReader(query.firestore);\n const filter = newQueryFilter(\n query._query,\n 'where',\n reader,\n query.firestore._databaseId,\n this._field,\n this._op,\n this._value\n );\n return filter;\n }\n}\n\n/**\n * Filter conditions in a {@link where} clause are specified using the\n * strings '<', '<=', '==', '!=', '>=', '>', 'array-contains', 'in',\n * 'array-contains-any', and 'not-in'.\n */\nexport type WhereFilterOp =\n | '<'\n | '<='\n | '=='\n | '!='\n | '>='\n | '>'\n | 'array-contains'\n | 'in'\n | 'array-contains-any'\n | 'not-in';\n\n/**\n * Creates a {@link QueryFieldFilterConstraint} that enforces that documents\n * must contain the specified field and that the value should satisfy the\n * relation constraint provided.\n *\n * @param fieldPath - The path to compare\n * @param opStr - The operation string (e.g \"<\", \"<=\", \"==\", \"<\",\n * \"<=\", \"!=\").\n * @param value - The value for comparison\n * @returns The created {@link QueryFieldFilterConstraint}.\n */\nexport function where(\n fieldPath: string | FieldPath,\n opStr: WhereFilterOp,\n value: unknown\n): QueryFieldFilterConstraint {\n const op = opStr as Operator;\n const field = fieldPathFromArgument('where', fieldPath);\n return QueryFieldFilterConstraint._create(field, op, value);\n}\n\n/**\n * A `QueryCompositeFilterConstraint` is used to narrow the set of documents\n * returned by a Firestore query by performing the logical OR or AND of multiple\n * {@link QueryFieldFilterConstraint}s or {@link QueryCompositeFilterConstraint}s.\n * `QueryCompositeFilterConstraint`s are created by invoking {@link or} or\n * {@link and} and can then be passed to {@link (query:1)} to create a new query\n * instance that also contains the `QueryCompositeFilterConstraint`.\n */\nexport class QueryCompositeFilterConstraint extends AppliableConstraint {\n /**\n * @internal\n */\n protected constructor(\n /** The type of this query constraint */\n readonly type: 'or' | 'and',\n private readonly _queryConstraints: QueryFilterConstraint[]\n ) {\n super();\n }\n\n static _create(\n type: 'or' | 'and',\n _queryConstraints: QueryFilterConstraint[]\n ): QueryCompositeFilterConstraint {\n return new QueryCompositeFilterConstraint(type, _queryConstraints);\n }\n\n _parse(\n query: Query\n ): Filter {\n const parsedFilters = this._queryConstraints\n .map(queryConstraint => {\n return queryConstraint._parse(query);\n })\n .filter(parsedFilter => parsedFilter.getFilters().length > 0);\n\n if (parsedFilters.length === 1) {\n return parsedFilters[0];\n }\n\n return CompositeFilter.create(parsedFilters, this._getOperator());\n }\n\n _apply(\n query: Query\n ): Query {\n const parsedFilter = this._parse(query);\n if (parsedFilter.getFilters().length === 0) {\n // Return the existing query if not adding any more filters (e.g. an empty\n // composite filter).\n return query;\n }\n validateNewFilter(query._query, parsedFilter);\n\n return new Query(\n query.firestore,\n query.converter,\n queryWithAddedFilter(query._query, parsedFilter)\n );\n }\n\n _getQueryConstraints(): readonly AppliableConstraint[] {\n return this._queryConstraints;\n }\n\n _getOperator(): CompositeOperator {\n return this.type === 'and' ? CompositeOperator.AND : CompositeOperator.OR;\n }\n}\n\n/**\n * `QueryNonFilterConstraint` is a helper union type that represents\n * QueryConstraints which are used to narrow or order the set of documents,\n * but that do not explicitly filter on a document field.\n * `QueryNonFilterConstraint`s are created by invoking {@link orderBy},\n * {@link (startAt:1)}, {@link (startAfter:1)}, {@link (endBefore:1)}, {@link (endAt:1)},\n * {@link limit} or {@link limitToLast} and can then be passed to {@link (query:1)}\n * to create a new query instance that also contains the `QueryConstraint`.\n */\nexport type QueryNonFilterConstraint =\n | QueryOrderByConstraint\n | QueryLimitConstraint\n | QueryStartAtConstraint\n | QueryEndAtConstraint;\n\n/**\n * `QueryFilterConstraint` is a helper union type that represents\n * {@link QueryFieldFilterConstraint} and {@link QueryCompositeFilterConstraint}.\n */\nexport type QueryFilterConstraint =\n | QueryFieldFilterConstraint\n | QueryCompositeFilterConstraint;\n\n/**\n * Creates a new {@link QueryCompositeFilterConstraint} that is a disjunction of\n * the given filter constraints. A disjunction filter includes a document if it\n * satisfies any of the given filters.\n *\n * @param queryConstraints - Optional. The list of\n * {@link QueryFilterConstraint}s to perform a disjunction for. These must be\n * created with calls to {@link where}, {@link or}, or {@link and}.\n * @returns The newly created {@link QueryCompositeFilterConstraint}.\n */\nexport function or(\n ...queryConstraints: QueryFilterConstraint[]\n): QueryCompositeFilterConstraint {\n // Only support QueryFilterConstraints\n queryConstraints.forEach(queryConstraint =>\n validateQueryFilterConstraint('or', queryConstraint)\n );\n\n return QueryCompositeFilterConstraint._create(\n CompositeOperator.OR,\n queryConstraints as QueryFilterConstraint[]\n );\n}\n\n/**\n * Creates a new {@link QueryCompositeFilterConstraint} that is a conjunction of\n * the given filter constraints. A conjunction filter includes a document if it\n * satisfies all of the given filters.\n *\n * @param queryConstraints - Optional. The list of\n * {@link QueryFilterConstraint}s to perform a conjunction for. These must be\n * created with calls to {@link where}, {@link or}, or {@link and}.\n * @returns The newly created {@link QueryCompositeFilterConstraint}.\n */\nexport function and(\n ...queryConstraints: QueryFilterConstraint[]\n): QueryCompositeFilterConstraint {\n // Only support QueryFilterConstraints\n queryConstraints.forEach(queryConstraint =>\n validateQueryFilterConstraint('and', queryConstraint)\n );\n\n return QueryCompositeFilterConstraint._create(\n CompositeOperator.AND,\n queryConstraints as QueryFilterConstraint[]\n );\n}\n\n/**\n * A `QueryOrderByConstraint` is used to sort the set of documents returned by a\n * Firestore query. `QueryOrderByConstraint`s are created by invoking\n * {@link orderBy} and can then be passed to {@link (query:1)} to create a new query\n * instance that also contains this `QueryOrderByConstraint`.\n *\n * Note: Documents that do not contain the orderBy field will not be present in\n * the query result.\n */\nexport class QueryOrderByConstraint extends QueryConstraint {\n /** The type of this query constraint */\n readonly type = 'orderBy';\n\n /**\n * @internal\n */\n protected constructor(\n private readonly _field: InternalFieldPath,\n private _direction: Direction\n ) {\n super();\n }\n\n static _create(\n _field: InternalFieldPath,\n _direction: Direction\n ): QueryOrderByConstraint {\n return new QueryOrderByConstraint(_field, _direction);\n }\n\n _apply(\n query: Query\n ): Query {\n const orderBy = newQueryOrderBy(query._query, this._field, this._direction);\n return new Query(\n query.firestore,\n query.converter,\n queryWithAddedOrderBy(query._query, orderBy)\n );\n }\n}\n\n/**\n * The direction of a {@link orderBy} clause is specified as 'desc' or 'asc'\n * (descending or ascending).\n */\nexport type OrderByDirection = 'desc' | 'asc';\n\n/**\n * Creates a {@link QueryOrderByConstraint} that sorts the query result by the\n * specified field, optionally in descending order instead of ascending.\n *\n * Note: Documents that do not contain the specified field will not be present\n * in the query result.\n *\n * @param fieldPath - The field to sort by.\n * @param directionStr - Optional direction to sort by ('asc' or 'desc'). If\n * not specified, order will be ascending.\n * @returns The created {@link QueryOrderByConstraint}.\n */\nexport function orderBy(\n fieldPath: string | FieldPath,\n directionStr: OrderByDirection = 'asc'\n): QueryOrderByConstraint {\n const direction = directionStr as Direction;\n const path = fieldPathFromArgument('orderBy', fieldPath);\n return QueryOrderByConstraint._create(path, direction);\n}\n\n/**\n * A `QueryLimitConstraint` is used to limit the number of documents returned by\n * a Firestore query.\n * `QueryLimitConstraint`s are created by invoking {@link limit} or\n * {@link limitToLast} and can then be passed to {@link (query:1)} to create a new\n * query instance that also contains this `QueryLimitConstraint`.\n */\nexport class QueryLimitConstraint extends QueryConstraint {\n /**\n * @internal\n */\n protected constructor(\n /** The type of this query constraint */\n readonly type: 'limit' | 'limitToLast',\n private readonly _limit: number,\n private readonly _limitType: LimitType\n ) {\n super();\n }\n\n static _create(\n type: 'limit' | 'limitToLast',\n _limit: number,\n _limitType: LimitType\n ): QueryLimitConstraint {\n return new QueryLimitConstraint(type, _limit, _limitType);\n }\n\n _apply(\n query: Query\n ): Query {\n return new Query(\n query.firestore,\n query.converter,\n queryWithLimit(query._query, this._limit, this._limitType)\n );\n }\n}\n\n/**\n * Creates a {@link QueryLimitConstraint} that only returns the first matching\n * documents.\n *\n * @param limit - The maximum number of items to return.\n * @returns The created {@link QueryLimitConstraint}.\n */\nexport function limit(limit: number): QueryLimitConstraint {\n validatePositiveNumber('limit', limit);\n return QueryLimitConstraint._create('limit', limit, LimitType.First);\n}\n\n/**\n * Creates a {@link QueryLimitConstraint} that only returns the last matching\n * documents.\n *\n * You must specify at least one `orderBy` clause for `limitToLast` queries,\n * otherwise an exception will be thrown during execution.\n *\n * @param limit - The maximum number of items to return.\n * @returns The created {@link QueryLimitConstraint}.\n */\nexport function limitToLast(limit: number): QueryLimitConstraint {\n validatePositiveNumber('limitToLast', limit);\n return QueryLimitConstraint._create('limitToLast', limit, LimitType.Last);\n}\n\n/**\n * A `QueryStartAtConstraint` is used to exclude documents from the start of a\n * result set returned by a Firestore query.\n * `QueryStartAtConstraint`s are created by invoking {@link (startAt:1)} or\n * {@link (startAfter:1)} and can then be passed to {@link (query:1)} to create a\n * new query instance that also contains this `QueryStartAtConstraint`.\n */\nexport class QueryStartAtConstraint extends QueryConstraint {\n /**\n * @internal\n */\n protected constructor(\n /** The type of this query constraint */\n readonly type: 'startAt' | 'startAfter',\n private readonly _docOrFields: Array>,\n private readonly _inclusive: boolean\n ) {\n super();\n }\n\n static _create(\n type: 'startAt' | 'startAfter',\n _docOrFields: Array>,\n _inclusive: boolean\n ): QueryStartAtConstraint {\n return new QueryStartAtConstraint(type, _docOrFields, _inclusive);\n }\n\n _apply(\n query: Query\n ): Query {\n const bound = newQueryBoundFromDocOrFields(\n query,\n this.type,\n this._docOrFields,\n this._inclusive\n );\n return new Query(\n query.firestore,\n query.converter,\n queryWithStartAt(query._query, bound)\n );\n }\n}\n\n/**\n * Creates a {@link QueryStartAtConstraint} that modifies the result set to\n * start at the provided document (inclusive). The starting position is relative\n * to the order of the query. The document must contain all of the fields\n * provided in the `orderBy` of this query.\n *\n * @param snapshot - The snapshot of the document to start at.\n * @returns A {@link QueryStartAtConstraint} to pass to `query()`.\n */\nexport function startAt(\n snapshot: DocumentSnapshot\n): QueryStartAtConstraint;\n/**\n * Creates a {@link QueryStartAtConstraint} that modifies the result set to\n * start at the provided fields relative to the order of the query. The order of\n * the field values must match the order of the order by clauses of the query.\n *\n * @param fieldValues - The field values to start this query at, in order\n * of the query's order by.\n * @returns A {@link QueryStartAtConstraint} to pass to `query()`.\n */\nexport function startAt(...fieldValues: unknown[]): QueryStartAtConstraint;\nexport function startAt(\n ...docOrFields: Array>\n): QueryStartAtConstraint {\n return QueryStartAtConstraint._create(\n 'startAt',\n docOrFields,\n /*inclusive=*/ true\n );\n}\n\n/**\n * Creates a {@link QueryStartAtConstraint} that modifies the result set to\n * start after the provided document (exclusive). The starting position is\n * relative to the order of the query. The document must contain all of the\n * fields provided in the orderBy of the query.\n *\n * @param snapshot - The snapshot of the document to start after.\n * @returns A {@link QueryStartAtConstraint} to pass to `query()`\n */\nexport function startAfter(\n snapshot: DocumentSnapshot\n): QueryStartAtConstraint;\n/**\n * Creates a {@link QueryStartAtConstraint} that modifies the result set to\n * start after the provided fields relative to the order of the query. The order\n * of the field values must match the order of the order by clauses of the query.\n *\n * @param fieldValues - The field values to start this query after, in order\n * of the query's order by.\n * @returns A {@link QueryStartAtConstraint} to pass to `query()`\n */\nexport function startAfter(...fieldValues: unknown[]): QueryStartAtConstraint;\nexport function startAfter(\n ...docOrFields: Array>\n): QueryStartAtConstraint {\n return QueryStartAtConstraint._create(\n 'startAfter',\n docOrFields,\n /*inclusive=*/ false\n );\n}\n\n/**\n * A `QueryEndAtConstraint` is used to exclude documents from the end of a\n * result set returned by a Firestore query.\n * `QueryEndAtConstraint`s are created by invoking {@link (endAt:1)} or\n * {@link (endBefore:1)} and can then be passed to {@link (query:1)} to create a new\n * query instance that also contains this `QueryEndAtConstraint`.\n */\nexport class QueryEndAtConstraint extends QueryConstraint {\n /**\n * @internal\n */\n protected constructor(\n /** The type of this query constraint */\n readonly type: 'endBefore' | 'endAt',\n private readonly _docOrFields: Array>,\n private readonly _inclusive: boolean\n ) {\n super();\n }\n\n static _create(\n type: 'endBefore' | 'endAt',\n _docOrFields: Array>,\n _inclusive: boolean\n ): QueryEndAtConstraint {\n return new QueryEndAtConstraint(type, _docOrFields, _inclusive);\n }\n\n _apply(\n query: Query\n ): Query {\n const bound = newQueryBoundFromDocOrFields(\n query,\n this.type,\n this._docOrFields,\n this._inclusive\n );\n return new Query(\n query.firestore,\n query.converter,\n queryWithEndAt(query._query, bound)\n );\n }\n}\n\n/**\n * Creates a {@link QueryEndAtConstraint} that modifies the result set to end\n * before the provided document (exclusive). The end position is relative to the\n * order of the query. The document must contain all of the fields provided in\n * the orderBy of the query.\n *\n * @param snapshot - The snapshot of the document to end before.\n * @returns A {@link QueryEndAtConstraint} to pass to `query()`\n */\nexport function endBefore(\n snapshot: DocumentSnapshot\n): QueryEndAtConstraint;\n/**\n * Creates a {@link QueryEndAtConstraint} that modifies the result set to end\n * before the provided fields relative to the order of the query. The order of\n * the field values must match the order of the order by clauses of the query.\n *\n * @param fieldValues - The field values to end this query before, in order\n * of the query's order by.\n * @returns A {@link QueryEndAtConstraint} to pass to `query()`\n */\nexport function endBefore(...fieldValues: unknown[]): QueryEndAtConstraint;\nexport function endBefore(\n ...docOrFields: Array>\n): QueryEndAtConstraint {\n return QueryEndAtConstraint._create(\n 'endBefore',\n docOrFields,\n /*inclusive=*/ false\n );\n}\n\n/**\n * Creates a {@link QueryEndAtConstraint} that modifies the result set to end at\n * the provided document (inclusive). The end position is relative to the order\n * of the query. The document must contain all of the fields provided in the\n * orderBy of the query.\n *\n * @param snapshot - The snapshot of the document to end at.\n * @returns A {@link QueryEndAtConstraint} to pass to `query()`\n */\nexport function endAt(\n snapshot: DocumentSnapshot\n): QueryEndAtConstraint;\n/**\n * Creates a {@link QueryEndAtConstraint} that modifies the result set to end at\n * the provided fields relative to the order of the query. The order of the field\n * values must match the order of the order by clauses of the query.\n *\n * @param fieldValues - The field values to end this query at, in order\n * of the query's order by.\n * @returns A {@link QueryEndAtConstraint} to pass to `query()`\n */\nexport function endAt(...fieldValues: unknown[]): QueryEndAtConstraint;\nexport function endAt(\n ...docOrFields: Array>\n): QueryEndAtConstraint {\n return QueryEndAtConstraint._create(\n 'endAt',\n docOrFields,\n /*inclusive=*/ true\n );\n}\n\n/** Helper function to create a bound from a document or fields */\nfunction newQueryBoundFromDocOrFields<\n AppModelType,\n DbModelType extends DocumentData\n>(\n query: Query,\n methodName: string,\n docOrFields: Array>,\n inclusive: boolean\n): Bound {\n docOrFields[0] = getModularInstance(docOrFields[0]);\n\n if (docOrFields[0] instanceof DocumentSnapshot) {\n return newQueryBoundFromDocument(\n query._query,\n query.firestore._databaseId,\n methodName,\n docOrFields[0]._document,\n inclusive\n );\n } else {\n const reader = newUserDataReader(query.firestore);\n return newQueryBoundFromFields(\n query._query,\n query.firestore._databaseId,\n reader,\n methodName,\n docOrFields,\n inclusive\n );\n }\n}\n\nexport function newQueryFilter(\n query: InternalQuery,\n methodName: string,\n dataReader: UserDataReader,\n databaseId: DatabaseId,\n fieldPath: InternalFieldPath,\n op: Operator,\n value: unknown\n): FieldFilter {\n let fieldValue: ProtoValue;\n if (fieldPath.isKeyField()) {\n if (op === Operator.ARRAY_CONTAINS || op === Operator.ARRAY_CONTAINS_ANY) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid Query. You can't perform '${op}' queries on documentId().`\n );\n } else if (op === Operator.IN || op === Operator.NOT_IN) {\n validateDisjunctiveFilterElements(value, op);\n const referenceList: ProtoValue[] = [];\n for (const arrayValue of value as ProtoValue[]) {\n referenceList.push(parseDocumentIdValue(databaseId, query, arrayValue));\n }\n fieldValue = { arrayValue: { values: referenceList } };\n } else {\n fieldValue = parseDocumentIdValue(databaseId, query, value);\n }\n } else {\n if (\n op === Operator.IN ||\n op === Operator.NOT_IN ||\n op === Operator.ARRAY_CONTAINS_ANY\n ) {\n validateDisjunctiveFilterElements(value, op);\n }\n fieldValue = parseQueryValue(\n dataReader,\n methodName,\n value,\n /* allowArrays= */ op === Operator.IN || op === Operator.NOT_IN\n );\n }\n const filter = FieldFilter.create(fieldPath, op, fieldValue);\n return filter;\n}\n\nexport function newQueryOrderBy(\n query: InternalQuery,\n fieldPath: InternalFieldPath,\n direction: Direction\n): OrderBy {\n if (query.startAt !== null) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Invalid query. You must not call startAt() or startAfter() before ' +\n 'calling orderBy().'\n );\n }\n if (query.endAt !== null) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Invalid query. You must not call endAt() or endBefore() before ' +\n 'calling orderBy().'\n );\n }\n const orderBy = new OrderBy(fieldPath, direction);\n return orderBy;\n}\n\n/**\n * Create a `Bound` from a query and a document.\n *\n * Note that the `Bound` will always include the key of the document\n * and so only the provided document will compare equal to the returned\n * position.\n *\n * Will throw if the document does not contain all fields of the order by\n * of the query or if any of the fields in the order by are an uncommitted\n * server timestamp.\n */\nexport function newQueryBoundFromDocument(\n query: InternalQuery,\n databaseId: DatabaseId,\n methodName: string,\n doc: Document | null,\n inclusive: boolean\n): Bound {\n if (!doc) {\n throw new FirestoreError(\n Code.NOT_FOUND,\n `Can't use a DocumentSnapshot that doesn't exist for ` +\n `${methodName}().`\n );\n }\n\n const components: ProtoValue[] = [];\n\n // Because people expect to continue/end a query at the exact document\n // provided, we need to use the implicit sort order rather than the explicit\n // sort order, because it's guaranteed to contain the document key. That way\n // the position becomes unambiguous and the query continues/ends exactly at\n // the provided document. Without the key (by using the explicit sort\n // orders), multiple documents could match the position, yielding duplicate\n // results.\n for (const orderBy of queryNormalizedOrderBy(query)) {\n if (orderBy.field.isKeyField()) {\n components.push(refValue(databaseId, doc.key));\n } else {\n const value = doc.data.field(orderBy.field);\n if (isServerTimestamp(value)) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Invalid query. You are trying to start or end a query using a ' +\n 'document for which the field \"' +\n orderBy.field +\n '\" is an uncommitted server timestamp. (Since the value of ' +\n 'this field is unknown, you cannot start/end a query with it.)'\n );\n } else if (value !== null) {\n components.push(value);\n } else {\n const field = orderBy.field.canonicalString();\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid query. You are trying to start or end a query using a ` +\n `document for which the field '${field}' (used as the ` +\n `orderBy) does not exist.`\n );\n }\n }\n }\n return new Bound(components, inclusive);\n}\n\n/**\n * Converts a list of field values to a `Bound` for the given query.\n */\nexport function newQueryBoundFromFields(\n query: InternalQuery,\n databaseId: DatabaseId,\n dataReader: UserDataReader,\n methodName: string,\n values: unknown[],\n inclusive: boolean\n): Bound {\n // Use explicit order by's because it has to match the query the user made\n const orderBy = query.explicitOrderBy;\n if (values.length > orderBy.length) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Too many arguments provided to ${methodName}(). ` +\n `The number of arguments must be less than or equal to the ` +\n `number of orderBy() clauses`\n );\n }\n\n const components: ProtoValue[] = [];\n for (let i = 0; i < values.length; i++) {\n const rawValue = values[i];\n const orderByComponent = orderBy[i];\n if (orderByComponent.field.isKeyField()) {\n if (typeof rawValue !== 'string') {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid query. Expected a string for document ID in ` +\n `${methodName}(), but got a ${typeof rawValue}`\n );\n }\n if (!isCollectionGroupQuery(query) && rawValue.indexOf('/') !== -1) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid query. When querying a collection and ordering by documentId(), ` +\n `the value passed to ${methodName}() must be a plain document ID, but ` +\n `'${rawValue}' contains a slash.`\n );\n }\n const path = query.path.child(ResourcePath.fromString(rawValue));\n if (!DocumentKey.isDocumentKey(path)) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid query. When querying a collection group and ordering by ` +\n `documentId(), the value passed to ${methodName}() must result in a ` +\n `valid document path, but '${path}' is not because it contains an odd number ` +\n `of segments.`\n );\n }\n const key = new DocumentKey(path);\n components.push(refValue(databaseId, key));\n } else {\n const wrapped = parseQueryValue(dataReader, methodName, rawValue);\n components.push(wrapped);\n }\n }\n\n return new Bound(components, inclusive);\n}\n\n/**\n * Parses the given `documentIdValue` into a `ReferenceValue`, throwing\n * appropriate errors if the value is anything other than a `DocumentReference`\n * or `string`, or if the string is malformed.\n */\nfunction parseDocumentIdValue(\n databaseId: DatabaseId,\n query: InternalQuery,\n documentIdValue: unknown\n): ProtoValue {\n documentIdValue = getModularInstance(documentIdValue);\n\n if (typeof documentIdValue === 'string') {\n if (documentIdValue === '') {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Invalid query. When querying with documentId(), you ' +\n 'must provide a valid document ID, but it was an empty string.'\n );\n }\n if (!isCollectionGroupQuery(query) && documentIdValue.indexOf('/') !== -1) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid query. When querying a collection by ` +\n `documentId(), you must provide a plain document ID, but ` +\n `'${documentIdValue}' contains a '/' character.`\n );\n }\n const path = query.path.child(ResourcePath.fromString(documentIdValue));\n if (!DocumentKey.isDocumentKey(path)) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid query. When querying a collection group by ` +\n `documentId(), the value provided must result in a valid document path, ` +\n `but '${path}' is not because it has an odd number of segments (${path.length}).`\n );\n }\n return refValue(databaseId, new DocumentKey(path));\n } else if (documentIdValue instanceof DocumentReference) {\n return refValue(databaseId, documentIdValue._key);\n } else {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid query. When querying with documentId(), you must provide a valid ` +\n `string or a DocumentReference, but it was: ` +\n `${valueDescription(documentIdValue)}.`\n );\n }\n}\n\n/**\n * Validates that the value passed into a disjunctive filter satisfies all\n * array requirements.\n */\nfunction validateDisjunctiveFilterElements(\n value: unknown,\n operator: Operator\n): void {\n if (!Array.isArray(value) || value.length === 0) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Invalid Query. A non-empty array is required for ' +\n `'${operator.toString()}' filters.`\n );\n }\n}\n\n/**\n * Given an operator, returns the set of operators that cannot be used with it.\n *\n * This is not a comprehensive check, and this function should be removed in the\n * long term. Validations should occur in the Firestore backend.\n *\n * Operators in a query must adhere to the following set of rules:\n * 1. Only one inequality per query.\n * 2. `NOT_IN` cannot be used with array, disjunctive, or `NOT_EQUAL` operators.\n */\nfunction conflictingOps(op: Operator): Operator[] {\n switch (op) {\n case Operator.NOT_EQUAL:\n return [Operator.NOT_EQUAL, Operator.NOT_IN];\n case Operator.ARRAY_CONTAINS_ANY:\n case Operator.IN:\n return [Operator.NOT_IN];\n case Operator.NOT_IN:\n return [\n Operator.ARRAY_CONTAINS_ANY,\n Operator.IN,\n Operator.NOT_IN,\n Operator.NOT_EQUAL\n ];\n default:\n return [];\n }\n}\n\nfunction validateNewFieldFilter(\n query: InternalQuery,\n fieldFilter: FieldFilter\n): void {\n const conflictingOp = findOpInsideFilters(\n query.filters,\n conflictingOps(fieldFilter.op)\n );\n if (conflictingOp !== null) {\n // Special case when it's a duplicate op to give a slightly clearer error message.\n if (conflictingOp === fieldFilter.op) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Invalid query. You cannot use more than one ' +\n `'${fieldFilter.op.toString()}' filter.`\n );\n } else {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid query. You cannot use '${fieldFilter.op.toString()}' filters ` +\n `with '${conflictingOp.toString()}' filters.`\n );\n }\n }\n}\n\nfunction validateNewFilter(query: InternalQuery, filter: Filter): void {\n let testQuery = query;\n const subFilters = filter.getFlattenedFilters();\n for (const subFilter of subFilters) {\n validateNewFieldFilter(testQuery, subFilter);\n testQuery = queryWithAddedFilter(testQuery, subFilter);\n }\n}\n\n// Checks if any of the provided filter operators are included in the given list of filters and\n// returns the first one that is, or null if none are.\nfunction findOpInsideFilters(\n filters: Filter[],\n operators: Operator[]\n): Operator | null {\n for (const filter of filters) {\n for (const fieldFilter of filter.getFlattenedFilters()) {\n if (operators.indexOf(fieldFilter.op) >= 0) {\n return fieldFilter.op;\n }\n }\n }\n return null;\n}\n\nexport function validateQueryFilterConstraint(\n functionName: string,\n queryConstraint: AppliableConstraint\n): void {\n if (\n !(queryConstraint instanceof QueryFieldFilterConstraint) &&\n !(queryConstraint instanceof QueryCompositeFilterConstraint)\n ) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Function ${functionName}() requires AppliableConstraints created with a call to 'where(...)', 'or(...)', or 'and(...)'.`\n );\n }\n}\n\nfunction validateQueryConstraintArray(\n queryConstraint: AppliableConstraint[]\n): void {\n const compositeFilterCount = queryConstraint.filter(\n filter => filter instanceof QueryCompositeFilterConstraint\n ).length;\n const fieldFilterCount = queryConstraint.filter(\n filter => filter instanceof QueryFieldFilterConstraint\n ).length;\n\n if (\n compositeFilterCount > 1 ||\n (compositeFilterCount > 0 && fieldFilterCount > 0)\n ) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'InvalidQuery. When using composite filters, you cannot use ' +\n 'more than one filter at the top level. Consider nesting the multiple ' +\n 'filters within an `and(...)` statement. For example: ' +\n 'change `query(query, where(...), or(...))` to ' +\n '`query(query, and(where(...), or(...)))`.'\n );\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DocumentData } from '@firebase/firestore-types';\n\nimport { DatabaseId } from '../core/database_info';\nimport { DocumentKey } from '../model/document_key';\nimport {\n normalizeByteString,\n normalizeNumber,\n normalizeTimestamp\n} from '../model/normalize';\nimport { ResourcePath } from '../model/path';\nimport {\n getLocalWriteTime,\n getPreviousValue\n} from '../model/server_timestamps';\nimport { TypeOrder } from '../model/type_order';\nimport { VECTOR_MAP_VECTORS_KEY, typeOrder } from '../model/values';\nimport {\n ApiClientObjectMap,\n ArrayValue as ProtoArrayValue,\n LatLng as ProtoLatLng,\n MapValue as ProtoMapValue,\n Timestamp as ProtoTimestamp,\n Value,\n Value as ProtoValue\n} from '../protos/firestore_proto_api';\nimport { isValidResourceName } from '../remote/serializer';\nimport { fail, hardAssert } from '../util/assert';\nimport { ByteString } from '../util/byte_string';\nimport { logError } from '../util/log';\nimport { forEach } from '../util/obj';\n\nimport { GeoPoint } from './geo_point';\nimport { Timestamp } from './timestamp';\nimport { VectorValue } from './vector_value';\n\nexport type ServerTimestampBehavior = 'estimate' | 'previous' | 'none';\n\n/**\n * Converts Firestore's internal types to the JavaScript types that we expose\n * to the user.\n *\n * @internal\n */\nexport abstract class AbstractUserDataWriter {\n convertValue(\n value: ProtoValue,\n serverTimestampBehavior: ServerTimestampBehavior = 'none'\n ): unknown {\n switch (typeOrder(value)) {\n case TypeOrder.NullValue:\n return null;\n case TypeOrder.BooleanValue:\n return value.booleanValue!;\n case TypeOrder.NumberValue:\n return normalizeNumber(value.integerValue || value.doubleValue);\n case TypeOrder.TimestampValue:\n return this.convertTimestamp(value.timestampValue!);\n case TypeOrder.ServerTimestampValue:\n return this.convertServerTimestamp(value, serverTimestampBehavior);\n case TypeOrder.StringValue:\n return value.stringValue!;\n case TypeOrder.BlobValue:\n return this.convertBytes(normalizeByteString(value.bytesValue!));\n case TypeOrder.RefValue:\n return this.convertReference(value.referenceValue!);\n case TypeOrder.GeoPointValue:\n return this.convertGeoPoint(value.geoPointValue!);\n case TypeOrder.ArrayValue:\n return this.convertArray(value.arrayValue!, serverTimestampBehavior);\n case TypeOrder.ObjectValue:\n return this.convertObject(value.mapValue!, serverTimestampBehavior);\n case TypeOrder.VectorValue:\n return this.convertVectorValue(value.mapValue!);\n default:\n throw fail(0xf2a2, 'Invalid value type', {\n value\n });\n }\n }\n\n private convertObject(\n mapValue: ProtoMapValue,\n serverTimestampBehavior: ServerTimestampBehavior\n ): DocumentData {\n return this.convertObjectMap(mapValue.fields, serverTimestampBehavior);\n }\n\n /**\n * @internal\n */\n convertObjectMap(\n fields: ApiClientObjectMap | undefined,\n serverTimestampBehavior: ServerTimestampBehavior = 'none'\n ): DocumentData {\n const result: DocumentData = {};\n forEach(fields, (key, value) => {\n result[key] = this.convertValue(value, serverTimestampBehavior);\n });\n return result;\n }\n\n /**\n * @internal\n */\n convertVectorValue(mapValue: ProtoMapValue): VectorValue {\n const values = mapValue.fields?.[\n VECTOR_MAP_VECTORS_KEY\n ].arrayValue?.values?.map(value => {\n return normalizeNumber(value.doubleValue);\n });\n\n return new VectorValue(values);\n }\n\n private convertGeoPoint(value: ProtoLatLng): GeoPoint {\n return new GeoPoint(\n normalizeNumber(value.latitude),\n normalizeNumber(value.longitude)\n );\n }\n\n private convertArray(\n arrayValue: ProtoArrayValue,\n serverTimestampBehavior: ServerTimestampBehavior\n ): unknown[] {\n return (arrayValue.values || []).map(value =>\n this.convertValue(value, serverTimestampBehavior)\n );\n }\n\n private convertServerTimestamp(\n value: ProtoValue,\n serverTimestampBehavior: ServerTimestampBehavior\n ): unknown {\n switch (serverTimestampBehavior) {\n case 'previous':\n const previousValue = getPreviousValue(value);\n if (previousValue == null) {\n return null;\n }\n return this.convertValue(previousValue, serverTimestampBehavior);\n case 'estimate':\n return this.convertTimestamp(getLocalWriteTime(value));\n default:\n return null;\n }\n }\n\n private convertTimestamp(value: ProtoTimestamp): Timestamp {\n const normalizedValue = normalizeTimestamp(value);\n return new Timestamp(normalizedValue.seconds, normalizedValue.nanos);\n }\n\n protected convertDocumentKey(\n name: string,\n expectedDatabaseId: DatabaseId\n ): DocumentKey {\n const resourcePath = ResourcePath.fromString(name);\n hardAssert(\n isValidResourceName(resourcePath),\n 0x25d8,\n 'ReferenceValue is not valid',\n { name }\n );\n const databaseId = new DatabaseId(resourcePath.get(1), resourcePath.get(3));\n const key = new DocumentKey(resourcePath.popFirst(5));\n\n if (!databaseId.isEqual(expectedDatabaseId)) {\n // TODO(b/64130202): Somehow support foreign references.\n logError(\n `Document ${key} contains a document ` +\n `reference within a different database (` +\n `${databaseId.projectId}/${databaseId.database}) which is not ` +\n `supported. It will be treated as a reference in the current ` +\n `database (${expectedDatabaseId.projectId}/${expectedDatabaseId.database}) ` +\n `instead.`\n );\n }\n return key;\n }\n\n protected abstract convertReference(name: string): unknown;\n\n protected abstract convertBytes(bytes: ByteString): unknown;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n DocumentData as PublicDocumentData,\n SetOptions as PublicSetOptions\n} from '@firebase/firestore-types';\nimport { getModularInstance } from '@firebase/util';\n\nimport { LimitType } from '../core/query';\nimport { DeleteMutation, Precondition } from '../model/mutation';\nimport {\n invokeBatchGetDocumentsRpc,\n invokeCommitRpc,\n invokeRunQueryRpc\n} from '../remote/datastore';\nimport { hardAssert } from '../util/assert';\nimport { ByteString } from '../util/byte_string';\nimport { cast } from '../util/input_validation';\n\nimport { Bytes } from './bytes';\nimport { getDatastore } from './components';\nimport { Firestore } from './database';\nimport { FieldPath } from './field_path';\nimport { validateHasExplicitOrderByForLimitToLast } from './query';\nimport {\n CollectionReference,\n doc,\n DocumentData,\n DocumentReference,\n PartialWithFieldValue,\n Query,\n SetOptions,\n UpdateData,\n WithFieldValue\n} from './reference';\nimport {\n DocumentSnapshot,\n QueryDocumentSnapshot,\n QuerySnapshot\n} from './snapshot';\nimport {\n newUserDataReader,\n ParsedUpdateData,\n parseSetData,\n parseUpdateData,\n parseUpdateVarargs,\n UntypedFirestoreDataConverter\n} from './user_data_reader';\nimport { AbstractUserDataWriter } from './user_data_writer';\n\n/**\n * Converts custom model object of type T into `DocumentData` by applying the\n * converter if it exists.\n *\n * This function is used when converting user objects to `DocumentData`\n * because we want to provide the user with a more specific error message if\n * their `set()` or fails due to invalid data originating from a `toFirestore()`\n * call.\n */\nexport function applyFirestoreDataConverter(\n converter: UntypedFirestoreDataConverter | null,\n value: WithFieldValue | PartialWithFieldValue,\n options?: PublicSetOptions\n): PublicDocumentData {\n let convertedValue;\n if (converter) {\n if (options && (options.merge || options.mergeFields)) {\n // Cast to `any` in order to satisfy the union type constraint on\n // toFirestore().\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n convertedValue = (converter as any).toFirestore(value, options);\n } else {\n convertedValue = converter.toFirestore(value as WithFieldValue);\n }\n } else {\n convertedValue = value as PublicDocumentData;\n }\n return convertedValue;\n}\n\nexport class LiteUserDataWriter extends AbstractUserDataWriter {\n constructor(protected firestore: Firestore) {\n super();\n }\n\n protected convertBytes(bytes: ByteString): Bytes {\n return new Bytes(bytes);\n }\n\n protected convertReference(name: string): DocumentReference {\n const key = this.convertDocumentKey(name, this.firestore._databaseId);\n return new DocumentReference(this.firestore, /* converter= */ null, key);\n }\n}\n\n/**\n * Reads the document referred to by the specified document reference.\n *\n * All documents are directly fetched from the server, even if the document was\n * previously read or modified. Recent modifications are only reflected in the\n * retrieved `DocumentSnapshot` if they have already been applied by the\n * backend. If the client is offline, the read fails. If you like to use\n * caching or see local modifications, please use the full Firestore SDK.\n *\n * @param reference - The reference of the document to fetch.\n * @returns A Promise resolved with a `DocumentSnapshot` containing the current\n * document contents.\n */\nexport function getDoc(\n reference: DocumentReference\n): Promise> {\n reference = cast>(\n reference,\n DocumentReference\n );\n const datastore = getDatastore(reference.firestore);\n const userDataWriter = new LiteUserDataWriter(reference.firestore);\n\n return invokeBatchGetDocumentsRpc(datastore, [reference._key]).then(\n result => {\n hardAssert(\n result.length === 1,\n 0x3d02,\n 'Expected a single document result'\n );\n const document = result[0];\n return new DocumentSnapshot(\n reference.firestore,\n userDataWriter,\n reference._key,\n document.isFoundDocument() ? document : null,\n reference.converter\n );\n }\n );\n}\n\n/**\n * Executes the query and returns the results as a {@link QuerySnapshot}.\n *\n * All queries are executed directly by the server, even if the query was\n * previously executed. Recent modifications are only reflected in the retrieved\n * results if they have already been applied by the backend. If the client is\n * offline, the operation fails. To see previously cached result and local\n * modifications, use the full Firestore SDK.\n *\n * @param query - The `Query` to execute.\n * @returns A Promise that will be resolved with the results of the query.\n */\nexport function getDocs(\n query: Query\n): Promise> {\n query = cast>(query, Query);\n validateHasExplicitOrderByForLimitToLast(query._query);\n\n const datastore = getDatastore(query.firestore);\n const userDataWriter = new LiteUserDataWriter(query.firestore);\n return invokeRunQueryRpc(datastore, query._query).then(result => {\n const docs = result.map(\n doc =>\n new QueryDocumentSnapshot(\n query.firestore,\n userDataWriter,\n doc.key,\n doc,\n query.converter\n )\n );\n\n if (query._query.limitType === LimitType.Last) {\n // Limit to last queries reverse the orderBy constraint that was\n // specified by the user. As such, we need to reverse the order of the\n // results to return the documents in the expected order.\n docs.reverse();\n }\n\n return new QuerySnapshot(query, docs);\n });\n}\n\n/**\n * Writes to the document referred to by the specified `DocumentReference`. If\n * the document does not yet exist, it will be created.\n *\n * The result of this write will only be reflected in document reads that occur\n * after the returned promise resolves. If the client is offline, the\n * write fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the document to write.\n * @param data - A map of the fields and values for the document.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns A `Promise` resolved once the data has been successfully written\n * to the backend.\n */\nexport function setDoc(\n reference: DocumentReference,\n data: WithFieldValue\n): Promise;\n/**\n * Writes to the document referred to by the specified `DocumentReference`. If\n * the document does not yet exist, it will be created. If you provide `merge`\n * or `mergeFields`, the provided data can be merged into an existing document.\n *\n * The result of this write will only be reflected in document reads that occur\n * after the returned promise resolves. If the client is offline, the\n * write fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the document to write.\n * @param data - A map of the fields and values for the document.\n * @param options - An object to configure the set behavior.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns A `Promise` resolved once the data has been successfully written\n * to the backend.\n */\nexport function setDoc(\n reference: DocumentReference,\n data: PartialWithFieldValue,\n options: SetOptions\n): Promise;\nexport function setDoc(\n reference: DocumentReference,\n data: PartialWithFieldValue,\n options?: SetOptions\n): Promise {\n reference = cast>(\n reference,\n DocumentReference\n );\n const convertedValue = applyFirestoreDataConverter(\n reference.converter,\n data,\n options\n );\n const dataReader = newUserDataReader(reference.firestore);\n const parsed = parseSetData(\n dataReader,\n 'setDoc',\n reference._key,\n convertedValue,\n reference.converter !== null,\n options\n );\n\n const datastore = getDatastore(reference.firestore);\n return invokeCommitRpc(datastore, [\n parsed.toMutation(reference._key, Precondition.none())\n ]);\n}\n\n/**\n * Updates fields in the document referred to by the specified\n * `DocumentReference`. The update will fail if applied to a document that does\n * not exist.\n *\n * The result of this update will only be reflected in document reads that occur\n * after the returned promise resolves. If the client is offline, the\n * update fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the document to update.\n * @param data - An object containing the fields and values with which to\n * update the document. Fields can contain dots to reference nested fields\n * within the document.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns A `Promise` resolved once the data has been successfully written\n * to the backend.\n */\nexport function updateDoc(\n reference: DocumentReference,\n data: UpdateData\n): Promise;\n/**\n * Updates fields in the document referred to by the specified\n * `DocumentReference` The update will fail if applied to a document that does\n * not exist.\n *\n * Nested fields can be updated by providing dot-separated field path\n * strings or by providing `FieldPath` objects.\n *\n * The result of this update will only be reflected in document reads that occur\n * after the returned promise resolves. If the client is offline, the\n * update fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the document to update.\n * @param field - The first field to update.\n * @param value - The first value.\n * @param moreFieldsAndValues - Additional key value pairs.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns A `Promise` resolved once the data has been successfully written\n * to the backend.\n */\nexport function updateDoc(\n reference: DocumentReference,\n field: string | FieldPath,\n value: unknown,\n ...moreFieldsAndValues: unknown[]\n): Promise;\nexport function updateDoc(\n reference: DocumentReference,\n fieldOrUpdateData: string | FieldPath | UpdateData,\n value?: unknown,\n ...moreFieldsAndValues: unknown[]\n): Promise {\n reference = cast>(\n reference,\n DocumentReference\n );\n const dataReader = newUserDataReader(reference.firestore);\n\n // For Compat types, we have to \"extract\" the underlying types before\n // performing validation.\n fieldOrUpdateData = getModularInstance(fieldOrUpdateData);\n\n let parsed: ParsedUpdateData;\n if (\n typeof fieldOrUpdateData === 'string' ||\n fieldOrUpdateData instanceof FieldPath\n ) {\n parsed = parseUpdateVarargs(\n dataReader,\n 'updateDoc',\n reference._key,\n fieldOrUpdateData,\n value,\n moreFieldsAndValues\n );\n } else {\n parsed = parseUpdateData(\n dataReader,\n 'updateDoc',\n reference._key,\n fieldOrUpdateData\n );\n }\n\n const datastore = getDatastore(reference.firestore);\n return invokeCommitRpc(datastore, [\n parsed.toMutation(reference._key, Precondition.exists(true))\n ]);\n}\n\n/**\n * Deletes the document referred to by the specified `DocumentReference`.\n *\n * The deletion will only be reflected in document reads that occur after the\n * returned promise resolves. If the client is offline, the\n * delete fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the document to delete.\n * @returns A `Promise` resolved once the document has been successfully\n * deleted from the backend.\n */\nexport function deleteDoc(\n reference: DocumentReference\n): Promise {\n reference = cast>(\n reference,\n DocumentReference\n );\n const datastore = getDatastore(reference.firestore);\n return invokeCommitRpc(datastore, [\n new DeleteMutation(reference._key, Precondition.none())\n ]);\n}\n\n/**\n * Add a new document to specified `CollectionReference` with the given data,\n * assigning it a document ID automatically.\n *\n * The result of this write will only be reflected in document reads that occur\n * after the returned promise resolves. If the client is offline, the\n * write fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the collection to add this document to.\n * @param data - An Object containing the data for the new document.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns A `Promise` resolved with a `DocumentReference` pointing to the\n * newly created document after it has been written to the backend.\n */\nexport function addDoc(\n reference: CollectionReference,\n data: WithFieldValue\n): Promise> {\n reference = cast>(\n reference,\n CollectionReference\n );\n const docRef = doc(reference);\n\n const convertedValue = applyFirestoreDataConverter(\n reference.converter,\n data as PartialWithFieldValue\n );\n\n const dataReader = newUserDataReader(reference.firestore);\n const parsed = parseSetData(\n dataReader,\n 'addDoc',\n docRef._key,\n convertedValue,\n docRef.converter !== null,\n {}\n );\n\n const datastore = getDatastore(reference.firestore);\n return invokeCommitRpc(datastore, [\n parsed.toMutation(docRef._key, Precondition.exists(false))\n ]).then(() => docRef);\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { deepEqual } from '@firebase/util';\n\nimport { AggregateImpl } from '../core/aggregate';\nimport { ApiClientObjectMap, Value } from '../protos/firestore_proto_api';\nimport { invokeRunAggregationQueryRpc } from '../remote/datastore';\nimport { cast } from '../util/input_validation';\nimport { mapToArray } from '../util/obj';\n\nimport {\n AggregateField,\n AggregateQuerySnapshot,\n AggregateSpec\n} from './aggregate_types';\nimport { getDatastore } from './components';\nimport { Firestore } from './database';\nimport { FieldPath } from './field_path';\nimport { DocumentData, Query, queryEqual } from './reference';\nimport { LiteUserDataWriter } from './reference_impl';\nimport { fieldPathFromArgument } from './user_data_reader';\n\n/**\n * Calculates the number of documents in the result set of the given query\n * without actually downloading the documents.\n *\n * Using this function to count the documents is efficient because only the\n * final count, not the documents' data, is downloaded. This function can\n * count the documents in cases where the result set is prohibitively large to\n * download entirely (thousands of documents).\n *\n * @param query The query whose result set size is calculated.\n * @returns A Promise that will be resolved with the count; the count can be\n * retrieved from `snapshot.data().count`, where `snapshot` is the\n * `AggregateQuerySnapshot` to which the returned Promise resolves.\n */\nexport function getCount(\n query: Query\n): Promise<\n AggregateQuerySnapshot<\n { count: AggregateField },\n AppModelType,\n DbModelType\n >\n> {\n const countQuerySpec: { count: AggregateField } = {\n count: count()\n };\n\n return getAggregate(query, countQuerySpec);\n}\n\n/**\n * Calculates the specified aggregations over the documents in the result\n * set of the given query without actually downloading the documents.\n *\n * Using this function to perform aggregations is efficient because only the\n * final aggregation values, not the documents' data, are downloaded. This\n * function can perform aggregations of the documents in cases where the result\n * set is prohibitively large to download entirely (thousands of documents).\n *\n * @param query The query whose result set is aggregated over.\n * @param aggregateSpec An `AggregateSpec` object that specifies the aggregates\n * to perform over the result set. The AggregateSpec specifies aliases for each\n * aggregate, which can be used to retrieve the aggregate result.\n * @example\n * ```typescript\n * const aggregateSnapshot = await getAggregate(query, {\n * countOfDocs: count(),\n * totalHours: sum('hours'),\n * averageScore: average('score')\n * });\n *\n * const countOfDocs: number = aggregateSnapshot.data().countOfDocs;\n * const totalHours: number = aggregateSnapshot.data().totalHours;\n * const averageScore: number | null = aggregateSnapshot.data().averageScore;\n * ```\n */\nexport function getAggregate<\n AggregateSpecType extends AggregateSpec,\n AppModelType,\n DbModelType extends DocumentData\n>(\n query: Query,\n aggregateSpec: AggregateSpecType\n): Promise<\n AggregateQuerySnapshot\n> {\n const firestore = cast(query.firestore, Firestore);\n const datastore = getDatastore(firestore);\n\n const internalAggregates = mapToArray(aggregateSpec, (aggregate, alias) => {\n return new AggregateImpl(\n alias,\n aggregate.aggregateType,\n aggregate._internalFieldPath\n );\n });\n\n // Run the aggregation and convert the results\n return invokeRunAggregationQueryRpc(\n datastore,\n query._query,\n internalAggregates\n ).then(aggregateResult =>\n convertToAggregateQuerySnapshot(firestore, query, aggregateResult)\n );\n}\n\nfunction convertToAggregateQuerySnapshot<\n AggregateSpecType extends AggregateSpec,\n AppModelType,\n DbModelType extends DocumentData\n>(\n firestore: Firestore,\n query: Query,\n aggregateResult: ApiClientObjectMap\n): AggregateQuerySnapshot {\n const userDataWriter = new LiteUserDataWriter(firestore);\n const querySnapshot = new AggregateQuerySnapshot<\n AggregateSpecType,\n AppModelType,\n DbModelType\n >(query, userDataWriter, aggregateResult);\n return querySnapshot;\n}\n\n/**\n * Create an AggregateField object that can be used to compute the sum of\n * a specified field over a range of documents in the result set of a query.\n * @param field Specifies the field to sum across the result set.\n */\nexport function sum(field: string | FieldPath): AggregateField {\n return new AggregateField('sum', fieldPathFromArgument('sum', field));\n}\n\n/**\n * Create an AggregateField object that can be used to compute the average of\n * a specified field over a range of documents in the result set of a query.\n * @param field Specifies the field to average across the result set.\n */\nexport function average(\n field: string | FieldPath\n): AggregateField {\n return new AggregateField('avg', fieldPathFromArgument('average', field));\n}\n\n/**\n * Create an AggregateField object that can be used to compute the count of\n * documents in the result set of a query.\n */\nexport function count(): AggregateField {\n return new AggregateField('count');\n}\n\n/**\n * Compares two 'AggregateField` instances for equality.\n *\n * @param left Compare this AggregateField to the `right`.\n * @param right Compare this AggregateField to the `left`.\n */\nexport function aggregateFieldEqual(\n left: AggregateField,\n right: AggregateField\n): boolean {\n return (\n left instanceof AggregateField &&\n right instanceof AggregateField &&\n left.aggregateType === right.aggregateType &&\n left._internalFieldPath?.canonicalString() ===\n right._internalFieldPath?.canonicalString()\n );\n}\n\n/**\n * Compares two `AggregateQuerySnapshot` instances for equality.\n *\n * Two `AggregateQuerySnapshot` instances are considered \"equal\" if they have\n * underlying queries that compare equal, and the same data.\n *\n * @param left - The first `AggregateQuerySnapshot` to compare.\n * @param right - The second `AggregateQuerySnapshot` to compare.\n *\n * @returns `true` if the objects are \"equal\", as defined above, or `false`\n * otherwise.\n */\nexport function aggregateQuerySnapshotEqual<\n AggregateSpecType extends AggregateSpec,\n AppModelType,\n DbModelType extends DocumentData\n>(\n left: AggregateQuerySnapshot,\n right: AggregateQuerySnapshot\n): boolean {\n return (\n queryEqual(left.query, right.query) && deepEqual(left.data(), right.data())\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FieldValue } from './field_value';\nimport {\n ArrayRemoveFieldValueImpl,\n ArrayUnionFieldValueImpl,\n DeleteFieldValueImpl,\n NumericIncrementFieldValueImpl,\n ServerTimestampFieldValueImpl\n} from './user_data_reader';\nimport { VectorValue } from './vector_value';\n\n/**\n * Returns a sentinel for use with {@link @firebase/firestore/lite#(updateDoc:1)} or\n * {@link @firebase/firestore/lite#(setDoc:1)} with `{merge: true}` to mark a field for deletion.\n */\nexport function deleteField(): FieldValue {\n return new DeleteFieldValueImpl('deleteField');\n}\n\n/**\n * Returns a sentinel used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link @firebase/firestore/lite#(updateDoc:1)} to\n * include a server-generated timestamp in the written data.\n */\nexport function serverTimestamp(): FieldValue {\n return new ServerTimestampFieldValueImpl('serverTimestamp');\n}\n\n/**\n * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link\n * @firebase/firestore/lite#(updateDoc:1)} that tells the server to union the given elements with any array\n * value that already exists on the server. Each specified element that doesn't\n * already exist in the array will be added to the end. If the field being\n * modified is not already an array it will be overwritten with an array\n * containing exactly the specified elements.\n *\n * @param elements - The elements to union into the array.\n * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or\n * `updateDoc()`.\n */\nexport function arrayUnion(...elements: unknown[]): FieldValue {\n // NOTE: We don't actually parse the data until it's used in set() or\n // update() since we'd need the Firestore instance to do this.\n return new ArrayUnionFieldValueImpl('arrayUnion', elements);\n}\n\n/**\n * Returns a special value that can be used with {@link (setDoc:1)} or {@link\n * updateDoc:1} that tells the server to remove the given elements from any\n * array value that already exists on the server. All instances of each element\n * specified will be removed from the array. If the field being modified is not\n * already an array it will be overwritten with an empty array.\n *\n * @param elements - The elements to remove from the array.\n * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or\n * `updateDoc()`\n */\nexport function arrayRemove(...elements: unknown[]): FieldValue {\n // NOTE: We don't actually parse the data until it's used in set() or\n // update() since we'd need the Firestore instance to do this.\n return new ArrayRemoveFieldValueImpl('arrayRemove', elements);\n}\n\n/**\n * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link\n * @firebase/firestore/lite#(updateDoc:1)} that tells the server to increment the field's current value by\n * the given value.\n *\n * If either the operand or the current field value uses floating point\n * precision, all arithmetic follows IEEE 754 semantics. If both values are\n * integers, values outside of JavaScript's safe number range\n * (`Number.MIN_SAFE_INTEGER` to `Number.MAX_SAFE_INTEGER`) are also subject to\n * precision loss. Furthermore, once processed by the Firestore backend, all\n * integer operations are capped between -2^63 and 2^63-1.\n *\n * If the current field value is not of type `number`, or if the field does not\n * yet exist, the transformation sets the field to the given value.\n *\n * @param n - The value to increment by.\n * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or\n * `updateDoc()`\n */\nexport function increment(n: number): FieldValue {\n return new NumericIncrementFieldValueImpl('increment', n);\n}\n\n/**\n * Creates a new `VectorValue` constructed with a copy of the given array of numbers.\n *\n * @param values - Create a `VectorValue` instance with a copy of this array of numbers.\n *\n * @returns A new `VectorValue` constructed with a copy of the given array of numbers.\n */\nexport function vector(values?: number[]): VectorValue {\n return new VectorValue(values);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Compat, getModularInstance } from '@firebase/util';\n\nimport { DeleteMutation, Mutation, Precondition } from '../model/mutation';\nimport { invokeCommitRpc } from '../remote/datastore';\nimport { Code, FirestoreError } from '../util/error';\nimport { cast } from '../util/input_validation';\n\nimport { getDatastore } from './components';\nimport { Firestore } from './database';\nimport { FieldPath } from './field_path';\nimport {\n DocumentData,\n DocumentReference,\n PartialWithFieldValue,\n SetOptions,\n UpdateData,\n WithFieldValue\n} from './reference';\nimport { applyFirestoreDataConverter } from './reference_impl';\nimport {\n newUserDataReader,\n parseSetData,\n parseUpdateData,\n parseUpdateVarargs,\n UserDataReader\n} from './user_data_reader';\n\n/**\n * A write batch, used to perform multiple writes as a single atomic unit.\n *\n * A `WriteBatch` object can be acquired by calling {@link writeBatch}. It\n * provides methods for adding writes to the write batch. None of the writes\n * will be committed (or visible locally) until {@link WriteBatch.commit} is\n * called.\n */\nexport class WriteBatch {\n // This is the lite version of the WriteBatch API used in the legacy SDK. The\n // class is a close copy but takes different input types.\n\n private readonly _dataReader: UserDataReader;\n private _mutations = [] as Mutation[];\n private _committed = false;\n\n /** @hideconstructor */\n constructor(\n private readonly _firestore: Firestore,\n private readonly _commitHandler: (m: Mutation[]) => Promise\n ) {\n this._dataReader = newUserDataReader(_firestore);\n }\n\n /**\n * Writes to the document referred to by the provided {@link\n * DocumentReference}. If the document does not exist yet, it will be created.\n *\n * @param documentRef - A reference to the document to be set.\n * @param data - An object of the fields and values for the document.\n * @returns This `WriteBatch` instance. Used for chaining method calls.\n */\n set(\n documentRef: DocumentReference,\n data: WithFieldValue\n ): WriteBatch;\n /**\n * Writes to the document referred to by the provided {@link\n * DocumentReference}. If the document does not exist yet, it will be created.\n * If you provide `merge` or `mergeFields`, the provided data can be merged\n * into an existing document.\n *\n * @param documentRef - A reference to the document to be set.\n * @param data - An object of the fields and values for the document.\n * @param options - An object to configure the set behavior.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns This `WriteBatch` instance. Used for chaining method calls.\n */\n set(\n documentRef: DocumentReference,\n data: PartialWithFieldValue,\n options: SetOptions\n ): WriteBatch;\n set(\n documentRef: DocumentReference,\n data: WithFieldValue | PartialWithFieldValue,\n options?: SetOptions\n ): WriteBatch {\n this._verifyNotCommitted();\n const ref = validateReference(documentRef, this._firestore);\n\n const convertedValue = applyFirestoreDataConverter(\n ref.converter,\n data,\n options\n );\n const parsed = parseSetData(\n this._dataReader,\n 'WriteBatch.set',\n ref._key,\n convertedValue,\n ref.converter !== null,\n options\n );\n this._mutations.push(parsed.toMutation(ref._key, Precondition.none()));\n return this;\n }\n\n /**\n * Updates fields in the document referred to by the provided {@link\n * DocumentReference}. The update will fail if applied to a document that does\n * not exist.\n *\n * @param documentRef - A reference to the document to be updated.\n * @param data - An object containing the fields and values with which to\n * update the document. Fields can contain dots to reference nested fields\n * within the document.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns This `WriteBatch` instance. Used for chaining method calls.\n */\n update(\n documentRef: DocumentReference,\n data: UpdateData\n ): WriteBatch;\n /**\n * Updates fields in the document referred to by this {@link\n * DocumentReference}. The update will fail if applied to a document that does\n * not exist.\n *\n * Nested fields can be update by providing dot-separated field path strings\n * or by providing `FieldPath` objects.\n *\n * @param documentRef - A reference to the document to be updated.\n * @param field - The first field to update.\n * @param value - The first value.\n * @param moreFieldsAndValues - Additional key value pairs.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns This `WriteBatch` instance. Used for chaining method calls.\n */\n update(\n documentRef: DocumentReference,\n field: string | FieldPath,\n value: unknown,\n ...moreFieldsAndValues: unknown[]\n ): WriteBatch;\n update(\n documentRef: DocumentReference,\n fieldOrUpdateData: string | FieldPath | UpdateData,\n value?: unknown,\n ...moreFieldsAndValues: unknown[]\n ): WriteBatch {\n this._verifyNotCommitted();\n const ref = validateReference(documentRef, this._firestore);\n\n // For Compat types, we have to \"extract\" the underlying types before\n // performing validation.\n fieldOrUpdateData = getModularInstance(fieldOrUpdateData);\n\n let parsed;\n if (\n typeof fieldOrUpdateData === 'string' ||\n fieldOrUpdateData instanceof FieldPath\n ) {\n parsed = parseUpdateVarargs(\n this._dataReader,\n 'WriteBatch.update',\n ref._key,\n fieldOrUpdateData,\n value,\n moreFieldsAndValues\n );\n } else {\n parsed = parseUpdateData(\n this._dataReader,\n 'WriteBatch.update',\n ref._key,\n fieldOrUpdateData\n );\n }\n\n this._mutations.push(\n parsed.toMutation(ref._key, Precondition.exists(true))\n );\n return this;\n }\n\n /**\n * Deletes the document referred to by the provided {@link DocumentReference}.\n *\n * @param documentRef - A reference to the document to be deleted.\n * @returns This `WriteBatch` instance. Used for chaining method calls.\n */\n delete(\n documentRef: DocumentReference\n ): WriteBatch {\n this._verifyNotCommitted();\n const ref = validateReference(documentRef, this._firestore);\n this._mutations = this._mutations.concat(\n new DeleteMutation(ref._key, Precondition.none())\n );\n return this;\n }\n\n /**\n * Commits all of the writes in this write batch as a single atomic unit.\n *\n * The result of these writes will only be reflected in document reads that\n * occur after the returned promise resolves. If the client is offline, the\n * write fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @returns A `Promise` resolved once all of the writes in the batch have been\n * successfully written to the backend as an atomic unit (note that it won't\n * resolve while you're offline).\n */\n commit(): Promise {\n this._verifyNotCommitted();\n this._committed = true;\n if (this._mutations.length > 0) {\n return this._commitHandler(this._mutations);\n }\n\n return Promise.resolve();\n }\n\n private _verifyNotCommitted(): void {\n if (this._committed) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'A write batch can no longer be used after commit() ' +\n 'has been called.'\n );\n }\n }\n}\n\nexport function validateReference<\n AppModelType,\n DbModelType extends DocumentData\n>(\n documentRef:\n | DocumentReference\n | Compat>,\n firestore: Firestore\n): DocumentReference {\n documentRef = getModularInstance(documentRef);\n\n if (documentRef.firestore !== firestore) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Provided document reference is from a different Firestore instance.'\n );\n } else {\n return documentRef as DocumentReference;\n }\n}\n\n/**\n * Creates a write batch, used for performing multiple writes as a single\n * atomic operation. The maximum number of writes allowed in a single WriteBatch\n * is 500.\n *\n * The result of these writes will only be reflected in document reads that\n * occur after the returned promise resolves. If the client is offline, the\n * write fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @returns A `WriteBatch` that can be used to atomically execute multiple\n * writes.\n */\nexport function writeBatch(firestore: Firestore): WriteBatch {\n firestore = cast(firestore, Firestore);\n const datastore = getDatastore(firestore);\n return new WriteBatch(firestore, writes =>\n invokeCommitRpc(datastore, writes)\n );\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Code, FirestoreError } from '../util/error';\n\nexport const DEFAULT_TRANSACTION_OPTIONS: TransactionOptions = {\n maxAttempts: 5\n};\n\n/**\n * Options to customize transaction behavior.\n */\nexport declare interface TransactionOptions {\n /** Maximum number of attempts to commit, after which transaction fails. Default is 5. */\n readonly maxAttempts: number;\n}\n\nexport function validateTransactionOptions(options: TransactionOptions): void {\n if (options.maxAttempts < 1) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Max attempts must be at least 1'\n );\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ParsedSetData, ParsedUpdateData } from '../lite-api/user_data_reader';\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport {\n DeleteMutation,\n Mutation,\n Precondition,\n VerifyMutation\n} from '../model/mutation';\nimport {\n Datastore,\n invokeBatchGetDocumentsRpc,\n invokeCommitRpc\n} from '../remote/datastore';\nimport { fail, debugAssert } from '../util/assert';\nimport { Code, FirestoreError } from '../util/error';\n\nimport { SnapshotVersion } from './snapshot_version';\n\n/**\n * Internal transaction object responsible for accumulating the mutations to\n * perform and the base versions for any documents read.\n */\nexport class Transaction {\n // The version of each document that was read during this transaction.\n private readVersions = new Map();\n private mutations: Mutation[] = [];\n private committed = false;\n\n /**\n * A deferred usage error that occurred previously in this transaction that\n * will cause the transaction to fail once it actually commits.\n */\n private lastTransactionError: FirestoreError | null = null;\n\n /**\n * Set of documents that have been written in the transaction.\n *\n * When there's more than one write to the same key in a transaction, any\n * writes after the first are handled differently.\n */\n private writtenDocs: Set = new Set();\n\n constructor(private datastore: Datastore) {}\n\n async lookup(keys: DocumentKey[]): Promise {\n this.ensureCommitNotCalled();\n\n if (this.mutations.length > 0) {\n this.lastTransactionError = new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Firestore transactions require all reads to be executed before all writes.'\n );\n throw this.lastTransactionError;\n }\n const docs = await invokeBatchGetDocumentsRpc(this.datastore, keys);\n docs.forEach(doc => this.recordVersion(doc));\n return docs;\n }\n\n set(key: DocumentKey, data: ParsedSetData): void {\n this.write(data.toMutation(key, this.precondition(key)));\n this.writtenDocs.add(key.toString());\n }\n\n update(key: DocumentKey, data: ParsedUpdateData): void {\n try {\n this.write(data.toMutation(key, this.preconditionForUpdate(key)));\n } catch (e) {\n this.lastTransactionError = e as FirestoreError | null;\n }\n this.writtenDocs.add(key.toString());\n }\n\n delete(key: DocumentKey): void {\n this.write(new DeleteMutation(key, this.precondition(key)));\n this.writtenDocs.add(key.toString());\n }\n\n async commit(): Promise {\n this.ensureCommitNotCalled();\n\n if (this.lastTransactionError) {\n throw this.lastTransactionError;\n }\n const unwritten = this.readVersions;\n // For each mutation, note that the doc was written.\n this.mutations.forEach(mutation => {\n unwritten.delete(mutation.key.toString());\n });\n // For each document that was read but not written to, we want to perform\n // a `verify` operation.\n unwritten.forEach((_, path) => {\n const key = DocumentKey.fromPath(path);\n this.mutations.push(new VerifyMutation(key, this.precondition(key)));\n });\n await invokeCommitRpc(this.datastore, this.mutations);\n this.committed = true;\n }\n\n private recordVersion(doc: Document): void {\n let docVersion: SnapshotVersion;\n\n if (doc.isFoundDocument()) {\n docVersion = doc.version;\n } else if (doc.isNoDocument()) {\n // Represent a deleted doc using SnapshotVersion.min().\n docVersion = SnapshotVersion.min();\n } else {\n throw fail(0xc542, 'Document in a transaction was a ', {\n documentName: doc.constructor.name\n });\n }\n\n const existingVersion = this.readVersions.get(doc.key.toString());\n if (existingVersion) {\n if (!docVersion.isEqual(existingVersion)) {\n // This transaction will fail no matter what.\n throw new FirestoreError(\n Code.ABORTED,\n 'Document version changed between two reads.'\n );\n }\n } else {\n this.readVersions.set(doc.key.toString(), docVersion);\n }\n }\n\n /**\n * Returns the version of this document when it was read in this transaction,\n * as a precondition, or no precondition if it was not read.\n */\n private precondition(key: DocumentKey): Precondition {\n const version = this.readVersions.get(key.toString());\n if (!this.writtenDocs.has(key.toString()) && version) {\n if (version.isEqual(SnapshotVersion.min())) {\n return Precondition.exists(false);\n } else {\n return Precondition.updateTime(version);\n }\n } else {\n return Precondition.none();\n }\n }\n\n /**\n * Returns the precondition for a document if the operation is an update.\n */\n private preconditionForUpdate(key: DocumentKey): Precondition {\n const version = this.readVersions.get(key.toString());\n // The first time a document is written, we want to take into account the\n // read time and existence\n if (!this.writtenDocs.has(key.toString()) && version) {\n if (version.isEqual(SnapshotVersion.min())) {\n // The document doesn't exist, so fail the transaction.\n\n // This has to be validated locally because you can't send a\n // precondition that a document does not exist without changing the\n // semantics of the backend write to be an insert. This is the reverse\n // of what we want, since we want to assert that the document doesn't\n // exist but then send the update and have it fail. Since we can't\n // express that to the backend, we have to validate locally.\n\n // Note: this can change once we can send separate verify writes in the\n // transaction.\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n \"Can't update a document that doesn't exist.\"\n );\n }\n // Document exists, base precondition on document update time.\n return Precondition.updateTime(version);\n } else {\n // Document was not read, so we just use the preconditions for a blind\n // update.\n return Precondition.exists(true);\n }\n }\n\n private write(mutation: Mutation): void {\n this.ensureCommitNotCalled();\n this.mutations.push(mutation);\n }\n\n private ensureCommitNotCalled(): void {\n debugAssert(\n !this.committed,\n 'A transaction object cannot be used after its update callback has been invoked.'\n );\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ExponentialBackoff } from '../remote/backoff';\nimport { Datastore } from '../remote/datastore';\nimport { isPermanentError } from '../remote/rpc_error';\nimport { AsyncQueue, TimerId } from '../util/async_queue';\nimport { FirestoreError } from '../util/error';\nimport { Deferred } from '../util/promise';\nimport { isNullOrUndefined } from '../util/types';\n\nimport { Transaction } from './transaction';\nimport { TransactionOptions } from './transaction_options';\n\n/**\n * TransactionRunner encapsulates the logic needed to run and retry transactions\n * with backoff.\n */\nexport class TransactionRunner {\n private attemptsRemaining: number;\n private backoff: ExponentialBackoff;\n\n constructor(\n private readonly asyncQueue: AsyncQueue,\n private readonly datastore: Datastore,\n private readonly options: TransactionOptions,\n private readonly updateFunction: (transaction: Transaction) => Promise,\n private readonly deferred: Deferred\n ) {\n this.attemptsRemaining = options.maxAttempts;\n this.backoff = new ExponentialBackoff(\n this.asyncQueue,\n TimerId.TransactionRetry\n );\n }\n\n /** Runs the transaction and sets the result on deferred. */\n run(): void {\n this.attemptsRemaining -= 1;\n this.runWithBackOff();\n }\n\n private runWithBackOff(): void {\n this.backoff.backoffAndRun(async () => {\n const transaction = new Transaction(this.datastore);\n const userPromise = this.tryRunUpdateFunction(transaction);\n if (userPromise) {\n userPromise\n .then(result => {\n this.asyncQueue.enqueueAndForget(() => {\n return transaction\n .commit()\n .then(() => {\n this.deferred.resolve(result);\n })\n .catch(commitError => {\n this.handleTransactionError(commitError);\n });\n });\n })\n .catch(userPromiseError => {\n this.handleTransactionError(userPromiseError);\n });\n }\n });\n }\n\n private tryRunUpdateFunction(transaction: Transaction): Promise | null {\n try {\n const userPromise = this.updateFunction(transaction);\n if (\n isNullOrUndefined(userPromise) ||\n !userPromise.catch ||\n !userPromise.then\n ) {\n this.deferred.reject(\n Error('Transaction callback must return a Promise')\n );\n return null;\n }\n return userPromise;\n } catch (error) {\n // Do not retry errors thrown by user provided updateFunction.\n this.deferred.reject(error as Error);\n return null;\n }\n }\n\n private handleTransactionError(error: Error): void {\n if (this.attemptsRemaining > 0 && this.isRetryableTransactionError(error)) {\n this.attemptsRemaining -= 1;\n this.asyncQueue.enqueueAndForget(() => {\n this.runWithBackOff();\n return Promise.resolve();\n });\n } else {\n this.deferred.reject(error);\n }\n }\n\n private isRetryableTransactionError(error: Error | undefined): boolean {\n if (error?.name === 'FirebaseError') {\n // In transactions, the backend will fail outdated reads with FAILED_PRECONDITION and\n // non-matching document versions with ABORTED. These errors should be retried.\n const code = (error as FirestoreError).code;\n return (\n code === 'aborted' ||\n code === 'failed-precondition' ||\n code === 'already-exists' ||\n !isPermanentError(code)\n );\n }\n return false;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isIndexedDbTransactionError } from '../local/simple_db';\n\nimport { Code, FirestoreError } from './error';\nimport { logError } from './log';\nimport { Deferred } from './promise';\n\nconst LOG_TAG = 'AsyncQueue';\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype TimerHandle = any;\n\n/**\n * Wellknown \"timer\" IDs used when scheduling delayed operations on the\n * AsyncQueue. These IDs can then be used from tests to check for the presence\n * of operations or to run them early.\n *\n * The string values are used when encoding these timer IDs in JSON spec tests.\n */\nexport const enum TimerId {\n /** All can be used with runDelayedOperationsEarly() to run all timers. */\n All = 'all',\n\n /**\n * The following 5 timers are used in persistent_stream.ts for the listen and\n * write streams. The \"Idle\" timer is used to close the stream due to\n * inactivity. The \"ConnectionBackoff\" timer is used to restart a stream once\n * the appropriate backoff delay has elapsed. The health check is used to mark\n * a stream healthy if it has not received an error during its initial setup.\n */\n ListenStreamIdle = 'listen_stream_idle',\n ListenStreamConnectionBackoff = 'listen_stream_connection_backoff',\n WriteStreamIdle = 'write_stream_idle',\n WriteStreamConnectionBackoff = 'write_stream_connection_backoff',\n HealthCheckTimeout = 'health_check_timeout',\n\n /**\n * A timer used in online_state_tracker.ts to transition from\n * OnlineState.Unknown to Offline after a set timeout, rather than waiting\n * indefinitely for success or failure.\n */\n OnlineStateTimeout = 'online_state_timeout',\n\n /**\n * A timer used to update the client metadata in IndexedDb, which is used\n * to determine the primary leaseholder.\n */\n ClientMetadataRefresh = 'client_metadata_refresh',\n\n /** A timer used to periodically attempt LRU Garbage collection */\n LruGarbageCollection = 'lru_garbage_collection',\n\n /**\n * A timer used to retry transactions. Since there can be multiple concurrent\n * transactions, multiple of these may be in the queue at a given time.\n */\n TransactionRetry = 'transaction_retry',\n\n /**\n * A timer used to retry operations scheduled via retryable AsyncQueue\n * operations.\n */\n AsyncQueueRetry = 'async_queue_retry',\n\n /**\n * A timer used to periodically attempt index backfill.\n */\n IndexBackfill = 'index_backfill'\n}\n\n/**\n * Represents an operation scheduled to be run in the future on an AsyncQueue.\n *\n * It is created via DelayedOperation.createAndSchedule().\n *\n * Supports cancellation (via cancel()) and early execution (via skipDelay()).\n *\n * Note: We implement `PromiseLike` instead of `Promise`, as the `Promise` type\n * in newer versions of TypeScript defines `finally`, which is not available in\n * IE.\n */\nexport class DelayedOperation implements PromiseLike {\n // handle for use with clearTimeout(), or null if the operation has been\n // executed or canceled already.\n private timerHandle: TimerHandle | null;\n\n private readonly deferred = new Deferred();\n\n private constructor(\n private readonly asyncQueue: AsyncQueue,\n readonly timerId: TimerId,\n readonly targetTimeMs: number,\n private readonly op: () => Promise,\n private readonly removalCallback: (op: DelayedOperation) => void\n ) {\n // It's normal for the deferred promise to be canceled (due to cancellation)\n // and so we attach a dummy catch callback to avoid\n // 'UnhandledPromiseRejectionWarning' log spam.\n this.deferred.promise.catch(err => {});\n }\n\n get promise(): Promise {\n return this.deferred.promise;\n }\n\n /**\n * Creates and returns a DelayedOperation that has been scheduled to be\n * executed on the provided asyncQueue after the provided delayMs.\n *\n * @param asyncQueue - The queue to schedule the operation on.\n * @param id - A Timer ID identifying the type of operation this is.\n * @param delayMs - The delay (ms) before the operation should be scheduled.\n * @param op - The operation to run.\n * @param removalCallback - A callback to be called synchronously once the\n * operation is executed or canceled, notifying the AsyncQueue to remove it\n * from its delayedOperations list.\n * PORTING NOTE: This exists to prevent making removeDelayedOperation() and\n * the DelayedOperation class public.\n */\n static createAndSchedule(\n asyncQueue: AsyncQueue,\n timerId: TimerId,\n delayMs: number,\n op: () => Promise,\n removalCallback: (op: DelayedOperation) => void\n ): DelayedOperation {\n const targetTime = Date.now() + delayMs;\n const delayedOp = new DelayedOperation(\n asyncQueue,\n timerId,\n targetTime,\n op,\n removalCallback\n );\n delayedOp.start(delayMs);\n return delayedOp;\n }\n\n /**\n * Starts the timer. This is called immediately after construction by\n * createAndSchedule().\n */\n private start(delayMs: number): void {\n this.timerHandle = setTimeout(() => this.handleDelayElapsed(), delayMs);\n }\n\n /**\n * Queues the operation to run immediately (if it hasn't already been run or\n * canceled).\n */\n skipDelay(): void {\n return this.handleDelayElapsed();\n }\n\n /**\n * Cancels the operation if it hasn't already been executed or canceled. The\n * promise will be rejected.\n *\n * As long as the operation has not yet been run, calling cancel() provides a\n * guarantee that the operation will not be run.\n */\n cancel(reason?: string): void {\n if (this.timerHandle !== null) {\n this.clearTimeout();\n this.deferred.reject(\n new FirestoreError(\n Code.CANCELLED,\n 'Operation cancelled' + (reason ? ': ' + reason : '')\n )\n );\n }\n }\n\n then = this.deferred.promise.then.bind(this.deferred.promise);\n\n private handleDelayElapsed(): void {\n this.asyncQueue.enqueueAndForget(() => {\n if (this.timerHandle !== null) {\n this.clearTimeout();\n return this.op().then(result => {\n return this.deferred.resolve(result);\n });\n } else {\n return Promise.resolve();\n }\n });\n }\n\n private clearTimeout(): void {\n if (this.timerHandle !== null) {\n this.removalCallback(this);\n clearTimeout(this.timerHandle);\n this.timerHandle = null;\n }\n }\n}\n\nexport interface AsyncQueue {\n // Is this AsyncQueue being shut down? If true, this instance will not enqueue\n // any new operations, Promises from enqueue requests will not resolve.\n readonly isShuttingDown: boolean;\n\n /**\n * Adds a new operation to the queue without waiting for it to complete (i.e.\n * we ignore the Promise result).\n */\n enqueueAndForget(op: () => Promise): void;\n\n /**\n * Regardless if the queue has initialized shutdown, adds a new operation to the\n * queue without waiting for it to complete (i.e. we ignore the Promise result).\n */\n enqueueAndForgetEvenWhileRestricted(\n op: () => Promise\n ): void;\n\n /**\n * Initialize the shutdown of this queue. Once this method is called, the\n * only possible way to request running an operation is through\n * `enqueueEvenWhileRestricted()`.\n *\n * @param purgeExistingTasks Whether already enqueued tasked should be\n * rejected (unless enqueued with `enqueueEvenWhileRestricted()`). Defaults\n * to false.\n */\n enterRestrictedMode(purgeExistingTasks?: boolean): void;\n\n /**\n * Adds a new operation to the queue. Returns a promise that will be resolved\n * when the promise returned by the new operation is (with its value).\n */\n enqueue(op: () => Promise): Promise;\n\n /**\n * Enqueue a retryable operation.\n *\n * A retryable operation is rescheduled with backoff if it fails with a\n * IndexedDbTransactionError (the error type used by SimpleDb). All\n * retryable operations are executed in order and only run if all prior\n * operations were retried successfully.\n */\n enqueueRetryable(op: () => Promise): void;\n\n /**\n * Schedules an operation to be queued on the AsyncQueue once the specified\n * `delayMs` has elapsed. The returned DelayedOperation can be used to cancel\n * or fast-forward the operation prior to its running.\n */\n enqueueAfterDelay(\n timerId: TimerId,\n delayMs: number,\n op: () => Promise\n ): DelayedOperation;\n\n /**\n * Verifies there's an operation currently in-progress on the AsyncQueue.\n * Unfortunately we can't verify that the running code is in the promise chain\n * of that operation, so this isn't a foolproof check, but it should be enough\n * to catch some bugs.\n */\n verifyOperationInProgress(): void;\n}\n\n/**\n * Returns a FirestoreError that can be surfaced to the user if the provided\n * error is an IndexedDbTransactionError. Re-throws the error otherwise.\n */\nexport function wrapInUserErrorIfRecoverable(\n e: Error,\n msg: string\n): FirestoreError {\n logError(LOG_TAG, `${msg}: ${e}`);\n if (isIndexedDbTransactionError(e)) {\n return new FirestoreError(Code.UNAVAILABLE, `${msg}: ${e}`);\n } else {\n throw e;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isIndexedDbTransactionError } from '../local/simple_db';\nimport { getDocument } from '../platform/dom';\nimport { ExponentialBackoff } from '../remote/backoff';\n\nimport { debugAssert, fail } from './assert';\nimport { AsyncQueue, DelayedOperation, TimerId } from './async_queue';\nimport { FirestoreError } from './error';\nimport { logDebug, logError } from './log';\nimport { Deferred } from './promise';\n\nconst LOG_TAG = 'AsyncQueue';\n\nexport class AsyncQueueImpl implements AsyncQueue {\n // The last promise in the queue.\n private tail: Promise;\n\n // A list of retryable operations. Retryable operations are run in order and\n // retried with backoff.\n private retryableOps: Array<() => Promise> = [];\n\n // Is this AsyncQueue being shut down? Once it is set to true, it will not\n // be changed again.\n private _isShuttingDown: boolean = false;\n\n // Operations scheduled to be queued in the future. Operations are\n // automatically removed after they are run or canceled.\n private delayedOperations: Array> = [];\n\n // visible for testing\n failure: FirestoreError | null = null;\n\n // Flag set while there's an outstanding AsyncQueue operation, used for\n // assertion sanity-checks.\n private operationInProgress = false;\n\n // Enabled during shutdown on Safari to prevent future access to IndexedDB.\n private skipNonRestrictedTasks = false;\n\n // List of TimerIds to fast-forward delays for.\n private timerIdsToSkip: TimerId[] = [];\n\n // Backoff timer used to schedule retries for retryable operations\n private backoff = new ExponentialBackoff(this, TimerId.AsyncQueueRetry);\n\n // Visibility handler that triggers an immediate retry of all retryable\n // operations. Meant to speed up recovery when we regain file system access\n // after page comes into foreground.\n private visibilityHandler: () => void = () => {\n const document = getDocument();\n if (document) {\n logDebug(\n LOG_TAG,\n 'Visibility state changed to ' + document.visibilityState\n );\n }\n this.backoff.skipBackoff();\n };\n\n constructor(tail: Promise = Promise.resolve()) {\n this.tail = tail;\n const document = getDocument();\n if (document && typeof document.addEventListener === 'function') {\n document.addEventListener('visibilitychange', this.visibilityHandler);\n }\n }\n\n get isShuttingDown(): boolean {\n return this._isShuttingDown;\n }\n\n /**\n * Adds a new operation to the queue without waiting for it to complete (i.e.\n * we ignore the Promise result).\n */\n enqueueAndForget(op: () => Promise): void {\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.enqueue(op);\n }\n\n enqueueAndForgetEvenWhileRestricted(\n op: () => Promise\n ): void {\n this.verifyNotFailed();\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.enqueueInternal(op);\n }\n\n enterRestrictedMode(purgeExistingTasks?: boolean): void {\n if (!this._isShuttingDown) {\n this._isShuttingDown = true;\n this.skipNonRestrictedTasks = purgeExistingTasks || false;\n const document = getDocument();\n if (document && typeof document.removeEventListener === 'function') {\n document.removeEventListener(\n 'visibilitychange',\n this.visibilityHandler\n );\n }\n }\n }\n\n enqueue(op: () => Promise): Promise {\n this.verifyNotFailed();\n if (this._isShuttingDown) {\n // Return a Promise which never resolves.\n return new Promise(() => {});\n }\n\n // Create a deferred Promise that we can return to the callee. This\n // allows us to return a \"hanging Promise\" only to the callee and still\n // advance the queue even when the operation is not run.\n const task = new Deferred();\n return this.enqueueInternal(() => {\n if (this._isShuttingDown && this.skipNonRestrictedTasks) {\n // We do not resolve 'task'\n return Promise.resolve();\n }\n\n op().then(task.resolve, task.reject);\n return task.promise;\n }).then(() => task.promise);\n }\n\n enqueueRetryable(op: () => Promise): void {\n this.enqueueAndForget(() => {\n this.retryableOps.push(op);\n return this.retryNextOp();\n });\n }\n\n /**\n * Runs the next operation from the retryable queue. If the operation fails,\n * reschedules with backoff.\n */\n private async retryNextOp(): Promise {\n if (this.retryableOps.length === 0) {\n return;\n }\n\n try {\n await this.retryableOps[0]();\n this.retryableOps.shift();\n this.backoff.reset();\n } catch (e) {\n if (isIndexedDbTransactionError(e as Error)) {\n logDebug(LOG_TAG, 'Operation failed with retryable error: ' + e);\n } else {\n throw e; // Failure will be handled by AsyncQueue\n }\n }\n\n if (this.retryableOps.length > 0) {\n // If there are additional operations, we re-schedule `retryNextOp()`.\n // This is necessary to run retryable operations that failed during\n // their initial attempt since we don't know whether they are already\n // enqueued. If, for example, `op1`, `op2`, `op3` are enqueued and `op1`\n // needs to be re-run, we will run `op1`, `op1`, `op2` using the\n // already enqueued calls to `retryNextOp()`. `op3()` will then run in the\n // call scheduled here.\n // Since `backoffAndRun()` cancels an existing backoff and schedules a\n // new backoff on every call, there is only ever a single additional\n // operation in the queue.\n this.backoff.backoffAndRun(() => this.retryNextOp());\n }\n }\n\n private enqueueInternal(op: () => Promise): Promise {\n const newTail = this.tail.then(() => {\n this.operationInProgress = true;\n return op()\n .catch((error: FirestoreError) => {\n this.failure = error;\n this.operationInProgress = false;\n const message = getMessageOrStack(error);\n logError('INTERNAL UNHANDLED ERROR: ', message);\n\n // Re-throw the error so that this.tail becomes a rejected Promise and\n // all further attempts to chain (via .then) will just short-circuit\n // and return the rejected Promise.\n throw error;\n })\n .then(result => {\n this.operationInProgress = false;\n return result;\n });\n });\n this.tail = newTail;\n return newTail;\n }\n\n enqueueAfterDelay(\n timerId: TimerId,\n delayMs: number,\n op: () => Promise\n ): DelayedOperation {\n this.verifyNotFailed();\n\n debugAssert(\n delayMs >= 0,\n `Attempted to schedule an operation with a negative delay of ${delayMs}`\n );\n\n // Fast-forward delays for timerIds that have been overridden.\n if (this.timerIdsToSkip.indexOf(timerId) > -1) {\n delayMs = 0;\n }\n\n const delayedOp = DelayedOperation.createAndSchedule(\n this,\n timerId,\n delayMs,\n op,\n removedOp =>\n this.removeDelayedOperation(removedOp as DelayedOperation)\n );\n this.delayedOperations.push(delayedOp as DelayedOperation);\n return delayedOp;\n }\n\n private verifyNotFailed(): void {\n if (this.failure) {\n fail(0xb815, 'AsyncQueue is already failed', {\n messageOrStack: getMessageOrStack(this.failure)\n });\n }\n }\n\n verifyOperationInProgress(): void {\n debugAssert(\n this.operationInProgress,\n 'verifyOpInProgress() called when no op in progress on this queue.'\n );\n }\n\n /**\n * Waits until all currently queued tasks are finished executing. Delayed\n * operations are not run.\n */\n async drain(): Promise {\n // Operations in the queue prior to draining may have enqueued additional\n // operations. Keep draining the queue until the tail is no longer advanced,\n // which indicates that no more new operations were enqueued and that all\n // operations were executed.\n let currentTail: Promise;\n do {\n currentTail = this.tail;\n await currentTail;\n } while (currentTail !== this.tail);\n }\n\n /**\n * For Tests: Determine if a delayed operation with a particular TimerId\n * exists.\n */\n containsDelayedOperation(timerId: TimerId): boolean {\n for (const op of this.delayedOperations) {\n if (op.timerId === timerId) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * For Tests: Runs some or all delayed operations early.\n *\n * @param lastTimerId - Delayed operations up to and including this TimerId\n * will be drained. Pass TimerId.All to run all delayed operations.\n * @returns a Promise that resolves once all operations have been run.\n */\n runAllDelayedOperationsUntil(lastTimerId: TimerId): Promise {\n // Note that draining may generate more delayed ops, so we do that first.\n return this.drain().then(() => {\n // Run ops in the same order they'd run if they ran naturally.\n /* eslint-disable-next-line @typescript-eslint/no-floating-promises */\n this.delayedOperations.sort((a, b) => a.targetTimeMs - b.targetTimeMs);\n\n for (const op of this.delayedOperations) {\n op.skipDelay();\n if (lastTimerId !== TimerId.All && op.timerId === lastTimerId) {\n break;\n }\n }\n\n return this.drain();\n });\n }\n\n /**\n * For Tests: Skip all subsequent delays for a timer id.\n */\n skipDelaysForTimerId(timerId: TimerId): void {\n this.timerIdsToSkip.push(timerId);\n }\n\n /** Called once a DelayedOperation is run or canceled. */\n private removeDelayedOperation(op: DelayedOperation): void {\n // NOTE: indexOf / slice are O(n), but delayedOperations is expected to be small.\n const index = this.delayedOperations.indexOf(op);\n debugAssert(index >= 0, 'Delayed operation not found.');\n /* eslint-disable-next-line @typescript-eslint/no-floating-promises */\n this.delayedOperations.splice(index, 1);\n }\n}\n\nexport function newAsyncQueue(): AsyncQueue {\n return new AsyncQueueImpl();\n}\n\n/**\n * Chrome includes Error.message in Error.stack. Other browsers do not.\n * This returns expected output of message + stack when available.\n * @param error - Error or FirestoreError\n */\nfunction getMessageOrStack(error: Error): string {\n let message = error.message || '';\n if (error.stack) {\n if (error.stack.includes(error.message)) {\n message = error.stack;\n } else {\n message = error.message + '\\n' + error.stack;\n }\n }\n return message;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getModularInstance } from '@firebase/util';\n\nimport { Transaction as InternalTransaction } from '../core/transaction';\nimport {\n DEFAULT_TRANSACTION_OPTIONS,\n TransactionOptions as TransactionOptionsInternal,\n validateTransactionOptions\n} from '../core/transaction_options';\nimport { TransactionRunner } from '../core/transaction_runner';\nimport { fail } from '../util/assert';\nimport { newAsyncQueue } from '../util/async_queue_impl';\nimport { cast } from '../util/input_validation';\nimport { Deferred } from '../util/promise';\n\nimport { getDatastore } from './components';\nimport { Firestore } from './database';\nimport { FieldPath } from './field_path';\nimport {\n DocumentData,\n DocumentReference,\n PartialWithFieldValue,\n SetOptions,\n UpdateData,\n WithFieldValue\n} from './reference';\nimport {\n applyFirestoreDataConverter,\n LiteUserDataWriter\n} from './reference_impl';\nimport { DocumentSnapshot } from './snapshot';\nimport { TransactionOptions } from './transaction_options';\nimport {\n newUserDataReader,\n parseSetData,\n parseUpdateData,\n parseUpdateVarargs,\n UserDataReader\n} from './user_data_reader';\nimport { validateReference } from './write_batch';\n\n// TODO(mrschmidt) Consider using `BaseTransaction` as the base class in the\n// legacy SDK.\n\n/**\n * A reference to a transaction.\n *\n * The `Transaction` object passed to a transaction's `updateFunction` provides\n * the methods to read and write data within the transaction context. See\n * {@link runTransaction}.\n */\nexport class Transaction {\n // This is the tree-shakeable version of the Transaction class used in the\n // legacy SDK. The class is a close copy but takes different input and output\n // types. The firestore-exp SDK further extends this class to return its API\n // type.\n\n private readonly _dataReader: UserDataReader;\n\n /** @hideconstructor */\n constructor(\n protected readonly _firestore: Firestore,\n private readonly _transaction: InternalTransaction\n ) {\n this._dataReader = newUserDataReader(_firestore);\n }\n\n /**\n * Reads the document referenced by the provided {@link DocumentReference}.\n *\n * @param documentRef - A reference to the document to be read.\n * @returns A `DocumentSnapshot` with the read data.\n */\n get(\n documentRef: DocumentReference\n ): Promise> {\n const ref = validateReference(documentRef, this._firestore);\n const userDataWriter = new LiteUserDataWriter(this._firestore);\n return this._transaction.lookup([ref._key]).then(docs => {\n if (!docs || docs.length !== 1) {\n return fail(0x5de9, 'Mismatch in docs returned from document lookup.');\n }\n const doc = docs[0];\n if (doc.isFoundDocument()) {\n return new DocumentSnapshot(\n this._firestore,\n userDataWriter,\n doc.key,\n doc,\n ref.converter\n );\n } else if (doc.isNoDocument()) {\n return new DocumentSnapshot(\n this._firestore,\n userDataWriter,\n ref._key,\n null,\n ref.converter\n );\n } else {\n throw fail(\n 0x4801,\n 'BatchGetDocumentsRequest returned unexpected document',\n {\n doc\n }\n );\n }\n });\n }\n\n /**\n * Writes to the document referred to by the provided {@link\n * DocumentReference}. If the document does not exist yet, it will be created.\n *\n * @param documentRef - A reference to the document to be set.\n * @param data - An object of the fields and values for the document.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns This `Transaction` instance. Used for chaining method calls.\n */\n set(\n documentRef: DocumentReference,\n data: WithFieldValue\n ): this;\n /**\n * Writes to the document referred to by the provided {@link\n * DocumentReference}. If the document does not exist yet, it will be created.\n * If you provide `merge` or `mergeFields`, the provided data can be merged\n * into an existing document.\n *\n * @param documentRef - A reference to the document to be set.\n * @param data - An object of the fields and values for the document.\n * @param options - An object to configure the set behavior.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns This `Transaction` instance. Used for chaining method calls.\n */\n set(\n documentRef: DocumentReference,\n data: PartialWithFieldValue,\n options: SetOptions\n ): this;\n set(\n documentRef: DocumentReference,\n value: PartialWithFieldValue,\n options?: SetOptions\n ): this {\n const ref = validateReference(documentRef, this._firestore);\n const convertedValue = applyFirestoreDataConverter(\n ref.converter,\n value,\n options\n );\n const parsed = parseSetData(\n this._dataReader,\n 'Transaction.set',\n ref._key,\n convertedValue,\n ref.converter !== null,\n options\n );\n this._transaction.set(ref._key, parsed);\n return this;\n }\n\n /**\n * Updates fields in the document referred to by the provided {@link\n * DocumentReference}. The update will fail if applied to a document that does\n * not exist.\n *\n * @param documentRef - A reference to the document to be updated.\n * @param data - An object containing the fields and values with which to\n * update the document. Fields can contain dots to reference nested fields\n * within the document.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns This `Transaction` instance. Used for chaining method calls.\n */\n update(\n documentRef: DocumentReference,\n data: UpdateData\n ): this;\n /**\n * Updates fields in the document referred to by the provided {@link\n * DocumentReference}. The update will fail if applied to a document that does\n * not exist.\n *\n * Nested fields can be updated by providing dot-separated field path\n * strings or by providing `FieldPath` objects.\n *\n * @param documentRef - A reference to the document to be updated.\n * @param field - The first field to update.\n * @param value - The first value.\n * @param moreFieldsAndValues - Additional key/value pairs.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns This `Transaction` instance. Used for chaining method calls.\n */\n update(\n documentRef: DocumentReference,\n field: string | FieldPath,\n value: unknown,\n ...moreFieldsAndValues: unknown[]\n ): this;\n update(\n documentRef: DocumentReference,\n fieldOrUpdateData: string | FieldPath | UpdateData,\n value?: unknown,\n ...moreFieldsAndValues: unknown[]\n ): this {\n const ref = validateReference(documentRef, this._firestore);\n\n // For Compat types, we have to \"extract\" the underlying types before\n // performing validation.\n fieldOrUpdateData = getModularInstance(fieldOrUpdateData);\n\n let parsed;\n if (\n typeof fieldOrUpdateData === 'string' ||\n fieldOrUpdateData instanceof FieldPath\n ) {\n parsed = parseUpdateVarargs(\n this._dataReader,\n 'Transaction.update',\n ref._key,\n fieldOrUpdateData,\n value,\n moreFieldsAndValues\n );\n } else {\n parsed = parseUpdateData(\n this._dataReader,\n 'Transaction.update',\n ref._key,\n fieldOrUpdateData\n );\n }\n\n this._transaction.update(ref._key, parsed);\n return this;\n }\n\n /**\n * Deletes the document referred to by the provided {@link DocumentReference}.\n *\n * @param documentRef - A reference to the document to be deleted.\n * @returns This `Transaction` instance. Used for chaining method calls.\n */\n delete(\n documentRef: DocumentReference\n ): this {\n const ref = validateReference(documentRef, this._firestore);\n this._transaction.delete(ref._key);\n return this;\n }\n}\n\n/**\n * Executes the given `updateFunction` and then attempts to commit the changes\n * applied within the transaction. If any document read within the transaction\n * has changed, Cloud Firestore retries the `updateFunction`. If it fails to\n * commit after 5 attempts, the transaction fails.\n *\n * The maximum number of writes allowed in a single transaction is 500.\n *\n * @param firestore - A reference to the Firestore database to run this\n * transaction against.\n * @param updateFunction - The function to execute within the transaction\n * context.\n * @param options - An options object to configure maximum number of attempts to\n * commit.\n * @returns If the transaction completed successfully or was explicitly aborted\n * (the `updateFunction` returned a failed promise), the promise returned by the\n * `updateFunction `is returned here. Otherwise, if the transaction failed, a\n * rejected promise with the corresponding failure error is returned.\n */\nexport function runTransaction(\n firestore: Firestore,\n updateFunction: (transaction: Transaction) => Promise,\n options?: TransactionOptions\n): Promise {\n firestore = cast(firestore, Firestore);\n const datastore = getDatastore(firestore);\n const optionsWithDefaults: TransactionOptionsInternal = {\n ...DEFAULT_TRANSACTION_OPTIONS,\n ...options\n };\n validateTransactionOptions(optionsWithDefaults);\n const deferred = new Deferred();\n new TransactionRunner(\n newAsyncQueue(),\n datastore,\n optionsWithDefaults,\n internalTransaction =>\n updateFunction(new Transaction(firestore, internalTransaction)),\n deferred\n ).run();\n return deferred.promise;\n}\n","/**\n * Firestore Lite\n *\n * @remarks Firestore Lite is a small online-only SDK that allows read\n * and write access to your Firestore database. All operations connect\n * directly to the backend, and `onSnapshot()` APIs are not supported.\n * @packageDocumentation\n */\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { registerFirestore } from './register';\nregisterFirestore();\n\nexport {\n aggregateQuerySnapshotEqual,\n getCount,\n getAggregate,\n count,\n sum,\n average,\n aggregateFieldEqual\n} from '../src/lite-api/aggregate';\n\nexport {\n AggregateField,\n AggregateFieldType,\n AggregateSpec,\n AggregateSpecData,\n AggregateQuerySnapshot,\n AggregateType\n} from '../src/lite-api/aggregate_types';\n\nexport { FirestoreSettings as Settings } from '../src/lite-api/settings';\n\nexport {\n Firestore as Firestore,\n EmulatorMockTokenOptions,\n initializeFirestore,\n getFirestore,\n terminate,\n connectFirestoreEmulator\n} from '../src/lite-api/database';\n\nexport {\n DocumentData,\n UpdateData,\n WithFieldValue,\n PartialWithFieldValue,\n SetOptions,\n DocumentReference,\n Query,\n CollectionReference,\n collection,\n collectionGroup,\n doc,\n refEqual,\n queryEqual\n} from '../src/lite-api/reference';\n\nexport {\n and,\n endAt,\n endBefore,\n startAt,\n startAfter,\n limit,\n limitToLast,\n where,\n or,\n orderBy,\n query,\n QueryConstraint,\n QueryConstraintType,\n QueryCompositeFilterConstraint,\n QueryFilterConstraint,\n QueryFieldFilterConstraint,\n QueryOrderByConstraint,\n QueryLimitConstraint,\n QueryNonFilterConstraint,\n QueryStartAtConstraint,\n QueryEndAtConstraint,\n OrderByDirection,\n WhereFilterOp\n} from '../src/lite-api/query';\n\nexport {\n addDoc,\n deleteDoc,\n updateDoc,\n setDoc,\n getDoc,\n getDocs\n} from '../src/lite-api/reference_impl';\n\nexport {\n Primitive,\n NestedUpdateFields,\n ChildUpdateFields,\n AddPrefixToKeys,\n UnionToIntersection\n} from '../src/lite-api/types';\n\n// TODO(firestorelite): Add tests when Queries are usable\nexport { FieldPath, documentId } from '../src/lite-api/field_path';\n\n// TODO(firestorelite): Add tests when setDoc() is available\nexport { FieldValue } from '../src/lite-api/field_value';\n\nexport {\n increment,\n arrayRemove,\n arrayUnion,\n serverTimestamp,\n deleteField,\n vector\n} from '../src/lite-api/field_value_impl';\n\nexport {\n FirestoreDataConverter,\n DocumentSnapshot,\n QueryDocumentSnapshot,\n QuerySnapshot,\n snapshotEqual\n} from '../src/lite-api/snapshot';\n\nexport { VectorValue } from '../src/lite-api/vector_value';\n\nexport { WriteBatch, writeBatch } from '../src/lite-api/write_batch';\n\nexport { TransactionOptions } from '../src/lite-api/transaction_options';\n\nexport { Transaction, runTransaction } from '../src/lite-api/transaction';\n\nexport { setLogLevel, LogLevelString as LogLevel } from '../src/util/log';\n\nexport { Bytes } from '../src/lite-api/bytes';\n\nexport { GeoPoint } from '../src/lite-api/geo_point';\n\nexport { Timestamp } from '../src/lite-api/timestamp';\n\nexport { FirestoreErrorCode, FirestoreError } from '../src/util/error';\n"],"names":["generateRandomBytes","FieldPath","LOG_TAG","TYPE_KEY","SDK_VERSION","version","InternalFieldPath","fieldPathFromArgument","Transaction"],"mappings":";;;;;;;;;;AAAA;;;;;;;;;;;;;;;AAeG;AAEH;;;AAGG;AACU,MAAA,IAAI,CAAA;AAUf,IAAA,WAAA,CAAqB,GAAkB,EAAA;AAAlB,QAAA,IAAG,CAAA,GAAA,GAAH,GAAG,CAAe;AAAI,KAAA;AAE3C,IAAA,eAAe,GAAA;AACb,QAAA,OAAO,IAAI,CAAC,GAAG,IAAI,IAAI,CAAC;AACzB,KAAA;AAED;;;AAGG;AACH,IAAA,KAAK,GAAA;AACH,QAAA,IAAI,IAAI,CAAC,eAAe,EAAE,EAAE;AAC1B,YAAA,OAAO,MAAM,GAAG,IAAI,CAAC,GAAG,CAAC;AAC1B,SAAA;AAAM,aAAA;AACL,YAAA,OAAO,gBAAgB,CAAC;AACzB,SAAA;AACF,KAAA;AAED,IAAA,OAAO,CAAC,SAAe,EAAA;AACrB,QAAA,OAAO,SAAS,CAAC,GAAG,KAAK,IAAI,CAAC,GAAG,CAAC;AACnC,KAAA;;AA7BD;AACgB,IAAA,CAAA,eAAe,GAAG,IAAI,IAAI,CAAC,IAAI,CAAC,CAAC;AAEjD;AACA;AACgB,IAAA,CAAA,kBAAkB,GAAG,IAAI,IAAI,CAAC,wBAAwB,CAAC,CAA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,YAAY,CAAC,MAAM,CAAC,GAAG,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC;AAC3C,QAAA,OAAO,IAAI,CAAC;AACb,KAAA;AAED;;;;;AAKG;AACH,IAAA,MAAM,CACJ,WAAyD,EAAA;QAEzD,MAAM,GAAG,GAAG,iBAAiB,CAAC,WAAW,EAAE,IAAI,CAAC,UAAU,CAAC,CAAC;QAC5D,IAAI,CAAC,YAAY,CAAC,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;AACnC,QAAA,OAAO,IAAI,CAAC;AACb,KAAA;AACF,CAAA;AAED;;;;;;;;;;;;;;;;;;AAkBG;AACa,SAAA,cAAc,CAC5B,SAAoB,EACpB,cAAwD,EACxD,OAA4B,EAAA;AAE5B,IAAA,SAAS,GAAG,IAAI,CAAC,SAAS,EAAE,SAAS,CAAC,CAAC;AACvC,IAAA,MAAM,SAAS,GAAG,YAAY,CAAC,SAAS,CAAC,CAAC;AAC1C,IAAA,MAAM,mBAAmB,GAA+B;AACtD,QAAA,GAAG,2BAA2B;AAC9B,QAAA,GAAG,OAAO;KACX,CAAC;IACF,0BAA0B,CAAC,mBAAmB,CAAC,CAAC;AAChD,IAAA,MAAM,QAAQ,GAAG,IAAI,QAAQ,EAAK,CAAC;AACnC,IAAA,IAAI,iBAAiB,CACnB,aAAa,EAAE,EACf,SAAS,EACT,mBAAmB,EACnB,mBAAmB,IACjB,cAAc,CAAC,IAAI,WAAW,CAAC,SAAS,EAAE,mBAAmB,CAAC,CAAC,EACjE,QAAQ,CACT,CAAC,GAAG,EAAE,CAAC;IACR,OAAO,QAAQ,CAAC,OAAO,CAAC;AAC1B,CAAA;;ACvTA;;;;;;;AAOG;AAoBH,iBAAiB,EAAE;;;;"} \ No newline at end of file diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/index.rn.esm.js b/frontend-old/node_modules/@firebase/firestore/dist/lite/index.rn.esm.js new file mode 100644 index 0000000..d0db455 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/index.rn.esm.js @@ -0,0 +1,7672 @@ +import { _isFirebaseServerApp as t, _getProvider, getApp as e, _removeServiceInstance as r, _registerComponent as n, registerVersion as i, SDK_VERSION as s } from "@firebase/app"; + +import { Component as o } from "@firebase/component"; + +import { Logger as a, LogLevel as u } from "@firebase/logger"; + +import { FirebaseError as _, isCloudWorkstation as c, base64 as l, DecodeBase64StringError as h, getDefaultEmulatorHostnameAndPort as f, pingServer as d, updateEmulatorBanner as m, deepEqual as E, createMockUserToken as T, getModularInstance as P } from "@firebase/util"; + +import { Integer as A } from "@firebase/webchannel-wrapper/bloom-blob"; + +const R = "4.9.2"; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Simple wrapper around a nullable UID. Mostly exists to make code more + * readable. + */ class User { + constructor(t) { + this.uid = t; + } + isAuthenticated() { + return null != this.uid; + } + /** + * Returns a key representing this user, suitable for inclusion in a + * dictionary. + */ toKey() { + return this.isAuthenticated() ? "uid:" + this.uid : "anonymous-user"; + } + isEqual(t) { + return t.uid === this.uid; + } +} + +/** A user with a null UID. */ User.UNAUTHENTICATED = new User(null), +// TODO(mikelehen): Look into getting a proper uid-equivalent for +// non-FirebaseAuth providers. +User.GOOGLE_CREDENTIALS = new User("google-credentials-uid"), User.FIRST_PARTY = new User("first-party-uid"), +User.MOCK_USER = new User("mock-user"); + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +let V = "12.3.0"; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const I = new a("@firebase/firestore"); + +/** + * Sets the verbosity of Cloud Firestore logs (debug, error, or silent). + * + * @param logLevel - The verbosity you set for activity and error logging. Can + * be any of the following values: + * + *
    + *
  • `debug` for the most verbose logging level, primarily for + * debugging.
  • + *
  • `error` to log errors only.
  • + *
  • `silent` to turn off logging.
  • + *
+ */ function setLogLevel(t) { + I.setLogLevel(t); +} + +function __PRIVATE_logDebug(t, ...e) { + if (I.logLevel <= u.DEBUG) { + const r = e.map(__PRIVATE_argToString); + I.debug(`Firestore (${V}): ${t}`, ...r); + } +} + +function __PRIVATE_logError(t, ...e) { + if (I.logLevel <= u.ERROR) { + const r = e.map(__PRIVATE_argToString); + I.error(`Firestore (${V}): ${t}`, ...r); + } +} + +/** + * @internal + */ function __PRIVATE_logWarn(t, ...e) { + if (I.logLevel <= u.WARN) { + const r = e.map(__PRIVATE_argToString); + I.warn(`Firestore (${V}): ${t}`, ...r); + } +} + +/** + * Converts an additional log parameter to a string representation. + */ function __PRIVATE_argToString(t) { + if ("string" == typeof t) return t; + try { + /** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + /** Formats an object as a JSON string, suitable for logging. */ + return function __PRIVATE_formatJSON(t) { + return JSON.stringify(t); + }(t); + } catch (e) { + // Converting to JSON failed, just log the object directly + return t; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ function fail(t, e, r) { + let n = "Unexpected state"; + "string" == typeof e ? n = e : r = e, __PRIVATE__fail(t, n, r); +} + +function __PRIVATE__fail(t, e, r) { + // Log the failure in addition to throw an exception, just in case the + // exception is swallowed. + let n = `FIRESTORE (${V}) INTERNAL ASSERTION FAILED: ${e} (ID: ${t.toString(16)})`; + if (void 0 !== r) try { + n += " CONTEXT: " + JSON.stringify(r); + } catch (t) { + n += " CONTEXT: " + r; + } + // NOTE: We don't use FirestoreError here because these are internal failures + // that cannot be handled by the user. (Also it would create a circular + // dependency between the error and assert modules which doesn't work.) + throw __PRIVATE_logError(n), new Error(n); +} + +function __PRIVATE_hardAssert(t, e, r, n) { + let i = "Unexpected state"; + "string" == typeof r ? i = r : n = r, t || __PRIVATE__fail(e, i, n); +} + +/** + * Casts `obj` to `T`. In non-production builds, verifies that `obj` is an + * instance of `T` before casting. + */ function __PRIVATE_debugCast(t, +// eslint-disable-next-line @typescript-eslint/no-explicit-any +e) { + return t; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ const p = "ok", y = "cancelled", g = "unknown", w = "invalid-argument", F = "deadline-exceeded", v = "not-found", D = "already-exists", b = "permission-denied", S = "unauthenticated", C = "resource-exhausted", N = "failed-precondition", O = "aborted", q = "out-of-range", B = "unimplemented", $ = "internal", Q = "unavailable", k = "data-loss"; + +/** An error returned by a Firestore operation. */ class FirestoreError extends _ { + /** @hideconstructor */ + constructor( + /** + * The backend error code associated with this error. + */ + t, + /** + * A custom error description. + */ + e) { + super(t, e), this.code = t, this.message = e, + // HACK: We write a toString property directly because Error is not a real + // class and so inheritance does not work correctly. We could alternatively + // do the same "back-door inheritance" trick that FirebaseError does. + this.toString = () => `${this.name}: [code=${this.code}]: ${this.message}`; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ class __PRIVATE_Deferred { + constructor() { + this.promise = new Promise(((t, e) => { + this.resolve = t, this.reject = e; + })); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ class __PRIVATE_OAuthToken { + constructor(t, e) { + this.user = e, this.type = "OAuth", this.headers = new Map, this.headers.set("Authorization", `Bearer ${t}`); + } +} + +/** + * A CredentialsProvider that always yields an empty token. + * @internal + */ class __PRIVATE_EmptyAuthCredentialsProvider { + getToken() { + return Promise.resolve(null); + } + invalidateToken() {} + start(t, e) { + // Fire with initial user. + t.enqueueRetryable((() => e(User.UNAUTHENTICATED))); + } + shutdown() {} +} + +/** + * A CredentialsProvider that always returns a constant token. Used for + * emulator token mocking. + */ class __PRIVATE_EmulatorAuthCredentialsProvider { + constructor(t) { + this.token = t, + /** + * Stores the listener registered with setChangeListener() + * This isn't actually necessary since the UID never changes, but we use this + * to verify the listen contract is adhered to in tests. + */ + this.changeListener = null; + } + getToken() { + return Promise.resolve(this.token); + } + invalidateToken() {} + start(t, e) { + this.changeListener = e, + // Fire with initial user. + t.enqueueRetryable((() => e(this.token.user))); + } + shutdown() { + this.changeListener = null; + } +} + +/** Credential provider for the Lite SDK. */ class __PRIVATE_LiteAuthCredentialsProvider { + constructor(t) { + this.auth = null, t.onInit((t => { + this.auth = t; + })); + } + getToken() { + return this.auth ? this.auth.getToken().then((t => t ? (__PRIVATE_hardAssert("string" == typeof t.accessToken, 42297, { + t: t + }), new __PRIVATE_OAuthToken(t.accessToken, new User(this.auth.getUid()))) : null)) : Promise.resolve(null); + } + invalidateToken() {} + start(t, e) {} + shutdown() {} +} + +/* + * FirstPartyToken provides a fresh token each time its value + * is requested, because if the token is too old, requests will be rejected. + * Technically this may no longer be necessary since the SDK should gracefully + * recover from unauthenticated errors (see b/33147818 for context), but it's + * safer to keep the implementation as-is. + */ class __PRIVATE_FirstPartyToken { + constructor(t, e, r) { + this.i = t, this.o = e, this.u = r, this.type = "FirstParty", this.user = User.FIRST_PARTY, + this.l = new Map; + } + /** + * Gets an authorization token, using a provided factory function, or return + * null. + */ h() { + return this.u ? this.u() : null; + } + get headers() { + this.l.set("X-Goog-AuthUser", this.i); + // Use array notation to prevent minification + const t = this.h(); + return t && this.l.set("Authorization", t), this.o && this.l.set("X-Goog-Iam-Authorization-Token", this.o), + this.l; + } +} + +/* + * Provides user credentials required for the Firestore JavaScript SDK + * to authenticate the user, using technique that is only available + * to applications hosted by Google. + */ class __PRIVATE_FirstPartyAuthCredentialsProvider { + constructor(t, e, r) { + this.i = t, this.o = e, this.u = r; + } + getToken() { + return Promise.resolve(new __PRIVATE_FirstPartyToken(this.i, this.o, this.u)); + } + start(t, e) { + // Fire with initial uid. + t.enqueueRetryable((() => e(User.FIRST_PARTY))); + } + shutdown() {} + invalidateToken() {} +} + +class AppCheckToken { + constructor(t) { + this.value = t, this.type = "AppCheck", this.headers = new Map, t && t.length > 0 && this.headers.set("x-firebase-appcheck", this.value); + } +} + +/** AppCheck token provider for the Lite SDK. */ class __PRIVATE_LiteAppCheckTokenProvider { + constructor(e, r) { + this.m = r, this.appCheck = null, this.T = null, t(e) && e.settings.appCheckToken && (this.T = e.settings.appCheckToken), + r.onInit((t => { + this.appCheck = t; + })); + } + getToken() { + return this.T ? Promise.resolve(new AppCheckToken(this.T)) : this.appCheck ? this.appCheck.getToken().then((t => t ? (__PRIVATE_hardAssert("string" == typeof t.token, 3470, { + tokenResult: t + }), new AppCheckToken(t.token)) : null)) : Promise.resolve(null); + } + invalidateToken() {} + start(t, e) {} + shutdown() {} +} + +/** + * Builds a CredentialsProvider depending on the type of + * the credentials passed in. + */ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class DatabaseInfo { + /** + * Constructs a DatabaseInfo using the provided host, databaseId and + * persistenceKey. + * + * @param databaseId - The database to use. + * @param appId - The Firebase App Id. + * @param persistenceKey - A unique identifier for this Firestore's local + * storage (used in conjunction with the databaseId). + * @param host - The Firestore backend host to connect to. + * @param ssl - Whether to use SSL when connecting. + * @param forceLongPolling - Whether to use the forceLongPolling option + * when using WebChannel as the network transport. + * @param autoDetectLongPolling - Whether to use the detectBufferingProxy + * option when using WebChannel as the network transport. + * @param longPollingOptions Options that configure long-polling. + * @param useFetchStreams Whether to use the Fetch API instead of + * XMLHTTPRequest + */ + constructor(t, e, r, n, i, s, o, a, u, _) { + this.databaseId = t, this.appId = e, this.persistenceKey = r, this.host = n, this.ssl = i, + this.forceLongPolling = s, this.autoDetectLongPolling = o, this.longPollingOptions = a, + this.useFetchStreams = u, this.isUsingEmulator = _; + } +} + +/** The default database name for a project. */ const L = "(default)"; + +/** + * Represents the database ID a Firestore client is associated with. + * @internal + */ class DatabaseId { + constructor(t, e) { + this.projectId = t, this.database = e || L; + } + static empty() { + return new DatabaseId("", ""); + } + get isDefaultDatabase() { + return this.database === L; + } + isEqual(t) { + return t instanceof DatabaseId && t.projectId === this.projectId && t.database === this.database; + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Generates `nBytes` of random bytes. + * + * If `nBytes < 0` , an error will be thrown. + */ +function __PRIVATE_randomBytes(t) { + // Polyfills for IE and WebWorker by using `self` and `msCrypto` when `crypto` is not available. + const e = + // eslint-disable-next-line @typescript-eslint/no-explicit-any + "undefined" != typeof self && (self.crypto || self.msCrypto), r = new Uint8Array(t); + if (e && "function" == typeof e.getRandomValues) e.getRandomValues(r); else + // Falls back to Math.random + for (let e = 0; e < t; e++) r[e] = Math.floor(256 * Math.random()); + return r; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A utility class for generating unique alphanumeric IDs of a specified length. + * + * @internal + * Exported internally for testing purposes. + */ class __PRIVATE_AutoId { + static newId() { + // Alphanumeric characters + const t = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", e = 62 * Math.floor(256 / 62); + // The largest byte value that is a multiple of `char.length`. + let r = ""; + for (;r.length < 20; ) { + const n = __PRIVATE_randomBytes(40); + for (let i = 0; i < n.length; ++i) + // Only accept values that are [0, maxMultiple), this ensures they can + // be evenly mapped to indices of `chars` via a modulo operation. + r.length < 20 && n[i] < e && (r += t.charAt(n[i] % 62)); + } + return r; + } +} + +function __PRIVATE_primitiveComparator(t, e) { + return t < e ? -1 : t > e ? 1 : 0; +} + +/** Compare strings in UTF-8 encoded byte order */ function __PRIVATE_compareUtf8Strings(t, e) { + // Find the first differing character (a.k.a. "UTF-16 code unit") in the two strings and, + // if found, use that character to determine the relative ordering of the two strings as a + // whole. Comparing UTF-16 strings in UTF-8 byte order can be done simply and efficiently by + // comparing the UTF-16 code units (chars). This serendipitously works because of the way UTF-8 + // and UTF-16 happen to represent Unicode code points. + // After finding the first pair of differing characters, there are two cases: + // Case 1: Both characters are non-surrogates (code points less than or equal to 0xFFFF) or + // both are surrogates from a surrogate pair (that collectively represent code points greater + // than 0xFFFF). In this case their numeric order as UTF-16 code units is the same as the + // lexicographical order of their corresponding UTF-8 byte sequences. A direct comparison is + // sufficient. + // Case 2: One character is a surrogate and the other is not. In this case the surrogate- + // containing string is always ordered after the non-surrogate. This is because surrogates are + // used to represent code points greater than 0xFFFF which have 4-byte UTF-8 representations + // and are lexicographically greater than the 1, 2, or 3-byte representations of code points + // less than or equal to 0xFFFF. + // An example of why Case 2 is required is comparing the following two Unicode code points: + // |-----------------------|------------|---------------------|-----------------| + // | Name | Code Point | UTF-8 Encoding | UTF-16 Encoding | + // |-----------------------|------------|---------------------|-----------------| + // | Replacement Character | U+FFFD | 0xEF 0xBF 0xBD | 0xFFFD | + // | Grinning Face | U+1F600 | 0xF0 0x9F 0x98 0x80 | 0xD83D 0xDE00 | + // |-----------------------|------------|---------------------|-----------------| + // A lexicographical comparison of the UTF-8 encodings of these code points would order + // "Replacement Character" _before_ "Grinning Face" because 0xEF is less than 0xF0. However, a + // direct comparison of the UTF-16 code units, as would be done in case 1, would erroneously + // produce the _opposite_ ordering, because 0xFFFD is _greater than_ 0xD83D. As it turns out, + // this relative ordering holds for all comparisons of UTF-16 code points requiring a surrogate + // pair with those that do not. + const r = Math.min(t.length, e.length); + for (let n = 0; n < r; n++) { + const r = t.charAt(n), i = e.charAt(n); + if (r !== i) return __PRIVATE_isSurrogate(r) === __PRIVATE_isSurrogate(i) ? __PRIVATE_primitiveComparator(r, i) : __PRIVATE_isSurrogate(r) ? 1 : -1; + } + // Use the lengths of the strings to determine the overall comparison result since either the + // strings were equal or one is a prefix of the other. + return __PRIVATE_primitiveComparator(t.length, e.length); +} + +const M = 55296, x = 57343; + +function __PRIVATE_isSurrogate(t) { + const e = t.charCodeAt(0); + return e >= M && e <= x; +} + +/** Helper to compare arrays using isEqual(). */ function __PRIVATE_arrayEquals(t, e, r) { + return t.length === e.length && t.every(((t, n) => r(t, e[n]))); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ const U = "__name__"; + +/** + * Path represents an ordered sequence of string segments. + */ class BasePath { + constructor(t, e, r) { + void 0 === e ? e = 0 : e > t.length && fail(637, { + offset: e, + range: t.length + }), void 0 === r ? r = t.length - e : r > t.length - e && fail(1746, { + length: r, + range: t.length - e + }), this.segments = t, this.offset = e, this.len = r; + } + get length() { + return this.len; + } + isEqual(t) { + return 0 === BasePath.comparator(this, t); + } + child(t) { + const e = this.segments.slice(this.offset, this.limit()); + return t instanceof BasePath ? t.forEach((t => { + e.push(t); + })) : e.push(t), this.construct(e); + } + /** The index of one past the last segment of the path. */ limit() { + return this.offset + this.length; + } + popFirst(t) { + return t = void 0 === t ? 1 : t, this.construct(this.segments, this.offset + t, this.length - t); + } + popLast() { + return this.construct(this.segments, this.offset, this.length - 1); + } + firstSegment() { + return this.segments[this.offset]; + } + lastSegment() { + return this.get(this.length - 1); + } + get(t) { + return this.segments[this.offset + t]; + } + isEmpty() { + return 0 === this.length; + } + isPrefixOf(t) { + if (t.length < this.length) return !1; + for (let e = 0; e < this.length; e++) if (this.get(e) !== t.get(e)) return !1; + return !0; + } + isImmediateParentOf(t) { + if (this.length + 1 !== t.length) return !1; + for (let e = 0; e < this.length; e++) if (this.get(e) !== t.get(e)) return !1; + return !0; + } + forEach(t) { + for (let e = this.offset, r = this.limit(); e < r; e++) t(this.segments[e]); + } + toArray() { + return this.segments.slice(this.offset, this.limit()); + } + /** + * Compare 2 paths segment by segment, prioritizing numeric IDs + * (e.g., "__id123__") in numeric ascending order, followed by string + * segments in lexicographical order. + */ static comparator(t, e) { + const r = Math.min(t.length, e.length); + for (let n = 0; n < r; n++) { + const r = BasePath.compareSegments(t.get(n), e.get(n)); + if (0 !== r) return r; + } + return __PRIVATE_primitiveComparator(t.length, e.length); + } + static compareSegments(t, e) { + const r = BasePath.isNumericId(t), n = BasePath.isNumericId(e); + return r && !n ? -1 : !r && n ? 1 : r && n ? BasePath.extractNumericId(t).compare(BasePath.extractNumericId(e)) : __PRIVATE_compareUtf8Strings(t, e); + } + // Checks if a segment is a numeric ID (starts with "__id" and ends with "__"). + static isNumericId(t) { + return t.startsWith("__id") && t.endsWith("__"); + } + static extractNumericId(t) { + return A.fromString(t.substring(4, t.length - 2)); + } +} + +/** + * A slash-separated path for navigating resources (documents and collections) + * within Firestore. + * + * @internal + */ class ResourcePath extends BasePath { + construct(t, e, r) { + return new ResourcePath(t, e, r); + } + canonicalString() { + // NOTE: The client is ignorant of any path segments containing escape + // sequences (e.g. __id123__) and just passes them through raw (they exist + // for legacy reasons and should not be used frequently). + return this.toArray().join("/"); + } + toString() { + return this.canonicalString(); + } + /** + * Returns a string representation of this path + * where each path segment has been encoded with + * `encodeURIComponent`. + */ toUriEncodedString() { + return this.toArray().map(encodeURIComponent).join("/"); + } + /** + * Creates a resource path from the given slash-delimited string. If multiple + * arguments are provided, all components are combined. Leading and trailing + * slashes from all components are ignored. + */ static fromString(...t) { + // NOTE: The client is ignorant of any path segments containing escape + // sequences (e.g. __id123__) and just passes them through raw (they exist + // for legacy reasons and should not be used frequently). + const e = []; + for (const r of t) { + if (r.indexOf("//") >= 0) throw new FirestoreError(w, `Invalid segment (${r}). Paths must not contain // in them.`); + // Strip leading and trailing slashed. + e.push(...r.split("/").filter((t => t.length > 0))); + } + return new ResourcePath(e); + } + static emptyPath() { + return new ResourcePath([]); + } +} + +const j = /^[_a-zA-Z][_a-zA-Z0-9]*$/; + +/** + * A dot-separated path for navigating sub-objects within a document. + * @internal + */ class FieldPath$1 extends BasePath { + construct(t, e, r) { + return new FieldPath$1(t, e, r); + } + /** + * Returns true if the string could be used as a segment in a field path + * without escaping. + */ static isValidIdentifier(t) { + return j.test(t); + } + canonicalString() { + return this.toArray().map((t => (t = t.replace(/\\/g, "\\\\").replace(/`/g, "\\`"), + FieldPath$1.isValidIdentifier(t) || (t = "`" + t + "`"), t))).join("."); + } + toString() { + return this.canonicalString(); + } + /** + * Returns true if this field references the key of a document. + */ isKeyField() { + return 1 === this.length && this.get(0) === U; + } + /** + * The field designating the key of a document. + */ static keyField() { + return new FieldPath$1([ U ]); + } + /** + * Parses a field string from the given server-formatted string. + * + * - Splitting the empty string is not allowed (for now at least). + * - Empty segments within the string (e.g. if there are two consecutive + * separators) are not allowed. + * + * TODO(b/37244157): we should make this more strict. Right now, it allows + * non-identifier path components, even if they aren't escaped. + */ static fromServerFormat(t) { + const e = []; + let r = "", n = 0; + const __PRIVATE_addCurrentSegment = () => { + if (0 === r.length) throw new FirestoreError(w, `Invalid field path (${t}). Paths must not be empty, begin with '.', end with '.', or contain '..'`); + e.push(r), r = ""; + }; + let i = !1; + for (;n < t.length; ) { + const e = t[n]; + if ("\\" === e) { + if (n + 1 === t.length) throw new FirestoreError(w, "Path has trailing escape character: " + t); + const e = t[n + 1]; + if ("\\" !== e && "." !== e && "`" !== e) throw new FirestoreError(w, "Path has invalid escape sequence: " + t); + r += e, n += 2; + } else "`" === e ? (i = !i, n++) : "." !== e || i ? (r += e, n++) : (__PRIVATE_addCurrentSegment(), + n++); + } + if (__PRIVATE_addCurrentSegment(), i) throw new FirestoreError(w, "Unterminated ` in path: " + t); + return new FieldPath$1(e); + } + static emptyPath() { + return new FieldPath$1([]); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @internal + */ class DocumentKey { + constructor(t) { + this.path = t; + } + static fromPath(t) { + return new DocumentKey(ResourcePath.fromString(t)); + } + static fromName(t) { + return new DocumentKey(ResourcePath.fromString(t).popFirst(5)); + } + static empty() { + return new DocumentKey(ResourcePath.emptyPath()); + } + get collectionGroup() { + return this.path.popLast().lastSegment(); + } + /** Returns true if the document is in the specified collectionId. */ hasCollectionId(t) { + return this.path.length >= 2 && this.path.get(this.path.length - 2) === t; + } + /** Returns the collection group (i.e. the name of the parent collection) for this key. */ getCollectionGroup() { + return this.path.get(this.path.length - 2); + } + /** Returns the fully qualified path to the parent collection. */ getCollectionPath() { + return this.path.popLast(); + } + isEqual(t) { + return null !== t && 0 === ResourcePath.comparator(this.path, t.path); + } + toString() { + return this.path.toString(); + } + static comparator(t, e) { + return ResourcePath.comparator(t.path, e.path); + } + static isDocumentKey(t) { + return t.length % 2 == 0; + } + /** + * Creates and returns a new document key with the given segments. + * + * @param segments - The segments of the path to the document + * @returns A new instance of DocumentKey + */ static fromSegments(t) { + return new DocumentKey(new ResourcePath(t.slice())); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ function __PRIVATE_validateNonEmptyArgument(t, e, r) { + if (!r) throw new FirestoreError(w, `Function ${t}() cannot be called with an empty ${e}.`); +} + +/** + * Validates that two boolean options are not set at the same time. + * @internal + */ +/** + * Validates that `path` refers to a document (indicated by the fact it contains + * an even numbers of segments). + */ +function __PRIVATE_validateDocumentPath(t) { + if (!DocumentKey.isDocumentKey(t)) throw new FirestoreError(w, `Invalid document reference. Document references must have an even number of segments, but ${t} has ${t.length}.`); +} + +/** + * Validates that `path` refers to a collection (indicated by the fact it + * contains an odd numbers of segments). + */ function __PRIVATE_validateCollectionPath(t) { + if (DocumentKey.isDocumentKey(t)) throw new FirestoreError(w, `Invalid collection reference. Collection references must have an odd number of segments, but ${t} has ${t.length}.`); +} + +/** + * Returns true if it's a non-null object without a custom prototype + * (i.e. excludes Array, Date, etc.). + */ function __PRIVATE_isPlainObject(t) { + return "object" == typeof t && null !== t && (Object.getPrototypeOf(t) === Object.prototype || null === Object.getPrototypeOf(t)); +} + +/** Returns a string describing the type / value of the provided input. */ function __PRIVATE_valueDescription(t) { + if (void 0 === t) return "undefined"; + if (null === t) return "null"; + if ("string" == typeof t) return t.length > 20 && (t = `${t.substring(0, 20)}...`), + JSON.stringify(t); + if ("number" == typeof t || "boolean" == typeof t) return "" + t; + if ("object" == typeof t) { + if (t instanceof Array) return "an array"; + { + const e = + /** try to get the constructor name for an object. */ + function __PRIVATE_tryGetCustomObjectType(t) { + if (t.constructor) return t.constructor.name; + return null; + } + /** + * Casts `obj` to `T`, optionally unwrapping Compat types to expose the + * underlying instance. Throws if `obj` is not an instance of `T`. + * + * This cast is used in the Lite and Full SDK to verify instance types for + * arguments passed to the public API. + * @internal + */ (t); + return e ? `a custom ${e} object` : "an object"; + } + } + return "function" == typeof t ? "a function" : fail(12329, { + type: typeof t + }); +} + +function __PRIVATE_cast(t, +// eslint-disable-next-line @typescript-eslint/no-explicit-any +e) { + if ("_delegate" in t && ( + // Unwrap Compat types + // eslint-disable-next-line @typescript-eslint/no-explicit-any + t = t._delegate), !(t instanceof e)) { + if (e.name === t.constructor.name) throw new FirestoreError(w, "Type does not match the expected instance. Did you pass a reference from a different Firestore SDK?"); + { + const r = __PRIVATE_valueDescription(t); + throw new FirestoreError(w, `Expected type '${e.name}', but it was: ${r}`); + } + } + return t; +} + +function __PRIVATE_validatePositiveNumber(t, e) { + if (e <= 0) throw new FirestoreError(w, `Function ${t}() requires a positive number, but it was: ${e}.`); +} + +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Compares two `ExperimentalLongPollingOptions` objects for equality. + */ +/** + * Creates and returns a new `ExperimentalLongPollingOptions` with the same + * option values as the given instance. + */ +function __PRIVATE_cloneLongPollingOptions(t) { + const e = {}; + return void 0 !== t.timeoutSeconds && (e.timeoutSeconds = t.timeoutSeconds), e; +} + +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * The value returned from the most recent invocation of + * `generateUniqueDebugId()`, or null if it has never been invoked. + */ let z = null; + +/** + * Generates and returns an initial value for `lastUniqueDebugId`. + * + * The returned value is randomly selected from a range of integers that are + * represented as 8 hexadecimal digits. This means that (within reason) any + * numbers generated by incrementing the returned number by 1 will also be + * represented by 8 hexadecimal digits. This leads to all "IDs" having the same + * length when converted to a hexadecimal string, making reading logs containing + * these IDs easier to follow. And since the return value is randomly selected + * it will help to differentiate between logs from different executions. + */ +/** + * Generates and returns a unique ID as a hexadecimal string. + * + * The returned ID is intended to be used in debug logging messages to help + * correlate log messages that may be spatially separated in the logs, but + * logically related. For example, a network connection could include the same + * "debug ID" string in all of its log messages to help trace a specific + * connection over time. + * + * @return the 10-character generated ID (e.g. "0xa1b2c3d4"). + */ +function __PRIVATE_generateUniqueDebugId() { + return null === z ? z = function __PRIVATE_generateInitialUniqueDebugId() { + return 268435456 + Math.round(2147483648 * Math.random()); + }() : z++, "0x" + z.toString(16); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Returns whether a variable is either undefined or null. + */ function __PRIVATE_isNullOrUndefined(t) { + return null == t; +} + +/** Returns whether the value represents -0. */ function __PRIVATE_isNegativeZero(t) { + // Detect if the value is -0.0. Based on polyfill from + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is + return 0 === t && 1 / t == -1 / 0; +} + +/** + * Returns whether a value is an integer and in the safe integer range + * @param value - The value to test for being an integer and in the safe range + */ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const W = "RestConnection", K = { + BatchGetDocuments: "batchGet", + Commit: "commit", + RunQuery: "runQuery", + RunAggregationQuery: "runAggregationQuery" +}; + +/** + * Maps RPC names to the corresponding REST endpoint name. + * + * We use array notation to avoid mangling. + */ +/** + * Base class for all Rest-based connections to the backend (WebChannel and + * HTTP). + */ +class __PRIVATE_RestConnection { + get P() { + // Both `invokeRPC()` and `invokeStreamingRPC()` use their `path` arguments to determine + // where to run the query, and expect the `request` to NOT specify the "path". + return !1; + } + constructor(t) { + this.databaseInfo = t, this.databaseId = t.databaseId; + const e = t.ssl ? "https" : "http", r = encodeURIComponent(this.databaseId.projectId), n = encodeURIComponent(this.databaseId.database); + this.A = e + "://" + t.host, this.R = `projects/${r}/databases/${n}`, this.V = this.databaseId.database === L ? `project_id=${r}` : `project_id=${r}&database_id=${n}`; + } + I(t, e, r, n, i) { + const s = __PRIVATE_generateUniqueDebugId(), o = this.p(t, e.toUriEncodedString()); + __PRIVATE_logDebug(W, `Sending RPC '${t}' ${s}:`, o, r); + const a = { + "google-cloud-resource-prefix": this.R, + "x-goog-request-params": this.V + }; + this.F(a, n, i); + const {host: u} = new URL(o), _ = c(u); + return this.v(t, o, a, r, _).then((e => (__PRIVATE_logDebug(W, `Received RPC '${t}' ${s}: `, e), + e)), (e => { + throw __PRIVATE_logWarn(W, `RPC '${t}' ${s} failed with error: `, e, "url: ", o, "request:", r), + e; + })); + } + D(t, e, r, n, i, s) { + // The REST API automatically aggregates all of the streamed results, so we + // can just use the normal invoke() method. + return this.I(t, e, r, n, i); + } + /** + * Modifies the headers for a request, adding any authorization token if + * present and any additional headers for the request. + */ F(t, e, r) { + t["X-Goog-Api-Client"] = + // SDK_VERSION is updated to different value at runtime depending on the entry point, + // so we need to get its value when we need it in a function. + function __PRIVATE_getGoogApiClientValue() { + return "gl-js/ fire/" + V; + }(), + // Content-Type: text/plain will avoid preflight requests which might + // mess with CORS and redirects by proxies. If we add custom headers + // we will need to change this code to potentially use the $httpOverwrite + // parameter supported by ESF to avoid triggering preflight requests. + t["Content-Type"] = "text/plain", this.databaseInfo.appId && (t["X-Firebase-GMPID"] = this.databaseInfo.appId), + e && e.headers.forEach(((e, r) => t[r] = e)), r && r.headers.forEach(((e, r) => t[r] = e)); + } + p(t, e) { + const r = K[t]; + return `${this.A}/v1/${e}:${r}`; + } + /** + * Closes and cleans up any resources associated with the connection. This + * implementation is a no-op because there are no resources associated + * with the RestConnection that need to be cleaned up. + */ terminate() { + // No-op + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Error Codes describing the different ways GRPC can fail. These are copied + * directly from GRPC's sources here: + * + * https://github.com/grpc/grpc/blob/bceec94ea4fc5f0085d81235d8e1c06798dc341a/include/grpc%2B%2B/impl/codegen/status_code_enum.h + * + * Important! The names of these identifiers matter because the string forms + * are used for reverse lookups from the webchannel stream. Do NOT change the + * names of these identifiers or change this into a const enum. + */ var G, J; + +/** + * Converts an HTTP Status Code to the equivalent error code. + * + * @param status - An HTTP Status Code, like 200, 404, 503, etc. + * @returns The equivalent Code. Unknown status codes are mapped to + * Code.UNKNOWN. + */ +function __PRIVATE_mapCodeFromHttpStatus(t) { + if (void 0 === t) return __PRIVATE_logError("RPC_ERROR", "HTTP error has no status"), + g; + // The canonical error codes for Google APIs [1] specify mapping onto HTTP + // status codes but the mapping is not bijective. In each case of ambiguity + // this function chooses a primary error. + + // [1] + // https://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto + switch (t) { + case 200: + // OK + return p; + + case 400: + // Bad Request + return N; + + // Other possibilities based on the forward mapping + // return Code.INVALID_ARGUMENT; + // return Code.OUT_OF_RANGE; + case 401: + // Unauthorized + return S; + + case 403: + // Forbidden + return b; + + case 404: + // Not Found + return v; + + case 409: + // Conflict + return O; + + // Other possibilities: + // return Code.ALREADY_EXISTS; + case 416: + // Range Not Satisfiable + return q; + + case 429: + // Too Many Requests + return C; + + case 499: + // Client Closed Request + return y; + + case 500: + // Internal Server Error + return g; + + // Other possibilities: + // return Code.INTERNAL; + // return Code.DATA_LOSS; + case 501: + // Unimplemented + return B; + + case 503: + // Service Unavailable + return Q; + + case 504: + // Gateway Timeout + return F; + + default: + return t >= 200 && t < 300 ? p : t >= 400 && t < 500 ? N : t >= 500 && t < 600 ? $ : g; + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A Rest-based connection that relies on the native HTTP stack + * (e.g. `fetch` or a polyfill). + */ (J = G || (G = {}))[J.OK = 0] = "OK", J[J.CANCELLED = 1] = "CANCELLED", J[J.UNKNOWN = 2] = "UNKNOWN", +J[J.INVALID_ARGUMENT = 3] = "INVALID_ARGUMENT", J[J.DEADLINE_EXCEEDED = 4] = "DEADLINE_EXCEEDED", +J[J.NOT_FOUND = 5] = "NOT_FOUND", J[J.ALREADY_EXISTS = 6] = "ALREADY_EXISTS", J[J.PERMISSION_DENIED = 7] = "PERMISSION_DENIED", +J[J.UNAUTHENTICATED = 16] = "UNAUTHENTICATED", J[J.RESOURCE_EXHAUSTED = 8] = "RESOURCE_EXHAUSTED", +J[J.FAILED_PRECONDITION = 9] = "FAILED_PRECONDITION", J[J.ABORTED = 10] = "ABORTED", +J[J.OUT_OF_RANGE = 11] = "OUT_OF_RANGE", J[J.UNIMPLEMENTED = 12] = "UNIMPLEMENTED", +J[J.INTERNAL = 13] = "INTERNAL", J[J.UNAVAILABLE = 14] = "UNAVAILABLE", J[J.DATA_LOSS = 15] = "DATA_LOSS"; + +class __PRIVATE_FetchConnection extends __PRIVATE_RestConnection { + S(t, e) { + throw new Error("Not supported by FetchConnection"); + } + async v(t, e, r, n, i) { + const s = JSON.stringify(n); + let o; + try { + const t = { + method: "POST", + headers: r, + body: s + }; + i && (t.credentials = "include"), o = await fetch(e, t); + } catch (t) { + const e = t; + throw new FirestoreError(__PRIVATE_mapCodeFromHttpStatus(e.status), "Request failed with error: " + e.statusText); + } + if (!o.ok) { + let t = await o.json(); + Array.isArray(t) && (t = t[0]); + const e = t?.error?.message; + throw new FirestoreError(__PRIVATE_mapCodeFromHttpStatus(o.status), `Request failed with error: ${e ?? o.statusText}`); + } + return o.json(); + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Initializes the HTTP connection for the REST API. */ +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Concrete implementation of the Aggregate type. + */ +class __PRIVATE_AggregateImpl { + constructor(t, e, r) { + this.alias = t, this.aggregateType = e, this.fieldPath = r; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ function __PRIVATE_objectSize(t) { + let e = 0; + for (const r in t) Object.prototype.hasOwnProperty.call(t, r) && e++; + return e; +} + +function forEach(t, e) { + for (const r in t) Object.prototype.hasOwnProperty.call(t, r) && e(r, t[r]); +} + +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An error encountered while decoding base64 string. + */ +class __PRIVATE_Base64DecodeError extends Error { + constructor() { + super(...arguments), this.name = "Base64DecodeError"; + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// WebSafe uses a different URL-encoding safe alphabet that doesn't match +// the encoding used on the backend. +const H = !1; + +/** Converts a Base64 encoded string to a binary string. */ function __PRIVATE_decodeBase64(t) { + try { + return String.fromCharCode.apply(null, + // We use `decodeStringToByteArray()` instead of `decodeString()` since + // `decodeString()` returns Unicode strings, which doesn't match the values + // returned by `atob()`'s Latin1 representation. + l.decodeStringToByteArray(t, H)); + } catch (t) { + throw t instanceof h ? new __PRIVATE_Base64DecodeError("Invalid base64 string: " + t) : t; + } +} + +/** Converts a binary string to a Base64 encoded string. */ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Immutable class that represents a "proto" byte string. + * + * Proto byte strings can either be Base64-encoded strings or Uint8Arrays when + * sent on the wire. This class abstracts away this differentiation by holding + * the proto byte string in a common class that must be converted into a string + * before being sent as a proto. + * @internal + */ +class ByteString { + constructor(t) { + this.binaryString = t; + } + static fromBase64String(t) { + const e = __PRIVATE_decodeBase64(t); + return new ByteString(e); + } + static fromUint8Array(t) { + // TODO(indexing); Remove the copy of the byte string here as this method + // is frequently called during indexing. + const e = + /** + * Helper function to convert an Uint8array to a binary string. + */ + function __PRIVATE_binaryStringFromUint8Array(t) { + let e = ""; + for (let r = 0; r < t.length; ++r) e += String.fromCharCode(t[r]); + return e; + } + /** + * Helper function to convert a binary string to an Uint8Array. + */ (t); + return new ByteString(e); + } + [Symbol.iterator]() { + let t = 0; + return { + next: () => t < this.binaryString.length ? { + value: this.binaryString.charCodeAt(t++), + done: !1 + } : { + value: void 0, + done: !0 + } + }; + } + toBase64() { + return function __PRIVATE_encodeBase64(t) { + const e = []; + for (let r = 0; r < t.length; r++) e[r] = t.charCodeAt(r); + return l.encodeByteArray(e, H); + }(this.binaryString); + } + toUint8Array() { + return function __PRIVATE_uint8ArrayFromBinaryString(t) { + const e = new Uint8Array(t.length); + for (let r = 0; r < t.length; r++) e[r] = t.charCodeAt(r); + return e; + } + /** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + // A RegExp matching ISO 8601 UTC timestamps with optional fraction. + (this.binaryString); + } + approximateByteSize() { + return 2 * this.binaryString.length; + } + compareTo(t) { + return __PRIVATE_primitiveComparator(this.binaryString, t.binaryString); + } + isEqual(t) { + return this.binaryString === t.binaryString; + } +} + +ByteString.EMPTY_BYTE_STRING = new ByteString(""); + +const Y = new RegExp(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.(\d+))?Z$/); + +/** + * Converts the possible Proto values for a timestamp value into a "seconds and + * nanos" representation. + */ function __PRIVATE_normalizeTimestamp(t) { + // The json interface (for the browser) will return an iso timestamp string, + // while the proto js library (for node) will return a + // google.protobuf.Timestamp instance. + if (__PRIVATE_hardAssert(!!t, 39018), "string" == typeof t) { + // The date string can have higher precision (nanos) than the Date class + // (millis), so we do some custom parsing here. + // Parse the nanos right out of the string. + let e = 0; + const r = Y.exec(t); + if (__PRIVATE_hardAssert(!!r, 46558, { + timestamp: t + }), r[1]) { + // Pad the fraction out to 9 digits (nanos). + let t = r[1]; + t = (t + "000000000").substr(0, 9), e = Number(t); + } + // Parse the date to get the seconds. + const n = new Date(t); + return { + seconds: Math.floor(n.getTime() / 1e3), + nanos: e + }; + } + return { + seconds: __PRIVATE_normalizeNumber(t.seconds), + nanos: __PRIVATE_normalizeNumber(t.nanos) + }; +} + +/** + * Converts the possible Proto types for numbers into a JavaScript number. + * Returns 0 if the value is not numeric. + */ function __PRIVATE_normalizeNumber(t) { + // TODO(bjornick): Handle int64 greater than 53 bits. + return "number" == typeof t ? t : "string" == typeof t ? Number(t) : 0; +} + +/** Converts the possible Proto types for Blobs into a ByteString. */ function __PRIVATE_normalizeByteString(t) { + return "string" == typeof t ? ByteString.fromBase64String(t) : ByteString.fromUint8Array(t); +} + +/** + * @license + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Helper function to define a JSON schema {@link Property}. + * @private + * @internal + */ function property(t, e) { + const r = { + typeString: t + }; + return e && (r.value = e), r; +} + +/** + * Validates the JSON object based on the provided schema, and narrows the type to the provided + * JSON schema. + * @private + * @internal + * + * @param json A JSON object to validate. + * @param scheme a {@link JsonSchema} that defines the properties to validate. + * @returns true if the JSON schema exists within the object. Throws a FirestoreError otherwise. + */ function __PRIVATE_validateJSON(t, e) { + if (!__PRIVATE_isPlainObject(t)) throw new FirestoreError(w, "JSON must be an object"); + let r; + for (const n in e) if (e[n]) { + const i = e[n].typeString, s = "value" in e[n] ? { + value: e[n].value + } : void 0; + if (!(n in t)) { + r = `JSON missing required field: '${n}'`; + break; + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const o = t[n]; + if (i && typeof o !== i) { + r = `JSON field '${n}' must be a ${i}.`; + break; + } + if (void 0 !== s && o !== s.value) { + r = `Expected '${n}' field to equal '${s.value}'`; + break; + } + } + if (r) throw new FirestoreError(w, r); + return !0; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// The earliest date supported by Firestore timestamps (0001-01-01T00:00:00Z). +const Z = -62135596800, X = 1e6; + +// Number of nanoseconds in a millisecond. +/** + * A `Timestamp` represents a point in time independent of any time zone or + * calendar, represented as seconds and fractions of seconds at nanosecond + * resolution in UTC Epoch time. + * + * It is encoded using the Proleptic Gregorian Calendar which extends the + * Gregorian calendar backwards to year one. It is encoded assuming all minutes + * are 60 seconds long, i.e. leap seconds are "smeared" so that no leap second + * table is needed for interpretation. Range is from 0001-01-01T00:00:00Z to + * 9999-12-31T23:59:59.999999999Z. + * + * For examples and further specifications, refer to the + * {@link https://github.com/google/protobuf/blob/master/src/google/protobuf/timestamp.proto | Timestamp definition}. + */ +class Timestamp { + /** + * Creates a new timestamp with the current date, with millisecond precision. + * + * @returns a new timestamp representing the current date. + */ + static now() { + return Timestamp.fromMillis(Date.now()); + } + /** + * Creates a new timestamp from the given date. + * + * @param date - The date to initialize the `Timestamp` from. + * @returns A new `Timestamp` representing the same point in time as the given + * date. + */ static fromDate(t) { + return Timestamp.fromMillis(t.getTime()); + } + /** + * Creates a new timestamp from the given number of milliseconds. + * + * @param milliseconds - Number of milliseconds since Unix epoch + * 1970-01-01T00:00:00Z. + * @returns A new `Timestamp` representing the same point in time as the given + * number of milliseconds. + */ static fromMillis(t) { + const e = Math.floor(t / 1e3), r = Math.floor((t - 1e3 * e) * X); + return new Timestamp(e, r); + } + /** + * Creates a new timestamp. + * + * @param seconds - The number of seconds of UTC time since Unix epoch + * 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to + * 9999-12-31T23:59:59Z inclusive. + * @param nanoseconds - The non-negative fractions of a second at nanosecond + * resolution. Negative second values with fractions must still have + * non-negative nanoseconds values that count forward in time. Must be + * from 0 to 999,999,999 inclusive. + */ constructor( + /** + * The number of seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z. + */ + t, + /** + * The fractions of a second at nanosecond resolution.* + */ + e) { + if (this.seconds = t, this.nanoseconds = e, e < 0) throw new FirestoreError(w, "Timestamp nanoseconds out of range: " + e); + if (e >= 1e9) throw new FirestoreError(w, "Timestamp nanoseconds out of range: " + e); + if (t < Z) throw new FirestoreError(w, "Timestamp seconds out of range: " + t); + // This will break in the year 10,000. + if (t >= 253402300800) throw new FirestoreError(w, "Timestamp seconds out of range: " + t); + } + /** + * Converts a `Timestamp` to a JavaScript `Date` object. This conversion + * causes a loss of precision since `Date` objects only support millisecond + * precision. + * + * @returns JavaScript `Date` object representing the same point in time as + * this `Timestamp`, with millisecond precision. + */ toDate() { + return new Date(this.toMillis()); + } + /** + * Converts a `Timestamp` to a numeric timestamp (in milliseconds since + * epoch). This operation causes a loss of precision. + * + * @returns The point in time corresponding to this timestamp, represented as + * the number of milliseconds since Unix epoch 1970-01-01T00:00:00Z. + */ toMillis() { + return 1e3 * this.seconds + this.nanoseconds / X; + } + _compareTo(t) { + return this.seconds === t.seconds ? __PRIVATE_primitiveComparator(this.nanoseconds, t.nanoseconds) : __PRIVATE_primitiveComparator(this.seconds, t.seconds); + } + /** + * Returns true if this `Timestamp` is equal to the provided one. + * + * @param other - The `Timestamp` to compare against. + * @returns true if this `Timestamp` is equal to the provided one. + */ isEqual(t) { + return t.seconds === this.seconds && t.nanoseconds === this.nanoseconds; + } + /** Returns a textual representation of this `Timestamp`. */ toString() { + return "Timestamp(seconds=" + this.seconds + ", nanoseconds=" + this.nanoseconds + ")"; + } + /** + * Returns a JSON-serializable representation of this `Timestamp`. + */ toJSON() { + return { + type: Timestamp._jsonSchemaVersion, + seconds: this.seconds, + nanoseconds: this.nanoseconds + }; + } + /** + * Builds a `Timestamp` instance from a JSON object created by {@link Timestamp.toJSON}. + */ static fromJSON(t) { + if (__PRIVATE_validateJSON(t, Timestamp._jsonSchema)) return new Timestamp(t.seconds, t.nanoseconds); + } + /** + * Converts this object to a primitive string, which allows `Timestamp` objects + * to be compared using the `>`, `<=`, `>=` and `>` operators. + */ valueOf() { + // This method returns a string of the form . where + // is translated to have a non-negative value and both + // and are left-padded with zeroes to be a consistent length. + // Strings with this format then have a lexicographical ordering that matches + // the expected ordering. The translation is done to avoid having + // a leading negative sign (i.e. a leading '-' character) in its string + // representation, which would affect its lexicographical ordering. + const t = this.seconds - Z; + // Note: Up to 12 decimal digits are required to represent all valid + // 'seconds' values. + return String(t).padStart(12, "0") + "." + String(this.nanoseconds).padStart(9, "0"); + } +} + +Timestamp._jsonSchemaVersion = "firestore/timestamp/1.0", Timestamp._jsonSchema = { + type: property("string", Timestamp._jsonSchemaVersion), + seconds: property("number"), + nanoseconds: property("number") +}; + +function __PRIVATE_isServerTimestamp(t) { + const e = (t?.mapValue?.fields || {}).__type__?.stringValue; + return "server_timestamp" === e; +} + +/** + * Returns the value of the field before this ServerTimestamp was set. + * + * Preserving the previous values allows the user to display the last resoled + * value until the backend responds with the timestamp. + */ function __PRIVATE_getPreviousValue(t) { + const e = t.mapValue.fields.__previous_value__; + return __PRIVATE_isServerTimestamp(e) ? __PRIVATE_getPreviousValue(e) : e; +} + +/** + * Returns the local time at which this timestamp was first set. + */ function __PRIVATE_getLocalWriteTime(t) { + const e = __PRIVATE_normalizeTimestamp(t.mapValue.fields.__local_write_time__.timestampValue); + return new Timestamp(e.seconds, e.nanos); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ const tt = "__type__", et = "__max__", rt = { + fields: { + __type__: { + stringValue: et + } + } +}, nt = "__vector__", it = "value"; + +/** Extracts the backend's type order for the provided value. */ +function __PRIVATE_typeOrder(t) { + return "nullValue" in t ? 0 /* TypeOrder.NullValue */ : "booleanValue" in t ? 1 /* TypeOrder.BooleanValue */ : "integerValue" in t || "doubleValue" in t ? 2 /* TypeOrder.NumberValue */ : "timestampValue" in t ? 3 /* TypeOrder.TimestampValue */ : "stringValue" in t ? 5 /* TypeOrder.StringValue */ : "bytesValue" in t ? 6 /* TypeOrder.BlobValue */ : "referenceValue" in t ? 7 /* TypeOrder.RefValue */ : "geoPointValue" in t ? 8 /* TypeOrder.GeoPointValue */ : "arrayValue" in t ? 9 /* TypeOrder.ArrayValue */ : "mapValue" in t ? __PRIVATE_isServerTimestamp(t) ? 4 /* TypeOrder.ServerTimestampValue */ : + /** Returns true if the Value represents the canonical {@link #MAX_VALUE} . */ + function __PRIVATE_isMaxValue(t) { + return (((t.mapValue || {}).fields || {}).__type__ || {}).stringValue === et; + } + /** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + /** + * Represents a bound of a query. + * + * The bound is specified with the given components representing a position and + * whether it's just before or just after the position (relative to whatever the + * query order is). + * + * The position represents a logical index position for a query. It's a prefix + * of values for the (potentially implicit) order by clauses of a query. + * + * Bound provides a function to determine whether a document comes before or + * after a bound. This is influenced by whether the position is just before or + * just after the provided values. + */ (t) ? 9007199254740991 /* TypeOrder.MaxValue */ : + /** Returns true if `value` is a VetorValue. */ + function __PRIVATE_isVectorValue(t) { + const e = (t?.mapValue?.fields || {})[tt]?.stringValue; + return e === nt; + } + /** Creates a deep copy of `source`. */ (t) ? 10 /* TypeOrder.VectorValue */ : 11 /* TypeOrder.ObjectValue */ : fail(28295, { + value: t + }); +} + +/** Tests `left` and `right` for equality based on the backend semantics. */ function __PRIVATE_valueEquals(t, e) { + if (t === e) return !0; + const r = __PRIVATE_typeOrder(t); + if (r !== __PRIVATE_typeOrder(e)) return !1; + switch (r) { + case 0 /* TypeOrder.NullValue */ : + case 9007199254740991 /* TypeOrder.MaxValue */ : + return !0; + + case 1 /* TypeOrder.BooleanValue */ : + return t.booleanValue === e.booleanValue; + + case 4 /* TypeOrder.ServerTimestampValue */ : + return __PRIVATE_getLocalWriteTime(t).isEqual(__PRIVATE_getLocalWriteTime(e)); + + case 3 /* TypeOrder.TimestampValue */ : + return function __PRIVATE_timestampEquals(t, e) { + if ("string" == typeof t.timestampValue && "string" == typeof e.timestampValue && t.timestampValue.length === e.timestampValue.length) + // Use string equality for ISO 8601 timestamps + return t.timestampValue === e.timestampValue; + const r = __PRIVATE_normalizeTimestamp(t.timestampValue), n = __PRIVATE_normalizeTimestamp(e.timestampValue); + return r.seconds === n.seconds && r.nanos === n.nanos; + }(t, e); + + case 5 /* TypeOrder.StringValue */ : + return t.stringValue === e.stringValue; + + case 6 /* TypeOrder.BlobValue */ : + return function __PRIVATE_blobEquals(t, e) { + return __PRIVATE_normalizeByteString(t.bytesValue).isEqual(__PRIVATE_normalizeByteString(e.bytesValue)); + }(t, e); + + case 7 /* TypeOrder.RefValue */ : + return t.referenceValue === e.referenceValue; + + case 8 /* TypeOrder.GeoPointValue */ : + return function __PRIVATE_geoPointEquals(t, e) { + return __PRIVATE_normalizeNumber(t.geoPointValue.latitude) === __PRIVATE_normalizeNumber(e.geoPointValue.latitude) && __PRIVATE_normalizeNumber(t.geoPointValue.longitude) === __PRIVATE_normalizeNumber(e.geoPointValue.longitude); + }(t, e); + + case 2 /* TypeOrder.NumberValue */ : + return function __PRIVATE_numberEquals(t, e) { + if ("integerValue" in t && "integerValue" in e) return __PRIVATE_normalizeNumber(t.integerValue) === __PRIVATE_normalizeNumber(e.integerValue); + if ("doubleValue" in t && "doubleValue" in e) { + const r = __PRIVATE_normalizeNumber(t.doubleValue), n = __PRIVATE_normalizeNumber(e.doubleValue); + return r === n ? __PRIVATE_isNegativeZero(r) === __PRIVATE_isNegativeZero(n) : isNaN(r) && isNaN(n); + } + return !1; + }(t, e); + + case 9 /* TypeOrder.ArrayValue */ : + return __PRIVATE_arrayEquals(t.arrayValue.values || [], e.arrayValue.values || [], __PRIVATE_valueEquals); + + case 10 /* TypeOrder.VectorValue */ : + case 11 /* TypeOrder.ObjectValue */ : + return function __PRIVATE_objectEquals(t, e) { + const r = t.mapValue.fields || {}, n = e.mapValue.fields || {}; + if (__PRIVATE_objectSize(r) !== __PRIVATE_objectSize(n)) return !1; + for (const t in r) if (r.hasOwnProperty(t) && (void 0 === n[t] || !__PRIVATE_valueEquals(r[t], n[t]))) return !1; + return !0; + } + /** Returns true if the ArrayValue contains the specified element. */ (t, e); + + default: + return fail(52216, { + left: t + }); + } +} + +function __PRIVATE_arrayValueContains(t, e) { + return void 0 !== (t.values || []).find((t => __PRIVATE_valueEquals(t, e))); +} + +function __PRIVATE_valueCompare(t, e) { + if (t === e) return 0; + const r = __PRIVATE_typeOrder(t), n = __PRIVATE_typeOrder(e); + if (r !== n) return __PRIVATE_primitiveComparator(r, n); + switch (r) { + case 0 /* TypeOrder.NullValue */ : + case 9007199254740991 /* TypeOrder.MaxValue */ : + return 0; + + case 1 /* TypeOrder.BooleanValue */ : + return __PRIVATE_primitiveComparator(t.booleanValue, e.booleanValue); + + case 2 /* TypeOrder.NumberValue */ : + return function __PRIVATE_compareNumbers(t, e) { + const r = __PRIVATE_normalizeNumber(t.integerValue || t.doubleValue), n = __PRIVATE_normalizeNumber(e.integerValue || e.doubleValue); + return r < n ? -1 : r > n ? 1 : r === n ? 0 : + // one or both are NaN. + isNaN(r) ? isNaN(n) ? 0 : -1 : 1; + }(t, e); + + case 3 /* TypeOrder.TimestampValue */ : + return __PRIVATE_compareTimestamps(t.timestampValue, e.timestampValue); + + case 4 /* TypeOrder.ServerTimestampValue */ : + return __PRIVATE_compareTimestamps(__PRIVATE_getLocalWriteTime(t), __PRIVATE_getLocalWriteTime(e)); + + case 5 /* TypeOrder.StringValue */ : + return __PRIVATE_compareUtf8Strings(t.stringValue, e.stringValue); + + case 6 /* TypeOrder.BlobValue */ : + return function __PRIVATE_compareBlobs(t, e) { + const r = __PRIVATE_normalizeByteString(t), n = __PRIVATE_normalizeByteString(e); + return r.compareTo(n); + }(t.bytesValue, e.bytesValue); + + case 7 /* TypeOrder.RefValue */ : + return function __PRIVATE_compareReferences(t, e) { + const r = t.split("/"), n = e.split("/"); + for (let t = 0; t < r.length && t < n.length; t++) { + const e = __PRIVATE_primitiveComparator(r[t], n[t]); + if (0 !== e) return e; + } + return __PRIVATE_primitiveComparator(r.length, n.length); + }(t.referenceValue, e.referenceValue); + + case 8 /* TypeOrder.GeoPointValue */ : + return function __PRIVATE_compareGeoPoints(t, e) { + const r = __PRIVATE_primitiveComparator(__PRIVATE_normalizeNumber(t.latitude), __PRIVATE_normalizeNumber(e.latitude)); + if (0 !== r) return r; + return __PRIVATE_primitiveComparator(__PRIVATE_normalizeNumber(t.longitude), __PRIVATE_normalizeNumber(e.longitude)); + }(t.geoPointValue, e.geoPointValue); + + case 9 /* TypeOrder.ArrayValue */ : + return __PRIVATE_compareArrays(t.arrayValue, e.arrayValue); + + case 10 /* TypeOrder.VectorValue */ : + return function __PRIVATE_compareVectors(t, e) { + const r = t.fields || {}, n = e.fields || {}, i = r[it]?.arrayValue, s = n[it]?.arrayValue, o = __PRIVATE_primitiveComparator(i?.values?.length || 0, s?.values?.length || 0); + if (0 !== o) return o; + return __PRIVATE_compareArrays(i, s); + }(t.mapValue, e.mapValue); + + case 11 /* TypeOrder.ObjectValue */ : + return function __PRIVATE_compareMaps(t, e) { + if (t === rt && e === rt) return 0; + if (t === rt) return 1; + if (e === rt) return -1; + const r = t.fields || {}, n = Object.keys(r), i = e.fields || {}, s = Object.keys(i); + // Even though MapValues are likely sorted correctly based on their insertion + // order (e.g. when received from the backend), local modifications can bring + // elements out of order. We need to re-sort the elements to ensure that + // canonical IDs are independent of insertion order. + n.sort(), s.sort(); + for (let t = 0; t < n.length && t < s.length; ++t) { + const e = __PRIVATE_compareUtf8Strings(n[t], s[t]); + if (0 !== e) return e; + const o = __PRIVATE_valueCompare(r[n[t]], i[s[t]]); + if (0 !== o) return o; + } + return __PRIVATE_primitiveComparator(n.length, s.length); + } + /** Returns a reference value for the provided database and key. */ (t.mapValue, e.mapValue); + + default: + throw fail(23264, { + C: r + }); + } +} + +function __PRIVATE_compareTimestamps(t, e) { + if ("string" == typeof t && "string" == typeof e && t.length === e.length) return __PRIVATE_primitiveComparator(t, e); + const r = __PRIVATE_normalizeTimestamp(t), n = __PRIVATE_normalizeTimestamp(e), i = __PRIVATE_primitiveComparator(r.seconds, n.seconds); + return 0 !== i ? i : __PRIVATE_primitiveComparator(r.nanos, n.nanos); +} + +function __PRIVATE_compareArrays(t, e) { + const r = t.values || [], n = e.values || []; + for (let t = 0; t < r.length && t < n.length; ++t) { + const e = __PRIVATE_valueCompare(r[t], n[t]); + if (e) return e; + } + return __PRIVATE_primitiveComparator(r.length, n.length); +} + +function __PRIVATE_refValue(t, e) { + return { + referenceValue: `projects/${t.projectId}/databases/${t.database}/documents/${e.path.canonicalString()}` + }; +} + +/** Returns true if `value` is an ArrayValue. */ function isArray(t) { + return !!t && "arrayValue" in t; +} + +/** Returns true if `value` is a NullValue. */ function __PRIVATE_isNullValue(t) { + return !!t && "nullValue" in t; +} + +/** Returns true if `value` is NaN. */ function __PRIVATE_isNanValue(t) { + return !!t && "doubleValue" in t && isNaN(Number(t.doubleValue)); +} + +/** Returns true if `value` is a MapValue. */ function __PRIVATE_isMapValue(t) { + return !!t && "mapValue" in t; +} + +function __PRIVATE_deepClone(t) { + if (t.geoPointValue) return { + geoPointValue: { + ...t.geoPointValue + } + }; + if (t.timestampValue && "object" == typeof t.timestampValue) return { + timestampValue: { + ...t.timestampValue + } + }; + if (t.mapValue) { + const e = { + mapValue: { + fields: {} + } + }; + return forEach(t.mapValue.fields, ((t, r) => e.mapValue.fields[t] = __PRIVATE_deepClone(r))), + e; + } + if (t.arrayValue) { + const e = { + arrayValue: { + values: [] + } + }; + for (let r = 0; r < (t.arrayValue.values || []).length; ++r) e.arrayValue.values[r] = __PRIVATE_deepClone(t.arrayValue.values[r]); + return e; + } + return { + ...t + }; +} + +class Bound { + constructor(t, e) { + this.position = t, this.inclusive = e; + } +} + +function __PRIVATE_boundEquals(t, e) { + if (null === t) return null === e; + if (null === e) return !1; + if (t.inclusive !== e.inclusive || t.position.length !== e.position.length) return !1; + for (let r = 0; r < t.position.length; r++) { + if (!__PRIVATE_valueEquals(t.position[r], e.position[r])) return !1; + } + return !0; +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ class Filter {} + +class FieldFilter extends Filter { + constructor(t, e, r) { + super(), this.field = t, this.op = e, this.value = r; + } + /** + * Creates a filter based on the provided arguments. + */ static create(t, e, r) { + return t.isKeyField() ? "in" /* Operator.IN */ === e || "not-in" /* Operator.NOT_IN */ === e ? this.createKeyFieldInFilter(t, e, r) : new __PRIVATE_KeyFieldFilter(t, e, r) : "array-contains" /* Operator.ARRAY_CONTAINS */ === e ? new __PRIVATE_ArrayContainsFilter(t, r) : "in" /* Operator.IN */ === e ? new __PRIVATE_InFilter(t, r) : "not-in" /* Operator.NOT_IN */ === e ? new __PRIVATE_NotInFilter(t, r) : "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ === e ? new __PRIVATE_ArrayContainsAnyFilter(t, r) : new FieldFilter(t, e, r); + } + static createKeyFieldInFilter(t, e, r) { + return "in" /* Operator.IN */ === e ? new __PRIVATE_KeyFieldInFilter(t, r) : new __PRIVATE_KeyFieldNotInFilter(t, r); + } + matches(t) { + const e = t.data.field(this.field); + // Types do not have to match in NOT_EQUAL filters. + return "!=" /* Operator.NOT_EQUAL */ === this.op ? null !== e && void 0 === e.nullValue && this.matchesComparison(__PRIVATE_valueCompare(e, this.value)) : null !== e && __PRIVATE_typeOrder(this.value) === __PRIVATE_typeOrder(e) && this.matchesComparison(__PRIVATE_valueCompare(e, this.value)); + // Only compare types with matching backend order (such as double and int). + } + matchesComparison(t) { + switch (this.op) { + case "<" /* Operator.LESS_THAN */ : + return t < 0; + + case "<=" /* Operator.LESS_THAN_OR_EQUAL */ : + return t <= 0; + + case "==" /* Operator.EQUAL */ : + return 0 === t; + + case "!=" /* Operator.NOT_EQUAL */ : + return 0 !== t; + + case ">" /* Operator.GREATER_THAN */ : + return t > 0; + + case ">=" /* Operator.GREATER_THAN_OR_EQUAL */ : + return t >= 0; + + default: + return fail(47266, { + operator: this.op + }); + } + } + isInequality() { + return [ "<" /* Operator.LESS_THAN */ , "<=" /* Operator.LESS_THAN_OR_EQUAL */ , ">" /* Operator.GREATER_THAN */ , ">=" /* Operator.GREATER_THAN_OR_EQUAL */ , "!=" /* Operator.NOT_EQUAL */ , "not-in" /* Operator.NOT_IN */ ].indexOf(this.op) >= 0; + } + getFlattenedFilters() { + return [ this ]; + } + getFilters() { + return [ this ]; + } +} + +class CompositeFilter extends Filter { + constructor(t, e) { + super(), this.filters = t, this.op = e, this.N = null; + } + /** + * Creates a filter based on the provided arguments. + */ static create(t, e) { + return new CompositeFilter(t, e); + } + matches(t) { + return function __PRIVATE_compositeFilterIsConjunction(t) { + return "and" /* CompositeOperator.AND */ === t.op; + }(this) ? void 0 === this.filters.find((e => !e.matches(t))) : void 0 !== this.filters.find((e => e.matches(t))); + } + getFlattenedFilters() { + return null !== this.N || (this.N = this.filters.reduce(((t, e) => t.concat(e.getFlattenedFilters())), [])), + this.N; + } + // Returns a mutable copy of `this.filters` + getFilters() { + return Object.assign([], this.filters); + } +} + +function __PRIVATE_filterEquals(t, e) { + return t instanceof FieldFilter ? function __PRIVATE_fieldFilterEquals(t, e) { + return e instanceof FieldFilter && t.op === e.op && t.field.isEqual(e.field) && __PRIVATE_valueEquals(t.value, e.value); + }(t, e) : t instanceof CompositeFilter ? function __PRIVATE_compositeFilterEquals(t, e) { + if (e instanceof CompositeFilter && t.op === e.op && t.filters.length === e.filters.length) { + return t.filters.reduce(((t, r, n) => t && __PRIVATE_filterEquals(r, e.filters[n])), !0); + } + return !1; + } + /** Filter that matches on key fields (i.e. '__name__'). */ (t, e) : void fail(19439); +} + +class __PRIVATE_KeyFieldFilter extends FieldFilter { + constructor(t, e, r) { + super(t, e, r), this.key = DocumentKey.fromName(r.referenceValue); + } + matches(t) { + const e = DocumentKey.comparator(t.key, this.key); + return this.matchesComparison(e); + } +} + +/** Filter that matches on key fields within an array. */ class __PRIVATE_KeyFieldInFilter extends FieldFilter { + constructor(t, e) { + super(t, "in" /* Operator.IN */ , e), this.keys = __PRIVATE_extractDocumentKeysFromArrayValue("in" /* Operator.IN */ , e); + } + matches(t) { + return this.keys.some((e => e.isEqual(t.key))); + } +} + +/** Filter that matches on key fields not present within an array. */ class __PRIVATE_KeyFieldNotInFilter extends FieldFilter { + constructor(t, e) { + super(t, "not-in" /* Operator.NOT_IN */ , e), this.keys = __PRIVATE_extractDocumentKeysFromArrayValue("not-in" /* Operator.NOT_IN */ , e); + } + matches(t) { + return !this.keys.some((e => e.isEqual(t.key))); + } +} + +function __PRIVATE_extractDocumentKeysFromArrayValue(t, e) { + return (e.arrayValue?.values || []).map((t => DocumentKey.fromName(t.referenceValue))); +} + +/** A Filter that implements the array-contains operator. */ class __PRIVATE_ArrayContainsFilter extends FieldFilter { + constructor(t, e) { + super(t, "array-contains" /* Operator.ARRAY_CONTAINS */ , e); + } + matches(t) { + const e = t.data.field(this.field); + return isArray(e) && __PRIVATE_arrayValueContains(e.arrayValue, this.value); + } +} + +/** A Filter that implements the IN operator. */ class __PRIVATE_InFilter extends FieldFilter { + constructor(t, e) { + super(t, "in" /* Operator.IN */ , e); + } + matches(t) { + const e = t.data.field(this.field); + return null !== e && __PRIVATE_arrayValueContains(this.value.arrayValue, e); + } +} + +/** A Filter that implements the not-in operator. */ class __PRIVATE_NotInFilter extends FieldFilter { + constructor(t, e) { + super(t, "not-in" /* Operator.NOT_IN */ , e); + } + matches(t) { + if (__PRIVATE_arrayValueContains(this.value.arrayValue, { + nullValue: "NULL_VALUE" + })) return !1; + const e = t.data.field(this.field); + return null !== e && void 0 === e.nullValue && !__PRIVATE_arrayValueContains(this.value.arrayValue, e); + } +} + +/** A Filter that implements the array-contains-any operator. */ class __PRIVATE_ArrayContainsAnyFilter extends FieldFilter { + constructor(t, e) { + super(t, "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ , e); + } + matches(t) { + const e = t.data.field(this.field); + return !(!isArray(e) || !e.arrayValue.values) && e.arrayValue.values.some((t => __PRIVATE_arrayValueContains(this.value.arrayValue, t))); + } +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An ordering on a field, in some Direction. Direction defaults to ASCENDING. + */ class OrderBy { + constructor(t, e = "asc" /* Direction.ASCENDING */) { + this.field = t, this.dir = e; + } +} + +function __PRIVATE_orderByEquals(t, e) { + return t.dir === e.dir && t.field.isEqual(e.field); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A version of a document in Firestore. This corresponds to the version + * timestamp, such as update_time or read_time. + */ class SnapshotVersion { + static fromTimestamp(t) { + return new SnapshotVersion(t); + } + static min() { + return new SnapshotVersion(new Timestamp(0, 0)); + } + static max() { + return new SnapshotVersion(new Timestamp(253402300799, 999999999)); + } + constructor(t) { + this.timestamp = t; + } + compareTo(t) { + return this.timestamp._compareTo(t.timestamp); + } + isEqual(t) { + return this.timestamp.isEqual(t.timestamp); + } + /** Returns a number representation of the version for use in spec tests. */ toMicroseconds() { + // Convert to microseconds. + return 1e6 * this.timestamp.seconds + this.timestamp.nanoseconds / 1e3; + } + toString() { + return "SnapshotVersion(" + this.timestamp.toString() + ")"; + } + toTimestamp() { + return this.timestamp; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// An immutable sorted map implementation, based on a Left-leaning Red-Black +// tree. +class SortedMap { + constructor(t, e) { + this.comparator = t, this.root = e || LLRBNode.EMPTY; + } + // Returns a copy of the map, with the specified key/value added or replaced. + insert(t, e) { + return new SortedMap(this.comparator, this.root.insert(t, e, this.comparator).copy(null, null, LLRBNode.BLACK, null, null)); + } + // Returns a copy of the map, with the specified key removed. + remove(t) { + return new SortedMap(this.comparator, this.root.remove(t, this.comparator).copy(null, null, LLRBNode.BLACK, null, null)); + } + // Returns the value of the node with the given key, or null. + get(t) { + let e = this.root; + for (;!e.isEmpty(); ) { + const r = this.comparator(t, e.key); + if (0 === r) return e.value; + r < 0 ? e = e.left : r > 0 && (e = e.right); + } + return null; + } + // Returns the index of the element in this sorted map, or -1 if it doesn't + // exist. + indexOf(t) { + // Number of nodes that were pruned when descending right + let e = 0, r = this.root; + for (;!r.isEmpty(); ) { + const n = this.comparator(t, r.key); + if (0 === n) return e + r.left.size; + n < 0 ? r = r.left : ( + // Count all nodes left of the node plus the node itself + e += r.left.size + 1, r = r.right); + } + // Node not found + return -1; + } + isEmpty() { + return this.root.isEmpty(); + } + // Returns the total number of nodes in the map. + get size() { + return this.root.size; + } + // Returns the minimum key in the map. + minKey() { + return this.root.minKey(); + } + // Returns the maximum key in the map. + maxKey() { + return this.root.maxKey(); + } + // Traverses the map in key order and calls the specified action function + // for each key/value pair. If action returns true, traversal is aborted. + // Returns the first truthy value returned by action, or the last falsey + // value returned by action. + inorderTraversal(t) { + return this.root.inorderTraversal(t); + } + forEach(t) { + this.inorderTraversal(((e, r) => (t(e, r), !1))); + } + toString() { + const t = []; + return this.inorderTraversal(((e, r) => (t.push(`${e}:${r}`), !1))), `{${t.join(", ")}}`; + } + // Traverses the map in reverse key order and calls the specified action + // function for each key/value pair. If action returns true, traversal is + // aborted. + // Returns the first truthy value returned by action, or the last falsey + // value returned by action. + reverseTraversal(t) { + return this.root.reverseTraversal(t); + } + // Returns an iterator over the SortedMap. + getIterator() { + return new SortedMapIterator(this.root, null, this.comparator, !1); + } + getIteratorFrom(t) { + return new SortedMapIterator(this.root, t, this.comparator, !1); + } + getReverseIterator() { + return new SortedMapIterator(this.root, null, this.comparator, !0); + } + getReverseIteratorFrom(t) { + return new SortedMapIterator(this.root, t, this.comparator, !0); + } +} + + // end SortedMap +// An iterator over an LLRBNode. +class SortedMapIterator { + constructor(t, e, r, n) { + this.isReverse = n, this.nodeStack = []; + let i = 1; + for (;!t.isEmpty(); ) if (i = e ? r(t.key, e) : 1, + // flip the comparison if we're going in reverse + e && n && (i *= -1), i < 0) + // This node is less than our start key. ignore it + t = this.isReverse ? t.left : t.right; else { + if (0 === i) { + // This node is exactly equal to our start key. Push it on the stack, + // but stop iterating; + this.nodeStack.push(t); + break; + } + // This node is greater than our start key, add it to the stack and move + // to the next one + this.nodeStack.push(t), t = this.isReverse ? t.right : t.left; + } + } + getNext() { + let t = this.nodeStack.pop(); + const e = { + key: t.key, + value: t.value + }; + if (this.isReverse) for (t = t.left; !t.isEmpty(); ) this.nodeStack.push(t), t = t.right; else for (t = t.right; !t.isEmpty(); ) this.nodeStack.push(t), + t = t.left; + return e; + } + hasNext() { + return this.nodeStack.length > 0; + } + peek() { + if (0 === this.nodeStack.length) return null; + const t = this.nodeStack[this.nodeStack.length - 1]; + return { + key: t.key, + value: t.value + }; + } +} + + // end SortedMapIterator +// Represents a node in a Left-leaning Red-Black tree. +class LLRBNode { + constructor(t, e, r, n, i) { + this.key = t, this.value = e, this.color = null != r ? r : LLRBNode.RED, this.left = null != n ? n : LLRBNode.EMPTY, + this.right = null != i ? i : LLRBNode.EMPTY, this.size = this.left.size + 1 + this.right.size; + } + // Returns a copy of the current node, optionally replacing pieces of it. + copy(t, e, r, n, i) { + return new LLRBNode(null != t ? t : this.key, null != e ? e : this.value, null != r ? r : this.color, null != n ? n : this.left, null != i ? i : this.right); + } + isEmpty() { + return !1; + } + // Traverses the tree in key order and calls the specified action function + // for each node. If action returns true, traversal is aborted. + // Returns the first truthy value returned by action, or the last falsey + // value returned by action. + inorderTraversal(t) { + return this.left.inorderTraversal(t) || t(this.key, this.value) || this.right.inorderTraversal(t); + } + // Traverses the tree in reverse key order and calls the specified action + // function for each node. If action returns true, traversal is aborted. + // Returns the first truthy value returned by action, or the last falsey + // value returned by action. + reverseTraversal(t) { + return this.right.reverseTraversal(t) || t(this.key, this.value) || this.left.reverseTraversal(t); + } + // Returns the minimum node in the tree. + min() { + return this.left.isEmpty() ? this : this.left.min(); + } + // Returns the maximum key in the tree. + minKey() { + return this.min().key; + } + // Returns the maximum key in the tree. + maxKey() { + return this.right.isEmpty() ? this.key : this.right.maxKey(); + } + // Returns new tree, with the key/value added. + insert(t, e, r) { + let n = this; + const i = r(t, n.key); + return n = i < 0 ? n.copy(null, null, null, n.left.insert(t, e, r), null) : 0 === i ? n.copy(null, e, null, null, null) : n.copy(null, null, null, null, n.right.insert(t, e, r)), + n.fixUp(); + } + removeMin() { + if (this.left.isEmpty()) return LLRBNode.EMPTY; + let t = this; + return t.left.isRed() || t.left.left.isRed() || (t = t.moveRedLeft()), t = t.copy(null, null, null, t.left.removeMin(), null), + t.fixUp(); + } + // Returns new tree, with the specified item removed. + remove(t, e) { + let r, n = this; + if (e(t, n.key) < 0) n.left.isEmpty() || n.left.isRed() || n.left.left.isRed() || (n = n.moveRedLeft()), + n = n.copy(null, null, null, n.left.remove(t, e), null); else { + if (n.left.isRed() && (n = n.rotateRight()), n.right.isEmpty() || n.right.isRed() || n.right.left.isRed() || (n = n.moveRedRight()), + 0 === e(t, n.key)) { + if (n.right.isEmpty()) return LLRBNode.EMPTY; + r = n.right.min(), n = n.copy(r.key, r.value, null, null, n.right.removeMin()); + } + n = n.copy(null, null, null, null, n.right.remove(t, e)); + } + return n.fixUp(); + } + isRed() { + return this.color; + } + // Returns new tree after performing any needed rotations. + fixUp() { + let t = this; + return t.right.isRed() && !t.left.isRed() && (t = t.rotateLeft()), t.left.isRed() && t.left.left.isRed() && (t = t.rotateRight()), + t.left.isRed() && t.right.isRed() && (t = t.colorFlip()), t; + } + moveRedLeft() { + let t = this.colorFlip(); + return t.right.left.isRed() && (t = t.copy(null, null, null, null, t.right.rotateRight()), + t = t.rotateLeft(), t = t.colorFlip()), t; + } + moveRedRight() { + let t = this.colorFlip(); + return t.left.left.isRed() && (t = t.rotateRight(), t = t.colorFlip()), t; + } + rotateLeft() { + const t = this.copy(null, null, LLRBNode.RED, null, this.right.left); + return this.right.copy(null, null, this.color, t, null); + } + rotateRight() { + const t = this.copy(null, null, LLRBNode.RED, this.left.right, null); + return this.left.copy(null, null, this.color, null, t); + } + colorFlip() { + const t = this.left.copy(null, null, !this.left.color, null, null), e = this.right.copy(null, null, !this.right.color, null, null); + return this.copy(null, null, !this.color, t, e); + } + // For testing. + checkMaxDepth() { + const t = this.check(); + return Math.pow(2, t) <= this.size + 1; + } + // In a balanced RB tree, the black-depth (number of black nodes) from root to + // leaves is equal on both sides. This function verifies that or asserts. + check() { + if (this.isRed() && this.left.isRed()) throw fail(43730, { + key: this.key, + value: this.value + }); + if (this.right.isRed()) throw fail(14113, { + key: this.key, + value: this.value + }); + const t = this.left.check(); + if (t !== this.right.check()) throw fail(27949); + return t + (this.isRed() ? 0 : 1); + } +} + + // end LLRBNode +// Empty node is shared between all LLRB trees. +// eslint-disable-next-line @typescript-eslint/no-explicit-any +LLRBNode.EMPTY = null, LLRBNode.RED = !0, LLRBNode.BLACK = !1; + +// end LLRBEmptyNode +LLRBNode.EMPTY = new +// Represents an empty node (a leaf node in the Red-Black Tree). +class LLRBEmptyNode { + constructor() { + this.size = 0; + } + get key() { + throw fail(57766); + } + get value() { + throw fail(16141); + } + get color() { + throw fail(16727); + } + get left() { + throw fail(29726); + } + get right() { + throw fail(36894); + } + // Returns a copy of the current node. + copy(t, e, r, n, i) { + return this; + } + // Returns a copy of the tree, with the specified key/value added. + insert(t, e, r) { + return new LLRBNode(t, e); + } + // Returns a copy of the tree, with the specified key removed. + remove(t, e) { + return this; + } + isEmpty() { + return !0; + } + inorderTraversal(t) { + return !1; + } + reverseTraversal(t) { + return !1; + } + minKey() { + return null; + } + maxKey() { + return null; + } + isRed() { + return !1; + } + // For testing. + checkMaxDepth() { + return !0; + } + check() { + return 0; + } +}; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * SortedSet is an immutable (copy-on-write) collection that holds elements + * in order specified by the provided comparator. + * + * NOTE: if provided comparator returns 0 for two elements, we consider them to + * be equal! + */ +class SortedSet { + constructor(t) { + this.comparator = t, this.data = new SortedMap(this.comparator); + } + has(t) { + return null !== this.data.get(t); + } + first() { + return this.data.minKey(); + } + last() { + return this.data.maxKey(); + } + get size() { + return this.data.size; + } + indexOf(t) { + return this.data.indexOf(t); + } + /** Iterates elements in order defined by "comparator" */ forEach(t) { + this.data.inorderTraversal(((e, r) => (t(e), !1))); + } + /** Iterates over `elem`s such that: range[0] <= elem < range[1]. */ forEachInRange(t, e) { + const r = this.data.getIteratorFrom(t[0]); + for (;r.hasNext(); ) { + const n = r.getNext(); + if (this.comparator(n.key, t[1]) >= 0) return; + e(n.key); + } + } + /** + * Iterates over `elem`s such that: start <= elem until false is returned. + */ forEachWhile(t, e) { + let r; + for (r = void 0 !== e ? this.data.getIteratorFrom(e) : this.data.getIterator(); r.hasNext(); ) { + if (!t(r.getNext().key)) return; + } + } + /** Finds the least element greater than or equal to `elem`. */ firstAfterOrEqual(t) { + const e = this.data.getIteratorFrom(t); + return e.hasNext() ? e.getNext().key : null; + } + getIterator() { + return new SortedSetIterator(this.data.getIterator()); + } + getIteratorFrom(t) { + return new SortedSetIterator(this.data.getIteratorFrom(t)); + } + /** Inserts or updates an element */ add(t) { + return this.copy(this.data.remove(t).insert(t, !0)); + } + /** Deletes an element */ delete(t) { + return this.has(t) ? this.copy(this.data.remove(t)) : this; + } + isEmpty() { + return this.data.isEmpty(); + } + unionWith(t) { + let e = this; + // Make sure `result` always refers to the larger one of the two sets. + return e.size < t.size && (e = t, t = this), t.forEach((t => { + e = e.add(t); + })), e; + } + isEqual(t) { + if (!(t instanceof SortedSet)) return !1; + if (this.size !== t.size) return !1; + const e = this.data.getIterator(), r = t.data.getIterator(); + for (;e.hasNext(); ) { + const t = e.getNext().key, n = r.getNext().key; + if (0 !== this.comparator(t, n)) return !1; + } + return !0; + } + toArray() { + const t = []; + return this.forEach((e => { + t.push(e); + })), t; + } + toString() { + const t = []; + return this.forEach((e => t.push(e))), "SortedSet(" + t.toString() + ")"; + } + copy(t) { + const e = new SortedSet(this.comparator); + return e.data = t, e; + } +} + +class SortedSetIterator { + constructor(t) { + this.iter = t; + } + getNext() { + return this.iter.getNext().key; + } + hasNext() { + return this.iter.hasNext(); + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Provides a set of fields that can be used to partially patch a document. + * FieldMask is used in conjunction with ObjectValue. + * Examples: + * foo - Overwrites foo entirely with the provided value. If foo is not + * present in the companion ObjectValue, the field is deleted. + * foo.bar - Overwrites only the field bar of the object foo. + * If foo is not an object, foo is replaced with an object + * containing foo + */ class FieldMask { + constructor(t) { + this.fields = t, + // TODO(dimond): validation of FieldMask + // Sort the field mask to support `FieldMask.isEqual()` and assert below. + t.sort(FieldPath$1.comparator); + } + static empty() { + return new FieldMask([]); + } + /** + * Returns a new FieldMask object that is the result of adding all the given + * fields paths to this field mask. + */ unionWith(t) { + let e = new SortedSet(FieldPath$1.comparator); + for (const t of this.fields) e = e.add(t); + for (const r of t) e = e.add(r); + return new FieldMask(e.toArray()); + } + /** + * Verifies that `fieldPath` is included by at least one field in this field + * mask. + * + * This is an O(n) operation, where `n` is the size of the field mask. + */ covers(t) { + for (const e of this.fields) if (e.isPrefixOf(t)) return !0; + return !1; + } + isEqual(t) { + return __PRIVATE_arrayEquals(this.fields, t.fields, ((t, e) => t.isEqual(e))); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An ObjectValue represents a MapValue in the Firestore Proto and offers the + * ability to add and remove fields (via the ObjectValueBuilder). + */ class ObjectValue { + constructor(t) { + this.value = t; + } + static empty() { + return new ObjectValue({ + mapValue: {} + }); + } + /** + * Returns the value at the given path or null. + * + * @param path - the path to search + * @returns The value at the path or null if the path is not set. + */ field(t) { + if (t.isEmpty()) return this.value; + { + let e = this.value; + for (let r = 0; r < t.length - 1; ++r) if (e = (e.mapValue.fields || {})[t.get(r)], + !__PRIVATE_isMapValue(e)) return null; + return e = (e.mapValue.fields || {})[t.lastSegment()], e || null; + } + } + /** + * Sets the field to the provided value. + * + * @param path - The field path to set. + * @param value - The value to set. + */ set(t, e) { + this.getFieldsMap(t.popLast())[t.lastSegment()] = __PRIVATE_deepClone(e); + } + /** + * Sets the provided fields to the provided values. + * + * @param data - A map of fields to values (or null for deletes). + */ setAll(t) { + let e = FieldPath$1.emptyPath(), r = {}, n = []; + t.forEach(((t, i) => { + if (!e.isImmediateParentOf(i)) { + // Insert the accumulated changes at this parent location + const t = this.getFieldsMap(e); + this.applyChanges(t, r, n), r = {}, n = [], e = i.popLast(); + } + t ? r[i.lastSegment()] = __PRIVATE_deepClone(t) : n.push(i.lastSegment()); + })); + const i = this.getFieldsMap(e); + this.applyChanges(i, r, n); + } + /** + * Removes the field at the specified path. If there is no field at the + * specified path, nothing is changed. + * + * @param path - The field path to remove. + */ delete(t) { + const e = this.field(t.popLast()); + __PRIVATE_isMapValue(e) && e.mapValue.fields && delete e.mapValue.fields[t.lastSegment()]; + } + isEqual(t) { + return __PRIVATE_valueEquals(this.value, t.value); + } + /** + * Returns the map that contains the leaf element of `path`. If the parent + * entry does not yet exist, or if it is not a map, a new map will be created. + */ getFieldsMap(t) { + let e = this.value; + e.mapValue.fields || (e.mapValue = { + fields: {} + }); + for (let r = 0; r < t.length; ++r) { + let n = e.mapValue.fields[t.get(r)]; + __PRIVATE_isMapValue(n) && n.mapValue.fields || (n = { + mapValue: { + fields: {} + } + }, e.mapValue.fields[t.get(r)] = n), e = n; + } + return e.mapValue.fields; + } + /** + * Modifies `fieldsMap` by adding, replacing or deleting the specified + * entries. + */ applyChanges(t, e, r) { + forEach(e, ((e, r) => t[e] = r)); + for (const e of r) delete t[e]; + } + clone() { + return new ObjectValue(__PRIVATE_deepClone(this.value)); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Represents a document in Firestore with a key, version, data and whether it + * has local mutations applied to it. + * + * Documents can transition between states via `convertToFoundDocument()`, + * `convertToNoDocument()` and `convertToUnknownDocument()`. If a document does + * not transition to one of these states even after all mutations have been + * applied, `isValidDocument()` returns false and the document should be removed + * from all views. + */ class MutableDocument { + constructor(t, e, r, n, i, s, o) { + this.key = t, this.documentType = e, this.version = r, this.readTime = n, this.createTime = i, + this.data = s, this.documentState = o; + } + /** + * Creates a document with no known version or data, but which can serve as + * base document for mutations. + */ static newInvalidDocument(t) { + return new MutableDocument(t, 0 /* DocumentType.INVALID */ , + /* version */ SnapshotVersion.min(), + /* readTime */ SnapshotVersion.min(), + /* createTime */ SnapshotVersion.min(), ObjectValue.empty(), 0 /* DocumentState.SYNCED */); + } + /** + * Creates a new document that is known to exist with the given data at the + * given version. + */ static newFoundDocument(t, e, r, n) { + return new MutableDocument(t, 1 /* DocumentType.FOUND_DOCUMENT */ , + /* version */ e, + /* readTime */ SnapshotVersion.min(), + /* createTime */ r, n, 0 /* DocumentState.SYNCED */); + } + /** Creates a new document that is known to not exist at the given version. */ static newNoDocument(t, e) { + return new MutableDocument(t, 2 /* DocumentType.NO_DOCUMENT */ , + /* version */ e, + /* readTime */ SnapshotVersion.min(), + /* createTime */ SnapshotVersion.min(), ObjectValue.empty(), 0 /* DocumentState.SYNCED */); + } + /** + * Creates a new document that is known to exist at the given version but + * whose data is not known (e.g. a document that was updated without a known + * base document). + */ static newUnknownDocument(t, e) { + return new MutableDocument(t, 3 /* DocumentType.UNKNOWN_DOCUMENT */ , + /* version */ e, + /* readTime */ SnapshotVersion.min(), + /* createTime */ SnapshotVersion.min(), ObjectValue.empty(), 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */); + } + /** + * Changes the document type to indicate that it exists and that its version + * and data are known. + */ convertToFoundDocument(t, e) { + // If a document is switching state from being an invalid or deleted + // document to a valid (FOUND_DOCUMENT) document, either due to receiving an + // update from Watch or due to applying a local set mutation on top + // of a deleted document, our best guess about its createTime would be the + // version at which the document transitioned to a FOUND_DOCUMENT. + return !this.createTime.isEqual(SnapshotVersion.min()) || 2 /* DocumentType.NO_DOCUMENT */ !== this.documentType && 0 /* DocumentType.INVALID */ !== this.documentType || (this.createTime = t), + this.version = t, this.documentType = 1 /* DocumentType.FOUND_DOCUMENT */ , this.data = e, + this.documentState = 0 /* DocumentState.SYNCED */ , this; + } + /** + * Changes the document type to indicate that it doesn't exist at the given + * version. + */ convertToNoDocument(t) { + return this.version = t, this.documentType = 2 /* DocumentType.NO_DOCUMENT */ , + this.data = ObjectValue.empty(), this.documentState = 0 /* DocumentState.SYNCED */ , + this; + } + /** + * Changes the document type to indicate that it exists at a given version but + * that its data is not known (e.g. a document that was updated without a known + * base document). + */ convertToUnknownDocument(t) { + return this.version = t, this.documentType = 3 /* DocumentType.UNKNOWN_DOCUMENT */ , + this.data = ObjectValue.empty(), this.documentState = 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */ , + this; + } + setHasCommittedMutations() { + return this.documentState = 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */ , this; + } + setHasLocalMutations() { + return this.documentState = 1 /* DocumentState.HAS_LOCAL_MUTATIONS */ , this.version = SnapshotVersion.min(), + this; + } + setReadTime(t) { + return this.readTime = t, this; + } + get hasLocalMutations() { + return 1 /* DocumentState.HAS_LOCAL_MUTATIONS */ === this.documentState; + } + get hasCommittedMutations() { + return 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */ === this.documentState; + } + get hasPendingWrites() { + return this.hasLocalMutations || this.hasCommittedMutations; + } + isValidDocument() { + return 0 /* DocumentType.INVALID */ !== this.documentType; + } + isFoundDocument() { + return 1 /* DocumentType.FOUND_DOCUMENT */ === this.documentType; + } + isNoDocument() { + return 2 /* DocumentType.NO_DOCUMENT */ === this.documentType; + } + isUnknownDocument() { + return 3 /* DocumentType.UNKNOWN_DOCUMENT */ === this.documentType; + } + isEqual(t) { + return t instanceof MutableDocument && this.key.isEqual(t.key) && this.version.isEqual(t.version) && this.documentType === t.documentType && this.documentState === t.documentState && this.data.isEqual(t.data); + } + mutableCopy() { + return new MutableDocument(this.key, this.documentType, this.version, this.readTime, this.createTime, this.data.clone(), this.documentState); + } + toString() { + return `Document(${this.key}, ${this.version}, ${JSON.stringify(this.data.value)}, {createTime: ${this.createTime}}), {documentType: ${this.documentType}}), {documentState: ${this.documentState}})`; + } +} + +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// Visible for testing +class __PRIVATE_TargetImpl { + constructor(t, e = null, r = [], n = [], i = null, s = null, o = null) { + this.path = t, this.collectionGroup = e, this.orderBy = r, this.filters = n, this.limit = i, + this.startAt = s, this.endAt = o, this.O = null; + } +} + +/** + * Initializes a Target with a path and optional additional query constraints. + * Path must currently be empty if this is a collection group query. + * + * NOTE: you should always construct `Target` from `Query.toTarget` instead of + * using this factory method, because `Query` provides an implicit `orderBy` + * property. + */ function __PRIVATE_newTarget(t, e = null, r = [], n = [], i = null, s = null, o = null) { + return new __PRIVATE_TargetImpl(t, e, r, n, i, s, o); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Query encapsulates all the query attributes we support in the SDK. It can + * be run against the LocalStore, as well as be converted to a `Target` to + * query the RemoteStore results. + * + * Visible for testing. + */ +class __PRIVATE_QueryImpl { + /** + * Initializes a Query with a path and optional additional query constraints. + * Path must currently be empty if this is a collection group query. + */ + constructor(t, e = null, r = [], n = [], i = null, s = "F" /* LimitType.First */ , o = null, a = null) { + this.path = t, this.collectionGroup = e, this.explicitOrderBy = r, this.filters = n, + this.limit = i, this.limitType = s, this.startAt = o, this.endAt = a, this.q = null, + // The corresponding `Target` of this `Query` instance, for use with + // non-aggregate queries. + this.B = null, + // The corresponding `Target` of this `Query` instance, for use with + // aggregate queries. Unlike targets for non-aggregate queries, + // aggregate query targets do not contain normalized order-bys, they only + // contain explicit order-bys. + this.$ = null, this.startAt, this.endAt; + } +} + +/** Creates a new Query for a query that matches all documents at `path` */ +/** + * Returns whether the query matches a collection group rather than a specific + * collection. + */ +function __PRIVATE_isCollectionGroupQuery(t) { + return null !== t.collectionGroup; +} + +/** + * Returns the normalized order-by constraint that is used to execute the Query, + * which can be different from the order-by constraints the user provided (e.g. + * the SDK and backend always orders by `__name__`). The normalized order-by + * includes implicit order-bys in addition to the explicit user provided + * order-bys. + */ function __PRIVATE_queryNormalizedOrderBy(t) { + const e = __PRIVATE_debugCast(t); + if (null === e.q) { + e.q = []; + const t = new Set; + // Any explicit order by fields should be added as is. + for (const r of e.explicitOrderBy) e.q.push(r), t.add(r.field.canonicalString()); + // The order of the implicit ordering always matches the last explicit order by. + const r = e.explicitOrderBy.length > 0 ? e.explicitOrderBy[e.explicitOrderBy.length - 1].dir : "asc" /* Direction.ASCENDING */ , n = + // Returns the sorted set of inequality filter fields used in this query. + function __PRIVATE_getInequalityFilterFields(t) { + let e = new SortedSet(FieldPath$1.comparator); + return t.filters.forEach((t => { + t.getFlattenedFilters().forEach((t => { + t.isInequality() && (e = e.add(t.field)); + })); + })), e; + } + /** + * Creates a new Query for a collection group query that matches all documents + * within the provided collection group. + */ (e); + // Any inequality fields not explicitly ordered should be implicitly ordered in a lexicographical + // order. When there are multiple inequality filters on the same field, the field should be added + // only once. + // Note: `SortedSet` sorts the key field before other fields. However, we want the key + // field to be sorted last. + n.forEach((n => { + t.has(n.canonicalString()) || n.isKeyField() || e.q.push(new OrderBy(n, r)); + })), + // Add the document key field to the last if it is not explicitly ordered. + t.has(FieldPath$1.keyField().canonicalString()) || e.q.push(new OrderBy(FieldPath$1.keyField(), r)); + } + return e.q; +} + +/** + * Converts this `Query` instance to its corresponding `Target` representation. + */ function __PRIVATE_queryToTarget(t) { + const e = __PRIVATE_debugCast(t); + return e.B || (e.B = __PRIVATE__queryToTarget(e, __PRIVATE_queryNormalizedOrderBy(t))), + e.B; +} + +/** + * Converts this `Query` instance to its corresponding `Target` representation, + * for use within an aggregate query. Unlike targets for non-aggregate queries, + * aggregate query targets do not contain normalized order-bys, they only + * contain explicit order-bys. + */ function __PRIVATE__queryToTarget(t, e) { + if ("F" /* LimitType.First */ === t.limitType) return __PRIVATE_newTarget(t.path, t.collectionGroup, e, t.filters, t.limit, t.startAt, t.endAt); + { + // Flip the orderBy directions since we want the last results + e = e.map((t => { + const e = "desc" /* Direction.DESCENDING */ === t.dir ? "asc" /* Direction.ASCENDING */ : "desc" /* Direction.DESCENDING */; + return new OrderBy(t.field, e); + })); + // We need to swap the cursors to match the now-flipped query ordering. + const r = t.endAt ? new Bound(t.endAt.position, t.endAt.inclusive) : null, n = t.startAt ? new Bound(t.startAt.position, t.startAt.inclusive) : null; + // Now return as a LimitType.First query. + return __PRIVATE_newTarget(t.path, t.collectionGroup, e, t.filters, t.limit, r, n); + } +} + +function __PRIVATE_queryWithAddedFilter(t, e) { + const r = t.filters.concat([ e ]); + return new __PRIVATE_QueryImpl(t.path, t.collectionGroup, t.explicitOrderBy.slice(), r, t.limit, t.limitType, t.startAt, t.endAt); +} + +function __PRIVATE_queryEquals(t, e) { + return function __PRIVATE_targetEquals(t, e) { + if (t.limit !== e.limit) return !1; + if (t.orderBy.length !== e.orderBy.length) return !1; + for (let r = 0; r < t.orderBy.length; r++) if (!__PRIVATE_orderByEquals(t.orderBy[r], e.orderBy[r])) return !1; + if (t.filters.length !== e.filters.length) return !1; + for (let r = 0; r < t.filters.length; r++) if (!__PRIVATE_filterEquals(t.filters[r], e.filters[r])) return !1; + return t.collectionGroup === e.collectionGroup && !!t.path.isEqual(e.path) && !!__PRIVATE_boundEquals(t.startAt, e.startAt) && __PRIVATE_boundEquals(t.endAt, e.endAt); + }(__PRIVATE_queryToTarget(t), __PRIVATE_queryToTarget(e)) && t.limitType === e.limitType; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Returns an DoubleValue for `value` that is encoded based the serializer's + * `useProto3Json` setting. + */ function __PRIVATE_toDouble(t, e) { + if (t.useProto3Json) { + if (isNaN(e)) return { + doubleValue: "NaN" + }; + if (e === 1 / 0) return { + doubleValue: "Infinity" + }; + if (e === -1 / 0) return { + doubleValue: "-Infinity" + }; + } + return { + doubleValue: __PRIVATE_isNegativeZero(e) ? "-0" : e + }; +} + +/** + * Returns an IntegerValue for `value`. + */ +/** + * Returns a value for a number that's appropriate to put into a proto. + * The return value is an IntegerValue if it can safely represent the value, + * otherwise a DoubleValue is returned. + */ +function toNumber(t, e) { + return function isSafeInteger(t) { + return "number" == typeof t && Number.isInteger(t) && !__PRIVATE_isNegativeZero(t) && t <= Number.MAX_SAFE_INTEGER && t >= Number.MIN_SAFE_INTEGER; + }(e) ? function __PRIVATE_toInteger(t) { + return { + integerValue: "" + t + }; + }(e) : __PRIVATE_toDouble(t, e); +} + +/** + * @license + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Used to represent a field transform on a mutation. */ class TransformOperation { + constructor() { + // Make sure that the structural type of `TransformOperation` is unique. + // See https://github.com/microsoft/TypeScript/issues/5451 + this._ = void 0; + } +} + +/** Transforms a value into a server-generated timestamp. */ class __PRIVATE_ServerTimestampTransform extends TransformOperation {} + +/** Transforms an array value via a union operation. */ class __PRIVATE_ArrayUnionTransformOperation extends TransformOperation { + constructor(t) { + super(), this.elements = t; + } +} + +/** Transforms an array value via a remove operation. */ class __PRIVATE_ArrayRemoveTransformOperation extends TransformOperation { + constructor(t) { + super(), this.elements = t; + } +} + +/** + * Implements the backend semantics for locally computed NUMERIC_ADD (increment) + * transforms. Converts all field values to integers or doubles, but unlike the + * backend does not cap integer values at 2^63. Instead, JavaScript number + * arithmetic is used and precision loss can occur for values greater than 2^53. + */ class __PRIVATE_NumericIncrementTransformOperation extends TransformOperation { + constructor(t, e) { + super(), this.serializer = t, this.k = e; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** A field path and the TransformOperation to perform upon it. */ class FieldTransform { + constructor(t, e) { + this.field = t, this.transform = e; + } +} + +/** + * Encodes a precondition for a mutation. This follows the model that the + * backend accepts with the special case of an explicit "empty" precondition + * (meaning no precondition). + */ class Precondition { + constructor(t, e) { + this.updateTime = t, this.exists = e; + } + /** Creates a new empty Precondition. */ static none() { + return new Precondition; + } + /** Creates a new Precondition with an exists flag. */ static exists(t) { + return new Precondition(void 0, t); + } + /** Creates a new Precondition based on a version a document exists at. */ static updateTime(t) { + return new Precondition(t); + } + /** Returns whether this Precondition is empty. */ get isNone() { + return void 0 === this.updateTime && void 0 === this.exists; + } + isEqual(t) { + return this.exists === t.exists && (this.updateTime ? !!t.updateTime && this.updateTime.isEqual(t.updateTime) : !t.updateTime); + } +} + +/** + * A mutation describes a self-contained change to a document. Mutations can + * create, replace, delete, and update subsets of documents. + * + * Mutations not only act on the value of the document but also its version. + * + * For local mutations (mutations that haven't been committed yet), we preserve + * the existing version for Set and Patch mutations. For Delete mutations, we + * reset the version to 0. + * + * Here's the expected transition table. + * + * MUTATION APPLIED TO RESULTS IN + * + * SetMutation Document(v3) Document(v3) + * SetMutation NoDocument(v3) Document(v0) + * SetMutation InvalidDocument(v0) Document(v0) + * PatchMutation Document(v3) Document(v3) + * PatchMutation NoDocument(v3) NoDocument(v3) + * PatchMutation InvalidDocument(v0) UnknownDocument(v3) + * DeleteMutation Document(v3) NoDocument(v0) + * DeleteMutation NoDocument(v3) NoDocument(v0) + * DeleteMutation InvalidDocument(v0) NoDocument(v0) + * + * For acknowledged mutations, we use the updateTime of the WriteResponse as + * the resulting version for Set and Patch mutations. As deletes have no + * explicit update time, we use the commitTime of the WriteResponse for + * Delete mutations. + * + * If a mutation is acknowledged by the backend but fails the precondition check + * locally, we transition to an `UnknownDocument` and rely on Watch to send us + * the updated version. + * + * Field transforms are used only with Patch and Set Mutations. We use the + * `updateTransforms` message to store transforms, rather than the `transforms`s + * messages. + * + * ## Subclassing Notes + * + * Every type of mutation needs to implement its own applyToRemoteDocument() and + * applyToLocalView() to implement the actual behavior of applying the mutation + * to some source document (see `setMutationApplyToRemoteDocument()` for an + * example). + */ class Mutation {} + +/** + * A mutation that creates or replaces the document at the given key with the + * object value contents. + */ class __PRIVATE_SetMutation extends Mutation { + constructor(t, e, r, n = []) { + super(), this.key = t, this.value = e, this.precondition = r, this.fieldTransforms = n, + this.type = 0 /* MutationType.Set */; + } + getFieldMask() { + return null; + } +} + +/** + * A mutation that modifies fields of the document at the given key with the + * given values. The values are applied through a field mask: + * + * * When a field is in both the mask and the values, the corresponding field + * is updated. + * * When a field is in neither the mask nor the values, the corresponding + * field is unmodified. + * * When a field is in the mask but not in the values, the corresponding field + * is deleted. + * * When a field is not in the mask but is in the values, the values map is + * ignored. + */ class __PRIVATE_PatchMutation extends Mutation { + constructor(t, e, r, n, i = []) { + super(), this.key = t, this.data = e, this.fieldMask = r, this.precondition = n, + this.fieldTransforms = i, this.type = 1 /* MutationType.Patch */; + } + getFieldMask() { + return this.fieldMask; + } +} + +/** A mutation that deletes the document at the given key. */ class __PRIVATE_DeleteMutation extends Mutation { + constructor(t, e) { + super(), this.key = t, this.precondition = e, this.type = 2 /* MutationType.Delete */ , + this.fieldTransforms = []; + } + getFieldMask() { + return null; + } +} + +/** + * A mutation that verifies the existence of the document at the given key with + * the provided precondition. + * + * The `verify` operation is only used in Transactions, and this class serves + * primarily to facilitate serialization into protos. + */ class __PRIVATE_VerifyMutation extends Mutation { + constructor(t, e) { + super(), this.key = t, this.precondition = e, this.type = 3 /* MutationType.Verify */ , + this.fieldTransforms = []; + } + getFieldMask() { + return null; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ const st = (() => { + const t = { + asc: "ASCENDING", + desc: "DESCENDING" + }; + return t; +})(), ot = (() => { + const t = { + "<": "LESS_THAN", + "<=": "LESS_THAN_OR_EQUAL", + ">": "GREATER_THAN", + ">=": "GREATER_THAN_OR_EQUAL", + "==": "EQUAL", + "!=": "NOT_EQUAL", + "array-contains": "ARRAY_CONTAINS", + in: "IN", + "not-in": "NOT_IN", + "array-contains-any": "ARRAY_CONTAINS_ANY" + }; + return t; +})(), at = (() => { + const t = { + and: "AND", + or: "OR" + }; + return t; +})(); + +/** + * This class generates JsonObject values for the Datastore API suitable for + * sending to either GRPC stub methods or via the JSON/HTTP REST API. + * + * The serializer supports both Protobuf.js and Proto3 JSON formats. By + * setting `useProto3Json` to true, the serializer will use the Proto3 JSON + * format. + * + * For a description of the Proto3 JSON format check + * https://developers.google.com/protocol-buffers/docs/proto3#json + * + * TODO(klimt): We can remove the databaseId argument if we keep the full + * resource name in documents. + */ +class JsonProtoSerializer { + constructor(t, e) { + this.databaseId = t, this.useProto3Json = e; + } +} + +/** + * Returns a value for a number (or null) that's appropriate to put into + * a google.protobuf.Int32Value proto. + * DO NOT USE THIS FOR ANYTHING ELSE. + * This method cheats. It's typed as returning "number" because that's what + * our generated proto interfaces say Int32Value must be. But GRPC actually + * expects a { value: } struct. + */ +/** + * Returns a value for a Date that's appropriate to put into a proto. + */ +function toTimestamp(t, e) { + if (t.useProto3Json) { + return `${new Date(1e3 * e.seconds).toISOString().replace(/\.\d*/, "").replace("Z", "")}.${("000000000" + e.nanoseconds).slice(-9)}Z`; + } + return { + seconds: "" + e.seconds, + nanos: e.nanoseconds + }; +} + +/** + * Returns a Timestamp typed object given protobuf timestamp value. + */ +/** + * Returns a value for bytes that's appropriate to put in a proto. + * + * Visible for testing. + */ +function __PRIVATE_toBytes(t, e) { + return t.useProto3Json ? e.toBase64() : e.toUint8Array(); +} + +function __PRIVATE_toVersion(t, e) { + return toTimestamp(t, e.toTimestamp()); +} + +function __PRIVATE_fromVersion(t) { + return __PRIVATE_hardAssert(!!t, 49232), SnapshotVersion.fromTimestamp(function fromTimestamp(t) { + const e = __PRIVATE_normalizeTimestamp(t); + return new Timestamp(e.seconds, e.nanos); + }(t)); +} + +function __PRIVATE_toResourceName(t, e) { + return __PRIVATE_toResourcePath(t, e).canonicalString(); +} + +function __PRIVATE_toResourcePath(t, e) { + const r = function __PRIVATE_fullyQualifiedPrefixPath(t) { + return new ResourcePath([ "projects", t.projectId, "databases", t.database ]); + }(t).child("documents"); + return void 0 === e ? r : r.child(e); +} + +function __PRIVATE_toName(t, e) { + return __PRIVATE_toResourceName(t.databaseId, e.path); +} + +function fromName(t, e) { + const r = function __PRIVATE_fromResourceName(t) { + const e = ResourcePath.fromString(t); + return __PRIVATE_hardAssert(__PRIVATE_isValidResourceName(e), 10190, { + key: e.toString() + }), e; + }(e); + if (r.get(1) !== t.databaseId.projectId) throw new FirestoreError(w, "Tried to deserialize key from different project: " + r.get(1) + " vs " + t.databaseId.projectId); + if (r.get(3) !== t.databaseId.database) throw new FirestoreError(w, "Tried to deserialize key from different database: " + r.get(3) + " vs " + t.databaseId.database); + return new DocumentKey(function __PRIVATE_extractLocalPathFromResourceName(t) { + return __PRIVATE_hardAssert(t.length > 4 && "documents" === t.get(4), 29091, { + key: t.toString() + }), t.popFirst(5); + } + /** Creates a Document proto from key and fields (but no create/update time) */ (r)); +} + +function __PRIVATE_toMutationDocument(t, e, r) { + return { + name: __PRIVATE_toName(t, e), + fields: r.value.mapValue.fields + }; +} + +function __PRIVATE_fromBatchGetDocumentsResponse(t, e) { + return "found" in e ? function __PRIVATE_fromFound(t, e) { + __PRIVATE_hardAssert(!!e.found, 43571), e.found.name, e.found.updateTime; + const r = fromName(t, e.found.name), n = __PRIVATE_fromVersion(e.found.updateTime), i = e.found.createTime ? __PRIVATE_fromVersion(e.found.createTime) : SnapshotVersion.min(), s = new ObjectValue({ + mapValue: { + fields: e.found.fields + } + }); + return MutableDocument.newFoundDocument(r, n, i, s); + }(t, e) : "missing" in e ? function __PRIVATE_fromMissing(t, e) { + __PRIVATE_hardAssert(!!e.missing, 3894), __PRIVATE_hardAssert(!!e.readTime, 22933); + const r = fromName(t, e.missing), n = __PRIVATE_fromVersion(e.readTime); + return MutableDocument.newNoDocument(r, n); + }(t, e) : fail(7234, { + result: e + }); +} + +function toMutation(t, e) { + let r; + if (e instanceof __PRIVATE_SetMutation) r = { + update: __PRIVATE_toMutationDocument(t, e.key, e.value) + }; else if (e instanceof __PRIVATE_DeleteMutation) r = { + delete: __PRIVATE_toName(t, e.key) + }; else if (e instanceof __PRIVATE_PatchMutation) r = { + update: __PRIVATE_toMutationDocument(t, e.key, e.data), + updateMask: __PRIVATE_toDocumentMask(e.fieldMask) + }; else { + if (!(e instanceof __PRIVATE_VerifyMutation)) return fail(16599, { + L: e.type + }); + r = { + verify: __PRIVATE_toName(t, e.key) + }; + } + return e.fieldTransforms.length > 0 && (r.updateTransforms = e.fieldTransforms.map((t => function __PRIVATE_toFieldTransform(t, e) { + const r = e.transform; + if (r instanceof __PRIVATE_ServerTimestampTransform) return { + fieldPath: e.field.canonicalString(), + setToServerValue: "REQUEST_TIME" + }; + if (r instanceof __PRIVATE_ArrayUnionTransformOperation) return { + fieldPath: e.field.canonicalString(), + appendMissingElements: { + values: r.elements + } + }; + if (r instanceof __PRIVATE_ArrayRemoveTransformOperation) return { + fieldPath: e.field.canonicalString(), + removeAllFromArray: { + values: r.elements + } + }; + if (r instanceof __PRIVATE_NumericIncrementTransformOperation) return { + fieldPath: e.field.canonicalString(), + increment: r.k + }; + throw fail(20930, { + transform: e.transform + }); + }(0, t)))), e.precondition.isNone || (r.currentDocument = function __PRIVATE_toPrecondition(t, e) { + return void 0 !== e.updateTime ? { + updateTime: __PRIVATE_toVersion(t, e.updateTime) + } : void 0 !== e.exists ? { + exists: e.exists + } : fail(27497); + }(t, e.precondition)), r; +} + +function __PRIVATE_toQueryTarget(t, e) { + // Dissect the path into parent, collectionId, and optional key filter. + const r = { + structuredQuery: {} + }, n = e.path; + let i; + null !== e.collectionGroup ? (i = n, r.structuredQuery.from = [ { + collectionId: e.collectionGroup, + allDescendants: !0 + } ]) : (i = n.popLast(), r.structuredQuery.from = [ { + collectionId: n.lastSegment() + } ]), r.parent = function __PRIVATE_toQueryPath(t, e) { + return __PRIVATE_toResourceName(t.databaseId, e); + }(t, i); + const s = function __PRIVATE_toFilters(t) { + if (0 === t.length) return; + return __PRIVATE_toFilter(CompositeFilter.create(t, "and" /* CompositeOperator.AND */)); + }(e.filters); + s && (r.structuredQuery.where = s); + const o = function __PRIVATE_toOrder(t) { + if (0 === t.length) return; + return t.map((t => + // visible for testing + function __PRIVATE_toPropertyOrder(t) { + return { + field: __PRIVATE_toFieldPathReference(t.field), + direction: __PRIVATE_toDirection(t.dir) + }; + } + // visible for testing + (t))); + }(e.orderBy); + o && (r.structuredQuery.orderBy = o); + const a = function __PRIVATE_toInt32Proto(t, e) { + return t.useProto3Json || __PRIVATE_isNullOrUndefined(e) ? e : { + value: e + }; + }(t, e.limit); + return null !== a && (r.structuredQuery.limit = a), e.startAt && (r.structuredQuery.startAt = function __PRIVATE_toStartAtCursor(t) { + return { + before: t.inclusive, + values: t.position + }; + }(e.startAt)), e.endAt && (r.structuredQuery.endAt = function __PRIVATE_toEndAtCursor(t) { + return { + before: !t.inclusive, + values: t.position + }; + } + // visible for testing + (e.endAt)), { + M: r, + parent: i + }; +} + +function __PRIVATE_toDirection(t) { + return st[t]; +} + +// visible for testing +function __PRIVATE_toOperatorName(t) { + return ot[t]; +} + +function __PRIVATE_toCompositeOperatorName(t) { + return at[t]; +} + +function __PRIVATE_toFieldPathReference(t) { + return { + fieldPath: t.canonicalString() + }; +} + +function __PRIVATE_toFilter(t) { + return t instanceof FieldFilter ? function __PRIVATE_toUnaryOrFieldFilter(t) { + if ("==" /* Operator.EQUAL */ === t.op) { + if (__PRIVATE_isNanValue(t.value)) return { + unaryFilter: { + field: __PRIVATE_toFieldPathReference(t.field), + op: "IS_NAN" + } + }; + if (__PRIVATE_isNullValue(t.value)) return { + unaryFilter: { + field: __PRIVATE_toFieldPathReference(t.field), + op: "IS_NULL" + } + }; + } else if ("!=" /* Operator.NOT_EQUAL */ === t.op) { + if (__PRIVATE_isNanValue(t.value)) return { + unaryFilter: { + field: __PRIVATE_toFieldPathReference(t.field), + op: "IS_NOT_NAN" + } + }; + if (__PRIVATE_isNullValue(t.value)) return { + unaryFilter: { + field: __PRIVATE_toFieldPathReference(t.field), + op: "IS_NOT_NULL" + } + }; + } + return { + fieldFilter: { + field: __PRIVATE_toFieldPathReference(t.field), + op: __PRIVATE_toOperatorName(t.op), + value: t.value + } + }; + }(t) : t instanceof CompositeFilter ? function __PRIVATE_toCompositeFilter(t) { + const e = t.getFilters().map((t => __PRIVATE_toFilter(t))); + if (1 === e.length) return e[0]; + return { + compositeFilter: { + op: __PRIVATE_toCompositeOperatorName(t.op), + filters: e + } + }; + }(t) : fail(54877, { + filter: t + }); +} + +function __PRIVATE_toDocumentMask(t) { + const e = []; + return t.fields.forEach((t => e.push(t.canonicalString()))), { + fieldPaths: e + }; +} + +function __PRIVATE_isValidResourceName(t) { + // Resource names have at least 4 components (project ID, database ID) + return t.length >= 4 && "projects" === t.get(0) && "databases" === t.get(2); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ function __PRIVATE_newSerializer(t) { + return new JsonProtoSerializer(t, /* useProto3Json= */ !0); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A helper for running delayed tasks following an exponential backoff curve + * between attempts. + * + * Each delay is made up of a "base" delay which follows the exponential + * backoff curve, and a +/- 50% "jitter" that is calculated and added to the + * base delay. This prevents clients from accidentally synchronizing their + * delays causing spikes of load to the backend. + */ +class __PRIVATE_ExponentialBackoff { + constructor( + /** + * The AsyncQueue to run backoff operations on. + */ + t, + /** + * The ID to use when scheduling backoff operations on the AsyncQueue. + */ + e, + /** + * The initial delay (used as the base delay on the first retry attempt). + * Note that jitter will still be applied, so the actual delay could be as + * little as 0.5*initialDelayMs. + */ + r = 1e3 + /** + * The multiplier to use to determine the extended base delay after each + * attempt. + */ , n = 1.5 + /** + * The maximum base delay after which no further backoff is performed. + * Note that jitter will still be applied, so the actual delay could be as + * much as 1.5*maxDelayMs. + */ , i = 6e4) { + this.U = t, this.timerId = e, this.j = r, this.W = n, this.K = i, this.G = 0, this.J = null, + /** The last backoff attempt, as epoch milliseconds. */ + this.H = Date.now(), this.reset(); + } + /** + * Resets the backoff delay. + * + * The very next backoffAndWait() will have no delay. If it is called again + * (i.e. due to an error), initialDelayMs (plus jitter) will be used, and + * subsequent ones will increase according to the backoffFactor. + */ reset() { + this.G = 0; + } + /** + * Resets the backoff delay to the maximum delay (e.g. for use after a + * RESOURCE_EXHAUSTED error). + */ Y() { + this.G = this.K; + } + /** + * Returns a promise that resolves after currentDelayMs, and increases the + * delay for any subsequent attempts. If there was a pending backoff operation + * already, it will be canceled. + */ Z(t) { + // Cancel any pending backoff operation. + this.cancel(); + // First schedule using the current base (which may be 0 and should be + // honored as such). + const e = Math.floor(this.G + this.X()), r = Math.max(0, Date.now() - this.H), n = Math.max(0, e - r); + // Guard against lastAttemptTime being in the future due to a clock change. + n > 0 && __PRIVATE_logDebug("ExponentialBackoff", `Backing off for ${n} ms (base delay: ${this.G} ms, delay with jitter: ${e} ms, last attempt: ${r} ms ago)`), + this.J = this.U.enqueueAfterDelay(this.timerId, n, (() => (this.H = Date.now(), + t()))), + // Apply backoff factor to determine next delay and ensure it is within + // bounds. + this.G *= this.W, this.G < this.j && (this.G = this.j), this.G > this.K && (this.G = this.K); + } + tt() { + null !== this.J && (this.J.skipDelay(), this.J = null); + } + cancel() { + null !== this.J && (this.J.cancel(), this.J = null); + } + /** Returns a random value in the range [-currentBaseMs/2, currentBaseMs/2] */ X() { + return (Math.random() - .5) * this.G; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Datastore and its related methods are a wrapper around the external Google + * Cloud Datastore grpc API, which provides an interface that is more convenient + * for the rest of the client SDK architecture to consume. + */ class Datastore {} + +/** + * An implementation of Datastore that exposes additional state for internal + * consumption. + */ class __PRIVATE_DatastoreImpl extends Datastore { + constructor(t, e, r, n) { + super(), this.authCredentials = t, this.appCheckCredentials = e, this.connection = r, + this.serializer = n, this.et = !1; + } + rt() { + if (this.et) throw new FirestoreError(N, "The client has already been terminated."); + } + /** Invokes the provided RPC with auth and AppCheck tokens. */ I(t, e, r, n) { + return this.rt(), Promise.all([ this.authCredentials.getToken(), this.appCheckCredentials.getToken() ]).then((([i, s]) => this.connection.I(t, __PRIVATE_toResourcePath(e, r), n, i, s))).catch((t => { + throw "FirebaseError" === t.name ? (t.code === S && (this.authCredentials.invalidateToken(), + this.appCheckCredentials.invalidateToken()), t) : new FirestoreError(g, t.toString()); + })); + } + /** Invokes the provided RPC with streamed results with auth and AppCheck tokens. */ D(t, e, r, n, i) { + return this.rt(), Promise.all([ this.authCredentials.getToken(), this.appCheckCredentials.getToken() ]).then((([s, o]) => this.connection.D(t, __PRIVATE_toResourcePath(e, r), n, s, o, i))).catch((t => { + throw "FirebaseError" === t.name ? (t.code === S && (this.authCredentials.invalidateToken(), + this.appCheckCredentials.invalidateToken()), t) : new FirestoreError(g, t.toString()); + })); + } + terminate() { + this.et = !0, this.connection.terminate(); + } +} + +// TODO(firestorexp): Make sure there is only one Datastore instance per +// firestore-exp client. +async function __PRIVATE_invokeCommitRpc(t, e) { + const r = __PRIVATE_debugCast(t), n = { + writes: e.map((t => toMutation(r.serializer, t))) + }; + await r.I("Commit", r.serializer.databaseId, ResourcePath.emptyPath(), n); +} + +async function __PRIVATE_invokeBatchGetDocumentsRpc(t, e) { + const r = __PRIVATE_debugCast(t), n = { + documents: e.map((t => __PRIVATE_toName(r.serializer, t))) + }, i = await r.D("BatchGetDocuments", r.serializer.databaseId, ResourcePath.emptyPath(), n, e.length), s = new Map; + i.forEach((t => { + const e = __PRIVATE_fromBatchGetDocumentsResponse(r.serializer, t); + s.set(e.key.toString(), e); + })); + const o = []; + return e.forEach((t => { + const e = s.get(t.toString()); + __PRIVATE_hardAssert(!!e, 55234, { + key: t + }), o.push(e); + })), o; +} + +async function __PRIVATE_invokeRunQueryRpc(t, e) { + const r = __PRIVATE_debugCast(t), {M: n, parent: i} = __PRIVATE_toQueryTarget(r.serializer, __PRIVATE_queryToTarget(e)); + return (await r.D("RunQuery", r.serializer.databaseId, i, { + structuredQuery: n.structuredQuery + })).filter((t => !!t.document)).map((t => function __PRIVATE_fromDocument(t, e, r) { + const n = fromName(t, e.name), i = __PRIVATE_fromVersion(e.updateTime), s = e.createTime ? __PRIVATE_fromVersion(e.createTime) : SnapshotVersion.min(), o = new ObjectValue({ + mapValue: { + fields: e.fields + } + }), a = MutableDocument.newFoundDocument(n, i, s, o); + return r && a.setHasCommittedMutations(), r ? a.setHasCommittedMutations() : a; + }(r.serializer, t.document, void 0))); +} + +async function __PRIVATE_invokeRunAggregationQueryRpc(t, e, r) { + const n = __PRIVATE_debugCast(t), {request: i, nt: s, parent: o} = function __PRIVATE_toRunAggregationQueryRequest(t, e, r, n) { + const {M: i, parent: s} = __PRIVATE_toQueryTarget(t, e), o = {}, a = []; + let u = 0; + return r.forEach((t => { + // Map all client-side aliases to a unique short-form + // alias. This avoids issues with client-side aliases that + // exceed the 1500-byte string size limit. + const e = n ? t.alias : "aggregate_" + u++; + o[e] = t.alias, "count" === t.aggregateType ? a.push({ + alias: e, + count: {} + }) : "avg" === t.aggregateType ? a.push({ + alias: e, + avg: { + field: __PRIVATE_toFieldPathReference(t.fieldPath) + } + }) : "sum" === t.aggregateType && a.push({ + alias: e, + sum: { + field: __PRIVATE_toFieldPathReference(t.fieldPath) + } + }); + })), { + request: { + structuredAggregationQuery: { + aggregations: a, + structuredQuery: i.structuredQuery + }, + parent: i.parent + }, + nt: o, + parent: s + }; + }(n.serializer, function __PRIVATE_queryToAggregateTarget(t) { + const e = __PRIVATE_debugCast(t); + return e.$ || ( + // Do not include implicit order-bys for aggregate queries. + e.$ = __PRIVATE__queryToTarget(e, t.explicitOrderBy)), e.$; + }(e), r); + n.connection.P || delete i.parent; + const a = (await n.D("RunAggregationQuery", n.serializer.databaseId, o, i, + /*expectedResponseCount=*/ 1)).filter((t => !!t.result)); + // Omit RunAggregationQueryResponse that only contain readTimes. + __PRIVATE_hardAssert(1 === a.length, 64727); + // Remap the short-form aliases that were sent to the server + // to the client-side aliases. Users will access the results + // using the client-side alias. + const u = a[0].result?.aggregateFields; + return Object.keys(u).reduce(((t, e) => (t[s[e]] = u[e], t)), {}); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ const ut = "ComponentProvider", _t = new Map; + +/** + * An instance map that ensures only one Datastore exists per Firestore + * instance. + */ +/** + * Returns an initialized and started Datastore for the given Firestore + * instance. Callers must invoke removeComponents() when the Firestore + * instance is terminated. + */ +function __PRIVATE_getDatastore(t) { + if (t._terminated) throw new FirestoreError(N, "The client has already been terminated."); + if (!_t.has(t)) { + __PRIVATE_logDebug(ut, "Initializing Datastore"); + const e = function __PRIVATE_newConnection(t) { + return new __PRIVATE_FetchConnection(t); + }(function __PRIVATE_makeDatabaseInfo(t, e, r, n) { + return new DatabaseInfo(t, e, r, n.host, n.ssl, n.experimentalForceLongPolling, n.experimentalAutoDetectLongPolling, __PRIVATE_cloneLongPollingOptions(n.experimentalLongPollingOptions), n.useFetchStreams, n.isUsingEmulator); + } + /** + * @license + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ (t._databaseId, t.app.options.appId || "", t._persistenceKey, t._freezeSettings())), r = __PRIVATE_newSerializer(t._databaseId), n = function __PRIVATE_newDatastore(t, e, r, n) { + return new __PRIVATE_DatastoreImpl(t, e, r, n); + }(t._authCredentials, t._appCheckCredentials, e, r); + _t.set(t, n); + } + return _t.get(t); +} + +/** + * Removes all components associated with the provided instance. Must be called + * when the `Firestore` instance is terminated. + */ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const ct = 1048576, lt = "firestore.googleapis.com", ht = !0; + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// settings() defaults: +/** + * A concrete type describing all the values that can be applied via a + * user-supplied `FirestoreSettings` object. This is a separate type so that + * defaults can be supplied and the value can be checked for equality. + */ +class FirestoreSettingsImpl { + constructor(t) { + if (void 0 === t.host) { + if (void 0 !== t.ssl) throw new FirestoreError(w, "Can't provide ssl option if host option is not set"); + this.host = lt, this.ssl = ht; + } else this.host = t.host, this.ssl = t.ssl ?? ht; + if (this.isUsingEmulator = void 0 !== t.emulatorOptions, this.credentials = t.credentials, + this.ignoreUndefinedProperties = !!t.ignoreUndefinedProperties, this.localCache = t.localCache, + void 0 === t.cacheSizeBytes) this.cacheSizeBytes = 41943040; else { + if (-1 !== t.cacheSizeBytes && t.cacheSizeBytes < ct) throw new FirestoreError(w, "cacheSizeBytes must be at least 1048576"); + this.cacheSizeBytes = t.cacheSizeBytes; + } + !function __PRIVATE_validateIsNotUsedTogether(t, e, r, n) { + if (!0 === e && !0 === n) throw new FirestoreError(w, `${t} and ${r} cannot be used together.`); + }("experimentalForceLongPolling", t.experimentalForceLongPolling, "experimentalAutoDetectLongPolling", t.experimentalAutoDetectLongPolling), + this.experimentalForceLongPolling = !!t.experimentalForceLongPolling, this.experimentalForceLongPolling ? this.experimentalAutoDetectLongPolling = !1 : void 0 === t.experimentalAutoDetectLongPolling ? this.experimentalAutoDetectLongPolling = true : + // For backwards compatibility, coerce the value to boolean even though + // the TypeScript compiler has narrowed the type to boolean already. + // noinspection PointlessBooleanExpressionJS + this.experimentalAutoDetectLongPolling = !!t.experimentalAutoDetectLongPolling, + this.experimentalLongPollingOptions = __PRIVATE_cloneLongPollingOptions(t.experimentalLongPollingOptions ?? {}), + function __PRIVATE_validateLongPollingOptions(t) { + if (void 0 !== t.timeoutSeconds) { + if (isNaN(t.timeoutSeconds)) throw new FirestoreError(w, `invalid long polling timeout: ${t.timeoutSeconds} (must not be NaN)`); + if (t.timeoutSeconds < 5) throw new FirestoreError(w, `invalid long polling timeout: ${t.timeoutSeconds} (minimum allowed value is 5)`); + if (t.timeoutSeconds > 30) throw new FirestoreError(w, `invalid long polling timeout: ${t.timeoutSeconds} (maximum allowed value is 30)`); + } + } + /** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + /** + * The Cloud Firestore service interface. + * + * Do not call this constructor directly. Instead, use {@link (getFirestore:1)}. + */ (this.experimentalLongPollingOptions), this.useFetchStreams = !!t.useFetchStreams; + } + isEqual(t) { + return this.host === t.host && this.ssl === t.ssl && this.credentials === t.credentials && this.cacheSizeBytes === t.cacheSizeBytes && this.experimentalForceLongPolling === t.experimentalForceLongPolling && this.experimentalAutoDetectLongPolling === t.experimentalAutoDetectLongPolling && function __PRIVATE_longPollingOptionsEqual(t, e) { + return t.timeoutSeconds === e.timeoutSeconds; + }(this.experimentalLongPollingOptions, t.experimentalLongPollingOptions) && this.ignoreUndefinedProperties === t.ignoreUndefinedProperties && this.useFetchStreams === t.useFetchStreams; + } +} + +class Firestore { + /** @hideconstructor */ + constructor(t, e, r, n) { + this._authCredentials = t, this._appCheckCredentials = e, this._databaseId = r, + this._app = n, + /** + * Whether it's a Firestore or Firestore Lite instance. + */ + this.type = "firestore-lite", this._persistenceKey = "(lite)", this._settings = new FirestoreSettingsImpl({}), + this._settingsFrozen = !1, this._emulatorOptions = {}, + // A task that is assigned when the terminate() is invoked and resolved when + // all components have shut down. Otherwise, Firestore is not terminated, + // which can mean either the FirestoreClient is in the process of starting, + // or restarting. + this._terminateTask = "notTerminated"; + } + /** + * The {@link @firebase/app#FirebaseApp} associated with this `Firestore` service + * instance. + */ get app() { + if (!this._app) throw new FirestoreError(N, "Firestore was not initialized using the Firebase SDK. 'app' is not available"); + return this._app; + } + get _initialized() { + return this._settingsFrozen; + } + get _terminated() { + return "notTerminated" !== this._terminateTask; + } + _setSettings(t) { + if (this._settingsFrozen) throw new FirestoreError(N, "Firestore has already been started and its settings can no longer be changed. You can only modify settings before calling any other methods on a Firestore object."); + this._settings = new FirestoreSettingsImpl(t), this._emulatorOptions = t.emulatorOptions || {}, + void 0 !== t.credentials && (this._authCredentials = function __PRIVATE_makeAuthCredentialsProvider(t) { + if (!t) return new __PRIVATE_EmptyAuthCredentialsProvider; + switch (t.type) { + case "firstParty": + return new __PRIVATE_FirstPartyAuthCredentialsProvider(t.sessionIndex || "0", t.iamToken || null, t.authTokenFactory || null); + + case "provider": + return t.client; + + default: + throw new FirestoreError(w, "makeAuthCredentialsProvider failed due to invalid credential type"); + } + }(t.credentials)); + } + _getSettings() { + return this._settings; + } + _getEmulatorOptions() { + return this._emulatorOptions; + } + _freezeSettings() { + return this._settingsFrozen = !0, this._settings; + } + _delete() { + // The `_terminateTask` must be assigned future that completes when + // terminate is complete. The existence of this future puts SDK in state + // that will not accept further API interaction. + return "notTerminated" === this._terminateTask && (this._terminateTask = this._terminate()), + this._terminateTask; + } + async _restart() { + // The `_terminateTask` must equal 'notTerminated' after restart to + // signal that client is in a state that accepts API calls. + "notTerminated" === this._terminateTask ? await this._terminate() : this._terminateTask = "notTerminated"; + } + /** Returns a JSON-serializable representation of this `Firestore` instance. */ toJSON() { + return { + app: this._app, + databaseId: this._databaseId, + settings: this._settings + }; + } + /** + * Terminates all components used by this client. Subclasses can override + * this method to clean up their own dependencies, but must also call this + * method. + * + * Only ever called once. + */ _terminate() { + return function __PRIVATE_removeComponents(t) { + const e = _t.get(t); + e && (__PRIVATE_logDebug(ut, "Removing Datastore"), _t.delete(t), e.terminate()); + }(this), Promise.resolve(); + } +} + +function initializeFirestore(t, e, r) { + r || (r = L); + const n = _getProvider(t, "firestore/lite"); + if (n.isInitialized(r)) throw new FirestoreError(N, "Firestore can only be initialized once per app."); + return n.initialize({ + options: e, + instanceIdentifier: r + }); +} + +function getFirestore(t, r) { + const n = "object" == typeof t ? t : e(), i = "string" == typeof t ? t : r || "(default)", s = _getProvider(n, "firestore/lite").getImmediate({ + identifier: i + }); + if (!s._initialized) { + const t = f("firestore"); + t && connectFirestoreEmulator(s, ...t); + } + return s; +} + +/** + * Modify this instance to communicate with the Cloud Firestore emulator. + * + * Note: This must be called before this instance has been used to do any + * operations. + * + * @param firestore - The `Firestore` instance to configure to connect to the + * emulator. + * @param host - the emulator host (ex: localhost). + * @param port - the emulator port (ex: 9000). + * @param options.mockUserToken - the mock auth token to use for unit testing + * Security Rules. + */ function connectFirestoreEmulator(t, e, r, n = {}) { + t = __PRIVATE_cast(t, Firestore); + const i = c(e), s = t._getSettings(), o = { + ...s, + emulatorOptions: t._getEmulatorOptions() + }, a = `${e}:${r}`; + i && (d(`https://${a}`), m("Firestore", !0)), s.host !== lt && s.host !== a && __PRIVATE_logWarn("Host has been set in both settings() and connectFirestoreEmulator(), emulator host will be used."); + const u = { + ...s, + host: a, + ssl: i, + emulatorOptions: n + }; + // No-op if the new configuration matches the current configuration. This supports SSR + // enviornments which might call `connectFirestoreEmulator` multiple times as a standard practice. + if (!E(u, o) && (t._setSettings(u), n.mockUserToken)) { + let e, r; + if ("string" == typeof n.mockUserToken) e = n.mockUserToken, r = User.MOCK_USER; else { + // Let createMockUserToken validate first (catches common mistakes like + // invalid field "uid" and missing field "sub" / "user_id".) + e = T(n.mockUserToken, t._app?.options.projectId); + const i = n.mockUserToken.sub || n.mockUserToken.user_id; + if (!i) throw new FirestoreError(w, "mockUserToken must contain 'sub' or 'user_id' field!"); + r = new User(i); + } + t._authCredentials = new __PRIVATE_EmulatorAuthCredentialsProvider(new __PRIVATE_OAuthToken(e, r)); + } +} + +/** + * Terminates the provided `Firestore` instance. + * + * After calling `terminate()` only the `clearIndexedDbPersistence()` functions + * may be used. Any other function will throw a `FirestoreError`. Termination + * does not cancel any pending writes, and any promises that are awaiting a + * response from the server will not be resolved. + * + * To restart after termination, create a new instance of `Firestore` with + * {@link (getFirestore:1)}. + * + * Note: Under normal circumstances, calling `terminate()` is not required. This + * function is useful only when you want to force this instance to release all of + * its resources or in combination with {@link clearIndexedDbPersistence} to + * ensure that all local state is destroyed between test runs. + * + * @param firestore - The `Firestore` instance to terminate. + * @returns A `Promise` that is resolved when the instance has been successfully + * terminated. + */ function terminate(t) { + return t = __PRIVATE_cast(t, Firestore), r(t.app, "firestore/lite"), t._delete(); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Represents an aggregation that can be performed by Firestore. + */ +// eslint-disable-next-line @typescript-eslint/no-unused-vars +class AggregateField { + /** + * Create a new AggregateField + * @param aggregateType Specifies the type of aggregation operation to perform. + * @param _internalFieldPath Optionally specifies the field that is aggregated. + * @internal + */ + constructor(t = "count", e) { + this._internalFieldPath = e, + /** A type string to uniquely identify instances of this class. */ + this.type = "AggregateField", this.aggregateType = t; + } +} + +/** + * The results of executing an aggregation query. + */ class AggregateQuerySnapshot { + /** @hideconstructor */ + constructor(t, e, r) { + this._userDataWriter = e, this._data = r, + /** A type string to uniquely identify instances of this class. */ + this.type = "AggregateQuerySnapshot", this.query = t; + } + /** + * Returns the results of the aggregations performed over the underlying + * query. + * + * The keys of the returned object will be the same as those of the + * `AggregateSpec` object specified to the aggregation method, and the values + * will be the corresponding aggregation result. + * + * @returns The results of the aggregations performed over the underlying + * query. + */ data() { + return this._userDataWriter.convertObjectMap(this._data); + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A `Query` refers to a query which you can read or listen to. You can also + * construct refined `Query` objects by adding filters and ordering. + */ class Query { + // This is the lite version of the Query class in the main SDK. + /** @hideconstructor protected */ + constructor(t, + /** + * If provided, the `FirestoreDataConverter` associated with this instance. + */ + e, r) { + this.converter = e, this._query = r, + /** The type of this Firestore reference. */ + this.type = "query", this.firestore = t; + } + withConverter(t) { + return new Query(this.firestore, t, this._query); + } +} + +/** + * A `DocumentReference` refers to a document location in a Firestore database + * and can be used to write, read, or listen to the location. The document at + * the referenced location may or may not exist. + */ class DocumentReference { + /** @hideconstructor */ + constructor(t, + /** + * If provided, the `FirestoreDataConverter` associated with this instance. + */ + e, r) { + this.converter = e, this._key = r, + /** The type of this Firestore reference. */ + this.type = "document", this.firestore = t; + } + get _path() { + return this._key.path; + } + /** + * The document's identifier within its collection. + */ get id() { + return this._key.path.lastSegment(); + } + /** + * A string representing the path of the referenced document (relative + * to the root of the database). + */ get path() { + return this._key.path.canonicalString(); + } + /** + * The collection this `DocumentReference` belongs to. + */ get parent() { + return new CollectionReference(this.firestore, this.converter, this._key.path.popLast()); + } + withConverter(t) { + return new DocumentReference(this.firestore, t, this._key); + } + /** + * Returns a JSON-serializable representation of this `DocumentReference` instance. + * + * @returns a JSON representation of this object. + */ toJSON() { + return { + type: DocumentReference._jsonSchemaVersion, + referencePath: this._key.toString() + }; + } + static fromJSON(t, e, r) { + if (__PRIVATE_validateJSON(e, DocumentReference._jsonSchema)) return new DocumentReference(t, r || null, new DocumentKey(ResourcePath.fromString(e.referencePath))); + } +} + +DocumentReference._jsonSchemaVersion = "firestore/documentReference/1.0", DocumentReference._jsonSchema = { + type: property("string", DocumentReference._jsonSchemaVersion), + referencePath: property("string") +}; + +/** + * A `CollectionReference` object can be used for adding documents, getting + * document references, and querying for documents (using {@link (query:1)}). + */ +class CollectionReference extends Query { + /** @hideconstructor */ + constructor(t, e, r) { + super(t, e, function __PRIVATE_newQueryForPath(t) { + return new __PRIVATE_QueryImpl(t); + }(r)), this._path = r, + /** The type of this Firestore reference. */ + this.type = "collection"; + } + /** The collection's identifier. */ get id() { + return this._query.path.lastSegment(); + } + /** + * A string representing the path of the referenced collection (relative + * to the root of the database). + */ get path() { + return this._query.path.canonicalString(); + } + /** + * A reference to the containing `DocumentReference` if this is a + * subcollection. If this isn't a subcollection, the reference is null. + */ get parent() { + const t = this._path.popLast(); + return t.isEmpty() ? null : new DocumentReference(this.firestore, + /* converter= */ null, new DocumentKey(t)); + } + withConverter(t) { + return new CollectionReference(this.firestore, t, this._path); + } +} + +function collection(t, e, ...r) { + if (t = P(t), __PRIVATE_validateNonEmptyArgument("collection", "path", e), t instanceof Firestore) { + const n = ResourcePath.fromString(e, ...r); + return __PRIVATE_validateCollectionPath(n), new CollectionReference(t, /* converter= */ null, n); + } + { + if (!(t instanceof DocumentReference || t instanceof CollectionReference)) throw new FirestoreError(w, "Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore"); + const n = t._path.child(ResourcePath.fromString(e, ...r)); + return __PRIVATE_validateCollectionPath(n), new CollectionReference(t.firestore, + /* converter= */ null, n); + } +} + +// TODO(firestorelite): Consider using ErrorFactory - +// https://github.com/firebase/firebase-js-sdk/blob/0131e1f/packages/util/src/errors.ts#L106 +/** + * Creates and returns a new `Query` instance that includes all documents in the + * database that are contained in a collection or subcollection with the + * given `collectionId`. + * + * @param firestore - A reference to the root `Firestore` instance. + * @param collectionId - Identifies the collections to query over. Every + * collection or subcollection with this ID as the last segment of its path + * will be included. Cannot contain a slash. + * @returns The created `Query`. + */ function collectionGroup(t, e) { + if (t = __PRIVATE_cast(t, Firestore), __PRIVATE_validateNonEmptyArgument("collectionGroup", "collection id", e), + e.indexOf("/") >= 0) throw new FirestoreError(w, `Invalid collection ID '${e}' passed to function collectionGroup(). Collection IDs must not contain '/'.`); + return new Query(t, + /* converter= */ null, function __PRIVATE_newQueryForCollectionGroup(t) { + return new __PRIVATE_QueryImpl(ResourcePath.emptyPath(), t); + }(e)); +} + +function doc(t, e, ...r) { + if (t = P(t), + // We allow omission of 'pathString' but explicitly prohibit passing in both + // 'undefined' and 'null'. + 1 === arguments.length && (e = __PRIVATE_AutoId.newId()), __PRIVATE_validateNonEmptyArgument("doc", "path", e), + t instanceof Firestore) { + const n = ResourcePath.fromString(e, ...r); + return __PRIVATE_validateDocumentPath(n), new DocumentReference(t, + /* converter= */ null, new DocumentKey(n)); + } + { + if (!(t instanceof DocumentReference || t instanceof CollectionReference)) throw new FirestoreError(w, "Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore"); + const n = t._path.child(ResourcePath.fromString(e, ...r)); + return __PRIVATE_validateDocumentPath(n), new DocumentReference(t.firestore, t instanceof CollectionReference ? t.converter : null, new DocumentKey(n)); + } +} + +/** + * Returns true if the provided references are equal. + * + * @param left - A reference to compare. + * @param right - A reference to compare. + * @returns true if the references point to the same location in the same + * Firestore database. + */ function refEqual(t, e) { + return t = P(t), e = P(e), (t instanceof DocumentReference || t instanceof CollectionReference) && (e instanceof DocumentReference || e instanceof CollectionReference) && (t.firestore === e.firestore && t.path === e.path && t.converter === e.converter); +} + +/** + * Returns true if the provided queries point to the same collection and apply + * the same constraints. + * + * @param left - A `Query` to compare. + * @param right - A `Query` to compare. + * @returns true if the references point to the same location in the same + * Firestore database. + */ function queryEqual(t, e) { + return t = P(t), e = P(e), t instanceof Query && e instanceof Query && (t.firestore === e.firestore && __PRIVATE_queryEquals(t._query, e._query) && t.converter === e.converter); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An immutable object representing an array of bytes. + */ class Bytes { + /** @hideconstructor */ + constructor(t) { + this._byteString = t; + } + /** + * Creates a new `Bytes` object from the given Base64 string, converting it to + * bytes. + * + * @param base64 - The Base64 string used to create the `Bytes` object. + */ static fromBase64String(t) { + try { + return new Bytes(ByteString.fromBase64String(t)); + } catch (t) { + throw new FirestoreError(w, "Failed to construct data from Base64 string: " + t); + } + } + /** + * Creates a new `Bytes` object from the given Uint8Array. + * + * @param array - The Uint8Array used to create the `Bytes` object. + */ static fromUint8Array(t) { + return new Bytes(ByteString.fromUint8Array(t)); + } + /** + * Returns the underlying bytes as a Base64-encoded string. + * + * @returns The Base64-encoded string created from the `Bytes` object. + */ toBase64() { + return this._byteString.toBase64(); + } + /** + * Returns the underlying bytes in a new `Uint8Array`. + * + * @returns The Uint8Array created from the `Bytes` object. + */ toUint8Array() { + return this._byteString.toUint8Array(); + } + /** + * Returns a string representation of the `Bytes` object. + * + * @returns A string representation of the `Bytes` object. + */ toString() { + return "Bytes(base64: " + this.toBase64() + ")"; + } + /** + * Returns true if this `Bytes` object is equal to the provided one. + * + * @param other - The `Bytes` object to compare against. + * @returns true if this `Bytes` object is equal to the provided one. + */ isEqual(t) { + return this._byteString.isEqual(t._byteString); + } + /** + * Returns a JSON-serializable representation of this `Bytes` instance. + * + * @returns a JSON representation of this object. + */ toJSON() { + return { + type: Bytes._jsonSchemaVersion, + bytes: this.toBase64() + }; + } + /** + * Builds a `Bytes` instance from a JSON object created by {@link Bytes.toJSON}. + * + * @param json a JSON object represention of a `Bytes` instance + * @returns an instance of {@link Bytes} if the JSON object could be parsed. Throws a + * {@link FirestoreError} if an error occurs. + */ static fromJSON(t) { + if (__PRIVATE_validateJSON(t, Bytes._jsonSchema)) return Bytes.fromBase64String(t.bytes); + } +} + +Bytes._jsonSchemaVersion = "firestore/bytes/1.0", Bytes._jsonSchema = { + type: property("string", Bytes._jsonSchemaVersion), + bytes: property("string") +}; + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A `FieldPath` refers to a field in a document. The path may consist of a + * single field name (referring to a top-level field in the document), or a + * list of field names (referring to a nested field in the document). + * + * Create a `FieldPath` by providing field names. If more than one field + * name is provided, the path will point to a nested field in a document. + */ +class FieldPath { + /** + * Creates a `FieldPath` from the provided field names. If more than one field + * name is provided, the path will point to a nested field in a document. + * + * @param fieldNames - A list of field names. + */ + constructor(...t) { + for (let e = 0; e < t.length; ++e) if (0 === t[e].length) throw new FirestoreError(w, "Invalid field name at argument $(i + 1). Field names must not be empty."); + this._internalPath = new FieldPath$1(t); + } + /** + * Returns true if this `FieldPath` is equal to the provided one. + * + * @param other - The `FieldPath` to compare against. + * @returns true if this `FieldPath` is equal to the provided one. + */ isEqual(t) { + return this._internalPath.isEqual(t._internalPath); + } +} + +/** + * Returns a special sentinel `FieldPath` to refer to the ID of a document. + * It can be used in queries to sort or filter by the document ID. + */ function documentId() { + return new FieldPath(U); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Sentinel values that can be used when writing document fields with `set()` + * or `update()`. + */ class FieldValue { + /** + * @param _methodName - The public API endpoint that returns this class. + * @hideconstructor + */ + constructor(t) { + this._methodName = t; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An immutable object representing a geographic location in Firestore. The + * location is represented as latitude/longitude pair. + * + * Latitude values are in the range of [-90, 90]. + * Longitude values are in the range of [-180, 180]. + */ class GeoPoint { + /** + * Creates a new immutable `GeoPoint` object with the provided latitude and + * longitude values. + * @param latitude - The latitude as number between -90 and 90. + * @param longitude - The longitude as number between -180 and 180. + */ + constructor(t, e) { + if (!isFinite(t) || t < -90 || t > 90) throw new FirestoreError(w, "Latitude must be a number between -90 and 90, but was: " + t); + if (!isFinite(e) || e < -180 || e > 180) throw new FirestoreError(w, "Longitude must be a number between -180 and 180, but was: " + e); + this._lat = t, this._long = e; + } + /** + * The latitude of this `GeoPoint` instance. + */ get latitude() { + return this._lat; + } + /** + * The longitude of this `GeoPoint` instance. + */ get longitude() { + return this._long; + } + /** + * Returns true if this `GeoPoint` is equal to the provided one. + * + * @param other - The `GeoPoint` to compare against. + * @returns true if this `GeoPoint` is equal to the provided one. + */ isEqual(t) { + return this._lat === t._lat && this._long === t._long; + } + /** + * Actually private to JS consumers of our API, so this function is prefixed + * with an underscore. + */ _compareTo(t) { + return __PRIVATE_primitiveComparator(this._lat, t._lat) || __PRIVATE_primitiveComparator(this._long, t._long); + } + /** + * Returns a JSON-serializable representation of this `GeoPoint` instance. + * + * @returns a JSON representation of this object. + */ toJSON() { + return { + latitude: this._lat, + longitude: this._long, + type: GeoPoint._jsonSchemaVersion + }; + } + /** + * Builds a `GeoPoint` instance from a JSON object created by {@link GeoPoint.toJSON}. + * + * @param json a JSON object represention of a `GeoPoint` instance + * @returns an instance of {@link GeoPoint} if the JSON object could be parsed. Throws a + * {@link FirestoreError} if an error occurs. + */ static fromJSON(t) { + if (__PRIVATE_validateJSON(t, GeoPoint._jsonSchema)) return new GeoPoint(t.latitude, t.longitude); + } +} + +GeoPoint._jsonSchemaVersion = "firestore/geoPoint/1.0", GeoPoint._jsonSchema = { + type: property("string", GeoPoint._jsonSchemaVersion), + latitude: property("number"), + longitude: property("number") +}; + +/** + * @license + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Represents a vector type in Firestore documents. + * Create an instance with {@link vector}. + * + * @class VectorValue + */ +class VectorValue { + /** + * @private + * @internal + */ + constructor(t) { + // Making a copy of the parameter. + this._values = (t || []).map((t => t)); + } + /** + * Returns a copy of the raw number array form of the vector. + */ toArray() { + return this._values.map((t => t)); + } + /** + * Returns `true` if the two `VectorValue` values have the same raw number arrays, returns `false` otherwise. + */ isEqual(t) { + /** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + /** + * Verifies equality for an array of primitives. + * + * @private + * @internal + * @param left Array of primitives. + * @param right Array of primitives. + * @return True if arrays are equal. + */ + return function __PRIVATE_isPrimitiveArrayEqual(t, e) { + if (t.length !== e.length) return !1; + for (let r = 0; r < t.length; ++r) if (t[r] !== e[r]) return !1; + return !0; + }(this._values, t._values); + } + /** + * Returns a JSON-serializable representation of this `VectorValue` instance. + * + * @returns a JSON representation of this object. + */ toJSON() { + return { + type: VectorValue._jsonSchemaVersion, + vectorValues: this._values + }; + } + /** + * Builds a `VectorValue` instance from a JSON object created by {@link VectorValue.toJSON}. + * + * @param json a JSON object represention of a `VectorValue` instance. + * @returns an instance of {@link VectorValue} if the JSON object could be parsed. Throws a + * {@link FirestoreError} if an error occurs. + */ static fromJSON(t) { + if (__PRIVATE_validateJSON(t, VectorValue._jsonSchema)) { + if (Array.isArray(t.vectorValues) && t.vectorValues.every((t => "number" == typeof t))) return new VectorValue(t.vectorValues); + throw new FirestoreError(w, "Expected 'vectorValues' field to be a number array"); + } + } +} + +VectorValue._jsonSchemaVersion = "firestore/vectorValue/1.0", VectorValue._jsonSchema = { + type: property("string", VectorValue._jsonSchemaVersion), + vectorValues: property("object") +}; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const ft = /^__.*__$/; + +/** The result of parsing document data (e.g. for a setData call). */ class ParsedSetData { + constructor(t, e, r) { + this.data = t, this.fieldMask = e, this.fieldTransforms = r; + } + toMutation(t, e) { + return null !== this.fieldMask ? new __PRIVATE_PatchMutation(t, this.data, this.fieldMask, e, this.fieldTransforms) : new __PRIVATE_SetMutation(t, this.data, e, this.fieldTransforms); + } +} + +/** The result of parsing "update" data (i.e. for an updateData call). */ class ParsedUpdateData { + constructor(t, + // The fieldMask does not include document transforms. + e, r) { + this.data = t, this.fieldMask = e, this.fieldTransforms = r; + } + toMutation(t, e) { + return new __PRIVATE_PatchMutation(t, this.data, this.fieldMask, e, this.fieldTransforms); + } +} + +function __PRIVATE_isWrite(t) { + switch (t) { + case 0 /* UserDataSource.Set */ : + // fall through + case 2 /* UserDataSource.MergeSet */ : + // fall through + case 1 /* UserDataSource.Update */ : + return !0; + + case 3 /* UserDataSource.Argument */ : + case 4 /* UserDataSource.ArrayArgument */ : + return !1; + + default: + throw fail(40011, { + it: t + }); + } +} + +/** A "context" object passed around while parsing user data. */ class __PRIVATE_ParseContextImpl { + /** + * Initializes a ParseContext with the given source and path. + * + * @param settings - The settings for the parser. + * @param databaseId - The database ID of the Firestore instance. + * @param serializer - The serializer to use to generate the Value proto. + * @param ignoreUndefinedProperties - Whether to ignore undefined properties + * rather than throw. + * @param fieldTransforms - A mutable list of field transforms encountered + * while parsing the data. + * @param fieldMask - A mutable list of field paths encountered while parsing + * the data. + * + * TODO(b/34871131): We don't support array paths right now, so path can be + * null to indicate the context represents any location within an array (in + * which case certain features will not work and errors will be somewhat + * compromised). + */ + constructor(t, e, r, n, i, s) { + this.settings = t, this.databaseId = e, this.serializer = r, this.ignoreUndefinedProperties = n, + // Minor hack: If fieldTransforms is undefined, we assume this is an + // external call and we need to validate the entire path. + void 0 === i && this.st(), this.fieldTransforms = i || [], this.fieldMask = s || []; + } + get path() { + return this.settings.path; + } + get it() { + return this.settings.it; + } + /** Returns a new context with the specified settings overwritten. */ ot(t) { + return new __PRIVATE_ParseContextImpl({ + ...this.settings, + ...t + }, this.databaseId, this.serializer, this.ignoreUndefinedProperties, this.fieldTransforms, this.fieldMask); + } + ut(t) { + const e = this.path?.child(t), r = this.ot({ + path: e, + _t: !1 + }); + return r.ct(t), r; + } + lt(t) { + const e = this.path?.child(t), r = this.ot({ + path: e, + _t: !1 + }); + return r.st(), r; + } + ht(t) { + // TODO(b/34871131): We don't support array paths right now; so make path + // undefined. + return this.ot({ + path: void 0, + _t: !0 + }); + } + ft(t) { + return __PRIVATE_createError(t, this.settings.methodName, this.settings.dt || !1, this.path, this.settings.Et); + } + /** Returns 'true' if 'fieldPath' was traversed when creating this context. */ contains(t) { + return void 0 !== this.fieldMask.find((e => t.isPrefixOf(e))) || void 0 !== this.fieldTransforms.find((e => t.isPrefixOf(e.field))); + } + st() { + // TODO(b/34871131): Remove null check once we have proper paths for fields + // within arrays. + if (this.path) for (let t = 0; t < this.path.length; t++) this.ct(this.path.get(t)); + } + ct(t) { + if (0 === t.length) throw this.ft("Document fields must not be empty"); + if (__PRIVATE_isWrite(this.it) && ft.test(t)) throw this.ft('Document fields cannot begin and end with "__"'); + } +} + +/** + * Helper for parsing raw user input (provided via the API) into internal model + * classes. + */ class __PRIVATE_UserDataReader { + constructor(t, e, r) { + this.databaseId = t, this.ignoreUndefinedProperties = e, this.serializer = r || __PRIVATE_newSerializer(t); + } + /** Creates a new top-level parse context. */ Tt(t, e, r, n = !1) { + return new __PRIVATE_ParseContextImpl({ + it: t, + methodName: e, + Et: r, + path: FieldPath$1.emptyPath(), + _t: !1, + dt: n + }, this.databaseId, this.serializer, this.ignoreUndefinedProperties); + } +} + +function __PRIVATE_newUserDataReader(t) { + const e = t._freezeSettings(), r = __PRIVATE_newSerializer(t._databaseId); + return new __PRIVATE_UserDataReader(t._databaseId, !!e.ignoreUndefinedProperties, r); +} + +/** Parse document data from a set() call. */ function __PRIVATE_parseSetData(t, e, r, n, i, s = {}) { + const o = t.Tt(s.merge || s.mergeFields ? 2 /* UserDataSource.MergeSet */ : 0 /* UserDataSource.Set */ , e, r, i); + __PRIVATE_validatePlainObject("Data must be an object, but it was:", o, n); + const a = __PRIVATE_parseObject(n, o); + let u, _; + if (s.merge) u = new FieldMask(o.fieldMask), _ = o.fieldTransforms; else if (s.mergeFields) { + const t = []; + for (const n of s.mergeFields) { + const i = __PRIVATE_fieldPathFromArgument$1(e, n, r); + if (!o.contains(i)) throw new FirestoreError(w, `Field '${i}' is specified in your field mask but missing from your input data.`); + __PRIVATE_fieldMaskContains(t, i) || t.push(i); + } + u = new FieldMask(t), _ = o.fieldTransforms.filter((t => u.covers(t.field))); + } else u = null, _ = o.fieldTransforms; + return new ParsedSetData(new ObjectValue(a), u, _); +} + +class __PRIVATE_DeleteFieldValueImpl extends FieldValue { + _toFieldTransform(t) { + if (2 /* UserDataSource.MergeSet */ !== t.it) throw 1 /* UserDataSource.Update */ === t.it ? t.ft(`${this._methodName}() can only appear at the top level of your update data`) : t.ft(`${this._methodName}() cannot be used with set() unless you pass {merge:true}`); + // No transform to add for a delete, but we need to add it to our + // fieldMask so it gets deleted. + return t.fieldMask.push(t.path), null; + } + isEqual(t) { + return t instanceof __PRIVATE_DeleteFieldValueImpl; + } +} + +/** + * Creates a child context for parsing SerializableFieldValues. + * + * This is different than calling `ParseContext.contextWith` because it keeps + * the fieldTransforms and fieldMask separate. + * + * The created context has its `dataSource` set to `UserDataSource.Argument`. + * Although these values are used with writes, any elements in these FieldValues + * are not considered writes since they cannot contain any FieldValue sentinels, + * etc. + * + * @param fieldValue - The sentinel FieldValue for which to create a child + * context. + * @param context - The parent context. + * @param arrayElement - Whether or not the FieldValue has an array. + */ function __PRIVATE_createSentinelChildContext(t, e, r) { + return new __PRIVATE_ParseContextImpl({ + it: 3 /* UserDataSource.Argument */ , + Et: e.settings.Et, + methodName: t._methodName, + _t: r + }, e.databaseId, e.serializer, e.ignoreUndefinedProperties); +} + +class __PRIVATE_ServerTimestampFieldValueImpl extends FieldValue { + _toFieldTransform(t) { + return new FieldTransform(t.path, new __PRIVATE_ServerTimestampTransform); + } + isEqual(t) { + return t instanceof __PRIVATE_ServerTimestampFieldValueImpl; + } +} + +class __PRIVATE_ArrayUnionFieldValueImpl extends FieldValue { + constructor(t, e) { + super(t), this.Pt = e; + } + _toFieldTransform(t) { + const e = __PRIVATE_createSentinelChildContext(this, t, + /*array=*/ !0), r = this.Pt.map((t => __PRIVATE_parseData(t, e))), n = new __PRIVATE_ArrayUnionTransformOperation(r); + return new FieldTransform(t.path, n); + } + isEqual(t) { + return t instanceof __PRIVATE_ArrayUnionFieldValueImpl && E(this.Pt, t.Pt); + } +} + +class __PRIVATE_ArrayRemoveFieldValueImpl extends FieldValue { + constructor(t, e) { + super(t), this.Pt = e; + } + _toFieldTransform(t) { + const e = __PRIVATE_createSentinelChildContext(this, t, + /*array=*/ !0), r = this.Pt.map((t => __PRIVATE_parseData(t, e))), n = new __PRIVATE_ArrayRemoveTransformOperation(r); + return new FieldTransform(t.path, n); + } + isEqual(t) { + return t instanceof __PRIVATE_ArrayRemoveFieldValueImpl && E(this.Pt, t.Pt); + } +} + +class __PRIVATE_NumericIncrementFieldValueImpl extends FieldValue { + constructor(t, e) { + super(t), this.At = e; + } + _toFieldTransform(t) { + const e = new __PRIVATE_NumericIncrementTransformOperation(t.serializer, toNumber(t.serializer, this.At)); + return new FieldTransform(t.path, e); + } + isEqual(t) { + return t instanceof __PRIVATE_NumericIncrementFieldValueImpl && this.At === t.At; + } +} + +/** Parse update data from an update() call. */ function __PRIVATE_parseUpdateData(t, e, r, n) { + const i = t.Tt(1 /* UserDataSource.Update */ , e, r); + __PRIVATE_validatePlainObject("Data must be an object, but it was:", i, n); + const s = [], o = ObjectValue.empty(); + forEach(n, ((t, n) => { + const a = __PRIVATE_fieldPathFromDotSeparatedString(e, t, r); + // For Compat types, we have to "extract" the underlying types before + // performing validation. + n = P(n); + const u = i.lt(a); + if (n instanceof __PRIVATE_DeleteFieldValueImpl) + // Add it to the field mask, but don't add anything to updateData. + s.push(a); else { + const t = __PRIVATE_parseData(n, u); + null != t && (s.push(a), o.set(a, t)); + } + })); + const a = new FieldMask(s); + return new ParsedUpdateData(o, a, i.fieldTransforms); +} + +/** Parse update data from a list of field/value arguments. */ function __PRIVATE_parseUpdateVarargs(t, e, r, n, i, s) { + const o = t.Tt(1 /* UserDataSource.Update */ , e, r), a = [ __PRIVATE_fieldPathFromArgument$1(e, n, r) ], u = [ i ]; + if (s.length % 2 != 0) throw new FirestoreError(w, `Function ${e}() needs to be called with an even number of arguments that alternate between field names and values.`); + for (let t = 0; t < s.length; t += 2) a.push(__PRIVATE_fieldPathFromArgument$1(e, s[t])), + u.push(s[t + 1]); + const _ = [], c = ObjectValue.empty(); + // We iterate in reverse order to pick the last value for a field if the + // user specified the field multiple times. + for (let t = a.length - 1; t >= 0; --t) if (!__PRIVATE_fieldMaskContains(_, a[t])) { + const e = a[t]; + let r = u[t]; + // For Compat types, we have to "extract" the underlying types before + // performing validation. + r = P(r); + const n = o.lt(e); + if (r instanceof __PRIVATE_DeleteFieldValueImpl) + // Add it to the field mask, but don't add anything to updateData. + _.push(e); else { + const t = __PRIVATE_parseData(r, n); + null != t && (_.push(e), c.set(e, t)); + } + } + const l = new FieldMask(_); + return new ParsedUpdateData(c, l, o.fieldTransforms); +} + +/** + * Parse a "query value" (e.g. value in a where filter or a value in a cursor + * bound). + * + * @param allowArrays - Whether the query value is an array that may directly + * contain additional arrays (e.g. the operand of an `in` query). + */ function __PRIVATE_parseQueryValue(t, e, r, n = !1) { + return __PRIVATE_parseData(r, t.Tt(n ? 4 /* UserDataSource.ArrayArgument */ : 3 /* UserDataSource.Argument */ , e)); +} + +/** + * Parses user data to Protobuf Values. + * + * @param input - Data to be parsed. + * @param context - A context object representing the current path being parsed, + * the source of the data being parsed, etc. + * @returns The parsed value, or null if the value was a FieldValue sentinel + * that should not be included in the resulting parsed data. + */ function __PRIVATE_parseData(t, e) { + if (__PRIVATE_looksLikeJsonObject( + // Unwrap the API type from the Compat SDK. This will return the API type + // from firestore-exp. + t = P(t))) return __PRIVATE_validatePlainObject("Unsupported field value:", e, t), + __PRIVATE_parseObject(t, e); + if (t instanceof FieldValue) + // FieldValues usually parse into transforms (except deleteField()) + // in which case we do not want to include this field in our parsed data + // (as doing so will overwrite the field directly prior to the transform + // trying to transform it). So we don't add this location to + // context.fieldMask and we return null as our parsing result. + /** + * "Parses" the provided FieldValueImpl, adding any necessary transforms to + * context.fieldTransforms. + */ + return function __PRIVATE_parseSentinelFieldValue(t, e) { + // Sentinels are only supported with writes, and not within arrays. + if (!__PRIVATE_isWrite(e.it)) throw e.ft(`${t._methodName}() can only be used with update() and set()`); + if (!e.path) throw e.ft(`${t._methodName}() is not currently supported inside arrays`); + const r = t._toFieldTransform(e); + r && e.fieldTransforms.push(r); + } + /** + * Helper to parse a scalar value (i.e. not an Object, Array, or FieldValue) + * + * @returns The parsed value + */ (t, e), null; + if (void 0 === t && e.ignoreUndefinedProperties) + // If the input is undefined it can never participate in the fieldMask, so + // don't handle this below. If `ignoreUndefinedProperties` is false, + // `parseScalarValue` will reject an undefined value. + return null; + if ( + // If context.path is null we are inside an array and we don't support + // field mask paths more granular than the top-level array. + e.path && e.fieldMask.push(e.path), t instanceof Array) { + // TODO(b/34871131): Include the path containing the array in the error + // message. + // In the case of IN queries, the parsed data is an array (representing + // the set of values to be included for the IN query) that may directly + // contain additional arrays (each representing an individual field + // value), so we disable this validation. + if (e.settings._t && 4 /* UserDataSource.ArrayArgument */ !== e.it) throw e.ft("Nested arrays are not supported"); + return function __PRIVATE_parseArray(t, e) { + const r = []; + let n = 0; + for (const i of t) { + let t = __PRIVATE_parseData(i, e.ht(n)); + null == t && ( + // Just include nulls in the array for fields being replaced with a + // sentinel. + t = { + nullValue: "NULL_VALUE" + }), r.push(t), n++; + } + return { + arrayValue: { + values: r + } + }; + }(t, e); + } + return function __PRIVATE_parseScalarValue(t, e) { + if (null === (t = P(t))) return { + nullValue: "NULL_VALUE" + }; + if ("number" == typeof t) return toNumber(e.serializer, t); + if ("boolean" == typeof t) return { + booleanValue: t + }; + if ("string" == typeof t) return { + stringValue: t + }; + if (t instanceof Date) { + const r = Timestamp.fromDate(t); + return { + timestampValue: toTimestamp(e.serializer, r) + }; + } + if (t instanceof Timestamp) { + // Firestore backend truncates precision down to microseconds. To ensure + // offline mode works the same with regards to truncation, perform the + // truncation immediately without waiting for the backend to do that. + const r = new Timestamp(t.seconds, 1e3 * Math.floor(t.nanoseconds / 1e3)); + return { + timestampValue: toTimestamp(e.serializer, r) + }; + } + if (t instanceof GeoPoint) return { + geoPointValue: { + latitude: t.latitude, + longitude: t.longitude + } + }; + if (t instanceof Bytes) return { + bytesValue: __PRIVATE_toBytes(e.serializer, t._byteString) + }; + if (t instanceof DocumentReference) { + const r = e.databaseId, n = t.firestore._databaseId; + if (!n.isEqual(r)) throw e.ft(`Document reference is for database ${n.projectId}/${n.database} but should be for database ${r.projectId}/${r.database}`); + return { + referenceValue: __PRIVATE_toResourceName(t.firestore._databaseId || e.databaseId, t._key.path) + }; + } + if (t instanceof VectorValue) + /** + * Creates a new VectorValue proto value (using the internal format). + */ + return function __PRIVATE_parseVectorValue(t, e) { + const r = { + fields: { + [tt]: { + stringValue: nt + }, + [it]: { + arrayValue: { + values: t.toArray().map((t => { + if ("number" != typeof t) throw e.ft("VectorValues must only contain numeric values."); + return __PRIVATE_toDouble(e.serializer, t); + })) + } + } + } + }; + return { + mapValue: r + }; + } + /** + * Checks whether an object looks like a JSON object that should be converted + * into a struct. Normal class/prototype instances are considered to look like + * JSON objects since they should be converted to a struct value. Arrays, Dates, + * GeoPoints, etc. are not considered to look like JSON objects since they map + * to specific FieldValue types other than ObjectValue. + */ (t, e); + throw e.ft(`Unsupported field value: ${__PRIVATE_valueDescription(t)}`); + }(t, e); +} + +function __PRIVATE_parseObject(t, e) { + const r = {}; + return !function isEmpty(t) { + for (const e in t) if (Object.prototype.hasOwnProperty.call(t, e)) return !1; + return !0; + }(t) ? forEach(t, ((t, n) => { + const i = __PRIVATE_parseData(n, e.ut(t)); + null != i && (r[t] = i); + })) : + // If we encounter an empty object, we explicitly add it to the update + // mask to ensure that the server creates a map entry. + e.path && e.path.length > 0 && e.fieldMask.push(e.path), { + mapValue: { + fields: r + } + }; +} + +function __PRIVATE_looksLikeJsonObject(t) { + return !("object" != typeof t || null === t || t instanceof Array || t instanceof Date || t instanceof Timestamp || t instanceof GeoPoint || t instanceof Bytes || t instanceof DocumentReference || t instanceof FieldValue || t instanceof VectorValue); +} + +function __PRIVATE_validatePlainObject(t, e, r) { + if (!__PRIVATE_looksLikeJsonObject(r) || !__PRIVATE_isPlainObject(r)) { + const n = __PRIVATE_valueDescription(r); + throw "an object" === n ? e.ft(t + " a custom object") : e.ft(t + " " + n); + } +} + +/** + * Helper that calls fromDotSeparatedString() but wraps any error thrown. + */ function __PRIVATE_fieldPathFromArgument$1(t, e, r) { + if (( + // If required, replace the FieldPath Compat class with the firestore-exp + // FieldPath. + e = P(e)) instanceof FieldPath) return e._internalPath; + if ("string" == typeof e) return __PRIVATE_fieldPathFromDotSeparatedString(t, e); + throw __PRIVATE_createError("Field path arguments must be of type string or ", t, + /* hasConverter= */ !1, + /* path= */ void 0, r); +} + +/** + * Matches any characters in a field path string that are reserved. + */ const dt = new RegExp("[~\\*/\\[\\]]"); + +/** + * Wraps fromDotSeparatedString with an error message about the method that + * was thrown. + * @param methodName - The publicly visible method name + * @param path - The dot-separated string form of a field path which will be + * split on dots. + * @param targetDoc - The document against which the field path will be + * evaluated. + */ function __PRIVATE_fieldPathFromDotSeparatedString(t, e, r) { + if (e.search(dt) >= 0) throw __PRIVATE_createError(`Invalid field path (${e}). Paths must not contain '~', '*', '/', '[', or ']'`, t, + /* hasConverter= */ !1, + /* path= */ void 0, r); + try { + return new FieldPath(...e.split("."))._internalPath; + } catch (n) { + throw __PRIVATE_createError(`Invalid field path (${e}). Paths must not be empty, begin with '.', end with '.', or contain '..'`, t, + /* hasConverter= */ !1, + /* path= */ void 0, r); + } +} + +function __PRIVATE_createError(t, e, r, n, i) { + const s = n && !n.isEmpty(), o = void 0 !== i; + let a = `Function ${e}() called with invalid data`; + r && (a += " (via `toFirestore()`)"), a += ". "; + let u = ""; + return (s || o) && (u += " (found", s && (u += ` in field ${n}`), o && (u += ` in document ${i}`), + u += ")"), new FirestoreError(w, a + t + u); +} + +/** Checks `haystack` if FieldPath `needle` is present. Runs in O(n). */ function __PRIVATE_fieldMaskContains(t, e) { + return t.some((t => t.isEqual(e))); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A `DocumentSnapshot` contains data read from a document in your Firestore + * database. The data can be extracted with `.data()` or `.get()` to + * get a specific field. + * + * For a `DocumentSnapshot` that points to a non-existing document, any data + * access will return 'undefined'. You can use the `exists()` method to + * explicitly verify a document's existence. + */ class DocumentSnapshot { + // Note: This class is stripped down version of the DocumentSnapshot in + // the legacy SDK. The changes are: + // - No support for SnapshotMetadata. + // - No support for SnapshotOptions. + /** @hideconstructor protected */ + constructor(t, e, r, n, i) { + this._firestore = t, this._userDataWriter = e, this._key = r, this._document = n, + this._converter = i; + } + /** Property of the `DocumentSnapshot` that provides the document's ID. */ get id() { + return this._key.path.lastSegment(); + } + /** + * The `DocumentReference` for the document included in the `DocumentSnapshot`. + */ get ref() { + return new DocumentReference(this._firestore, this._converter, this._key); + } + /** + * Signals whether or not the document at the snapshot's location exists. + * + * @returns true if the document exists. + */ exists() { + return null !== this._document; + } + /** + * Retrieves all fields in the document as an `Object`. Returns `undefined` if + * the document doesn't exist. + * + * @returns An `Object` containing all fields in the document or `undefined` + * if the document doesn't exist. + */ data() { + if (this._document) { + if (this._converter) { + // We only want to use the converter and create a new DocumentSnapshot + // if a converter has been provided. + const t = new QueryDocumentSnapshot(this._firestore, this._userDataWriter, this._key, this._document, + /* converter= */ null); + return this._converter.fromFirestore(t); + } + return this._userDataWriter.convertValue(this._document.data.value); + } + } + /** + * Retrieves the field specified by `fieldPath`. Returns `undefined` if the + * document or field doesn't exist. + * + * @param fieldPath - The path (for example 'foo' or 'foo.bar') to a specific + * field. + * @returns The data at the specified field location or undefined if no such + * field exists in the document. + */ + // We are using `any` here to avoid an explicit cast by our users. + // eslint-disable-next-line @typescript-eslint/no-explicit-any + get(t) { + if (this._document) { + const e = this._document.data.field(__PRIVATE_fieldPathFromArgument("DocumentSnapshot.get", t)); + if (null !== e) return this._userDataWriter.convertValue(e); + } + } +} + +/** + * A `QueryDocumentSnapshot` contains data read from a document in your + * Firestore database as part of a query. The document is guaranteed to exist + * and its data can be extracted with `.data()` or `.get()` to get a + * specific field. + * + * A `QueryDocumentSnapshot` offers the same API surface as a + * `DocumentSnapshot`. Since query results contain only existing documents, the + * `exists` property will always be true and `data()` will never return + * 'undefined'. + */ class QueryDocumentSnapshot extends DocumentSnapshot { + /** + * Retrieves all fields in the document as an `Object`. + * + * @override + * @returns An `Object` containing all fields in the document. + */ + data() { + return super.data(); + } +} + +/** + * A `QuerySnapshot` contains zero or more `DocumentSnapshot` objects + * representing the results of a query. The documents can be accessed as an + * array via the `docs` property or enumerated using the `forEach` method. The + * number of documents can be determined via the `empty` and `size` + * properties. + */ class QuerySnapshot { + /** @hideconstructor */ + constructor(t, e) { + this._docs = e, this.query = t; + } + /** An array of all the documents in the `QuerySnapshot`. */ get docs() { + return [ ...this._docs ]; + } + /** The number of documents in the `QuerySnapshot`. */ get size() { + return this.docs.length; + } + /** True if there are no documents in the `QuerySnapshot`. */ get empty() { + return 0 === this.docs.length; + } + /** + * Enumerates all of the documents in the `QuerySnapshot`. + * + * @param callback - A callback to be called with a `QueryDocumentSnapshot` for + * each document in the snapshot. + * @param thisArg - The `this` binding for the callback. + */ forEach(t, e) { + this._docs.forEach(t, e); + } +} + +/** + * Returns true if the provided snapshots are equal. + * + * @param left - A snapshot to compare. + * @param right - A snapshot to compare. + * @returns true if the snapshots are equal. + */ function snapshotEqual(t, e) { + return t = P(t), e = P(e), t instanceof DocumentSnapshot && e instanceof DocumentSnapshot ? t._firestore === e._firestore && t._key.isEqual(e._key) && (null === t._document ? null === e._document : t._document.isEqual(e._document)) && t._converter === e._converter : t instanceof QuerySnapshot && e instanceof QuerySnapshot && (queryEqual(t.query, e.query) && __PRIVATE_arrayEquals(t.docs, e.docs, snapshotEqual)); +} + +/** + * Helper that calls `fromDotSeparatedString()` but wraps any error thrown. + */ function __PRIVATE_fieldPathFromArgument(t, e) { + return "string" == typeof e ? __PRIVATE_fieldPathFromDotSeparatedString(t, e) : e instanceof FieldPath ? e._internalPath : e._delegate._internalPath; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An `AppliableConstraint` is an abstraction of a constraint that can be applied + * to a Firestore query. + */ +class AppliableConstraint {} + +/** + * A `QueryConstraint` is used to narrow the set of documents returned by a + * Firestore query. `QueryConstraint`s are created by invoking {@link where}, + * {@link orderBy}, {@link (startAt:1)}, {@link (startAfter:1)}, {@link + * (endBefore:1)}, {@link (endAt:1)}, {@link limit}, {@link limitToLast} and + * can then be passed to {@link (query:1)} to create a new query instance that + * also contains this `QueryConstraint`. + */ class QueryConstraint extends AppliableConstraint {} + +function query(t, e, ...r) { + let n = []; + e instanceof AppliableConstraint && n.push(e), n = n.concat(r), function __PRIVATE_validateQueryConstraintArray(t) { + const e = t.filter((t => t instanceof QueryCompositeFilterConstraint)).length, r = t.filter((t => t instanceof QueryFieldFilterConstraint)).length; + if (e > 1 || e > 0 && r > 0) throw new FirestoreError(w, "InvalidQuery. When using composite filters, you cannot use more than one filter at the top level. Consider nesting the multiple filters within an `and(...)` statement. For example: change `query(query, where(...), or(...))` to `query(query, and(where(...), or(...)))`."); + } + /** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + /** + * Converts Firestore's internal types to the JavaScript types that we expose + * to the user. + * + * @internal + */ (n); + for (const e of n) t = e._apply(t); + return t; +} + +/** + * A `QueryFieldFilterConstraint` is used to narrow the set of documents returned by + * a Firestore query by filtering on one or more document fields. + * `QueryFieldFilterConstraint`s are created by invoking {@link where} and can then + * be passed to {@link (query:1)} to create a new query instance that also contains + * this `QueryFieldFilterConstraint`. + */ class QueryFieldFilterConstraint extends QueryConstraint { + /** + * @internal + */ + constructor(t, e, r) { + super(), this._field = t, this._op = e, this._value = r, + /** The type of this query constraint */ + this.type = "where"; + } + static _create(t, e, r) { + return new QueryFieldFilterConstraint(t, e, r); + } + _apply(t) { + const e = this._parse(t); + return __PRIVATE_validateNewFieldFilter(t._query, e), new Query(t.firestore, t.converter, __PRIVATE_queryWithAddedFilter(t._query, e)); + } + _parse(t) { + const e = __PRIVATE_newUserDataReader(t.firestore), r = function __PRIVATE_newQueryFilter(t, e, r, n, i, s, o) { + let a; + if (i.isKeyField()) { + if ("array-contains" /* Operator.ARRAY_CONTAINS */ === s || "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ === s) throw new FirestoreError(w, `Invalid Query. You can't perform '${s}' queries on documentId().`); + if ("in" /* Operator.IN */ === s || "not-in" /* Operator.NOT_IN */ === s) { + __PRIVATE_validateDisjunctiveFilterElements(o, s); + const e = []; + for (const r of o) e.push(__PRIVATE_parseDocumentIdValue(n, t, r)); + a = { + arrayValue: { + values: e + } + }; + } else a = __PRIVATE_parseDocumentIdValue(n, t, o); + } else "in" /* Operator.IN */ !== s && "not-in" /* Operator.NOT_IN */ !== s && "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ !== s || __PRIVATE_validateDisjunctiveFilterElements(o, s), + a = __PRIVATE_parseQueryValue(r, e, o, + /* allowArrays= */ "in" /* Operator.IN */ === s || "not-in" /* Operator.NOT_IN */ === s); + const u = FieldFilter.create(i, s, a); + return u; + }(t._query, "where", e, t.firestore._databaseId, this._field, this._op, this._value); + return r; + } +} + +/** + * Creates a {@link QueryFieldFilterConstraint} that enforces that documents + * must contain the specified field and that the value should satisfy the + * relation constraint provided. + * + * @param fieldPath - The path to compare + * @param opStr - The operation string (e.g "<", "<=", "==", "<", + * "<=", "!="). + * @param value - The value for comparison + * @returns The created {@link QueryFieldFilterConstraint}. + */ function where(t, e, r) { + const n = e, i = __PRIVATE_fieldPathFromArgument("where", t); + return QueryFieldFilterConstraint._create(i, n, r); +} + +/** + * A `QueryCompositeFilterConstraint` is used to narrow the set of documents + * returned by a Firestore query by performing the logical OR or AND of multiple + * {@link QueryFieldFilterConstraint}s or {@link QueryCompositeFilterConstraint}s. + * `QueryCompositeFilterConstraint`s are created by invoking {@link or} or + * {@link and} and can then be passed to {@link (query:1)} to create a new query + * instance that also contains the `QueryCompositeFilterConstraint`. + */ class QueryCompositeFilterConstraint extends AppliableConstraint { + /** + * @internal + */ + constructor( + /** The type of this query constraint */ + t, e) { + super(), this.type = t, this._queryConstraints = e; + } + static _create(t, e) { + return new QueryCompositeFilterConstraint(t, e); + } + _parse(t) { + const e = this._queryConstraints.map((e => e._parse(t))).filter((t => t.getFilters().length > 0)); + return 1 === e.length ? e[0] : CompositeFilter.create(e, this._getOperator()); + } + _apply(t) { + const e = this._parse(t); + return 0 === e.getFilters().length ? t : (function __PRIVATE_validateNewFilter(t, e) { + let r = t; + const n = e.getFlattenedFilters(); + for (const t of n) __PRIVATE_validateNewFieldFilter(r, t), r = __PRIVATE_queryWithAddedFilter(r, t); + } + // Checks if any of the provided filter operators are included in the given list of filters and + // returns the first one that is, or null if none are. + (t._query, e), new Query(t.firestore, t.converter, __PRIVATE_queryWithAddedFilter(t._query, e))); + } + _getQueryConstraints() { + return this._queryConstraints; + } + _getOperator() { + return "and" === this.type ? "and" /* CompositeOperator.AND */ : "or" /* CompositeOperator.OR */; + } +} + +/** + * Creates a new {@link QueryCompositeFilterConstraint} that is a disjunction of + * the given filter constraints. A disjunction filter includes a document if it + * satisfies any of the given filters. + * + * @param queryConstraints - Optional. The list of + * {@link QueryFilterConstraint}s to perform a disjunction for. These must be + * created with calls to {@link where}, {@link or}, or {@link and}. + * @returns The newly created {@link QueryCompositeFilterConstraint}. + */ function or(...t) { + // Only support QueryFilterConstraints + return t.forEach((t => __PRIVATE_validateQueryFilterConstraint("or", t))), QueryCompositeFilterConstraint._create("or" /* CompositeOperator.OR */ , t); +} + +/** + * Creates a new {@link QueryCompositeFilterConstraint} that is a conjunction of + * the given filter constraints. A conjunction filter includes a document if it + * satisfies all of the given filters. + * + * @param queryConstraints - Optional. The list of + * {@link QueryFilterConstraint}s to perform a conjunction for. These must be + * created with calls to {@link where}, {@link or}, or {@link and}. + * @returns The newly created {@link QueryCompositeFilterConstraint}. + */ function and(...t) { + // Only support QueryFilterConstraints + return t.forEach((t => __PRIVATE_validateQueryFilterConstraint("and", t))), QueryCompositeFilterConstraint._create("and" /* CompositeOperator.AND */ , t); +} + +/** + * A `QueryOrderByConstraint` is used to sort the set of documents returned by a + * Firestore query. `QueryOrderByConstraint`s are created by invoking + * {@link orderBy} and can then be passed to {@link (query:1)} to create a new query + * instance that also contains this `QueryOrderByConstraint`. + * + * Note: Documents that do not contain the orderBy field will not be present in + * the query result. + */ class QueryOrderByConstraint extends QueryConstraint { + /** + * @internal + */ + constructor(t, e) { + super(), this._field = t, this._direction = e, + /** The type of this query constraint */ + this.type = "orderBy"; + } + static _create(t, e) { + return new QueryOrderByConstraint(t, e); + } + _apply(t) { + const e = function __PRIVATE_newQueryOrderBy(t, e, r) { + if (null !== t.startAt) throw new FirestoreError(w, "Invalid query. You must not call startAt() or startAfter() before calling orderBy()."); + if (null !== t.endAt) throw new FirestoreError(w, "Invalid query. You must not call endAt() or endBefore() before calling orderBy()."); + const n = new OrderBy(e, r); + return n; + } + /** + * Create a `Bound` from a query and a document. + * + * Note that the `Bound` will always include the key of the document + * and so only the provided document will compare equal to the returned + * position. + * + * Will throw if the document does not contain all fields of the order by + * of the query or if any of the fields in the order by are an uncommitted + * server timestamp. + */ (t._query, this._field, this._direction); + return new Query(t.firestore, t.converter, function __PRIVATE_queryWithAddedOrderBy(t, e) { + // TODO(dimond): validate that orderBy does not list the same key twice. + const r = t.explicitOrderBy.concat([ e ]); + return new __PRIVATE_QueryImpl(t.path, t.collectionGroup, r, t.filters.slice(), t.limit, t.limitType, t.startAt, t.endAt); + }(t._query, e)); + } +} + +/** + * Creates a {@link QueryOrderByConstraint} that sorts the query result by the + * specified field, optionally in descending order instead of ascending. + * + * Note: Documents that do not contain the specified field will not be present + * in the query result. + * + * @param fieldPath - The field to sort by. + * @param directionStr - Optional direction to sort by ('asc' or 'desc'). If + * not specified, order will be ascending. + * @returns The created {@link QueryOrderByConstraint}. + */ function orderBy(t, e = "asc") { + const r = e, n = __PRIVATE_fieldPathFromArgument("orderBy", t); + return QueryOrderByConstraint._create(n, r); +} + +/** + * A `QueryLimitConstraint` is used to limit the number of documents returned by + * a Firestore query. + * `QueryLimitConstraint`s are created by invoking {@link limit} or + * {@link limitToLast} and can then be passed to {@link (query:1)} to create a new + * query instance that also contains this `QueryLimitConstraint`. + */ class QueryLimitConstraint extends QueryConstraint { + /** + * @internal + */ + constructor( + /** The type of this query constraint */ + t, e, r) { + super(), this.type = t, this._limit = e, this._limitType = r; + } + static _create(t, e, r) { + return new QueryLimitConstraint(t, e, r); + } + _apply(t) { + return new Query(t.firestore, t.converter, function __PRIVATE_queryWithLimit(t, e, r) { + return new __PRIVATE_QueryImpl(t.path, t.collectionGroup, t.explicitOrderBy.slice(), t.filters.slice(), e, r, t.startAt, t.endAt); + }(t._query, this._limit, this._limitType)); + } +} + +/** + * Creates a {@link QueryLimitConstraint} that only returns the first matching + * documents. + * + * @param limit - The maximum number of items to return. + * @returns The created {@link QueryLimitConstraint}. + */ function limit(t) { + return __PRIVATE_validatePositiveNumber("limit", t), QueryLimitConstraint._create("limit", t, "F" /* LimitType.First */); +} + +/** + * Creates a {@link QueryLimitConstraint} that only returns the last matching + * documents. + * + * You must specify at least one `orderBy` clause for `limitToLast` queries, + * otherwise an exception will be thrown during execution. + * + * @param limit - The maximum number of items to return. + * @returns The created {@link QueryLimitConstraint}. + */ function limitToLast(t) { + return __PRIVATE_validatePositiveNumber("limitToLast", t), QueryLimitConstraint._create("limitToLast", t, "L" /* LimitType.Last */); +} + +/** + * A `QueryStartAtConstraint` is used to exclude documents from the start of a + * result set returned by a Firestore query. + * `QueryStartAtConstraint`s are created by invoking {@link (startAt:1)} or + * {@link (startAfter:1)} and can then be passed to {@link (query:1)} to create a + * new query instance that also contains this `QueryStartAtConstraint`. + */ class QueryStartAtConstraint extends QueryConstraint { + /** + * @internal + */ + constructor( + /** The type of this query constraint */ + t, e, r) { + super(), this.type = t, this._docOrFields = e, this._inclusive = r; + } + static _create(t, e, r) { + return new QueryStartAtConstraint(t, e, r); + } + _apply(t) { + const e = __PRIVATE_newQueryBoundFromDocOrFields(t, this.type, this._docOrFields, this._inclusive); + return new Query(t.firestore, t.converter, function __PRIVATE_queryWithStartAt(t, e) { + return new __PRIVATE_QueryImpl(t.path, t.collectionGroup, t.explicitOrderBy.slice(), t.filters.slice(), t.limit, t.limitType, e, t.endAt); + }(t._query, e)); + } +} + +function startAt(...t) { + return QueryStartAtConstraint._create("startAt", t, + /*inclusive=*/ !0); +} + +function startAfter(...t) { + return QueryStartAtConstraint._create("startAfter", t, + /*inclusive=*/ !1); +} + +/** + * A `QueryEndAtConstraint` is used to exclude documents from the end of a + * result set returned by a Firestore query. + * `QueryEndAtConstraint`s are created by invoking {@link (endAt:1)} or + * {@link (endBefore:1)} and can then be passed to {@link (query:1)} to create a new + * query instance that also contains this `QueryEndAtConstraint`. + */ class QueryEndAtConstraint extends QueryConstraint { + /** + * @internal + */ + constructor( + /** The type of this query constraint */ + t, e, r) { + super(), this.type = t, this._docOrFields = e, this._inclusive = r; + } + static _create(t, e, r) { + return new QueryEndAtConstraint(t, e, r); + } + _apply(t) { + const e = __PRIVATE_newQueryBoundFromDocOrFields(t, this.type, this._docOrFields, this._inclusive); + return new Query(t.firestore, t.converter, function __PRIVATE_queryWithEndAt(t, e) { + return new __PRIVATE_QueryImpl(t.path, t.collectionGroup, t.explicitOrderBy.slice(), t.filters.slice(), t.limit, t.limitType, t.startAt, e); + }(t._query, e)); + } +} + +function endBefore(...t) { + return QueryEndAtConstraint._create("endBefore", t, + /*inclusive=*/ !1); +} + +function endAt(...t) { + return QueryEndAtConstraint._create("endAt", t, + /*inclusive=*/ !0); +} + +/** Helper function to create a bound from a document or fields */ function __PRIVATE_newQueryBoundFromDocOrFields(t, e, r, n) { + if (r[0] = P(r[0]), r[0] instanceof DocumentSnapshot) return function __PRIVATE_newQueryBoundFromDocument(t, e, r, n, i) { + if (!n) throw new FirestoreError(v, `Can't use a DocumentSnapshot that doesn't exist for ${r}().`); + const s = []; + // Because people expect to continue/end a query at the exact document + // provided, we need to use the implicit sort order rather than the explicit + // sort order, because it's guaranteed to contain the document key. That way + // the position becomes unambiguous and the query continues/ends exactly at + // the provided document. Without the key (by using the explicit sort + // orders), multiple documents could match the position, yielding duplicate + // results. + for (const r of __PRIVATE_queryNormalizedOrderBy(t)) if (r.field.isKeyField()) s.push(__PRIVATE_refValue(e, n.key)); else { + const t = n.data.field(r.field); + if (__PRIVATE_isServerTimestamp(t)) throw new FirestoreError(w, 'Invalid query. You are trying to start or end a query using a document for which the field "' + r.field + '" is an uncommitted server timestamp. (Since the value of this field is unknown, you cannot start/end a query with it.)'); + if (null === t) { + const t = r.field.canonicalString(); + throw new FirestoreError(w, `Invalid query. You are trying to start or end a query using a document for which the field '${t}' (used as the orderBy) does not exist.`); + } + s.push(t); + } + return new Bound(s, i); + } + /** + * Converts a list of field values to a `Bound` for the given query. + */ (t._query, t.firestore._databaseId, e, r[0]._document, n); + { + const i = __PRIVATE_newUserDataReader(t.firestore); + return function __PRIVATE_newQueryBoundFromFields(t, e, r, n, i, s) { + // Use explicit order by's because it has to match the query the user made + const o = t.explicitOrderBy; + if (i.length > o.length) throw new FirestoreError(w, `Too many arguments provided to ${n}(). The number of arguments must be less than or equal to the number of orderBy() clauses`); + const a = []; + for (let s = 0; s < i.length; s++) { + const u = i[s]; + if (o[s].field.isKeyField()) { + if ("string" != typeof u) throw new FirestoreError(w, `Invalid query. Expected a string for document ID in ${n}(), but got a ${typeof u}`); + if (!__PRIVATE_isCollectionGroupQuery(t) && -1 !== u.indexOf("/")) throw new FirestoreError(w, `Invalid query. When querying a collection and ordering by documentId(), the value passed to ${n}() must be a plain document ID, but '${u}' contains a slash.`); + const r = t.path.child(ResourcePath.fromString(u)); + if (!DocumentKey.isDocumentKey(r)) throw new FirestoreError(w, `Invalid query. When querying a collection group and ordering by documentId(), the value passed to ${n}() must result in a valid document path, but '${r}' is not because it contains an odd number of segments.`); + const i = new DocumentKey(r); + a.push(__PRIVATE_refValue(e, i)); + } else { + const t = __PRIVATE_parseQueryValue(r, n, u); + a.push(t); + } + } + return new Bound(a, s); + } + /** + * Parses the given `documentIdValue` into a `ReferenceValue`, throwing + * appropriate errors if the value is anything other than a `DocumentReference` + * or `string`, or if the string is malformed. + */ (t._query, t.firestore._databaseId, i, e, r, n); + } +} + +function __PRIVATE_parseDocumentIdValue(t, e, r) { + if ("string" == typeof (r = P(r))) { + if ("" === r) throw new FirestoreError(w, "Invalid query. When querying with documentId(), you must provide a valid document ID, but it was an empty string."); + if (!__PRIVATE_isCollectionGroupQuery(e) && -1 !== r.indexOf("/")) throw new FirestoreError(w, `Invalid query. When querying a collection by documentId(), you must provide a plain document ID, but '${r}' contains a '/' character.`); + const n = e.path.child(ResourcePath.fromString(r)); + if (!DocumentKey.isDocumentKey(n)) throw new FirestoreError(w, `Invalid query. When querying a collection group by documentId(), the value provided must result in a valid document path, but '${n}' is not because it has an odd number of segments (${n.length}).`); + return __PRIVATE_refValue(t, new DocumentKey(n)); + } + if (r instanceof DocumentReference) return __PRIVATE_refValue(t, r._key); + throw new FirestoreError(w, `Invalid query. When querying with documentId(), you must provide a valid string or a DocumentReference, but it was: ${__PRIVATE_valueDescription(r)}.`); +} + +/** + * Validates that the value passed into a disjunctive filter satisfies all + * array requirements. + */ function __PRIVATE_validateDisjunctiveFilterElements(t, e) { + if (!Array.isArray(t) || 0 === t.length) throw new FirestoreError(w, `Invalid Query. A non-empty array is required for '${e.toString()}' filters.`); +} + +/** + * Given an operator, returns the set of operators that cannot be used with it. + * + * This is not a comprehensive check, and this function should be removed in the + * long term. Validations should occur in the Firestore backend. + * + * Operators in a query must adhere to the following set of rules: + * 1. Only one inequality per query. + * 2. `NOT_IN` cannot be used with array, disjunctive, or `NOT_EQUAL` operators. + */ function __PRIVATE_validateNewFieldFilter(t, e) { + const r = function __PRIVATE_findOpInsideFilters(t, e) { + for (const r of t) for (const t of r.getFlattenedFilters()) if (e.indexOf(t.op) >= 0) return t.op; + return null; + }(t.filters, function __PRIVATE_conflictingOps(t) { + switch (t) { + case "!=" /* Operator.NOT_EQUAL */ : + return [ "!=" /* Operator.NOT_EQUAL */ , "not-in" /* Operator.NOT_IN */ ]; + + case "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ : + case "in" /* Operator.IN */ : + return [ "not-in" /* Operator.NOT_IN */ ]; + + case "not-in" /* Operator.NOT_IN */ : + return [ "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ , "in" /* Operator.IN */ , "not-in" /* Operator.NOT_IN */ , "!=" /* Operator.NOT_EQUAL */ ]; + + default: + return []; + } + }(e.op)); + if (null !== r) + // Special case when it's a duplicate op to give a slightly clearer error message. + throw r === e.op ? new FirestoreError(w, `Invalid query. You cannot use more than one '${e.op.toString()}' filter.`) : new FirestoreError(w, `Invalid query. You cannot use '${e.op.toString()}' filters with '${r.toString()}' filters.`); +} + +function __PRIVATE_validateQueryFilterConstraint(t, e) { + if (!(e instanceof QueryFieldFilterConstraint || e instanceof QueryCompositeFilterConstraint)) throw new FirestoreError(w, `Function ${t}() requires AppliableConstraints created with a call to 'where(...)', 'or(...)', or 'and(...)'.`); +} + +class AbstractUserDataWriter { + convertValue(t, e = "none") { + switch (__PRIVATE_typeOrder(t)) { + case 0 /* TypeOrder.NullValue */ : + return null; + + case 1 /* TypeOrder.BooleanValue */ : + return t.booleanValue; + + case 2 /* TypeOrder.NumberValue */ : + return __PRIVATE_normalizeNumber(t.integerValue || t.doubleValue); + + case 3 /* TypeOrder.TimestampValue */ : + return this.convertTimestamp(t.timestampValue); + + case 4 /* TypeOrder.ServerTimestampValue */ : + return this.convertServerTimestamp(t, e); + + case 5 /* TypeOrder.StringValue */ : + return t.stringValue; + + case 6 /* TypeOrder.BlobValue */ : + return this.convertBytes(__PRIVATE_normalizeByteString(t.bytesValue)); + + case 7 /* TypeOrder.RefValue */ : + return this.convertReference(t.referenceValue); + + case 8 /* TypeOrder.GeoPointValue */ : + return this.convertGeoPoint(t.geoPointValue); + + case 9 /* TypeOrder.ArrayValue */ : + return this.convertArray(t.arrayValue, e); + + case 11 /* TypeOrder.ObjectValue */ : + return this.convertObject(t.mapValue, e); + + case 10 /* TypeOrder.VectorValue */ : + return this.convertVectorValue(t.mapValue); + + default: + throw fail(62114, { + value: t + }); + } + } + convertObject(t, e) { + return this.convertObjectMap(t.fields, e); + } + /** + * @internal + */ convertObjectMap(t, e = "none") { + const r = {}; + return forEach(t, ((t, n) => { + r[t] = this.convertValue(n, e); + })), r; + } + /** + * @internal + */ convertVectorValue(t) { + const e = t.fields?.[it].arrayValue?.values?.map((t => __PRIVATE_normalizeNumber(t.doubleValue))); + return new VectorValue(e); + } + convertGeoPoint(t) { + return new GeoPoint(__PRIVATE_normalizeNumber(t.latitude), __PRIVATE_normalizeNumber(t.longitude)); + } + convertArray(t, e) { + return (t.values || []).map((t => this.convertValue(t, e))); + } + convertServerTimestamp(t, e) { + switch (e) { + case "previous": + const r = __PRIVATE_getPreviousValue(t); + return null == r ? null : this.convertValue(r, e); + + case "estimate": + return this.convertTimestamp(__PRIVATE_getLocalWriteTime(t)); + + default: + return null; + } + } + convertTimestamp(t) { + const e = __PRIVATE_normalizeTimestamp(t); + return new Timestamp(e.seconds, e.nanos); + } + convertDocumentKey(t, e) { + const r = ResourcePath.fromString(t); + __PRIVATE_hardAssert(__PRIVATE_isValidResourceName(r), 9688, { + name: t + }); + const n = new DatabaseId(r.get(1), r.get(3)), i = new DocumentKey(r.popFirst(5)); + return n.isEqual(e) || + // TODO(b/64130202): Somehow support foreign references. + __PRIVATE_logError(`Document ${i} contains a document reference within a different database (${n.projectId}/${n.database}) which is not supported. It will be treated as a reference in the current database (${e.projectId}/${e.database}) instead.`), + i; + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Converts custom model object of type T into `DocumentData` by applying the + * converter if it exists. + * + * This function is used when converting user objects to `DocumentData` + * because we want to provide the user with a more specific error message if + * their `set()` or fails due to invalid data originating from a `toFirestore()` + * call. + */ function __PRIVATE_applyFirestoreDataConverter(t, e, r) { + let n; + // Cast to `any` in order to satisfy the union type constraint on + // toFirestore(). + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return n = t ? r && (r.merge || r.mergeFields) ? t.toFirestore(e, r) : t.toFirestore(e) : e, + n; +} + +class __PRIVATE_LiteUserDataWriter extends AbstractUserDataWriter { + constructor(t) { + super(), this.firestore = t; + } + convertBytes(t) { + return new Bytes(t); + } + convertReference(t) { + const e = this.convertDocumentKey(t, this.firestore._databaseId); + return new DocumentReference(this.firestore, /* converter= */ null, e); + } +} + +/** + * Reads the document referred to by the specified document reference. + * + * All documents are directly fetched from the server, even if the document was + * previously read or modified. Recent modifications are only reflected in the + * retrieved `DocumentSnapshot` if they have already been applied by the + * backend. If the client is offline, the read fails. If you like to use + * caching or see local modifications, please use the full Firestore SDK. + * + * @param reference - The reference of the document to fetch. + * @returns A Promise resolved with a `DocumentSnapshot` containing the current + * document contents. + */ function getDoc(t) { + const e = __PRIVATE_getDatastore((t = __PRIVATE_cast(t, DocumentReference)).firestore), r = new __PRIVATE_LiteUserDataWriter(t.firestore); + return __PRIVATE_invokeBatchGetDocumentsRpc(e, [ t._key ]).then((e => { + __PRIVATE_hardAssert(1 === e.length, 15618); + const n = e[0]; + return new DocumentSnapshot(t.firestore, r, t._key, n.isFoundDocument() ? n : null, t.converter); + })); +} + +/** + * Executes the query and returns the results as a {@link QuerySnapshot}. + * + * All queries are executed directly by the server, even if the query was + * previously executed. Recent modifications are only reflected in the retrieved + * results if they have already been applied by the backend. If the client is + * offline, the operation fails. To see previously cached result and local + * modifications, use the full Firestore SDK. + * + * @param query - The `Query` to execute. + * @returns A Promise that will be resolved with the results of the query. + */ function getDocs(t) { + (function __PRIVATE_validateHasExplicitOrderByForLimitToLast(t) { + if ("L" /* LimitType.Last */ === t.limitType && 0 === t.explicitOrderBy.length) throw new FirestoreError(B, "limitToLast() queries require specifying at least one orderBy() clause"); + })((t = __PRIVATE_cast(t, Query))._query); + const e = __PRIVATE_getDatastore(t.firestore), r = new __PRIVATE_LiteUserDataWriter(t.firestore); + return __PRIVATE_invokeRunQueryRpc(e, t._query).then((e => { + const n = e.map((e => new QueryDocumentSnapshot(t.firestore, r, e.key, e, t.converter))); + return "L" /* LimitType.Last */ === t._query.limitType && + // Limit to last queries reverse the orderBy constraint that was + // specified by the user. As such, we need to reverse the order of the + // results to return the documents in the expected order. + n.reverse(), new QuerySnapshot(t, n); + })); +} + +function setDoc(t, e, r) { + const n = __PRIVATE_applyFirestoreDataConverter((t = __PRIVATE_cast(t, DocumentReference)).converter, e, r), i = __PRIVATE_parseSetData(__PRIVATE_newUserDataReader(t.firestore), "setDoc", t._key, n, null !== t.converter, r); + return __PRIVATE_invokeCommitRpc(__PRIVATE_getDatastore(t.firestore), [ i.toMutation(t._key, Precondition.none()) ]); +} + +function updateDoc(t, e, r, ...n) { + const i = __PRIVATE_newUserDataReader((t = __PRIVATE_cast(t, DocumentReference)).firestore); + // For Compat types, we have to "extract" the underlying types before + // performing validation. + let s; + s = "string" == typeof (e = P(e)) || e instanceof FieldPath ? __PRIVATE_parseUpdateVarargs(i, "updateDoc", t._key, e, r, n) : __PRIVATE_parseUpdateData(i, "updateDoc", t._key, e); + return __PRIVATE_invokeCommitRpc(__PRIVATE_getDatastore(t.firestore), [ s.toMutation(t._key, Precondition.exists(!0)) ]); +} + +/** + * Deletes the document referred to by the specified `DocumentReference`. + * + * The deletion will only be reflected in document reads that occur after the + * returned promise resolves. If the client is offline, the + * delete fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @param reference - A reference to the document to delete. + * @returns A `Promise` resolved once the document has been successfully + * deleted from the backend. + */ function deleteDoc(t) { + return __PRIVATE_invokeCommitRpc(__PRIVATE_getDatastore((t = __PRIVATE_cast(t, DocumentReference)).firestore), [ new __PRIVATE_DeleteMutation(t._key, Precondition.none()) ]); +} + +/** + * Add a new document to specified `CollectionReference` with the given data, + * assigning it a document ID automatically. + * + * The result of this write will only be reflected in document reads that occur + * after the returned promise resolves. If the client is offline, the + * write fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @param reference - A reference to the collection to add this document to. + * @param data - An Object containing the data for the new document. + * @throws Error - If the provided input is not a valid Firestore document. + * @returns A `Promise` resolved with a `DocumentReference` pointing to the + * newly created document after it has been written to the backend. + */ function addDoc(t, e) { + const r = doc(t = __PRIVATE_cast(t, CollectionReference)), n = __PRIVATE_applyFirestoreDataConverter(t.converter, e), i = __PRIVATE_parseSetData(__PRIVATE_newUserDataReader(t.firestore), "addDoc", r._key, n, null !== r.converter, {}); + return __PRIVATE_invokeCommitRpc(__PRIVATE_getDatastore(t.firestore), [ i.toMutation(r._key, Precondition.exists(!1)) ]).then((() => r)); +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Calculates the number of documents in the result set of the given query + * without actually downloading the documents. + * + * Using this function to count the documents is efficient because only the + * final count, not the documents' data, is downloaded. This function can + * count the documents in cases where the result set is prohibitively large to + * download entirely (thousands of documents). + * + * @param query The query whose result set size is calculated. + * @returns A Promise that will be resolved with the count; the count can be + * retrieved from `snapshot.data().count`, where `snapshot` is the + * `AggregateQuerySnapshot` to which the returned Promise resolves. + */ function getCount(t) { + return getAggregate(t, { + count: count() + }); +} + +/** + * Calculates the specified aggregations over the documents in the result + * set of the given query without actually downloading the documents. + * + * Using this function to perform aggregations is efficient because only the + * final aggregation values, not the documents' data, are downloaded. This + * function can perform aggregations of the documents in cases where the result + * set is prohibitively large to download entirely (thousands of documents). + * + * @param query The query whose result set is aggregated over. + * @param aggregateSpec An `AggregateSpec` object that specifies the aggregates + * to perform over the result set. The AggregateSpec specifies aliases for each + * aggregate, which can be used to retrieve the aggregate result. + * @example + * ```typescript + * const aggregateSnapshot = await getAggregate(query, { + * countOfDocs: count(), + * totalHours: sum('hours'), + * averageScore: average('score') + * }); + * + * const countOfDocs: number = aggregateSnapshot.data().countOfDocs; + * const totalHours: number = aggregateSnapshot.data().totalHours; + * const averageScore: number | null = aggregateSnapshot.data().averageScore; + * ``` + */ function getAggregate(t, e) { + const r = __PRIVATE_cast(t.firestore, Firestore), n = __PRIVATE_getDatastore(r), i = function __PRIVATE_mapToArray(t, e) { + const r = []; + for (const n in t) Object.prototype.hasOwnProperty.call(t, n) && r.push(e(t[n], n, t)); + return r; + }(e, ((t, e) => new __PRIVATE_AggregateImpl(e, t.aggregateType, t._internalFieldPath))); + // Run the aggregation and convert the results + return __PRIVATE_invokeRunAggregationQueryRpc(n, t._query, i).then((e => function __PRIVATE_convertToAggregateQuerySnapshot(t, e, r) { + const n = new __PRIVATE_LiteUserDataWriter(t), i = new AggregateQuerySnapshot(e, n, r); + return i; + } + /** + * Create an AggregateField object that can be used to compute the sum of + * a specified field over a range of documents in the result set of a query. + * @param field Specifies the field to sum across the result set. + */ (r, t, e))); +} + +function sum(t) { + return new AggregateField("sum", __PRIVATE_fieldPathFromArgument$1("sum", t)); +} + +/** + * Create an AggregateField object that can be used to compute the average of + * a specified field over a range of documents in the result set of a query. + * @param field Specifies the field to average across the result set. + */ function average(t) { + return new AggregateField("avg", __PRIVATE_fieldPathFromArgument$1("average", t)); +} + +/** + * Create an AggregateField object that can be used to compute the count of + * documents in the result set of a query. + */ function count() { + return new AggregateField("count"); +} + +/** + * Compares two 'AggregateField` instances for equality. + * + * @param left Compare this AggregateField to the `right`. + * @param right Compare this AggregateField to the `left`. + */ function aggregateFieldEqual(t, e) { + return t instanceof AggregateField && e instanceof AggregateField && t.aggregateType === e.aggregateType && t._internalFieldPath?.canonicalString() === e._internalFieldPath?.canonicalString(); +} + +/** + * Compares two `AggregateQuerySnapshot` instances for equality. + * + * Two `AggregateQuerySnapshot` instances are considered "equal" if they have + * underlying queries that compare equal, and the same data. + * + * @param left - The first `AggregateQuerySnapshot` to compare. + * @param right - The second `AggregateQuerySnapshot` to compare. + * + * @returns `true` if the objects are "equal", as defined above, or `false` + * otherwise. + */ function aggregateQuerySnapshotEqual(t, e) { + return queryEqual(t.query, e.query) && E(t.data(), e.data()); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Returns a sentinel for use with {@link @firebase/firestore/lite#(updateDoc:1)} or + * {@link @firebase/firestore/lite#(setDoc:1)} with `{merge: true}` to mark a field for deletion. + */ function deleteField() { + return new __PRIVATE_DeleteFieldValueImpl("deleteField"); +} + +/** + * Returns a sentinel used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link @firebase/firestore/lite#(updateDoc:1)} to + * include a server-generated timestamp in the written data. + */ function serverTimestamp() { + return new __PRIVATE_ServerTimestampFieldValueImpl("serverTimestamp"); +} + +/** + * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link + * @firebase/firestore/lite#(updateDoc:1)} that tells the server to union the given elements with any array + * value that already exists on the server. Each specified element that doesn't + * already exist in the array will be added to the end. If the field being + * modified is not already an array it will be overwritten with an array + * containing exactly the specified elements. + * + * @param elements - The elements to union into the array. + * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or + * `updateDoc()`. + */ function arrayUnion(...t) { + // NOTE: We don't actually parse the data until it's used in set() or + // update() since we'd need the Firestore instance to do this. + return new __PRIVATE_ArrayUnionFieldValueImpl("arrayUnion", t); +} + +/** + * Returns a special value that can be used with {@link (setDoc:1)} or {@link + * updateDoc:1} that tells the server to remove the given elements from any + * array value that already exists on the server. All instances of each element + * specified will be removed from the array. If the field being modified is not + * already an array it will be overwritten with an empty array. + * + * @param elements - The elements to remove from the array. + * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or + * `updateDoc()` + */ function arrayRemove(...t) { + // NOTE: We don't actually parse the data until it's used in set() or + // update() since we'd need the Firestore instance to do this. + return new __PRIVATE_ArrayRemoveFieldValueImpl("arrayRemove", t); +} + +/** + * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link + * @firebase/firestore/lite#(updateDoc:1)} that tells the server to increment the field's current value by + * the given value. + * + * If either the operand or the current field value uses floating point + * precision, all arithmetic follows IEEE 754 semantics. If both values are + * integers, values outside of JavaScript's safe number range + * (`Number.MIN_SAFE_INTEGER` to `Number.MAX_SAFE_INTEGER`) are also subject to + * precision loss. Furthermore, once processed by the Firestore backend, all + * integer operations are capped between -2^63 and 2^63-1. + * + * If the current field value is not of type `number`, or if the field does not + * yet exist, the transformation sets the field to the given value. + * + * @param n - The value to increment by. + * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or + * `updateDoc()` + */ function increment(t) { + return new __PRIVATE_NumericIncrementFieldValueImpl("increment", t); +} + +/** + * Creates a new `VectorValue` constructed with a copy of the given array of numbers. + * + * @param values - Create a `VectorValue` instance with a copy of this array of numbers. + * + * @returns A new `VectorValue` constructed with a copy of the given array of numbers. + */ function vector(t) { + return new VectorValue(t); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A write batch, used to perform multiple writes as a single atomic unit. + * + * A `WriteBatch` object can be acquired by calling {@link writeBatch}. It + * provides methods for adding writes to the write batch. None of the writes + * will be committed (or visible locally) until {@link WriteBatch.commit} is + * called. + */ class WriteBatch { + /** @hideconstructor */ + constructor(t, e) { + this._firestore = t, this._commitHandler = e, this._mutations = [], this._committed = !1, + this._dataReader = __PRIVATE_newUserDataReader(t); + } + set(t, e, r) { + this._verifyNotCommitted(); + const n = __PRIVATE_validateReference(t, this._firestore), i = __PRIVATE_applyFirestoreDataConverter(n.converter, e, r), s = __PRIVATE_parseSetData(this._dataReader, "WriteBatch.set", n._key, i, null !== n.converter, r); + return this._mutations.push(s.toMutation(n._key, Precondition.none())), this; + } + update(t, e, r, ...n) { + this._verifyNotCommitted(); + const i = __PRIVATE_validateReference(t, this._firestore); + // For Compat types, we have to "extract" the underlying types before + // performing validation. + let s; + return s = "string" == typeof (e = P(e)) || e instanceof FieldPath ? __PRIVATE_parseUpdateVarargs(this._dataReader, "WriteBatch.update", i._key, e, r, n) : __PRIVATE_parseUpdateData(this._dataReader, "WriteBatch.update", i._key, e), + this._mutations.push(s.toMutation(i._key, Precondition.exists(!0))), this; + } + /** + * Deletes the document referred to by the provided {@link DocumentReference}. + * + * @param documentRef - A reference to the document to be deleted. + * @returns This `WriteBatch` instance. Used for chaining method calls. + */ delete(t) { + this._verifyNotCommitted(); + const e = __PRIVATE_validateReference(t, this._firestore); + return this._mutations = this._mutations.concat(new __PRIVATE_DeleteMutation(e._key, Precondition.none())), + this; + } + /** + * Commits all of the writes in this write batch as a single atomic unit. + * + * The result of these writes will only be reflected in document reads that + * occur after the returned promise resolves. If the client is offline, the + * write fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @returns A `Promise` resolved once all of the writes in the batch have been + * successfully written to the backend as an atomic unit (note that it won't + * resolve while you're offline). + */ commit() { + return this._verifyNotCommitted(), this._committed = !0, this._mutations.length > 0 ? this._commitHandler(this._mutations) : Promise.resolve(); + } + _verifyNotCommitted() { + if (this._committed) throw new FirestoreError(N, "A write batch can no longer be used after commit() has been called."); + } +} + +function __PRIVATE_validateReference(t, e) { + if ((t = P(t)).firestore !== e) throw new FirestoreError(w, "Provided document reference is from a different Firestore instance."); + return t; +} + +/** + * Creates a write batch, used for performing multiple writes as a single + * atomic operation. The maximum number of writes allowed in a single WriteBatch + * is 500. + * + * The result of these writes will only be reflected in document reads that + * occur after the returned promise resolves. If the client is offline, the + * write fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @returns A `WriteBatch` that can be used to atomically execute multiple + * writes. + */ function writeBatch(t) { + const e = __PRIVATE_getDatastore(t = __PRIVATE_cast(t, Firestore)); + return new WriteBatch(t, (t => __PRIVATE_invokeCommitRpc(e, t))); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Internal transaction object responsible for accumulating the mutations to + * perform and the base versions for any documents read. + */ class Transaction$1 { + constructor(t) { + this.datastore = t, + // The version of each document that was read during this transaction. + this.readVersions = new Map, this.mutations = [], this.committed = !1, + /** + * A deferred usage error that occurred previously in this transaction that + * will cause the transaction to fail once it actually commits. + */ + this.lastTransactionError = null, + /** + * Set of documents that have been written in the transaction. + * + * When there's more than one write to the same key in a transaction, any + * writes after the first are handled differently. + */ + this.writtenDocs = new Set; + } + async lookup(t) { + if (this.ensureCommitNotCalled(), this.mutations.length > 0) throw this.lastTransactionError = new FirestoreError(w, "Firestore transactions require all reads to be executed before all writes."), + this.lastTransactionError; + const e = await __PRIVATE_invokeBatchGetDocumentsRpc(this.datastore, t); + return e.forEach((t => this.recordVersion(t))), e; + } + set(t, e) { + this.write(e.toMutation(t, this.precondition(t))), this.writtenDocs.add(t.toString()); + } + update(t, e) { + try { + this.write(e.toMutation(t, this.preconditionForUpdate(t))); + } catch (t) { + this.lastTransactionError = t; + } + this.writtenDocs.add(t.toString()); + } + delete(t) { + this.write(new __PRIVATE_DeleteMutation(t, this.precondition(t))), this.writtenDocs.add(t.toString()); + } + async commit() { + if (this.ensureCommitNotCalled(), this.lastTransactionError) throw this.lastTransactionError; + const t = this.readVersions; + // For each mutation, note that the doc was written. + this.mutations.forEach((e => { + t.delete(e.key.toString()); + })), + // For each document that was read but not written to, we want to perform + // a `verify` operation. + t.forEach(((t, e) => { + const r = DocumentKey.fromPath(e); + this.mutations.push(new __PRIVATE_VerifyMutation(r, this.precondition(r))); + })), await __PRIVATE_invokeCommitRpc(this.datastore, this.mutations), this.committed = !0; + } + recordVersion(t) { + let e; + if (t.isFoundDocument()) e = t.version; else { + if (!t.isNoDocument()) throw fail(50498, { + Rt: t.constructor.name + }); + // Represent a deleted doc using SnapshotVersion.min(). + e = SnapshotVersion.min(); + } + const r = this.readVersions.get(t.key.toString()); + if (r) { + if (!e.isEqual(r)) + // This transaction will fail no matter what. + throw new FirestoreError(O, "Document version changed between two reads."); + } else this.readVersions.set(t.key.toString(), e); + } + /** + * Returns the version of this document when it was read in this transaction, + * as a precondition, or no precondition if it was not read. + */ precondition(t) { + const e = this.readVersions.get(t.toString()); + return !this.writtenDocs.has(t.toString()) && e ? e.isEqual(SnapshotVersion.min()) ? Precondition.exists(!1) : Precondition.updateTime(e) : Precondition.none(); + } + /** + * Returns the precondition for a document if the operation is an update. + */ preconditionForUpdate(t) { + const e = this.readVersions.get(t.toString()); + // The first time a document is written, we want to take into account the + // read time and existence + if (!this.writtenDocs.has(t.toString()) && e) { + if (e.isEqual(SnapshotVersion.min())) + // The document doesn't exist, so fail the transaction. + // This has to be validated locally because you can't send a + // precondition that a document does not exist without changing the + // semantics of the backend write to be an insert. This is the reverse + // of what we want, since we want to assert that the document doesn't + // exist but then send the update and have it fail. Since we can't + // express that to the backend, we have to validate locally. + // Note: this can change once we can send separate verify writes in the + // transaction. + throw new FirestoreError(w, "Can't update a document that doesn't exist."); + // Document exists, base precondition on document update time. + return Precondition.updateTime(e); + } + // Document was not read, so we just use the preconditions for a blind + // update. + return Precondition.exists(!0); + } + write(t) { + this.ensureCommitNotCalled(), this.mutations.push(t); + } + ensureCommitNotCalled() {} +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ const mt = { + maxAttempts: 5 +}; + +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * TransactionRunner encapsulates the logic needed to run and retry transactions + * with backoff. + */ +class __PRIVATE_TransactionRunner { + constructor(t, e, r, n, i) { + this.asyncQueue = t, this.datastore = e, this.options = r, this.updateFunction = n, + this.deferred = i, this.Vt = r.maxAttempts, this.It = new __PRIVATE_ExponentialBackoff(this.asyncQueue, "transaction_retry" /* TimerId.TransactionRetry */); + } + /** Runs the transaction and sets the result on deferred. */ yt() { + this.Vt -= 1, this.gt(); + } + gt() { + this.It.Z((async () => { + const t = new Transaction$1(this.datastore), e = this.wt(t); + e && e.then((e => { + this.asyncQueue.enqueueAndForget((() => t.commit().then((() => { + this.deferred.resolve(e); + })).catch((t => { + this.Ft(t); + })))); + })).catch((t => { + this.Ft(t); + })); + })); + } + wt(t) { + try { + const e = this.updateFunction(t); + return !__PRIVATE_isNullOrUndefined(e) && e.catch && e.then ? e : (this.deferred.reject(Error("Transaction callback must return a Promise")), + null); + } catch (t) { + // Do not retry errors thrown by user provided updateFunction. + return this.deferred.reject(t), null; + } + } + Ft(t) { + this.Vt > 0 && this.vt(t) ? (this.Vt -= 1, this.asyncQueue.enqueueAndForget((() => (this.gt(), + Promise.resolve())))) : this.deferred.reject(t); + } + vt(t) { + if ("FirebaseError" === t?.name) { + // In transactions, the backend will fail outdated reads with FAILED_PRECONDITION and + // non-matching document versions with ABORTED. These errors should be retried. + const e = t.code; + return "aborted" === e || "failed-precondition" === e || "already-exists" === e || ! + /** + * Determines whether an error code represents a permanent error when received + * in response to a non-write operation. + * + * See isPermanentWriteError for classifying write errors. + */ + function __PRIVATE_isPermanentError(t) { + switch (t) { + case p: + return fail(64938); + + case y: + case g: + case F: + case C: + case $: + case Q: + // Unauthenticated means something went wrong with our token and we need + // to retry with new credentials which will happen automatically. + case S: + return !1; + + case w: + case v: + case D: + case b: + case N: + // Aborted might be retried in some scenarios, but that is dependent on + // the context and should handled individually by the calling code. + // See https://cloud.google.com/apis/design/errors. + case O: + case q: + case B: + case k: + return !0; + + default: + return fail(15467, { + code: t + }); + } + }(e); + } + return !1; + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** The Platform's 'document' implementation or null if not available. */ function getDocument() { + // `document` is not always available, e.g. in ReactNative and WebWorkers. + // eslint-disable-next-line no-restricted-globals + return "undefined" != typeof document ? document : null; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Represents an operation scheduled to be run in the future on an AsyncQueue. + * + * It is created via DelayedOperation.createAndSchedule(). + * + * Supports cancellation (via cancel()) and early execution (via skipDelay()). + * + * Note: We implement `PromiseLike` instead of `Promise`, as the `Promise` type + * in newer versions of TypeScript defines `finally`, which is not available in + * IE. + */ class DelayedOperation { + constructor(t, e, r, n, i) { + this.asyncQueue = t, this.timerId = e, this.targetTimeMs = r, this.op = n, this.removalCallback = i, + this.deferred = new __PRIVATE_Deferred, this.then = this.deferred.promise.then.bind(this.deferred.promise), + // It's normal for the deferred promise to be canceled (due to cancellation) + // and so we attach a dummy catch callback to avoid + // 'UnhandledPromiseRejectionWarning' log spam. + this.deferred.promise.catch((t => {})); + } + get promise() { + return this.deferred.promise; + } + /** + * Creates and returns a DelayedOperation that has been scheduled to be + * executed on the provided asyncQueue after the provided delayMs. + * + * @param asyncQueue - The queue to schedule the operation on. + * @param id - A Timer ID identifying the type of operation this is. + * @param delayMs - The delay (ms) before the operation should be scheduled. + * @param op - The operation to run. + * @param removalCallback - A callback to be called synchronously once the + * operation is executed or canceled, notifying the AsyncQueue to remove it + * from its delayedOperations list. + * PORTING NOTE: This exists to prevent making removeDelayedOperation() and + * the DelayedOperation class public. + */ static createAndSchedule(t, e, r, n, i) { + const s = Date.now() + r, o = new DelayedOperation(t, e, s, n, i); + return o.start(r), o; + } + /** + * Starts the timer. This is called immediately after construction by + * createAndSchedule(). + */ start(t) { + this.timerHandle = setTimeout((() => this.handleDelayElapsed()), t); + } + /** + * Queues the operation to run immediately (if it hasn't already been run or + * canceled). + */ skipDelay() { + return this.handleDelayElapsed(); + } + /** + * Cancels the operation if it hasn't already been executed or canceled. The + * promise will be rejected. + * + * As long as the operation has not yet been run, calling cancel() provides a + * guarantee that the operation will not be run. + */ cancel(t) { + null !== this.timerHandle && (this.clearTimeout(), this.deferred.reject(new FirestoreError(y, "Operation cancelled" + (t ? ": " + t : "")))); + } + handleDelayElapsed() { + this.asyncQueue.enqueueAndForget((() => null !== this.timerHandle ? (this.clearTimeout(), + this.op().then((t => this.deferred.resolve(t)))) : Promise.resolve())); + } + clearTimeout() { + null !== this.timerHandle && (this.removalCallback(this), clearTimeout(this.timerHandle), + this.timerHandle = null); + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ const Et = "AsyncQueue"; + +class __PRIVATE_AsyncQueueImpl { + constructor(t = Promise.resolve()) { + // A list of retryable operations. Retryable operations are run in order and + // retried with backoff. + this.Dt = [], + // Is this AsyncQueue being shut down? Once it is set to true, it will not + // be changed again. + this.bt = !1, + // Operations scheduled to be queued in the future. Operations are + // automatically removed after they are run or canceled. + this.St = [], + // visible for testing + this.Ct = null, + // Flag set while there's an outstanding AsyncQueue operation, used for + // assertion sanity-checks. + this.Nt = !1, + // Enabled during shutdown on Safari to prevent future access to IndexedDB. + this.Ot = !1, + // List of TimerIds to fast-forward delays for. + this.qt = [], + // Backoff timer used to schedule retries for retryable operations + this.It = new __PRIVATE_ExponentialBackoff(this, "async_queue_retry" /* TimerId.AsyncQueueRetry */), + // Visibility handler that triggers an immediate retry of all retryable + // operations. Meant to speed up recovery when we regain file system access + // after page comes into foreground. + this.Bt = () => { + const t = getDocument(); + t && __PRIVATE_logDebug(Et, "Visibility state changed to " + t.visibilityState), + this.It.tt(); + }, this.$t = t; + const e = getDocument(); + e && "function" == typeof e.addEventListener && e.addEventListener("visibilitychange", this.Bt); + } + get isShuttingDown() { + return this.bt; + } + /** + * Adds a new operation to the queue without waiting for it to complete (i.e. + * we ignore the Promise result). + */ enqueueAndForget(t) { + // eslint-disable-next-line @typescript-eslint/no-floating-promises + this.enqueue(t); + } + enqueueAndForgetEvenWhileRestricted(t) { + this.Qt(), + // eslint-disable-next-line @typescript-eslint/no-floating-promises + this.kt(t); + } + enterRestrictedMode(t) { + if (!this.bt) { + this.bt = !0, this.Ot = t || !1; + const e = getDocument(); + e && "function" == typeof e.removeEventListener && e.removeEventListener("visibilitychange", this.Bt); + } + } + enqueue(t) { + if (this.Qt(), this.bt) + // Return a Promise which never resolves. + return new Promise((() => {})); + // Create a deferred Promise that we can return to the callee. This + // allows us to return a "hanging Promise" only to the callee and still + // advance the queue even when the operation is not run. + const e = new __PRIVATE_Deferred; + return this.kt((() => this.bt && this.Ot ? Promise.resolve() : (t().then(e.resolve, e.reject), + e.promise))).then((() => e.promise)); + } + enqueueRetryable(t) { + this.enqueueAndForget((() => (this.Dt.push(t), this.Lt()))); + } + /** + * Runs the next operation from the retryable queue. If the operation fails, + * reschedules with backoff. + */ async Lt() { + if (0 !== this.Dt.length) { + try { + await this.Dt[0](), this.Dt.shift(), this.It.reset(); + } catch (t) { + if (! + /** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + /** Verifies whether `e` is an IndexedDbTransactionError. */ + function __PRIVATE_isIndexedDbTransactionError(t) { + // Use name equality, as instanceof checks on errors don't work with errors + // that wrap other errors. + return "IndexedDbTransactionError" === t.name; + }(t)) throw t; + // Failure will be handled by AsyncQueue + __PRIVATE_logDebug(Et, "Operation failed with retryable error: " + t); + } + this.Dt.length > 0 && + // If there are additional operations, we re-schedule `retryNextOp()`. + // This is necessary to run retryable operations that failed during + // their initial attempt since we don't know whether they are already + // enqueued. If, for example, `op1`, `op2`, `op3` are enqueued and `op1` + // needs to be re-run, we will run `op1`, `op1`, `op2` using the + // already enqueued calls to `retryNextOp()`. `op3()` will then run in the + // call scheduled here. + // Since `backoffAndRun()` cancels an existing backoff and schedules a + // new backoff on every call, there is only ever a single additional + // operation in the queue. + this.It.Z((() => this.Lt())); + } + } + kt(t) { + const e = this.$t.then((() => (this.Nt = !0, t().catch((t => { + this.Ct = t, this.Nt = !1; + // Re-throw the error so that this.tail becomes a rejected Promise and + // all further attempts to chain (via .then) will just short-circuit + // and return the rejected Promise. + throw __PRIVATE_logError("INTERNAL UNHANDLED ERROR: ", __PRIVATE_getMessageOrStack(t)), + t; + })).then((t => (this.Nt = !1, t)))))); + return this.$t = e, e; + } + enqueueAfterDelay(t, e, r) { + this.Qt(), + // Fast-forward delays for timerIds that have been overridden. + this.qt.indexOf(t) > -1 && (e = 0); + const n = DelayedOperation.createAndSchedule(this, t, e, r, (t => this.Mt(t))); + return this.St.push(n), n; + } + Qt() { + this.Ct && fail(47125, { + xt: __PRIVATE_getMessageOrStack(this.Ct) + }); + } + verifyOperationInProgress() {} + /** + * Waits until all currently queued tasks are finished executing. Delayed + * operations are not run. + */ async Ut() { + // Operations in the queue prior to draining may have enqueued additional + // operations. Keep draining the queue until the tail is no longer advanced, + // which indicates that no more new operations were enqueued and that all + // operations were executed. + let t; + do { + t = this.$t, await t; + } while (t !== this.$t); + } + /** + * For Tests: Determine if a delayed operation with a particular TimerId + * exists. + */ jt(t) { + for (const e of this.St) if (e.timerId === t) return !0; + return !1; + } + /** + * For Tests: Runs some or all delayed operations early. + * + * @param lastTimerId - Delayed operations up to and including this TimerId + * will be drained. Pass TimerId.All to run all delayed operations. + * @returns a Promise that resolves once all operations have been run. + */ zt(t) { + // Note that draining may generate more delayed ops, so we do that first. + return this.Ut().then((() => { + // Run ops in the same order they'd run if they ran naturally. + /* eslint-disable-next-line @typescript-eslint/no-floating-promises */ + this.St.sort(((t, e) => t.targetTimeMs - e.targetTimeMs)); + for (const e of this.St) if (e.skipDelay(), "all" /* TimerId.All */ !== t && e.timerId === t) break; + return this.Ut(); + })); + } + /** + * For Tests: Skip all subsequent delays for a timer id. + */ Wt(t) { + this.qt.push(t); + } + /** Called once a DelayedOperation is run or canceled. */ Mt(t) { + // NOTE: indexOf / slice are O(n), but delayedOperations is expected to be small. + const e = this.St.indexOf(t); + /* eslint-disable-next-line @typescript-eslint/no-floating-promises */ this.St.splice(e, 1); + } +} + +/** + * Chrome includes Error.message in Error.stack. Other browsers do not. + * This returns expected output of message + stack when available. + * @param error - Error or FirestoreError + */ +function __PRIVATE_getMessageOrStack(t) { + let e = t.message || ""; + return t.stack && (e = t.stack.includes(t.message) ? t.stack : t.message + "\n" + t.stack), + e; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// TODO(mrschmidt) Consider using `BaseTransaction` as the base class in the +// legacy SDK. +/** + * A reference to a transaction. + * + * The `Transaction` object passed to a transaction's `updateFunction` provides + * the methods to read and write data within the transaction context. See + * {@link runTransaction}. + */ class Transaction { + /** @hideconstructor */ + constructor(t, e) { + this._firestore = t, this._transaction = e, this._dataReader = __PRIVATE_newUserDataReader(t); + } + /** + * Reads the document referenced by the provided {@link DocumentReference}. + * + * @param documentRef - A reference to the document to be read. + * @returns A `DocumentSnapshot` with the read data. + */ get(t) { + const e = __PRIVATE_validateReference(t, this._firestore), r = new __PRIVATE_LiteUserDataWriter(this._firestore); + return this._transaction.lookup([ e._key ]).then((t => { + if (!t || 1 !== t.length) return fail(24041); + const n = t[0]; + if (n.isFoundDocument()) return new DocumentSnapshot(this._firestore, r, n.key, n, e.converter); + if (n.isNoDocument()) return new DocumentSnapshot(this._firestore, r, e._key, null, e.converter); + throw fail(18433, { + doc: n + }); + })); + } + set(t, e, r) { + const n = __PRIVATE_validateReference(t, this._firestore), i = __PRIVATE_applyFirestoreDataConverter(n.converter, e, r), s = __PRIVATE_parseSetData(this._dataReader, "Transaction.set", n._key, i, null !== n.converter, r); + return this._transaction.set(n._key, s), this; + } + update(t, e, r, ...n) { + const i = __PRIVATE_validateReference(t, this._firestore); + // For Compat types, we have to "extract" the underlying types before + // performing validation. + let s; + return s = "string" == typeof (e = P(e)) || e instanceof FieldPath ? __PRIVATE_parseUpdateVarargs(this._dataReader, "Transaction.update", i._key, e, r, n) : __PRIVATE_parseUpdateData(this._dataReader, "Transaction.update", i._key, e), + this._transaction.update(i._key, s), this; + } + /** + * Deletes the document referred to by the provided {@link DocumentReference}. + * + * @param documentRef - A reference to the document to be deleted. + * @returns This `Transaction` instance. Used for chaining method calls. + */ delete(t) { + const e = __PRIVATE_validateReference(t, this._firestore); + return this._transaction.delete(e._key), this; + } +} + +/** + * Executes the given `updateFunction` and then attempts to commit the changes + * applied within the transaction. If any document read within the transaction + * has changed, Cloud Firestore retries the `updateFunction`. If it fails to + * commit after 5 attempts, the transaction fails. + * + * The maximum number of writes allowed in a single transaction is 500. + * + * @param firestore - A reference to the Firestore database to run this + * transaction against. + * @param updateFunction - The function to execute within the transaction + * context. + * @param options - An options object to configure maximum number of attempts to + * commit. + * @returns If the transaction completed successfully or was explicitly aborted + * (the `updateFunction` returned a failed promise), the promise returned by the + * `updateFunction `is returned here. Otherwise, if the transaction failed, a + * rejected promise with the corresponding failure error is returned. + */ function runTransaction(t, e, r) { + const n = __PRIVATE_getDatastore(t = __PRIVATE_cast(t, Firestore)), i = { + ...mt, + ...r + }; + !function __PRIVATE_validateTransactionOptions(t) { + if (t.maxAttempts < 1) throw new FirestoreError(w, "Max attempts must be at least 1"); + }(i); + const s = new __PRIVATE_Deferred; + return new __PRIVATE_TransactionRunner(function __PRIVATE_newAsyncQueue() { + return new __PRIVATE_AsyncQueueImpl; + }(), n, i, (r => e(new Transaction(t, r))), s).yt(), s.promise; +} + +/** + * Firestore Lite + * + * @remarks Firestore Lite is a small online-only SDK that allows read + * and write access to your Firestore database. All operations connect + * directly to the backend, and `onSnapshot()` APIs are not supported. + * @packageDocumentation + */ !function __PRIVATE_registerFirestore() { + !function __PRIVATE_setSDKVersion(t) { + V = t; + }(`${s}_lite`), n(new o("firestore/lite", ((t, {instanceIdentifier: e, options: r}) => { + const n = t.getProvider("app").getImmediate(), i = new Firestore(new __PRIVATE_LiteAuthCredentialsProvider(t.getProvider("auth-internal")), new __PRIVATE_LiteAppCheckTokenProvider(n, t.getProvider("app-check-internal")), function __PRIVATE_databaseIdFromApp(t, e) { + if (!Object.prototype.hasOwnProperty.apply(t.options, [ "projectId" ])) throw new FirestoreError(w, '"projectId" not provided in firebase.initializeApp.'); + return new DatabaseId(t.options.projectId, e); + }(n, e), n); + return r && i._setSettings(r), i; + }), "PUBLIC").setMultipleInstances(!0)), + // RUNTIME_ENV and BUILD_TARGET are replaced by real values during the compilation + i("firestore-lite", R, "rn"), i("firestore-lite", R, "esm2020"); +}(); + +export { AggregateField, AggregateQuerySnapshot, Bytes, CollectionReference, DocumentReference, DocumentSnapshot, FieldPath, FieldValue, Firestore, FirestoreError, GeoPoint, Query, QueryCompositeFilterConstraint, QueryConstraint, QueryDocumentSnapshot, QueryEndAtConstraint, QueryFieldFilterConstraint, QueryLimitConstraint, QueryOrderByConstraint, QuerySnapshot, QueryStartAtConstraint, Timestamp, Transaction, VectorValue, WriteBatch, addDoc, aggregateFieldEqual, aggregateQuerySnapshotEqual, and, arrayRemove, arrayUnion, average, collection, collectionGroup, connectFirestoreEmulator, count, deleteDoc, deleteField, doc, documentId, endAt, endBefore, getAggregate, getCount, getDoc, getDocs, getFirestore, increment, initializeFirestore, limit, limitToLast, or, orderBy, query, queryEqual, refEqual, runTransaction, serverTimestamp, setDoc, setLogLevel, snapshotEqual, startAfter, startAt, sum, terminate, updateDoc, vector, where, writeBatch }; +//# sourceMappingURL=index.rn.esm.js.map diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/index.rn.esm.js.map b/frontend-old/node_modules/@firebase/firestore/dist/lite/index.rn.esm.js.map new file mode 100644 index 0000000..f2bcc16 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/index.rn.esm.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.rn.esm.js","sources":["../../src/auth/user.ts","../../src/core/version.ts","../../src/util/log.ts","../../src/platform/browser/format_json.ts","../../src/util/assert.ts","../../src/util/error.ts","../../src/util/promise.ts","../../src/api/credentials.ts","../../src/core/database_info.ts","../../src/platform/browser/random_bytes.ts","../../src/util/misc.ts","../../src/model/path.ts","../../src/model/document_key.ts","../../src/util/input_validation.ts","../../src/api/long_polling_options.ts","../../src/util/debug_uid.ts","../../src/util/types.ts","../../src/remote/rest_connection.ts","../../src/remote/rpc_error.ts","../../src/platform/browser_lite/fetch_connection.ts","../../src/core/aggregate.ts","../../src/util/obj.ts","../../src/util/base64_decode_error.ts","../../src/platform/rn/base64.ts","../../src/util/byte_string.ts","../../src/model/normalize.ts","../../src/util/json_validation.ts","../../src/lite-api/timestamp.ts","../../src/model/server_timestamps.ts","../../src/model/values.ts","../../src/core/bound.ts","../../src/core/filter.ts","../../src/core/order_by.ts","../../src/core/snapshot_version.ts","../../src/util/sorted_map.ts","../../src/util/sorted_set.ts","../../src/model/field_mask.ts","../../src/model/object_value.ts","../../src/model/document.ts","../../src/core/target.ts","../../src/core/query.ts","../../src/remote/number_serializer.ts","../../src/model/transform_operation.ts","../../src/model/mutation.ts","../../src/remote/serializer.ts","../../src/platform/browser/serializer.ts","../../src/remote/backoff.ts","../../src/remote/datastore.ts","../../src/lite-api/components.ts","../../src/platform/browser_lite/connection.ts","../../src/local/lru_garbage_collector_impl.ts","../../src/lite-api/settings.ts","../../src/local/lru_garbage_collector.ts","../../src/lite-api/database.ts","../../src/lite-api/aggregate_types.ts","../../src/lite-api/reference.ts","../../src/lite-api/bytes.ts","../../src/lite-api/field_path.ts","../../src/lite-api/field_value.ts","../../src/lite-api/geo_point.ts","../../src/lite-api/vector_value.ts","../../src/util/array.ts","../../src/lite-api/user_data_reader.ts","../../src/lite-api/snapshot.ts","../../src/lite-api/query.ts","../../src/lite-api/user_data_writer.ts","../../src/lite-api/reference_impl.ts","../../src/lite-api/aggregate.ts","../../src/lite-api/field_value_impl.ts","../../src/lite-api/write_batch.ts","../../src/core/transaction.ts","../../src/core/transaction_options.ts","../../src/core/transaction_runner.ts","../../src/platform/browser/dom.ts","../../src/util/async_queue.ts","../../src/util/async_queue_impl.ts","../../src/local/simple_db.ts","../../src/lite-api/transaction.ts","../../lite/register.ts","../../lite/index.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Simple wrapper around a nullable UID. Mostly exists to make code more\n * readable.\n */\nexport class User {\n /** A user with a null UID. */\n static readonly UNAUTHENTICATED = new User(null);\n\n // TODO(mikelehen): Look into getting a proper uid-equivalent for\n // non-FirebaseAuth providers.\n static readonly GOOGLE_CREDENTIALS = new User('google-credentials-uid');\n static readonly FIRST_PARTY = new User('first-party-uid');\n static readonly MOCK_USER = new User('mock-user');\n\n constructor(readonly uid: string | null) {}\n\n isAuthenticated(): boolean {\n return this.uid != null;\n }\n\n /**\n * Returns a key representing this user, suitable for inclusion in a\n * dictionary.\n */\n toKey(): string {\n if (this.isAuthenticated()) {\n return 'uid:' + this.uid;\n } else {\n return 'anonymous-user';\n }\n }\n\n isEqual(otherUser: User): boolean {\n return otherUser.uid === this.uid;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** The semver (www.semver.org) version of the SDK. */\nimport { version } from '../../../firebase/package.json';\nexport let SDK_VERSION = version;\nexport function setSDKVersion(version: string): void {\n SDK_VERSION = version;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Logger, LogLevel, LogLevelString } from '@firebase/logger';\n\nimport { SDK_VERSION } from '../core/version';\nimport { formatJSON } from '../platform/format_json';\n\nexport { LogLevel, LogLevelString };\n\nconst logClient = new Logger('@firebase/firestore');\n\n// Helper methods are needed because variables can't be exported as read/write\nexport function getLogLevel(): LogLevel {\n return logClient.logLevel;\n}\n\n/**\n * Sets the verbosity of Cloud Firestore logs (debug, error, or silent).\n *\n * @param logLevel - The verbosity you set for activity and error logging. Can\n * be any of the following values:\n *\n *
    \n *
  • `debug` for the most verbose logging level, primarily for\n * debugging.
  • \n *
  • `error` to log errors only.
  • \n *
  • `silent` to turn off logging.
  • \n *
\n */\nexport function setLogLevel(logLevel: LogLevelString): void {\n logClient.setLogLevel(logLevel);\n}\n\nexport function logDebug(msg: string, ...obj: unknown[]): void {\n if (logClient.logLevel <= LogLevel.DEBUG) {\n const args = obj.map(argToString);\n logClient.debug(`Firestore (${SDK_VERSION}): ${msg}`, ...args);\n }\n}\n\nexport function logError(msg: string, ...obj: unknown[]): void {\n if (logClient.logLevel <= LogLevel.ERROR) {\n const args = obj.map(argToString);\n logClient.error(`Firestore (${SDK_VERSION}): ${msg}`, ...args);\n }\n}\n\n/**\n * @internal\n */\nexport function logWarn(msg: string, ...obj: unknown[]): void {\n if (logClient.logLevel <= LogLevel.WARN) {\n const args = obj.map(argToString);\n logClient.warn(`Firestore (${SDK_VERSION}): ${msg}`, ...args);\n }\n}\n\n/**\n * Converts an additional log parameter to a string representation.\n */\nfunction argToString(obj: unknown): string | unknown {\n if (typeof obj === 'string') {\n return obj;\n } else {\n try {\n return formatJSON(obj);\n } catch (e) {\n // Converting to JSON failed, just log the object directly\n return obj;\n }\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** Formats an object as a JSON string, suitable for logging. */\nexport function formatJSON(value: unknown): string {\n return JSON.stringify(value);\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SDK_VERSION } from '../core/version';\n\nimport { logError } from './log';\n\n/**\n * Unconditionally fails, throwing an Error with the given message.\n * Messages are stripped in production builds.\n *\n * Returns `never` and can be used in expressions:\n * @example\n * let futureVar = fail('not implemented yet');\n *\n * @param code generate a new unique value with `yarn assertion-id:generate`\n * Search for an existing value using `yarn assertion-id:find X`\n */\nexport function fail(\n code: number,\n message: string,\n context?: Record\n): never;\n\n/**\n * Unconditionally fails, throwing an Error with the given message.\n * Messages are stripped in production builds.\n *\n * Returns `never` and can be used in expressions:\n * @example\n * let futureVar = fail('not implemented yet');\n *\n * @param id generate a new unique value with `yarn assertion-id:generate`\n * Search for an existing value using `yarn assertion-id:find X`\n */\nexport function fail(id: number, context?: Record): never;\n\nexport function fail(\n id: number,\n messageOrContext?: string | Record,\n context?: Record\n): never {\n let message = 'Unexpected state';\n if (typeof messageOrContext === 'string') {\n message = messageOrContext;\n } else {\n context = messageOrContext;\n }\n _fail(id, message, context);\n}\n\nfunction _fail(\n id: number,\n failure: string,\n context?: Record\n): never {\n // Log the failure in addition to throw an exception, just in case the\n // exception is swallowed.\n let message = `FIRESTORE (${SDK_VERSION}) INTERNAL ASSERTION FAILED: ${failure} (ID: ${id.toString(\n 16\n )})`;\n if (context !== undefined) {\n try {\n const stringContext = JSON.stringify(context);\n message += ' CONTEXT: ' + stringContext;\n } catch (e) {\n message += ' CONTEXT: ' + context;\n }\n }\n logError(message);\n\n // NOTE: We don't use FirestoreError here because these are internal failures\n // that cannot be handled by the user. (Also it would create a circular\n // dependency between the error and assert modules which doesn't work.)\n throw new Error(message);\n}\n\n/**\n * Fails if the given assertion condition is false, throwing an Error with the\n * given message if it did.\n *\n * Messages are stripped in production builds.\n *\n * @param id generate a new unique value with `yarn assertion-idgenerate`.\n * Search for an existing value using `yarn assertion-id:find X`\n */\nexport function hardAssert(\n assertion: boolean,\n id: number,\n message: string,\n context?: Record\n): asserts assertion;\n\n/**\n * Fails if the given assertion condition is false, throwing an Error with the\n * given message if it did.\n *\n * Messages are stripped in production builds.\n *\n * @param id generate a new unique value with `yarn assertion-id:generate`.\n * Search for an existing value using `yarn assertion-id:find X`\n */\nexport function hardAssert(\n assertion: boolean,\n id: number,\n context?: Record\n): asserts assertion;\n\nexport function hardAssert(\n assertion: boolean,\n id: number,\n messageOrContext?: string | Record,\n context?: Record\n): asserts assertion {\n let message = 'Unexpected state';\n if (typeof messageOrContext === 'string') {\n message = messageOrContext;\n } else {\n context = messageOrContext;\n }\n\n if (!assertion) {\n _fail(id, message, context);\n }\n}\n\n/**\n * Fails if the given assertion condition is false, throwing an Error with the\n * given message if it did.\n *\n * The code of callsites invoking this function are stripped out in production\n * builds. Any side-effects of code within the debugAssert() invocation will not\n * happen in this case.\n *\n * @internal\n */\nexport function debugAssert(\n assertion: boolean,\n message: string\n): asserts assertion {\n if (!assertion) {\n fail(0xdeb6, message);\n }\n}\n\n/**\n * Casts `obj` to `T`. In non-production builds, verifies that `obj` is an\n * instance of `T` before casting.\n */\nexport function debugCast(\n obj: object,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n constructor: { new (...args: any[]): T }\n): T | never {\n debugAssert(\n obj instanceof constructor,\n `Expected type '${constructor.name}', but was '${obj.constructor.name}'`\n );\n return obj as T;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseError } from '@firebase/util';\n\n/**\n * The set of Firestore status codes. The codes are the same at the ones\n * exposed by gRPC here:\n * https://github.com/grpc/grpc/blob/master/doc/statuscodes.md\n *\n * Possible values:\n * - 'cancelled': The operation was cancelled (typically by the caller).\n * - 'unknown': Unknown error or an error from a different error domain.\n * - 'invalid-argument': Client specified an invalid argument. Note that this\n * differs from 'failed-precondition'. 'invalid-argument' indicates\n * arguments that are problematic regardless of the state of the system\n * (e.g. an invalid field name).\n * - 'deadline-exceeded': Deadline expired before operation could complete.\n * For operations that change the state of the system, this error may be\n * returned even if the operation has completed successfully. For example,\n * a successful response from a server could have been delayed long enough\n * for the deadline to expire.\n * - 'not-found': Some requested document was not found.\n * - 'already-exists': Some document that we attempted to create already\n * exists.\n * - 'permission-denied': The caller does not have permission to execute the\n * specified operation.\n * - 'resource-exhausted': Some resource has been exhausted, perhaps a\n * per-user quota, or perhaps the entire file system is out of space.\n * - 'failed-precondition': Operation was rejected because the system is not\n * in a state required for the operation's execution.\n * - 'aborted': The operation was aborted, typically due to a concurrency\n * issue like transaction aborts, etc.\n * - 'out-of-range': Operation was attempted past the valid range.\n * - 'unimplemented': Operation is not implemented or not supported/enabled.\n * - 'internal': Internal errors. Means some invariants expected by\n * underlying system has been broken. If you see one of these errors,\n * something is very broken.\n * - 'unavailable': The service is currently unavailable. This is most likely\n * a transient condition and may be corrected by retrying with a backoff.\n * - 'data-loss': Unrecoverable data loss or corruption.\n * - 'unauthenticated': The request does not have valid authentication\n * credentials for the operation.\n */\nexport type FirestoreErrorCode =\n | 'cancelled'\n | 'unknown'\n | 'invalid-argument'\n | 'deadline-exceeded'\n | 'not-found'\n | 'already-exists'\n | 'permission-denied'\n | 'resource-exhausted'\n | 'failed-precondition'\n | 'aborted'\n | 'out-of-range'\n | 'unimplemented'\n | 'internal'\n | 'unavailable'\n | 'data-loss'\n | 'unauthenticated';\n\n/**\n * Error Codes describing the different ways Firestore can fail. These come\n * directly from GRPC.\n */\nexport type Code = FirestoreErrorCode;\n\nexport const Code = {\n // Causes are copied from:\n // https://github.com/grpc/grpc/blob/bceec94ea4fc5f0085d81235d8e1c06798dc341a/include/grpc%2B%2B/impl/codegen/status_code_enum.h\n /** Not an error; returned on success. */\n OK: 'ok' as FirestoreErrorCode,\n\n /** The operation was cancelled (typically by the caller). */\n CANCELLED: 'cancelled' as FirestoreErrorCode,\n\n /** Unknown error or an error from a different error domain. */\n UNKNOWN: 'unknown' as FirestoreErrorCode,\n\n /**\n * Client specified an invalid argument. Note that this differs from\n * FAILED_PRECONDITION. INVALID_ARGUMENT indicates arguments that are\n * problematic regardless of the state of the system (e.g., a malformed file\n * name).\n */\n INVALID_ARGUMENT: 'invalid-argument' as FirestoreErrorCode,\n\n /**\n * Deadline expired before operation could complete. For operations that\n * change the state of the system, this error may be returned even if the\n * operation has completed successfully. For example, a successful response\n * from a server could have been delayed long enough for the deadline to\n * expire.\n */\n DEADLINE_EXCEEDED: 'deadline-exceeded' as FirestoreErrorCode,\n\n /** Some requested entity (e.g., file or directory) was not found. */\n NOT_FOUND: 'not-found' as FirestoreErrorCode,\n\n /**\n * Some entity that we attempted to create (e.g., file or directory) already\n * exists.\n */\n ALREADY_EXISTS: 'already-exists' as FirestoreErrorCode,\n\n /**\n * The caller does not have permission to execute the specified operation.\n * PERMISSION_DENIED must not be used for rejections caused by exhausting\n * some resource (use RESOURCE_EXHAUSTED instead for those errors).\n * PERMISSION_DENIED must not be used if the caller cannot be identified\n * (use UNAUTHENTICATED instead for those errors).\n */\n PERMISSION_DENIED: 'permission-denied' as FirestoreErrorCode,\n\n /**\n * The request does not have valid authentication credentials for the\n * operation.\n */\n UNAUTHENTICATED: 'unauthenticated' as FirestoreErrorCode,\n\n /**\n * Some resource has been exhausted, perhaps a per-user quota, or perhaps the\n * entire file system is out of space.\n */\n RESOURCE_EXHAUSTED: 'resource-exhausted' as FirestoreErrorCode,\n\n /**\n * Operation was rejected because the system is not in a state required for\n * the operation's execution. For example, directory to be deleted may be\n * non-empty, an rmdir operation is applied to a non-directory, etc.\n *\n * A litmus test that may help a service implementor in deciding\n * between FAILED_PRECONDITION, ABORTED, and UNAVAILABLE:\n * (a) Use UNAVAILABLE if the client can retry just the failing call.\n * (b) Use ABORTED if the client should retry at a higher-level\n * (e.g., restarting a read-modify-write sequence).\n * (c) Use FAILED_PRECONDITION if the client should not retry until\n * the system state has been explicitly fixed. E.g., if an \"rmdir\"\n * fails because the directory is non-empty, FAILED_PRECONDITION\n * should be returned since the client should not retry unless\n * they have first fixed up the directory by deleting files from it.\n * (d) Use FAILED_PRECONDITION if the client performs conditional\n * REST Get/Update/Delete on a resource and the resource on the\n * server does not match the condition. E.g., conflicting\n * read-modify-write on the same resource.\n */\n FAILED_PRECONDITION: 'failed-precondition' as FirestoreErrorCode,\n\n /**\n * The operation was aborted, typically due to a concurrency issue like\n * sequencer check failures, transaction aborts, etc.\n *\n * See litmus test above for deciding between FAILED_PRECONDITION, ABORTED,\n * and UNAVAILABLE.\n */\n ABORTED: 'aborted' as FirestoreErrorCode,\n\n /**\n * Operation was attempted past the valid range. E.g., seeking or reading\n * past end of file.\n *\n * Unlike INVALID_ARGUMENT, this error indicates a problem that may be fixed\n * if the system state changes. For example, a 32-bit file system will\n * generate INVALID_ARGUMENT if asked to read at an offset that is not in the\n * range [0,2^32-1], but it will generate OUT_OF_RANGE if asked to read from\n * an offset past the current file size.\n *\n * There is a fair bit of overlap between FAILED_PRECONDITION and\n * OUT_OF_RANGE. We recommend using OUT_OF_RANGE (the more specific error)\n * when it applies so that callers who are iterating through a space can\n * easily look for an OUT_OF_RANGE error to detect when they are done.\n */\n OUT_OF_RANGE: 'out-of-range' as FirestoreErrorCode,\n\n /** Operation is not implemented or not supported/enabled in this service. */\n UNIMPLEMENTED: 'unimplemented' as FirestoreErrorCode,\n\n /**\n * Internal errors. Means some invariants expected by underlying System has\n * been broken. If you see one of these errors, Something is very broken.\n */\n INTERNAL: 'internal' as FirestoreErrorCode,\n\n /**\n * The service is currently unavailable. This is a most likely a transient\n * condition and may be corrected by retrying with a backoff.\n *\n * See litmus test above for deciding between FAILED_PRECONDITION, ABORTED,\n * and UNAVAILABLE.\n */\n UNAVAILABLE: 'unavailable' as FirestoreErrorCode,\n\n /** Unrecoverable data loss or corruption. */\n DATA_LOSS: 'data-loss' as FirestoreErrorCode\n};\n\n/** An error returned by a Firestore operation. */\nexport class FirestoreError extends FirebaseError {\n /** The stack of the error. */\n readonly stack?: string;\n\n /** @hideconstructor */\n constructor(\n /**\n * The backend error code associated with this error.\n */\n readonly code: FirestoreErrorCode,\n /**\n * A custom error description.\n */\n readonly message: string\n ) {\n super(code, message);\n\n // HACK: We write a toString property directly because Error is not a real\n // class and so inheritance does not work correctly. We could alternatively\n // do the same \"back-door inheritance\" trick that FirebaseError does.\n this.toString = () => `${this.name}: [code=${this.code}]: ${this.message}`;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport interface Resolver {\n (value: R | Promise): void;\n}\n\nexport interface Rejecter {\n (reason?: Error): void;\n}\n\nexport class Deferred {\n promise: Promise;\n // Assigned synchronously in constructor by Promise constructor callback.\n resolve!: Resolver;\n reject!: Rejecter;\n\n constructor() {\n this.promise = new Promise((resolve: Resolver, reject: Rejecter) => {\n this.resolve = resolve;\n this.reject = reject;\n });\n }\n}\n\n/**\n * Takes an array of values and a function from a value to a Promise. The function is run on each\n * value sequentially, waiting for the previous promise to resolve before starting the next one.\n * The returned promise resolves once the function has been run on all values.\n */\nexport function sequence(\n values: T[],\n fn: (value: T) => Promise\n): Promise {\n let p = Promise.resolve();\n for (const value of values) {\n p = p.then(() => fn(value));\n }\n return p;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseApp, _isFirebaseServerApp } from '@firebase/app';\nimport {\n AppCheckInternalComponentName,\n AppCheckTokenListener,\n AppCheckTokenResult,\n FirebaseAppCheckInternal\n} from '@firebase/app-check-interop-types';\nimport {\n FirebaseAuthInternal,\n FirebaseAuthInternalName\n} from '@firebase/auth-interop-types';\nimport { Provider } from '@firebase/component';\n\nimport { User } from '../auth/user';\nimport { debugAssert, hardAssert } from '../util/assert';\nimport { AsyncQueue } from '../util/async_queue';\nimport { Code, FirestoreError } from '../util/error';\nimport { logDebug } from '../util/log';\nimport { Deferred } from '../util/promise';\n\n// TODO(mikelehen): This should be split into multiple files and probably\n// moved to an auth/ folder to match other platforms.\n\n/**\n * @internal\n */\nexport type AuthTokenFactory = () => string;\n\n/**\n * @internal\n */\nexport interface FirstPartyCredentialsSettings {\n // These are external types. Prevent minification.\n ['type']: 'firstParty';\n ['sessionIndex']: string;\n ['iamToken']: string | null;\n ['authTokenFactory']: AuthTokenFactory | null;\n}\n\nexport interface ProviderCredentialsSettings {\n // These are external types. Prevent minification.\n ['type']: 'provider';\n ['client']: CredentialsProvider;\n}\n\n/** Settings for private credentials */\nexport type CredentialsSettings =\n | FirstPartyCredentialsSettings\n | ProviderCredentialsSettings;\n\nexport type TokenType = 'OAuth' | 'FirstParty' | 'AppCheck';\nexport interface Token {\n /** Type of token. */\n type: TokenType;\n\n /**\n * The user with which the token is associated (used for persisting user\n * state on disk, etc.).\n * This will be null for Tokens of the type 'AppCheck'.\n */\n user?: User;\n\n /** Header values to set for this token */\n headers: Map;\n}\n\nexport class OAuthToken implements Token {\n type = 'OAuth' as TokenType;\n headers = new Map();\n\n constructor(value: string, public user: User) {\n this.headers.set('Authorization', `Bearer ${value}`);\n }\n}\n\n/**\n * A Listener for credential change events. The listener should fetch a new\n * token and may need to invalidate other state if the current user has also\n * changed.\n */\nexport type CredentialChangeListener = (credential: T) => Promise;\n\n/**\n * Provides methods for getting the uid and token for the current user and\n * listening for changes.\n */\nexport interface CredentialsProvider {\n /**\n * Starts the credentials provider and specifies a listener to be notified of\n * credential changes (sign-in / sign-out, token changes). It is immediately\n * called once with the initial user.\n *\n * The change listener is invoked on the provided AsyncQueue.\n */\n start(\n asyncQueue: AsyncQueue,\n changeListener: CredentialChangeListener\n ): void;\n\n /** Requests a token for the current user. */\n getToken(): Promise;\n\n /**\n * Marks the last retrieved token as invalid, making the next GetToken request\n * force-refresh the token.\n */\n invalidateToken(): void;\n\n shutdown(): void;\n}\n\n/**\n * A CredentialsProvider that always yields an empty token.\n * @internal\n */\nexport class EmptyAuthCredentialsProvider implements CredentialsProvider {\n getToken(): Promise {\n return Promise.resolve(null);\n }\n\n invalidateToken(): void {}\n\n start(\n asyncQueue: AsyncQueue,\n changeListener: CredentialChangeListener\n ): void {\n // Fire with initial user.\n asyncQueue.enqueueRetryable(() => changeListener(User.UNAUTHENTICATED));\n }\n\n shutdown(): void {}\n}\n\n/**\n * A CredentialsProvider that always returns a constant token. Used for\n * emulator token mocking.\n */\nexport class EmulatorAuthCredentialsProvider\n implements CredentialsProvider\n{\n constructor(private token: Token) {}\n\n /**\n * Stores the listener registered with setChangeListener()\n * This isn't actually necessary since the UID never changes, but we use this\n * to verify the listen contract is adhered to in tests.\n */\n private changeListener: CredentialChangeListener | null = null;\n\n getToken(): Promise {\n return Promise.resolve(this.token);\n }\n\n invalidateToken(): void {}\n\n start(\n asyncQueue: AsyncQueue,\n changeListener: CredentialChangeListener\n ): void {\n debugAssert(\n !this.changeListener,\n 'Can only call setChangeListener() once.'\n );\n this.changeListener = changeListener;\n // Fire with initial user.\n asyncQueue.enqueueRetryable(() => changeListener(this.token.user!));\n }\n\n shutdown(): void {\n this.changeListener = null;\n }\n}\n\n/** Credential provider for the Lite SDK. */\nexport class LiteAuthCredentialsProvider implements CredentialsProvider {\n private auth: FirebaseAuthInternal | null = null;\n\n constructor(authProvider: Provider) {\n authProvider.onInit(auth => {\n this.auth = auth;\n });\n }\n\n getToken(): Promise {\n if (!this.auth) {\n return Promise.resolve(null);\n }\n\n return this.auth.getToken().then(tokenData => {\n if (tokenData) {\n hardAssert(\n typeof tokenData.accessToken === 'string',\n 0xa539,\n 'Invalid tokenData returned from getToken()',\n { tokenData }\n );\n return new OAuthToken(\n tokenData.accessToken,\n new User(this.auth!.getUid())\n );\n } else {\n return null;\n }\n });\n }\n\n invalidateToken(): void {}\n\n start(\n asyncQueue: AsyncQueue,\n changeListener: CredentialChangeListener\n ): void {}\n\n shutdown(): void {}\n}\n\nexport class FirebaseAuthCredentialsProvider\n implements CredentialsProvider\n{\n /**\n * The auth token listener registered with FirebaseApp, retained here so we\n * can unregister it.\n */\n private tokenListener: (() => void) | undefined;\n\n /** Tracks the current User. */\n private currentUser: User = User.UNAUTHENTICATED;\n\n /**\n * Counter used to detect if the token changed while a getToken request was\n * outstanding.\n */\n private tokenCounter = 0;\n\n private forceRefresh = false;\n\n private auth: FirebaseAuthInternal | null = null;\n\n constructor(private authProvider: Provider) {}\n\n start(\n asyncQueue: AsyncQueue,\n changeListener: CredentialChangeListener\n ): void {\n hardAssert(\n this.tokenListener === undefined,\n 0xa540,\n 'Token listener already added'\n );\n let lastTokenId = this.tokenCounter;\n\n // A change listener that prevents double-firing for the same token change.\n const guardedChangeListener: (user: User) => Promise = user => {\n if (this.tokenCounter !== lastTokenId) {\n lastTokenId = this.tokenCounter;\n return changeListener(user);\n } else {\n return Promise.resolve();\n }\n };\n\n // A promise that can be waited on to block on the next token change.\n // This promise is re-created after each change.\n let nextToken = new Deferred();\n\n this.tokenListener = () => {\n this.tokenCounter++;\n this.currentUser = this.getUser();\n nextToken.resolve();\n nextToken = new Deferred();\n asyncQueue.enqueueRetryable(() =>\n guardedChangeListener(this.currentUser)\n );\n };\n\n const awaitNextToken: () => void = () => {\n const currentTokenAttempt = nextToken;\n asyncQueue.enqueueRetryable(async () => {\n await currentTokenAttempt.promise;\n await guardedChangeListener(this.currentUser);\n });\n };\n\n const registerAuth = (auth: FirebaseAuthInternal): void => {\n logDebug('FirebaseAuthCredentialsProvider', 'Auth detected');\n this.auth = auth;\n if (this.tokenListener) {\n this.auth.addAuthTokenListener(this.tokenListener);\n awaitNextToken();\n }\n };\n\n this.authProvider.onInit(auth => registerAuth(auth));\n\n // Our users can initialize Auth right after Firestore, so we give it\n // a chance to register itself with the component framework before we\n // determine whether to start up in unauthenticated mode.\n setTimeout(() => {\n if (!this.auth) {\n const auth = this.authProvider.getImmediate({ optional: true });\n if (auth) {\n registerAuth(auth);\n } else {\n // If auth is still not available, proceed with `null` user\n logDebug('FirebaseAuthCredentialsProvider', 'Auth not yet detected');\n nextToken.resolve();\n nextToken = new Deferred();\n }\n }\n }, 0);\n\n awaitNextToken();\n }\n\n getToken(): Promise {\n debugAssert(\n this.tokenListener != null,\n 'FirebaseAuthCredentialsProvider not started.'\n );\n\n // Take note of the current value of the tokenCounter so that this method\n // can fail (with an ABORTED error) if there is a token change while the\n // request is outstanding.\n const initialTokenCounter = this.tokenCounter;\n const forceRefresh = this.forceRefresh;\n this.forceRefresh = false;\n\n if (!this.auth) {\n return Promise.resolve(null);\n }\n\n return this.auth.getToken(forceRefresh).then(tokenData => {\n // Cancel the request since the token changed while the request was\n // outstanding so the response is potentially for a previous user (which\n // user, we can't be sure).\n if (this.tokenCounter !== initialTokenCounter) {\n logDebug(\n 'FirebaseAuthCredentialsProvider',\n 'getToken aborted due to token change.'\n );\n return this.getToken();\n } else {\n if (tokenData) {\n hardAssert(\n typeof tokenData.accessToken === 'string',\n 0x7c5d,\n 'Invalid tokenData returned from getToken()',\n { tokenData }\n );\n return new OAuthToken(tokenData.accessToken, this.currentUser);\n } else {\n return null;\n }\n }\n });\n }\n\n invalidateToken(): void {\n this.forceRefresh = true;\n }\n\n shutdown(): void {\n if (this.auth && this.tokenListener) {\n this.auth.removeAuthTokenListener(this.tokenListener);\n }\n this.tokenListener = undefined;\n }\n\n // Auth.getUid() can return null even with a user logged in. It is because\n // getUid() is synchronous, but the auth code populating Uid is asynchronous.\n // This method should only be called in the AuthTokenListener callback\n // to guarantee to get the actual user.\n private getUser(): User {\n const currentUid = this.auth && this.auth.getUid();\n hardAssert(\n currentUid === null || typeof currentUid === 'string',\n 0x0807,\n 'Received invalid UID',\n { currentUid }\n );\n return new User(currentUid);\n }\n}\n\n/*\n * FirstPartyToken provides a fresh token each time its value\n * is requested, because if the token is too old, requests will be rejected.\n * Technically this may no longer be necessary since the SDK should gracefully\n * recover from unauthenticated errors (see b/33147818 for context), but it's\n * safer to keep the implementation as-is.\n */\nexport class FirstPartyToken implements Token {\n type = 'FirstParty' as TokenType;\n user = User.FIRST_PARTY;\n private _headers = new Map();\n\n constructor(\n private readonly sessionIndex: string,\n private readonly iamToken: string | null,\n private readonly authTokenFactory: AuthTokenFactory | null\n ) {}\n\n /**\n * Gets an authorization token, using a provided factory function, or return\n * null.\n */\n private getAuthToken(): string | null {\n if (this.authTokenFactory) {\n return this.authTokenFactory();\n } else {\n return null;\n }\n }\n\n get headers(): Map {\n this._headers.set('X-Goog-AuthUser', this.sessionIndex);\n // Use array notation to prevent minification\n const authHeaderTokenValue = this.getAuthToken();\n if (authHeaderTokenValue) {\n this._headers.set('Authorization', authHeaderTokenValue);\n }\n if (this.iamToken) {\n this._headers.set('X-Goog-Iam-Authorization-Token', this.iamToken);\n }\n\n return this._headers;\n }\n}\n\n/*\n * Provides user credentials required for the Firestore JavaScript SDK\n * to authenticate the user, using technique that is only available\n * to applications hosted by Google.\n */\nexport class FirstPartyAuthCredentialsProvider\n implements CredentialsProvider\n{\n constructor(\n private sessionIndex: string,\n private iamToken: string | null,\n private authTokenFactory: AuthTokenFactory | null\n ) {}\n\n getToken(): Promise {\n return Promise.resolve(\n new FirstPartyToken(\n this.sessionIndex,\n this.iamToken,\n this.authTokenFactory\n )\n );\n }\n\n start(\n asyncQueue: AsyncQueue,\n changeListener: CredentialChangeListener\n ): void {\n // Fire with initial uid.\n asyncQueue.enqueueRetryable(() => changeListener(User.FIRST_PARTY));\n }\n\n shutdown(): void {}\n\n invalidateToken(): void {}\n}\n\nexport class AppCheckToken implements Token {\n type = 'AppCheck' as TokenType;\n headers = new Map();\n\n constructor(private value: string) {\n if (value && value.length > 0) {\n this.headers.set('x-firebase-appcheck', this.value);\n }\n }\n}\n\nexport class FirebaseAppCheckTokenProvider\n implements CredentialsProvider\n{\n /**\n * The AppCheck token listener registered with FirebaseApp, retained here so\n * we can unregister it.\n */\n private tokenListener: AppCheckTokenListener | undefined;\n private forceRefresh = false;\n private appCheck: FirebaseAppCheckInternal | null = null;\n private latestAppCheckToken: string | null = null;\n private serverAppAppCheckToken: string | null = null;\n\n constructor(\n app: FirebaseApp,\n private appCheckProvider: Provider\n ) {\n if (_isFirebaseServerApp(app) && app.settings.appCheckToken) {\n this.serverAppAppCheckToken = app.settings.appCheckToken;\n }\n }\n\n start(\n asyncQueue: AsyncQueue,\n changeListener: CredentialChangeListener\n ): void {\n hardAssert(\n this.tokenListener === undefined,\n 0x0db8,\n 'Token listener already added'\n );\n\n const onTokenChanged: (\n tokenResult: AppCheckTokenResult\n ) => Promise = tokenResult => {\n if (tokenResult.error != null) {\n logDebug(\n 'FirebaseAppCheckTokenProvider',\n `Error getting App Check token; using placeholder token instead. Error: ${tokenResult.error.message}`\n );\n }\n const tokenUpdated = tokenResult.token !== this.latestAppCheckToken;\n this.latestAppCheckToken = tokenResult.token;\n logDebug(\n 'FirebaseAppCheckTokenProvider',\n `Received ${tokenUpdated ? 'new' : 'existing'} token.`\n );\n return tokenUpdated\n ? changeListener(tokenResult.token)\n : Promise.resolve();\n };\n\n this.tokenListener = (tokenResult: AppCheckTokenResult) => {\n asyncQueue.enqueueRetryable(() => onTokenChanged(tokenResult));\n };\n\n const registerAppCheck = (appCheck: FirebaseAppCheckInternal): void => {\n logDebug('FirebaseAppCheckTokenProvider', 'AppCheck detected');\n this.appCheck = appCheck;\n if (this.tokenListener) {\n this.appCheck.addTokenListener(this.tokenListener);\n }\n };\n\n this.appCheckProvider.onInit(appCheck => registerAppCheck(appCheck));\n\n // Our users can initialize AppCheck after Firestore, so we give it\n // a chance to register itself with the component framework.\n setTimeout(() => {\n if (!this.appCheck) {\n const appCheck = this.appCheckProvider.getImmediate({ optional: true });\n if (appCheck) {\n registerAppCheck(appCheck);\n } else {\n // If AppCheck is still not available, proceed without it.\n logDebug(\n 'FirebaseAppCheckTokenProvider',\n 'AppCheck not yet detected'\n );\n }\n }\n }, 0);\n }\n\n getToken(): Promise {\n if (this.serverAppAppCheckToken) {\n return Promise.resolve(new AppCheckToken(this.serverAppAppCheckToken));\n }\n debugAssert(\n this.tokenListener != null,\n 'FirebaseAppCheckTokenProvider not started.'\n );\n\n const forceRefresh = this.forceRefresh;\n this.forceRefresh = false;\n\n if (!this.appCheck) {\n return Promise.resolve(null);\n }\n\n return this.appCheck.getToken(forceRefresh).then(tokenResult => {\n if (tokenResult) {\n hardAssert(\n typeof tokenResult.token === 'string',\n 0xae0e,\n 'Invalid tokenResult returned from getToken()',\n { tokenResult }\n );\n this.latestAppCheckToken = tokenResult.token;\n return new AppCheckToken(tokenResult.token);\n } else {\n return null;\n }\n });\n }\n\n invalidateToken(): void {\n this.forceRefresh = true;\n }\n\n shutdown(): void {\n if (this.appCheck && this.tokenListener) {\n this.appCheck.removeTokenListener(this.tokenListener);\n }\n this.tokenListener = undefined;\n }\n}\n\n/**\n * An AppCheck token provider that always yields an empty token.\n * @internal\n */\nexport class EmptyAppCheckTokenProvider implements CredentialsProvider {\n getToken(): Promise {\n return Promise.resolve(new AppCheckToken(''));\n }\n\n invalidateToken(): void {}\n\n start(\n asyncQueue: AsyncQueue,\n changeListener: CredentialChangeListener\n ): void {}\n\n shutdown(): void {}\n}\n\n/** AppCheck token provider for the Lite SDK. */\nexport class LiteAppCheckTokenProvider implements CredentialsProvider {\n private appCheck: FirebaseAppCheckInternal | null = null;\n private serverAppAppCheckToken: string | null = null;\n\n constructor(\n app: FirebaseApp,\n private appCheckProvider: Provider\n ) {\n if (_isFirebaseServerApp(app) && app.settings.appCheckToken) {\n this.serverAppAppCheckToken = app.settings.appCheckToken;\n }\n appCheckProvider.onInit(appCheck => {\n this.appCheck = appCheck;\n });\n }\n\n getToken(): Promise {\n if (this.serverAppAppCheckToken) {\n return Promise.resolve(new AppCheckToken(this.serverAppAppCheckToken));\n }\n\n if (!this.appCheck) {\n return Promise.resolve(null);\n }\n\n return this.appCheck.getToken().then(tokenResult => {\n if (tokenResult) {\n hardAssert(\n typeof tokenResult.token === 'string',\n 0x0d8e,\n 'Invalid tokenResult returned from getToken()',\n { tokenResult }\n );\n return new AppCheckToken(tokenResult.token);\n } else {\n return null;\n }\n });\n }\n\n invalidateToken(): void {}\n\n start(\n asyncQueue: AsyncQueue,\n changeListener: CredentialChangeListener\n ): void {}\n\n shutdown(): void {}\n}\n\n/**\n * Builds a CredentialsProvider depending on the type of\n * the credentials passed in.\n */\nexport function makeAuthCredentialsProvider(\n credentials?: CredentialsSettings\n): CredentialsProvider {\n if (!credentials) {\n return new EmptyAuthCredentialsProvider();\n }\n switch (credentials['type']) {\n case 'firstParty':\n return new FirstPartyAuthCredentialsProvider(\n credentials['sessionIndex'] || '0',\n credentials['iamToken'] || null,\n credentials['authTokenFactory'] || null\n );\n\n case 'provider':\n return credentials['client'];\n\n default:\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'makeAuthCredentialsProvider failed due to invalid credential type'\n );\n }\n}\n","import { FirebaseApp } from '@firebase/app';\n\nimport { ExperimentalLongPollingOptions } from '../api/long_polling_options';\nimport { Code, FirestoreError } from '../util/error';\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport class DatabaseInfo {\n /**\n * Constructs a DatabaseInfo using the provided host, databaseId and\n * persistenceKey.\n *\n * @param databaseId - The database to use.\n * @param appId - The Firebase App Id.\n * @param persistenceKey - A unique identifier for this Firestore's local\n * storage (used in conjunction with the databaseId).\n * @param host - The Firestore backend host to connect to.\n * @param ssl - Whether to use SSL when connecting.\n * @param forceLongPolling - Whether to use the forceLongPolling option\n * when using WebChannel as the network transport.\n * @param autoDetectLongPolling - Whether to use the detectBufferingProxy\n * option when using WebChannel as the network transport.\n * @param longPollingOptions Options that configure long-polling.\n * @param useFetchStreams Whether to use the Fetch API instead of\n * XMLHTTPRequest\n */\n constructor(\n readonly databaseId: DatabaseId,\n readonly appId: string,\n readonly persistenceKey: string,\n readonly host: string,\n readonly ssl: boolean,\n readonly forceLongPolling: boolean,\n readonly autoDetectLongPolling: boolean,\n readonly longPollingOptions: ExperimentalLongPollingOptions,\n readonly useFetchStreams: boolean,\n readonly isUsingEmulator: boolean\n ) {}\n}\n\n/** The default database name for a project. */\nexport const DEFAULT_DATABASE_NAME = '(default)';\n\n/**\n * Represents the database ID a Firestore client is associated with.\n * @internal\n */\nexport class DatabaseId {\n readonly database: string;\n constructor(readonly projectId: string, database?: string) {\n this.database = database ? database : DEFAULT_DATABASE_NAME;\n }\n\n static empty(): DatabaseId {\n return new DatabaseId('', '');\n }\n\n get isDefaultDatabase(): boolean {\n return this.database === DEFAULT_DATABASE_NAME;\n }\n\n isEqual(other: {}): boolean {\n return (\n other instanceof DatabaseId &&\n other.projectId === this.projectId &&\n other.database === this.database\n );\n }\n}\n\nexport function databaseIdFromApp(\n app: FirebaseApp,\n database?: string\n): DatabaseId {\n if (!Object.prototype.hasOwnProperty.apply(app.options, ['projectId'])) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n '\"projectId\" not provided in firebase.initializeApp.'\n );\n }\n\n return new DatabaseId(app.options.projectId!, database);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { debugAssert } from '../../util/assert';\n\n/**\n * Generates `nBytes` of random bytes.\n *\n * If `nBytes < 0` , an error will be thrown.\n */\nexport function randomBytes(nBytes: number): Uint8Array {\n debugAssert(nBytes >= 0, `Expecting non-negative nBytes, got: ${nBytes}`);\n\n // Polyfills for IE and WebWorker by using `self` and `msCrypto` when `crypto` is not available.\n const crypto =\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n typeof self !== 'undefined' && (self.crypto || (self as any)['msCrypto']);\n const bytes = new Uint8Array(nBytes);\n if (crypto && typeof crypto.getRandomValues === 'function') {\n crypto.getRandomValues(bytes);\n } else {\n // Falls back to Math.random\n for (let i = 0; i < nBytes; i++) {\n bytes[i] = Math.floor(Math.random() * 256);\n }\n }\n return bytes;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { randomBytes } from '../platform/random_bytes';\n\nimport { debugAssert } from './assert';\n\nexport type EventHandler = (value: E) => void;\nexport interface Indexable {\n [k: string]: unknown;\n}\n\n/**\n * A utility class for generating unique alphanumeric IDs of a specified length.\n *\n * @internal\n * Exported internally for testing purposes.\n */\nexport class AutoId {\n static newId(): string {\n // Alphanumeric characters\n const chars =\n 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';\n // The largest byte value that is a multiple of `char.length`.\n const maxMultiple = Math.floor(256 / chars.length) * chars.length;\n debugAssert(\n 0 < maxMultiple && maxMultiple < 256,\n `Expect maxMultiple to be (0, 256), but got ${maxMultiple}`\n );\n\n let autoId = '';\n const targetLength = 20;\n while (autoId.length < targetLength) {\n const bytes = randomBytes(40);\n for (let i = 0; i < bytes.length; ++i) {\n // Only accept values that are [0, maxMultiple), this ensures they can\n // be evenly mapped to indices of `chars` via a modulo operation.\n if (autoId.length < targetLength && bytes[i] < maxMultiple) {\n autoId += chars.charAt(bytes[i] % chars.length);\n }\n }\n }\n debugAssert(autoId.length === targetLength, 'Invalid auto ID: ' + autoId);\n\n return autoId;\n }\n}\n\nexport function primitiveComparator(left: T, right: T): number {\n if (left < right) {\n return -1;\n }\n if (left > right) {\n return 1;\n }\n return 0;\n}\n\nexport interface Equatable {\n isEqual(other: T): boolean;\n}\n\n/** Compare strings in UTF-8 encoded byte order */\nexport function compareUtf8Strings(left: string, right: string): number {\n // Find the first differing character (a.k.a. \"UTF-16 code unit\") in the two strings and,\n // if found, use that character to determine the relative ordering of the two strings as a\n // whole. Comparing UTF-16 strings in UTF-8 byte order can be done simply and efficiently by\n // comparing the UTF-16 code units (chars). This serendipitously works because of the way UTF-8\n // and UTF-16 happen to represent Unicode code points.\n //\n // After finding the first pair of differing characters, there are two cases:\n //\n // Case 1: Both characters are non-surrogates (code points less than or equal to 0xFFFF) or\n // both are surrogates from a surrogate pair (that collectively represent code points greater\n // than 0xFFFF). In this case their numeric order as UTF-16 code units is the same as the\n // lexicographical order of their corresponding UTF-8 byte sequences. A direct comparison is\n // sufficient.\n //\n // Case 2: One character is a surrogate and the other is not. In this case the surrogate-\n // containing string is always ordered after the non-surrogate. This is because surrogates are\n // used to represent code points greater than 0xFFFF which have 4-byte UTF-8 representations\n // and are lexicographically greater than the 1, 2, or 3-byte representations of code points\n // less than or equal to 0xFFFF.\n //\n // An example of why Case 2 is required is comparing the following two Unicode code points:\n //\n // |-----------------------|------------|---------------------|-----------------|\n // | Name | Code Point | UTF-8 Encoding | UTF-16 Encoding |\n // |-----------------------|------------|---------------------|-----------------|\n // | Replacement Character | U+FFFD | 0xEF 0xBF 0xBD | 0xFFFD |\n // | Grinning Face | U+1F600 | 0xF0 0x9F 0x98 0x80 | 0xD83D 0xDE00 |\n // |-----------------------|------------|---------------------|-----------------|\n //\n // A lexicographical comparison of the UTF-8 encodings of these code points would order\n // \"Replacement Character\" _before_ \"Grinning Face\" because 0xEF is less than 0xF0. However, a\n // direct comparison of the UTF-16 code units, as would be done in case 1, would erroneously\n // produce the _opposite_ ordering, because 0xFFFD is _greater than_ 0xD83D. As it turns out,\n // this relative ordering holds for all comparisons of UTF-16 code points requiring a surrogate\n // pair with those that do not.\n const length = Math.min(left.length, right.length);\n for (let i = 0; i < length; i++) {\n const leftChar = left.charAt(i);\n const rightChar = right.charAt(i);\n if (leftChar !== rightChar) {\n return isSurrogate(leftChar) === isSurrogate(rightChar)\n ? primitiveComparator(leftChar, rightChar)\n : isSurrogate(leftChar)\n ? 1\n : -1;\n }\n }\n\n // Use the lengths of the strings to determine the overall comparison result since either the\n // strings were equal or one is a prefix of the other.\n return primitiveComparator(left.length, right.length);\n}\n\nconst MIN_SURROGATE = 0xd800;\nconst MAX_SURROGATE = 0xdfff;\n\nexport function isSurrogate(s: string): boolean {\n debugAssert(s.length === 1, `s.length == ${s.length}, but expected 1`);\n const c = s.charCodeAt(0);\n return c >= MIN_SURROGATE && c <= MAX_SURROGATE;\n}\n\nexport interface Iterable {\n forEach: (cb: (v: V) => void) => void;\n}\n\n/** Helper to compare arrays using isEqual(). */\nexport function arrayEquals(\n left: T[],\n right: T[],\n comparator: (l: T, r: T) => boolean\n): boolean {\n if (left.length !== right.length) {\n return false;\n }\n return left.every((value, index) => comparator(value, right[index]));\n}\n/**\n * Returns the immediate lexicographically-following string. This is useful to\n * construct an inclusive range for indexeddb iterators.\n */\nexport function immediateSuccessor(s: string): string {\n // Return the input string, with an additional NUL byte appended.\n return s + '\\0';\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Integer } from '@firebase/webchannel-wrapper/bloom-blob';\n\nimport { debugAssert, fail } from '../util/assert';\nimport { Code, FirestoreError } from '../util/error';\nimport { compareUtf8Strings, primitiveComparator } from '../util/misc';\n\nexport const DOCUMENT_KEY_NAME = '__name__';\n\n/**\n * Path represents an ordered sequence of string segments.\n */\nabstract class BasePath> {\n private segments: string[];\n private offset: number;\n private len: number;\n\n constructor(segments: string[], offset?: number, length?: number) {\n if (offset === undefined) {\n offset = 0;\n } else if (offset > segments.length) {\n fail(0x027d, 'offset out of range', {\n offset,\n range: segments.length\n });\n }\n\n if (length === undefined) {\n length = segments.length - offset;\n } else if (length > segments.length - offset) {\n fail(0x06d2, 'length out of range', {\n length,\n range: segments.length - offset\n });\n }\n this.segments = segments;\n this.offset = offset;\n this.len = length;\n }\n\n /**\n * Abstract constructor method to construct an instance of B with the given\n * parameters.\n */\n protected abstract construct(\n segments: string[],\n offset?: number,\n length?: number\n ): B;\n\n /**\n * Returns a String representation.\n *\n * Implementing classes are required to provide deterministic implementations as\n * the String representation is used to obtain canonical Query IDs.\n */\n abstract toString(): string;\n\n get length(): number {\n return this.len;\n }\n\n isEqual(other: B): boolean {\n return BasePath.comparator(this, other) === 0;\n }\n\n child(nameOrPath: string | B): B {\n const segments = this.segments.slice(this.offset, this.limit());\n if (nameOrPath instanceof BasePath) {\n nameOrPath.forEach(segment => {\n segments.push(segment);\n });\n } else {\n segments.push(nameOrPath);\n }\n return this.construct(segments);\n }\n\n /** The index of one past the last segment of the path. */\n private limit(): number {\n return this.offset + this.length;\n }\n\n popFirst(size?: number): B {\n size = size === undefined ? 1 : size;\n debugAssert(\n this.length >= size,\n \"Can't call popFirst() with less segments\"\n );\n return this.construct(\n this.segments,\n this.offset + size,\n this.length - size\n );\n }\n\n popLast(): B {\n debugAssert(!this.isEmpty(), \"Can't call popLast() on empty path\");\n return this.construct(this.segments, this.offset, this.length - 1);\n }\n\n firstSegment(): string {\n debugAssert(!this.isEmpty(), \"Can't call firstSegment() on empty path\");\n return this.segments[this.offset];\n }\n\n lastSegment(): string {\n debugAssert(!this.isEmpty(), \"Can't call lastSegment() on empty path\");\n return this.get(this.length - 1);\n }\n\n get(index: number): string {\n debugAssert(index < this.length, 'Index out of range');\n return this.segments[this.offset + index];\n }\n\n isEmpty(): boolean {\n return this.length === 0;\n }\n\n isPrefixOf(other: this): boolean {\n if (other.length < this.length) {\n return false;\n }\n\n for (let i = 0; i < this.length; i++) {\n if (this.get(i) !== other.get(i)) {\n return false;\n }\n }\n\n return true;\n }\n\n isImmediateParentOf(potentialChild: this): boolean {\n if (this.length + 1 !== potentialChild.length) {\n return false;\n }\n\n for (let i = 0; i < this.length; i++) {\n if (this.get(i) !== potentialChild.get(i)) {\n return false;\n }\n }\n\n return true;\n }\n\n forEach(fn: (segment: string) => void): void {\n for (let i = this.offset, end = this.limit(); i < end; i++) {\n fn(this.segments[i]);\n }\n }\n\n toArray(): string[] {\n return this.segments.slice(this.offset, this.limit());\n }\n\n /**\n * Compare 2 paths segment by segment, prioritizing numeric IDs\n * (e.g., \"__id123__\") in numeric ascending order, followed by string\n * segments in lexicographical order.\n */\n static comparator>(\n p1: BasePath,\n p2: BasePath\n ): number {\n const len = Math.min(p1.length, p2.length);\n for (let i = 0; i < len; i++) {\n const comparison = BasePath.compareSegments(p1.get(i), p2.get(i));\n if (comparison !== 0) {\n return comparison;\n }\n }\n return primitiveComparator(p1.length, p2.length);\n }\n\n private static compareSegments(lhs: string, rhs: string): number {\n const isLhsNumeric = BasePath.isNumericId(lhs);\n const isRhsNumeric = BasePath.isNumericId(rhs);\n\n if (isLhsNumeric && !isRhsNumeric) {\n // Only lhs is numeric\n return -1;\n } else if (!isLhsNumeric && isRhsNumeric) {\n // Only rhs is numeric\n return 1;\n } else if (isLhsNumeric && isRhsNumeric) {\n // both numeric\n return BasePath.extractNumericId(lhs).compare(\n BasePath.extractNumericId(rhs)\n );\n } else {\n // both non-numeric\n return compareUtf8Strings(lhs, rhs);\n }\n }\n\n // Checks if a segment is a numeric ID (starts with \"__id\" and ends with \"__\").\n private static isNumericId(segment: string): boolean {\n return segment.startsWith('__id') && segment.endsWith('__');\n }\n\n private static extractNumericId(segment: string): Integer {\n return Integer.fromString(segment.substring(4, segment.length - 2));\n }\n}\n\n/**\n * A slash-separated path for navigating resources (documents and collections)\n * within Firestore.\n *\n * @internal\n */\nexport class ResourcePath extends BasePath {\n protected construct(\n segments: string[],\n offset?: number,\n length?: number\n ): ResourcePath {\n return new ResourcePath(segments, offset, length);\n }\n\n canonicalString(): string {\n // NOTE: The client is ignorant of any path segments containing escape\n // sequences (e.g. __id123__) and just passes them through raw (they exist\n // for legacy reasons and should not be used frequently).\n\n return this.toArray().join('/');\n }\n\n toString(): string {\n return this.canonicalString();\n }\n\n /**\n * Returns a string representation of this path\n * where each path segment has been encoded with\n * `encodeURIComponent`.\n */\n toUriEncodedString(): string {\n return this.toArray().map(encodeURIComponent).join('/');\n }\n\n /**\n * Creates a resource path from the given slash-delimited string. If multiple\n * arguments are provided, all components are combined. Leading and trailing\n * slashes from all components are ignored.\n */\n static fromString(...pathComponents: string[]): ResourcePath {\n // NOTE: The client is ignorant of any path segments containing escape\n // sequences (e.g. __id123__) and just passes them through raw (they exist\n // for legacy reasons and should not be used frequently).\n\n const segments: string[] = [];\n for (const path of pathComponents) {\n if (path.indexOf('//') >= 0) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid segment (${path}). Paths must not contain // in them.`\n );\n }\n // Strip leading and trailing slashed.\n segments.push(...path.split('/').filter(segment => segment.length > 0));\n }\n\n return new ResourcePath(segments);\n }\n\n static emptyPath(): ResourcePath {\n return new ResourcePath([]);\n }\n}\n\nconst identifierRegExp = /^[_a-zA-Z][_a-zA-Z0-9]*$/;\n\n/**\n * A dot-separated path for navigating sub-objects within a document.\n * @internal\n */\nexport class FieldPath extends BasePath {\n protected construct(\n segments: string[],\n offset?: number,\n length?: number\n ): FieldPath {\n return new FieldPath(segments, offset, length);\n }\n\n /**\n * Returns true if the string could be used as a segment in a field path\n * without escaping.\n */\n private static isValidIdentifier(segment: string): boolean {\n return identifierRegExp.test(segment);\n }\n\n canonicalString(): string {\n return this.toArray()\n .map(str => {\n str = str.replace(/\\\\/g, '\\\\\\\\').replace(/`/g, '\\\\`');\n if (!FieldPath.isValidIdentifier(str)) {\n str = '`' + str + '`';\n }\n return str;\n })\n .join('.');\n }\n\n toString(): string {\n return this.canonicalString();\n }\n\n /**\n * Returns true if this field references the key of a document.\n */\n isKeyField(): boolean {\n return this.length === 1 && this.get(0) === DOCUMENT_KEY_NAME;\n }\n\n /**\n * The field designating the key of a document.\n */\n static keyField(): FieldPath {\n return new FieldPath([DOCUMENT_KEY_NAME]);\n }\n\n /**\n * Parses a field string from the given server-formatted string.\n *\n * - Splitting the empty string is not allowed (for now at least).\n * - Empty segments within the string (e.g. if there are two consecutive\n * separators) are not allowed.\n *\n * TODO(b/37244157): we should make this more strict. Right now, it allows\n * non-identifier path components, even if they aren't escaped.\n */\n static fromServerFormat(path: string): FieldPath {\n const segments: string[] = [];\n let current = '';\n let i = 0;\n\n const addCurrentSegment = (): void => {\n if (current.length === 0) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid field path (${path}). Paths must not be empty, begin ` +\n `with '.', end with '.', or contain '..'`\n );\n }\n segments.push(current);\n current = '';\n };\n\n let inBackticks = false;\n\n while (i < path.length) {\n const c = path[i];\n if (c === '\\\\') {\n if (i + 1 === path.length) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Path has trailing escape character: ' + path\n );\n }\n const next = path[i + 1];\n if (!(next === '\\\\' || next === '.' || next === '`')) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Path has invalid escape sequence: ' + path\n );\n }\n current += next;\n i += 2;\n } else if (c === '`') {\n inBackticks = !inBackticks;\n i++;\n } else if (c === '.' && !inBackticks) {\n addCurrentSegment();\n i++;\n } else {\n current += c;\n i++;\n }\n }\n addCurrentSegment();\n\n if (inBackticks) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Unterminated ` in path: ' + path\n );\n }\n\n return new FieldPath(segments);\n }\n\n static emptyPath(): FieldPath {\n return new FieldPath([]);\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { debugAssert } from '../util/assert';\n\nimport { ResourcePath } from './path';\n\n/**\n * @internal\n */\nexport class DocumentKey {\n constructor(readonly path: ResourcePath) {\n debugAssert(\n DocumentKey.isDocumentKey(path),\n 'Invalid DocumentKey with an odd number of segments: ' +\n path.toArray().join('/')\n );\n }\n\n static fromPath(path: string): DocumentKey {\n return new DocumentKey(ResourcePath.fromString(path));\n }\n\n static fromName(name: string): DocumentKey {\n return new DocumentKey(ResourcePath.fromString(name).popFirst(5));\n }\n\n static empty(): DocumentKey {\n return new DocumentKey(ResourcePath.emptyPath());\n }\n\n get collectionGroup(): string {\n debugAssert(\n !this.path.isEmpty(),\n 'Cannot get collection group for empty key'\n );\n return this.path.popLast().lastSegment();\n }\n\n /** Returns true if the document is in the specified collectionId. */\n hasCollectionId(collectionId: string): boolean {\n return (\n this.path.length >= 2 &&\n this.path.get(this.path.length - 2) === collectionId\n );\n }\n\n /** Returns the collection group (i.e. the name of the parent collection) for this key. */\n getCollectionGroup(): string {\n debugAssert(\n !this.path.isEmpty(),\n 'Cannot get collection group for empty key'\n );\n return this.path.get(this.path.length - 2);\n }\n\n /** Returns the fully qualified path to the parent collection. */\n getCollectionPath(): ResourcePath {\n return this.path.popLast();\n }\n\n isEqual(other: DocumentKey | null): boolean {\n return (\n other !== null && ResourcePath.comparator(this.path, other.path) === 0\n );\n }\n\n toString(): string {\n return this.path.toString();\n }\n\n static comparator(k1: DocumentKey, k2: DocumentKey): number {\n return ResourcePath.comparator(k1.path, k2.path);\n }\n\n static isDocumentKey(path: ResourcePath): boolean {\n return path.length % 2 === 0;\n }\n\n /**\n * Creates and returns a new document key with the given segments.\n *\n * @param segments - The segments of the path to the document\n * @returns A new instance of DocumentKey\n */\n static fromSegments(segments: string[]): DocumentKey {\n return new DocumentKey(new ResourcePath(segments.slice()));\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DocumentKey } from '../model/document_key';\nimport { ResourcePath } from '../model/path';\n\nimport { fail } from './assert';\nimport { Code, FirestoreError } from './error';\n\n/** Types accepted by validateType() and related methods for validation. */\nexport type ValidationType =\n | 'undefined'\n | 'object'\n | 'function'\n | 'boolean'\n | 'number'\n | 'string'\n | 'non-empty string';\n\nexport function validateNonEmptyArgument(\n functionName: string,\n argumentName: string,\n argument?: string\n): asserts argument is string {\n if (!argument) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Function ${functionName}() cannot be called with an empty ${argumentName}.`\n );\n }\n}\n\n/**\n * Validates that two boolean options are not set at the same time.\n * @internal\n */\nexport function validateIsNotUsedTogether(\n optionName1: string,\n argument1: boolean | undefined,\n optionName2: string,\n argument2: boolean | undefined\n): void {\n if (argument1 === true && argument2 === true) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `${optionName1} and ${optionName2} cannot be used together.`\n );\n }\n}\n\n/**\n * Validates that `path` refers to a document (indicated by the fact it contains\n * an even numbers of segments).\n */\nexport function validateDocumentPath(path: ResourcePath): void {\n if (!DocumentKey.isDocumentKey(path)) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid document reference. Document references must have an even number of segments, but ${path} has ${path.length}.`\n );\n }\n}\n\n/**\n * Validates that `path` refers to a collection (indicated by the fact it\n * contains an odd numbers of segments).\n */\nexport function validateCollectionPath(path: ResourcePath): void {\n if (DocumentKey.isDocumentKey(path)) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid collection reference. Collection references must have an odd number of segments, but ${path} has ${path.length}.`\n );\n }\n}\n\n/**\n * Returns true if it's a non-null object without a custom prototype\n * (i.e. excludes Array, Date, etc.).\n */\nexport function isPlainObject(input: unknown): boolean {\n return (\n typeof input === 'object' &&\n input !== null &&\n (Object.getPrototypeOf(input) === Object.prototype ||\n Object.getPrototypeOf(input) === null)\n );\n}\n\n/** Returns a string describing the type / value of the provided input. */\nexport function valueDescription(input: unknown): string {\n if (input === undefined) {\n return 'undefined';\n } else if (input === null) {\n return 'null';\n } else if (typeof input === 'string') {\n if (input.length > 20) {\n input = `${input.substring(0, 20)}...`;\n }\n return JSON.stringify(input);\n } else if (typeof input === 'number' || typeof input === 'boolean') {\n return '' + input;\n } else if (typeof input === 'object') {\n if (input instanceof Array) {\n return 'an array';\n } else {\n const customObjectName = tryGetCustomObjectType(input!);\n if (customObjectName) {\n return `a custom ${customObjectName} object`;\n } else {\n return 'an object';\n }\n }\n } else if (typeof input === 'function') {\n return 'a function';\n } else {\n return fail(0x3029, 'Unknown wrong type', { type: typeof input });\n }\n}\n\n/** try to get the constructor name for an object. */\nexport function tryGetCustomObjectType(input: object): string | null {\n if (input.constructor) {\n return input.constructor.name;\n }\n return null;\n}\n\n/**\n * Casts `obj` to `T`, optionally unwrapping Compat types to expose the\n * underlying instance. Throws if `obj` is not an instance of `T`.\n *\n * This cast is used in the Lite and Full SDK to verify instance types for\n * arguments passed to the public API.\n * @internal\n */\nexport function cast(\n obj: object,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n constructor: { new (...args: any[]): T }\n): T | never {\n if ('_delegate' in obj) {\n // Unwrap Compat types\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n obj = (obj as any)._delegate;\n }\n\n if (!(obj instanceof constructor)) {\n if (constructor.name === obj.constructor.name) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Type does not match the expected instance. Did you pass a ' +\n `reference from a different Firestore SDK?`\n );\n } else {\n const description = valueDescription(obj);\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Expected type '${constructor.name}', but it was: ${description}`\n );\n }\n }\n return obj as T;\n}\n\nexport function validatePositiveNumber(functionName: string, n: number): void {\n if (n <= 0) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Function ${functionName}() requires a positive number, but it was: ${n}.`\n );\n }\n}\n","/**\n * @license\n * Copyright 2023 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Options that configure the SDK’s underlying network transport (WebChannel)\n * when long-polling is used.\n *\n * Note: This interface is \"experimental\" and is subject to change.\n *\n * See `FirestoreSettings.experimentalAutoDetectLongPolling`,\n * `FirestoreSettings.experimentalForceLongPolling`, and\n * `FirestoreSettings.experimentalLongPollingOptions`.\n */\nexport interface ExperimentalLongPollingOptions {\n /**\n * The desired maximum timeout interval, in seconds, to complete a\n * long-polling GET response. Valid values are between 5 and 30, inclusive.\n * Floating point values are allowed and will be rounded to the nearest\n * millisecond.\n *\n * By default, when long-polling is used the \"hanging GET\" request sent by\n * the client times out after 30 seconds. To request a different timeout\n * from the server, set this setting with the desired timeout.\n *\n * Changing the default timeout may be useful, for example, if the buffering\n * proxy that necessitated enabling long-polling in the first place has a\n * shorter timeout for hanging GET requests, in which case setting the\n * long-polling timeout to a shorter value, such as 25 seconds, may fix\n * prematurely-closed hanging GET requests.\n * For example, see https://github.com/firebase/firebase-js-sdk/issues/6987.\n */\n timeoutSeconds?: number;\n}\n\n/**\n * Compares two `ExperimentalLongPollingOptions` objects for equality.\n */\nexport function longPollingOptionsEqual(\n options1: ExperimentalLongPollingOptions,\n options2: ExperimentalLongPollingOptions\n): boolean {\n return options1.timeoutSeconds === options2.timeoutSeconds;\n}\n\n/**\n * Creates and returns a new `ExperimentalLongPollingOptions` with the same\n * option values as the given instance.\n */\nexport function cloneLongPollingOptions(\n options: ExperimentalLongPollingOptions\n): ExperimentalLongPollingOptions {\n const clone: ExperimentalLongPollingOptions = {};\n\n if (options.timeoutSeconds !== undefined) {\n clone.timeoutSeconds = options.timeoutSeconds;\n }\n\n return clone;\n}\n","/**\n * @license\n * Copyright 2023 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * The value returned from the most recent invocation of\n * `generateUniqueDebugId()`, or null if it has never been invoked.\n */\nlet lastUniqueDebugId: number | null = null;\n\n/**\n * Generates and returns an initial value for `lastUniqueDebugId`.\n *\n * The returned value is randomly selected from a range of integers that are\n * represented as 8 hexadecimal digits. This means that (within reason) any\n * numbers generated by incrementing the returned number by 1 will also be\n * represented by 8 hexadecimal digits. This leads to all \"IDs\" having the same\n * length when converted to a hexadecimal string, making reading logs containing\n * these IDs easier to follow. And since the return value is randomly selected\n * it will help to differentiate between logs from different executions.\n */\nfunction generateInitialUniqueDebugId(): number {\n const minResult = 0x10000000;\n const maxResult = 0x90000000;\n const resultRange = maxResult - minResult;\n const resultOffset = Math.round(resultRange * Math.random());\n return minResult + resultOffset;\n}\n\n/**\n * Generates and returns a unique ID as a hexadecimal string.\n *\n * The returned ID is intended to be used in debug logging messages to help\n * correlate log messages that may be spatially separated in the logs, but\n * logically related. For example, a network connection could include the same\n * \"debug ID\" string in all of its log messages to help trace a specific\n * connection over time.\n *\n * @return the 10-character generated ID (e.g. \"0xa1b2c3d4\").\n */\nexport function generateUniqueDebugId(): string {\n if (lastUniqueDebugId === null) {\n lastUniqueDebugId = generateInitialUniqueDebugId();\n } else {\n lastUniqueDebugId++;\n }\n return '0x' + lastUniqueDebugId.toString(16);\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** Sentinel value that sorts before any Mutation Batch ID. */\nexport const BATCHID_UNKNOWN = -1;\n\n// An Object whose keys and values are strings.\nexport interface StringMap {\n [key: string]: string;\n}\n\n/**\n * Returns whether a variable is either undefined or null.\n */\nexport function isNullOrUndefined(value: unknown): value is null | undefined {\n return value === null || value === undefined;\n}\n\n/** Returns whether the value represents -0. */\nexport function isNegativeZero(value: number): boolean {\n // Detect if the value is -0.0. Based on polyfill from\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is\n return value === 0 && 1 / value === 1 / -0;\n}\n\n/**\n * Returns whether a value is an integer and in the safe integer range\n * @param value - The value to test for being an integer and in the safe range\n */\nexport function isSafeInteger(value: unknown): boolean {\n return (\n typeof value === 'number' &&\n Number.isInteger(value) &&\n !isNegativeZero(value) &&\n value <= Number.MAX_SAFE_INTEGER &&\n value >= Number.MIN_SAFE_INTEGER\n );\n}\n\n/** The subset of the browser's Window interface used by the SDK. */\nexport interface WindowLike {\n readonly localStorage: Storage;\n readonly indexedDB: IDBFactory | null;\n addEventListener(type: string, listener: EventListener): void;\n removeEventListener(type: string, listener: EventListener): void;\n}\n\n/** The subset of the browser's Document interface used by the SDK. */\nexport interface DocumentLike {\n readonly visibilityState: DocumentVisibilityState;\n addEventListener(type: string, listener: EventListener): void;\n removeEventListener(type: string, listener: EventListener): void;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isCloudWorkstation } from '@firebase/util';\n\nimport { SDK_VERSION } from '../../src/core/version';\nimport { Token } from '../api/credentials';\nimport {\n DatabaseId,\n DatabaseInfo,\n DEFAULT_DATABASE_NAME\n} from '../core/database_info';\nimport { ResourcePath } from '../model/path';\nimport { debugAssert } from '../util/assert';\nimport { generateUniqueDebugId } from '../util/debug_uid';\nimport { FirestoreError } from '../util/error';\nimport { logDebug, logWarn } from '../util/log';\nimport { StringMap } from '../util/types';\n\nimport { Connection, Stream } from './connection';\n\nconst LOG_TAG = 'RestConnection';\n\n/**\n * Maps RPC names to the corresponding REST endpoint name.\n *\n * We use array notation to avoid mangling.\n */\nconst RPC_NAME_URL_MAPPING: StringMap = {};\n\nRPC_NAME_URL_MAPPING['BatchGetDocuments'] = 'batchGet';\nRPC_NAME_URL_MAPPING['Commit'] = 'commit';\nRPC_NAME_URL_MAPPING['RunQuery'] = 'runQuery';\nRPC_NAME_URL_MAPPING['RunAggregationQuery'] = 'runAggregationQuery';\n\nconst RPC_URL_VERSION = 'v1';\n\n// SDK_VERSION is updated to different value at runtime depending on the entry point,\n// so we need to get its value when we need it in a function.\nfunction getGoogApiClientValue(): string {\n return 'gl-js/ fire/' + SDK_VERSION;\n}\n/**\n * Base class for all Rest-based connections to the backend (WebChannel and\n * HTTP).\n */\nexport abstract class RestConnection implements Connection {\n protected readonly databaseId: DatabaseId;\n protected readonly baseUrl: string;\n private readonly databasePath: string;\n private readonly requestParams: string;\n\n get shouldResourcePathBeIncludedInRequest(): boolean {\n // Both `invokeRPC()` and `invokeStreamingRPC()` use their `path` arguments to determine\n // where to run the query, and expect the `request` to NOT specify the \"path\".\n return false;\n }\n\n constructor(private readonly databaseInfo: DatabaseInfo) {\n this.databaseId = databaseInfo.databaseId;\n const proto = databaseInfo.ssl ? 'https' : 'http';\n const projectId = encodeURIComponent(this.databaseId.projectId);\n const databaseId = encodeURIComponent(this.databaseId.database);\n this.baseUrl = proto + '://' + databaseInfo.host;\n this.databasePath = `projects/${projectId}/databases/${databaseId}`;\n this.requestParams =\n this.databaseId.database === DEFAULT_DATABASE_NAME\n ? `project_id=${projectId}`\n : `project_id=${projectId}&database_id=${databaseId}`;\n }\n\n invokeRPC(\n rpcName: string,\n path: ResourcePath,\n req: Req,\n authToken: Token | null,\n appCheckToken: Token | null\n ): Promise {\n const streamId = generateUniqueDebugId();\n const url = this.makeUrl(rpcName, path.toUriEncodedString());\n logDebug(LOG_TAG, `Sending RPC '${rpcName}' ${streamId}:`, url, req);\n\n const headers: StringMap = {\n 'google-cloud-resource-prefix': this.databasePath,\n 'x-goog-request-params': this.requestParams\n };\n this.modifyHeadersForRequest(headers, authToken, appCheckToken);\n\n const { host } = new URL(url);\n const forwardCredentials = isCloudWorkstation(host);\n return this.performRPCRequest(\n rpcName,\n url,\n headers,\n req,\n forwardCredentials\n ).then(\n response => {\n logDebug(LOG_TAG, `Received RPC '${rpcName}' ${streamId}: `, response);\n return response;\n },\n (err: FirestoreError) => {\n logWarn(\n LOG_TAG,\n `RPC '${rpcName}' ${streamId} failed with error: `,\n err,\n 'url: ',\n url,\n 'request:',\n req\n );\n throw err;\n }\n );\n }\n\n invokeStreamingRPC(\n rpcName: string,\n path: ResourcePath,\n request: Req,\n authToken: Token | null,\n appCheckToken: Token | null,\n expectedResponseCount?: number\n ): Promise {\n // The REST API automatically aggregates all of the streamed results, so we\n // can just use the normal invoke() method.\n return this.invokeRPC(\n rpcName,\n path,\n request,\n authToken,\n appCheckToken\n );\n }\n\n abstract openStream(\n rpcName: string,\n authToken: Token | null,\n appCheckToken: Token | null\n ): Stream;\n\n /**\n * Modifies the headers for a request, adding any authorization token if\n * present and any additional headers for the request.\n */\n protected modifyHeadersForRequest(\n headers: StringMap,\n authToken: Token | null,\n appCheckToken: Token | null\n ): void {\n headers['X-Goog-Api-Client'] = getGoogApiClientValue();\n\n // Content-Type: text/plain will avoid preflight requests which might\n // mess with CORS and redirects by proxies. If we add custom headers\n // we will need to change this code to potentially use the $httpOverwrite\n // parameter supported by ESF to avoid triggering preflight requests.\n headers['Content-Type'] = 'text/plain';\n\n if (this.databaseInfo.appId) {\n headers['X-Firebase-GMPID'] = this.databaseInfo.appId;\n }\n\n if (authToken) {\n authToken.headers.forEach((value, key) => (headers[key] = value));\n }\n if (appCheckToken) {\n appCheckToken.headers.forEach((value, key) => (headers[key] = value));\n }\n }\n\n /**\n * Performs an RPC request using an implementation specific networking layer.\n */\n protected abstract performRPCRequest(\n rpcName: string,\n url: string,\n headers: StringMap,\n body: Req,\n _forwardCredentials: boolean\n ): Promise;\n\n private makeUrl(rpcName: string, path: string): string {\n const urlRpcName = RPC_NAME_URL_MAPPING[rpcName];\n debugAssert(\n urlRpcName !== undefined,\n 'Unknown REST mapping for: ' + rpcName\n );\n return `${this.baseUrl}/${RPC_URL_VERSION}/${path}:${urlRpcName}`;\n }\n\n /**\n * Closes and cleans up any resources associated with the connection. This\n * implementation is a no-op because there are no resources associated\n * with the RestConnection that need to be cleaned up.\n */\n terminate(): void {\n // No-op\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { fail } from '../util/assert';\nimport { Code } from '../util/error';\nimport { logError } from '../util/log';\n\n/**\n * Error Codes describing the different ways GRPC can fail. These are copied\n * directly from GRPC's sources here:\n *\n * https://github.com/grpc/grpc/blob/bceec94ea4fc5f0085d81235d8e1c06798dc341a/include/grpc%2B%2B/impl/codegen/status_code_enum.h\n *\n * Important! The names of these identifiers matter because the string forms\n * are used for reverse lookups from the webchannel stream. Do NOT change the\n * names of these identifiers or change this into a const enum.\n */\nenum RpcCode {\n OK = 0,\n CANCELLED = 1,\n UNKNOWN = 2,\n INVALID_ARGUMENT = 3,\n DEADLINE_EXCEEDED = 4,\n NOT_FOUND = 5,\n ALREADY_EXISTS = 6,\n PERMISSION_DENIED = 7,\n UNAUTHENTICATED = 16,\n RESOURCE_EXHAUSTED = 8,\n FAILED_PRECONDITION = 9,\n ABORTED = 10,\n OUT_OF_RANGE = 11,\n UNIMPLEMENTED = 12,\n INTERNAL = 13,\n UNAVAILABLE = 14,\n DATA_LOSS = 15\n}\n\n/**\n * Determines whether an error code represents a permanent error when received\n * in response to a non-write operation.\n *\n * See isPermanentWriteError for classifying write errors.\n */\nexport function isPermanentError(code: Code): boolean {\n switch (code) {\n case Code.OK:\n return fail(0xfdaa, 'Treated status OK as error');\n case Code.CANCELLED:\n case Code.UNKNOWN:\n case Code.DEADLINE_EXCEEDED:\n case Code.RESOURCE_EXHAUSTED:\n case Code.INTERNAL:\n case Code.UNAVAILABLE:\n // Unauthenticated means something went wrong with our token and we need\n // to retry with new credentials which will happen automatically.\n case Code.UNAUTHENTICATED:\n return false;\n case Code.INVALID_ARGUMENT:\n case Code.NOT_FOUND:\n case Code.ALREADY_EXISTS:\n case Code.PERMISSION_DENIED:\n case Code.FAILED_PRECONDITION:\n // Aborted might be retried in some scenarios, but that is dependent on\n // the context and should handled individually by the calling code.\n // See https://cloud.google.com/apis/design/errors.\n case Code.ABORTED:\n case Code.OUT_OF_RANGE:\n case Code.UNIMPLEMENTED:\n case Code.DATA_LOSS:\n return true;\n default:\n return fail(0x3c6b, 'Unknown status code', { code });\n }\n}\n\n/**\n * Determines whether an error code represents a permanent error when received\n * in response to a write operation.\n *\n * Write operations must be handled specially because as of b/119437764, ABORTED\n * errors on the write stream should be retried too (even though ABORTED errors\n * are not generally retryable).\n *\n * Note that during the initial handshake on the write stream an ABORTED error\n * signals that we should discard our stream token (i.e. it is permanent). This\n * means a handshake error should be classified with isPermanentError, above.\n */\nexport function isPermanentWriteError(code: Code): boolean {\n return isPermanentError(code) && code !== Code.ABORTED;\n}\n\n/**\n * Maps an error Code from a GRPC status identifier like 'NOT_FOUND'.\n *\n * @returns The Code equivalent to the given status string or undefined if\n * there is no match.\n */\nexport function mapCodeFromRpcStatus(status: string): Code | undefined {\n // lookup by string\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const code: RpcCode = RpcCode[status as any] as any;\n if (code === undefined) {\n return undefined;\n }\n\n return mapCodeFromRpcCode(code);\n}\n\n/**\n * Maps an error Code from GRPC status code number, like 0, 1, or 14. These\n * are not the same as HTTP status codes.\n *\n * @returns The Code equivalent to the given GRPC status code. Fails if there\n * is no match.\n */\nexport function mapCodeFromRpcCode(code: number | undefined): Code {\n if (code === undefined) {\n // This shouldn't normally happen, but in certain error cases (like trying\n // to send invalid proto messages) we may get an error with no GRPC code.\n logError('GRPC error has no .code');\n return Code.UNKNOWN;\n }\n\n switch (code) {\n case RpcCode.OK:\n return Code.OK;\n case RpcCode.CANCELLED:\n return Code.CANCELLED;\n case RpcCode.UNKNOWN:\n return Code.UNKNOWN;\n case RpcCode.DEADLINE_EXCEEDED:\n return Code.DEADLINE_EXCEEDED;\n case RpcCode.RESOURCE_EXHAUSTED:\n return Code.RESOURCE_EXHAUSTED;\n case RpcCode.INTERNAL:\n return Code.INTERNAL;\n case RpcCode.UNAVAILABLE:\n return Code.UNAVAILABLE;\n case RpcCode.UNAUTHENTICATED:\n return Code.UNAUTHENTICATED;\n case RpcCode.INVALID_ARGUMENT:\n return Code.INVALID_ARGUMENT;\n case RpcCode.NOT_FOUND:\n return Code.NOT_FOUND;\n case RpcCode.ALREADY_EXISTS:\n return Code.ALREADY_EXISTS;\n case RpcCode.PERMISSION_DENIED:\n return Code.PERMISSION_DENIED;\n case RpcCode.FAILED_PRECONDITION:\n return Code.FAILED_PRECONDITION;\n case RpcCode.ABORTED:\n return Code.ABORTED;\n case RpcCode.OUT_OF_RANGE:\n return Code.OUT_OF_RANGE;\n case RpcCode.UNIMPLEMENTED:\n return Code.UNIMPLEMENTED;\n case RpcCode.DATA_LOSS:\n return Code.DATA_LOSS;\n default:\n return fail(0x999b, 'Unknown status code', { code });\n }\n}\n\n/**\n * Maps an RPC code from a Code. This is the reverse operation from\n * mapCodeFromRpcCode and should really only be used in tests.\n */\nexport function mapRpcCodeFromCode(code: Code | undefined): number {\n if (code === undefined) {\n return RpcCode.OK;\n }\n\n switch (code) {\n case Code.OK:\n return RpcCode.OK;\n case Code.CANCELLED:\n return RpcCode.CANCELLED;\n case Code.UNKNOWN:\n return RpcCode.UNKNOWN;\n case Code.DEADLINE_EXCEEDED:\n return RpcCode.DEADLINE_EXCEEDED;\n case Code.RESOURCE_EXHAUSTED:\n return RpcCode.RESOURCE_EXHAUSTED;\n case Code.INTERNAL:\n return RpcCode.INTERNAL;\n case Code.UNAVAILABLE:\n return RpcCode.UNAVAILABLE;\n case Code.UNAUTHENTICATED:\n return RpcCode.UNAUTHENTICATED;\n case Code.INVALID_ARGUMENT:\n return RpcCode.INVALID_ARGUMENT;\n case Code.NOT_FOUND:\n return RpcCode.NOT_FOUND;\n case Code.ALREADY_EXISTS:\n return RpcCode.ALREADY_EXISTS;\n case Code.PERMISSION_DENIED:\n return RpcCode.PERMISSION_DENIED;\n case Code.FAILED_PRECONDITION:\n return RpcCode.FAILED_PRECONDITION;\n case Code.ABORTED:\n return RpcCode.ABORTED;\n case Code.OUT_OF_RANGE:\n return RpcCode.OUT_OF_RANGE;\n case Code.UNIMPLEMENTED:\n return RpcCode.UNIMPLEMENTED;\n case Code.DATA_LOSS:\n return RpcCode.DATA_LOSS;\n default:\n return fail(0x3019, 'Unknown status code', { code });\n }\n}\n\n/**\n * Converts an HTTP Status Code to the equivalent error code.\n *\n * @param status - An HTTP Status Code, like 200, 404, 503, etc.\n * @returns The equivalent Code. Unknown status codes are mapped to\n * Code.UNKNOWN.\n */\nexport function mapCodeFromHttpStatus(status?: number): Code {\n if (status === undefined) {\n logError('RPC_ERROR', 'HTTP error has no status');\n return Code.UNKNOWN;\n }\n\n // The canonical error codes for Google APIs [1] specify mapping onto HTTP\n // status codes but the mapping is not bijective. In each case of ambiguity\n // this function chooses a primary error.\n //\n // [1]\n // https://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto\n switch (status) {\n case 200: // OK\n return Code.OK;\n\n case 400: // Bad Request\n return Code.FAILED_PRECONDITION;\n // Other possibilities based on the forward mapping\n // return Code.INVALID_ARGUMENT;\n // return Code.OUT_OF_RANGE;\n\n case 401: // Unauthorized\n return Code.UNAUTHENTICATED;\n\n case 403: // Forbidden\n return Code.PERMISSION_DENIED;\n\n case 404: // Not Found\n return Code.NOT_FOUND;\n\n case 409: // Conflict\n return Code.ABORTED;\n // Other possibilities:\n // return Code.ALREADY_EXISTS;\n\n case 416: // Range Not Satisfiable\n return Code.OUT_OF_RANGE;\n\n case 429: // Too Many Requests\n return Code.RESOURCE_EXHAUSTED;\n\n case 499: // Client Closed Request\n return Code.CANCELLED;\n\n case 500: // Internal Server Error\n return Code.UNKNOWN;\n // Other possibilities:\n // return Code.INTERNAL;\n // return Code.DATA_LOSS;\n\n case 501: // Unimplemented\n return Code.UNIMPLEMENTED;\n\n case 503: // Service Unavailable\n return Code.UNAVAILABLE;\n\n case 504: // Gateway Timeout\n return Code.DEADLINE_EXCEEDED;\n\n default:\n if (status >= 200 && status < 300) {\n return Code.OK;\n }\n if (status >= 400 && status < 500) {\n return Code.FAILED_PRECONDITION;\n }\n if (status >= 500 && status < 600) {\n return Code.INTERNAL;\n }\n return Code.UNKNOWN;\n }\n}\n\n/**\n * Converts an HTTP response's error status to the equivalent error code.\n *\n * @param status - An HTTP error response status (\"FAILED_PRECONDITION\",\n * \"UNKNOWN\", etc.)\n * @returns The equivalent Code. Non-matching responses are mapped to\n * Code.UNKNOWN.\n */\nexport function mapCodeFromHttpResponseErrorStatus(status: string): Code {\n const serverError = status.toLowerCase().replace(/_/g, '-');\n return Object.values(Code).indexOf(serverError as Code) >= 0\n ? (serverError as Code)\n : Code.UNKNOWN;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Token } from '../../api/credentials';\nimport { Stream } from '../../remote/connection';\nimport { RestConnection } from '../../remote/rest_connection';\nimport { mapCodeFromHttpStatus } from '../../remote/rpc_error';\nimport { FirestoreError } from '../../util/error';\nimport { StringMap } from '../../util/types';\n\n/**\n * A Rest-based connection that relies on the native HTTP stack\n * (e.g. `fetch` or a polyfill).\n */\nexport class FetchConnection extends RestConnection {\n openStream(\n rpcName: string,\n token: Token | null\n ): Stream {\n throw new Error('Not supported by FetchConnection');\n }\n\n protected async performRPCRequest(\n rpcName: string,\n url: string,\n headers: StringMap,\n body: Req,\n forwardCredentials: boolean\n ): Promise {\n const requestJson = JSON.stringify(body);\n let response: Response;\n\n try {\n const fetchArgs: RequestInit = {\n method: 'POST',\n headers,\n body: requestJson\n };\n if (forwardCredentials) {\n fetchArgs.credentials = 'include';\n }\n response = await fetch(url, fetchArgs);\n } catch (e) {\n const err = e as { status: number | undefined; statusText: string };\n throw new FirestoreError(\n mapCodeFromHttpStatus(err.status),\n 'Request failed with error: ' + err.statusText\n );\n }\n\n if (!response.ok) {\n let errorResponse = await response.json();\n if (Array.isArray(errorResponse)) {\n errorResponse = errorResponse[0];\n }\n const errorMessage = errorResponse?.error?.message;\n throw new FirestoreError(\n mapCodeFromHttpStatus(response.status),\n `Request failed with error: ${errorMessage ?? response.statusText}`\n );\n }\n\n return response.json();\n }\n}\n","/**\n * @license\n * Copyright 2023 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FieldPath } from '../model/path';\n\n/**\n * Union type representing the aggregate type to be performed.\n */\nexport type AggregateType = 'count' | 'avg' | 'sum';\n\n/**\n * Represents an Aggregate to be performed over a query result set.\n */\nexport interface Aggregate {\n readonly fieldPath?: FieldPath;\n readonly alias: string;\n readonly aggregateType: AggregateType;\n}\n\n/**\n * Concrete implementation of the Aggregate type.\n */\nexport class AggregateImpl implements Aggregate {\n constructor(\n readonly alias: string,\n readonly aggregateType: AggregateType,\n readonly fieldPath?: FieldPath\n ) {}\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { debugAssert } from './assert';\n\nexport interface Dict {\n [stringKey: string]: V;\n}\n\nexport function objectSize(obj: object): number {\n let count = 0;\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n count++;\n }\n }\n return count;\n}\n\nexport function forEach(\n obj: Dict | undefined,\n fn: (key: string, val: V) => void\n): void {\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n fn(key, obj[key]);\n }\n }\n}\n\nexport function mapToArray(\n obj: Dict,\n fn: (element: V, key: string, obj: Dict) => R\n): R[] {\n const result: R[] = [];\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n result.push(fn(obj[key], key, obj));\n }\n }\n return result;\n}\n\nexport function isEmpty(obj: Dict): boolean {\n debugAssert(\n obj != null && typeof obj === 'object',\n 'isEmpty() expects object parameter.'\n );\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n return false;\n }\n }\n return true;\n}\n","/**\n * @license\n * Copyright 2023 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * An error encountered while decoding base64 string.\n */\nexport class Base64DecodeError extends Error {\n readonly name = 'Base64DecodeError';\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { base64, DecodeBase64StringError } from '@firebase/util';\n\nimport { Base64DecodeError } from '../../util/base64_decode_error';\n\n// WebSafe uses a different URL-encoding safe alphabet that doesn't match\n// the encoding used on the backend.\nconst WEB_SAFE = false;\n\n/** Converts a Base64 encoded string to a binary string. */\nexport function decodeBase64(encoded: string): string {\n try {\n return String.fromCharCode.apply(\n null,\n // We use `decodeStringToByteArray()` instead of `decodeString()` since\n // `decodeString()` returns Unicode strings, which doesn't match the values\n // returned by `atob()`'s Latin1 representation.\n base64.decodeStringToByteArray(encoded, WEB_SAFE)\n );\n } catch (e) {\n if (e instanceof DecodeBase64StringError) {\n throw new Base64DecodeError('Invalid base64 string: ' + e);\n } else {\n throw e;\n }\n }\n}\n\n/** Converts a binary string to a Base64 encoded string. */\nexport function encodeBase64(raw: string): string {\n const bytes: number[] = [];\n for (let i = 0; i < raw.length; i++) {\n bytes[i] = raw.charCodeAt(i);\n }\n return base64.encodeByteArray(bytes, WEB_SAFE);\n}\n\n/** True if and only if the Base64 conversion functions are available. */\nexport function isBase64Available(): boolean {\n return true;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { decodeBase64, encodeBase64 } from '../platform/base64';\n\nimport { primitiveComparator } from './misc';\n\n/**\n * Immutable class that represents a \"proto\" byte string.\n *\n * Proto byte strings can either be Base64-encoded strings or Uint8Arrays when\n * sent on the wire. This class abstracts away this differentiation by holding\n * the proto byte string in a common class that must be converted into a string\n * before being sent as a proto.\n * @internal\n */\nexport class ByteString {\n static readonly EMPTY_BYTE_STRING = new ByteString('');\n\n private constructor(private readonly binaryString: string) {}\n\n static fromBase64String(base64: string): ByteString {\n const binaryString = decodeBase64(base64);\n return new ByteString(binaryString);\n }\n\n static fromUint8Array(array: Uint8Array): ByteString {\n // TODO(indexing); Remove the copy of the byte string here as this method\n // is frequently called during indexing.\n const binaryString = binaryStringFromUint8Array(array);\n return new ByteString(binaryString);\n }\n\n [Symbol.iterator](): Iterator {\n let i = 0;\n return {\n next: () => {\n if (i < this.binaryString.length) {\n return { value: this.binaryString.charCodeAt(i++), done: false };\n } else {\n return { value: undefined, done: true };\n }\n }\n };\n }\n\n toBase64(): string {\n return encodeBase64(this.binaryString);\n }\n\n toUint8Array(): Uint8Array {\n return uint8ArrayFromBinaryString(this.binaryString);\n }\n\n approximateByteSize(): number {\n return this.binaryString.length * 2;\n }\n\n compareTo(other: ByteString): number {\n return primitiveComparator(this.binaryString, other.binaryString);\n }\n\n isEqual(other: ByteString): boolean {\n return this.binaryString === other.binaryString;\n }\n}\n\n/**\n * Helper function to convert an Uint8array to a binary string.\n */\nexport function binaryStringFromUint8Array(array: Uint8Array): string {\n let binaryString = '';\n for (let i = 0; i < array.length; ++i) {\n binaryString += String.fromCharCode(array[i]);\n }\n return binaryString;\n}\n\n/**\n * Helper function to convert a binary string to an Uint8Array.\n */\nexport function uint8ArrayFromBinaryString(binaryString: string): Uint8Array {\n const buffer = new Uint8Array(binaryString.length);\n for (let i = 0; i < binaryString.length; i++) {\n buffer[i] = binaryString.charCodeAt(i);\n }\n return buffer;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Timestamp } from '../protos/firestore_proto_api';\nimport { hardAssert } from '../util/assert';\nimport { ByteString } from '../util/byte_string';\n\n// A RegExp matching ISO 8601 UTC timestamps with optional fraction.\nconst ISO_TIMESTAMP_REG_EXP = new RegExp(\n /^\\d{4}-\\d\\d-\\d\\dT\\d\\d:\\d\\d:\\d\\d(?:\\.(\\d+))?Z$/\n);\n\n/**\n * Converts the possible Proto values for a timestamp value into a \"seconds and\n * nanos\" representation.\n */\nexport function normalizeTimestamp(date: Timestamp): {\n seconds: number;\n nanos: number;\n} {\n hardAssert(!!date, 0x986a, 'Cannot normalize null or undefined timestamp.');\n\n // The json interface (for the browser) will return an iso timestamp string,\n // while the proto js library (for node) will return a\n // google.protobuf.Timestamp instance.\n if (typeof date === 'string') {\n // The date string can have higher precision (nanos) than the Date class\n // (millis), so we do some custom parsing here.\n\n // Parse the nanos right out of the string.\n let nanos = 0;\n const fraction = ISO_TIMESTAMP_REG_EXP.exec(date);\n hardAssert(!!fraction, 0xb5de, 'invalid timestamp', {\n timestamp: date\n });\n if (fraction[1]) {\n // Pad the fraction out to 9 digits (nanos).\n let nanoStr = fraction[1];\n nanoStr = (nanoStr + '000000000').substr(0, 9);\n nanos = Number(nanoStr);\n }\n\n // Parse the date to get the seconds.\n const parsedDate = new Date(date);\n const seconds = Math.floor(parsedDate.getTime() / 1000);\n\n return { seconds, nanos };\n } else {\n // TODO(b/37282237): Use strings for Proto3 timestamps\n // assert(!this.options.useProto3Json,\n // 'The timestamp instance format requires Proto JS.');\n const seconds = normalizeNumber(date.seconds);\n const nanos = normalizeNumber(date.nanos);\n return { seconds, nanos };\n }\n}\n\n/**\n * Converts the possible Proto types for numbers into a JavaScript number.\n * Returns 0 if the value is not numeric.\n */\nexport function normalizeNumber(value: number | string | undefined): number {\n // TODO(bjornick): Handle int64 greater than 53 bits.\n if (typeof value === 'number') {\n return value;\n } else if (typeof value === 'string') {\n return Number(value);\n } else {\n return 0;\n }\n}\n\n/** Converts the possible Proto types for Blobs into a ByteString. */\nexport function normalizeByteString(blob: string | Uint8Array): ByteString {\n if (typeof blob === 'string') {\n return ByteString.fromBase64String(blob);\n } else {\n return ByteString.fromUint8Array(blob);\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isPlainObject } from '../util/input_validation';\n\nimport { Code, FirestoreError } from './error';\n\n/**\n * A list of data types Firestore objects may serialize in their toJSON implemenetations.\n * @private\n * @internal\n */\nexport type JsonTypeDesc =\n | 'object'\n | 'string'\n | 'number'\n | 'boolean'\n | 'null'\n | 'undefined';\n\n/**\n * An association of JsonTypeDesc values to their native types.\n * @private\n * @internal\n */\nexport type TSType = T extends 'object'\n ? object\n : T extends 'string'\n ? string\n : T extends 'number'\n ? number\n : T extends 'boolean'\n ? boolean\n : T extends 'null'\n ? null\n : T extends 'undefined'\n ? undefined\n : never;\n\n/**\n * The representation of a JSON object property name and its type value.\n * @private\n * @internal\n */\nexport interface Property {\n value?: TSType;\n typeString: JsonTypeDesc;\n}\n\n/**\n * A type Firestore data types may use to define the fields used in their JSON serialization.\n * @private\n * @internal\n */\nexport interface JsonSchema {\n [key: string]: Property;\n}\n\n/**\n * Associates the JSON property type to the native type and sets them to be Required.\n * @private\n * @internal\n */\nexport type Json = {\n [K in keyof T]: Required['value'];\n};\n\n/**\n * Helper function to define a JSON schema {@link Property}.\n * @private\n * @internal\n */\nexport function property(\n typeString: T,\n optionalValue?: TSType\n): Property {\n const result: Property = {\n typeString\n };\n if (optionalValue) {\n result.value = optionalValue;\n }\n return result;\n}\n\n/**\n * Validates the JSON object based on the provided schema, and narrows the type to the provided\n * JSON schema.\n * @private\n * @internal\n *\n * @param json A JSON object to validate.\n * @param scheme a {@link JsonSchema} that defines the properties to validate.\n * @returns true if the JSON schema exists within the object. Throws a FirestoreError otherwise.\n */\nexport function validateJSON(\n json: object,\n schema: S\n): json is Json {\n if (!isPlainObject(json)) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'JSON must be an object');\n }\n let error: string | undefined = undefined;\n for (const key in schema) {\n if (schema[key]) {\n const typeString = schema[key].typeString;\n const value: { value: unknown } | undefined =\n 'value' in schema[key] ? { value: schema[key].value } : undefined;\n if (!(key in json)) {\n error = `JSON missing required field: '${key}'`;\n break;\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const fieldValue = (json as any)[key];\n if (typeString && typeof fieldValue !== typeString) {\n error = `JSON field '${key}' must be a ${typeString}.`;\n break;\n } else if (value !== undefined && fieldValue !== value.value) {\n error = `Expected '${key}' field to equal '${value.value}'`;\n break;\n }\n }\n }\n if (error) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, error);\n }\n return true;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Code, FirestoreError } from '../util/error';\n// API extractor fails importing 'property' unless we also explicitly import 'Property'.\n// eslint-disable-next-line @typescript-eslint/no-unused-vars, unused-imports/no-unused-imports-ts\nimport { Property, property, validateJSON } from '../util/json_validation';\nimport { primitiveComparator } from '../util/misc';\n\n// The earliest date supported by Firestore timestamps (0001-01-01T00:00:00Z).\nconst MIN_SECONDS = -62135596800;\n\n// Number of nanoseconds in a millisecond.\nconst MS_TO_NANOS = 1e6;\n\n/**\n * A `Timestamp` represents a point in time independent of any time zone or\n * calendar, represented as seconds and fractions of seconds at nanosecond\n * resolution in UTC Epoch time.\n *\n * It is encoded using the Proleptic Gregorian Calendar which extends the\n * Gregorian calendar backwards to year one. It is encoded assuming all minutes\n * are 60 seconds long, i.e. leap seconds are \"smeared\" so that no leap second\n * table is needed for interpretation. Range is from 0001-01-01T00:00:00Z to\n * 9999-12-31T23:59:59.999999999Z.\n *\n * For examples and further specifications, refer to the\n * {@link https://github.com/google/protobuf/blob/master/src/google/protobuf/timestamp.proto | Timestamp definition}.\n */\nexport class Timestamp {\n /**\n * Creates a new timestamp with the current date, with millisecond precision.\n *\n * @returns a new timestamp representing the current date.\n */\n static now(): Timestamp {\n return Timestamp.fromMillis(Date.now());\n }\n\n /**\n * Creates a new timestamp from the given date.\n *\n * @param date - The date to initialize the `Timestamp` from.\n * @returns A new `Timestamp` representing the same point in time as the given\n * date.\n */\n static fromDate(date: Date): Timestamp {\n return Timestamp.fromMillis(date.getTime());\n }\n\n /**\n * Creates a new timestamp from the given number of milliseconds.\n *\n * @param milliseconds - Number of milliseconds since Unix epoch\n * 1970-01-01T00:00:00Z.\n * @returns A new `Timestamp` representing the same point in time as the given\n * number of milliseconds.\n */\n static fromMillis(milliseconds: number): Timestamp {\n const seconds = Math.floor(milliseconds / 1000);\n const nanos = Math.floor((milliseconds - seconds * 1000) * MS_TO_NANOS);\n return new Timestamp(seconds, nanos);\n }\n\n /**\n * Creates a new timestamp.\n *\n * @param seconds - The number of seconds of UTC time since Unix epoch\n * 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to\n * 9999-12-31T23:59:59Z inclusive.\n * @param nanoseconds - The non-negative fractions of a second at nanosecond\n * resolution. Negative second values with fractions must still have\n * non-negative nanoseconds values that count forward in time. Must be\n * from 0 to 999,999,999 inclusive.\n */\n constructor(\n /**\n * The number of seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z.\n */\n readonly seconds: number,\n /**\n * The fractions of a second at nanosecond resolution.*\n */\n readonly nanoseconds: number\n ) {\n if (nanoseconds < 0) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Timestamp nanoseconds out of range: ' + nanoseconds\n );\n }\n if (nanoseconds >= 1e9) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Timestamp nanoseconds out of range: ' + nanoseconds\n );\n }\n if (seconds < MIN_SECONDS) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Timestamp seconds out of range: ' + seconds\n );\n }\n // This will break in the year 10,000.\n if (seconds >= 253402300800) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Timestamp seconds out of range: ' + seconds\n );\n }\n }\n\n /**\n * Converts a `Timestamp` to a JavaScript `Date` object. This conversion\n * causes a loss of precision since `Date` objects only support millisecond\n * precision.\n *\n * @returns JavaScript `Date` object representing the same point in time as\n * this `Timestamp`, with millisecond precision.\n */\n toDate(): Date {\n return new Date(this.toMillis());\n }\n\n /**\n * Converts a `Timestamp` to a numeric timestamp (in milliseconds since\n * epoch). This operation causes a loss of precision.\n *\n * @returns The point in time corresponding to this timestamp, represented as\n * the number of milliseconds since Unix epoch 1970-01-01T00:00:00Z.\n */\n toMillis(): number {\n return this.seconds * 1000 + this.nanoseconds / MS_TO_NANOS;\n }\n\n _compareTo(other: Timestamp): number {\n if (this.seconds === other.seconds) {\n return primitiveComparator(this.nanoseconds, other.nanoseconds);\n }\n return primitiveComparator(this.seconds, other.seconds);\n }\n\n /**\n * Returns true if this `Timestamp` is equal to the provided one.\n *\n * @param other - The `Timestamp` to compare against.\n * @returns true if this `Timestamp` is equal to the provided one.\n */\n isEqual(other: Timestamp): boolean {\n return (\n other.seconds === this.seconds && other.nanoseconds === this.nanoseconds\n );\n }\n\n /** Returns a textual representation of this `Timestamp`. */\n toString(): string {\n return (\n 'Timestamp(seconds=' +\n this.seconds +\n ', nanoseconds=' +\n this.nanoseconds +\n ')'\n );\n }\n\n static _jsonSchemaVersion: string = 'firestore/timestamp/1.0';\n static _jsonSchema = {\n type: property('string', Timestamp._jsonSchemaVersion),\n seconds: property('number'),\n nanoseconds: property('number')\n };\n\n /**\n * Returns a JSON-serializable representation of this `Timestamp`.\n */\n toJSON(): { seconds: number; nanoseconds: number; type: string } {\n return {\n type: Timestamp._jsonSchemaVersion,\n seconds: this.seconds,\n nanoseconds: this.nanoseconds\n };\n }\n\n /**\n * Builds a `Timestamp` instance from a JSON object created by {@link Timestamp.toJSON}.\n */\n static fromJSON(json: object): Timestamp {\n if (validateJSON(json, Timestamp._jsonSchema)) {\n return new Timestamp(json.seconds, json.nanoseconds);\n }\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Unexpected error creating Timestamp from JSON.'\n );\n }\n\n /**\n * Converts this object to a primitive string, which allows `Timestamp` objects\n * to be compared using the `>`, `<=`, `>=` and `>` operators.\n */\n valueOf(): string {\n // This method returns a string of the form . where\n // is translated to have a non-negative value and both \n // and are left-padded with zeroes to be a consistent length.\n // Strings with this format then have a lexicographical ordering that matches\n // the expected ordering. The translation is done to avoid having\n // a leading negative sign (i.e. a leading '-' character) in its string\n // representation, which would affect its lexicographical ordering.\n const adjustedSeconds = this.seconds - MIN_SECONDS;\n // Note: Up to 12 decimal digits are required to represent all valid\n // 'seconds' values.\n const formattedSeconds = String(adjustedSeconds).padStart(12, '0');\n const formattedNanoseconds = String(this.nanoseconds).padStart(9, '0');\n return formattedSeconds + '.' + formattedNanoseconds;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Timestamp } from '../lite-api/timestamp';\nimport {\n Value as ProtoValue,\n MapValue as ProtoMapValue\n} from '../protos/firestore_proto_api';\n\nimport { normalizeTimestamp } from './normalize';\n\n/**\n * Represents a locally-applied ServerTimestamp.\n *\n * Server Timestamps are backed by MapValues that contain an internal field\n * `__type__` with a value of `server_timestamp`. The previous value and local\n * write time are stored in its `__previous_value__` and `__local_write_time__`\n * fields respectively.\n *\n * Notes:\n * - ServerTimestampValue instances are created as the result of applying a\n * transform. They can only exist in the local view of a document. Therefore\n * they do not need to be parsed or serialized.\n * - When evaluated locally (e.g. for snapshot.data()), they by default\n * evaluate to `null`. This behavior can be configured by passing custom\n * FieldValueOptions to value().\n * - With respect to other ServerTimestampValues, they sort by their\n * localWriteTime.\n */\n\nconst SERVER_TIMESTAMP_SENTINEL = 'server_timestamp';\nconst TYPE_KEY = '__type__';\nconst PREVIOUS_VALUE_KEY = '__previous_value__';\nconst LOCAL_WRITE_TIME_KEY = '__local_write_time__';\n\nexport function isServerTimestamp(value: ProtoValue | null): boolean {\n const type = (value?.mapValue?.fields || {})[TYPE_KEY]?.stringValue;\n return type === SERVER_TIMESTAMP_SENTINEL;\n}\n\n/**\n * Creates a new ServerTimestamp proto value (using the internal format).\n */\nexport function serverTimestamp(\n localWriteTime: Timestamp,\n previousValue: ProtoValue | null\n): ProtoValue {\n const mapValue: ProtoMapValue = {\n fields: {\n [TYPE_KEY]: {\n stringValue: SERVER_TIMESTAMP_SENTINEL\n },\n [LOCAL_WRITE_TIME_KEY]: {\n timestampValue: {\n seconds: localWriteTime.seconds,\n nanos: localWriteTime.nanoseconds\n }\n }\n }\n };\n\n // We should avoid storing deeply nested server timestamp map values\n // because we never use the intermediate \"previous values\".\n // For example:\n // previous: 42L, add: t1, result: t1 -> 42L\n // previous: t1, add: t2, result: t2 -> 42L (NOT t2 -> t1 -> 42L)\n // previous: t2, add: t3, result: t3 -> 42L (NOT t3 -> t2 -> t1 -> 42L)\n // `getPreviousValue` recursively traverses server timestamps to find the\n // least recent Value.\n if (previousValue && isServerTimestamp(previousValue)) {\n previousValue = getPreviousValue(previousValue);\n }\n if (previousValue) {\n mapValue.fields![PREVIOUS_VALUE_KEY] = previousValue;\n }\n\n return { mapValue };\n}\n\n/**\n * Returns the value of the field before this ServerTimestamp was set.\n *\n * Preserving the previous values allows the user to display the last resoled\n * value until the backend responds with the timestamp.\n */\nexport function getPreviousValue(value: ProtoValue): ProtoValue | null {\n const previousValue = value.mapValue!.fields![PREVIOUS_VALUE_KEY];\n\n if (isServerTimestamp(previousValue)) {\n return getPreviousValue(previousValue);\n }\n return previousValue;\n}\n\n/**\n * Returns the local time at which this timestamp was first set.\n */\nexport function getLocalWriteTime(value: ProtoValue): Timestamp {\n const localWriteTime = normalizeTimestamp(\n value.mapValue!.fields![LOCAL_WRITE_TIME_KEY].timestampValue!\n );\n return new Timestamp(localWriteTime.seconds, localWriteTime.nanos);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DatabaseId } from '../core/database_info';\nimport {\n ArrayValue,\n LatLng,\n MapValue,\n Timestamp,\n Value as ProtoValue,\n Value\n} from '../protos/firestore_proto_api';\nimport { fail } from '../util/assert';\nimport {\n arrayEquals,\n compareUtf8Strings,\n primitiveComparator\n} from '../util/misc';\nimport { forEach, objectSize } from '../util/obj';\nimport { isNegativeZero } from '../util/types';\n\nimport { DocumentKey } from './document_key';\nimport {\n normalizeByteString,\n normalizeNumber,\n normalizeTimestamp\n} from './normalize';\nimport {\n getLocalWriteTime,\n getPreviousValue,\n isServerTimestamp\n} from './server_timestamps';\nimport { TypeOrder } from './type_order';\n\nexport const TYPE_KEY = '__type__';\nconst MAX_VALUE_TYPE = '__max__';\nexport const MAX_VALUE: Value = {\n mapValue: {\n fields: {\n '__type__': { stringValue: MAX_VALUE_TYPE }\n }\n }\n};\n\nexport const VECTOR_VALUE_SENTINEL = '__vector__';\nexport const VECTOR_MAP_VECTORS_KEY = 'value';\n\nexport const MIN_VALUE: Value = {\n nullValue: 'NULL_VALUE'\n};\n\n/** Extracts the backend's type order for the provided value. */\nexport function typeOrder(value: Value): TypeOrder {\n if ('nullValue' in value) {\n return TypeOrder.NullValue;\n } else if ('booleanValue' in value) {\n return TypeOrder.BooleanValue;\n } else if ('integerValue' in value || 'doubleValue' in value) {\n return TypeOrder.NumberValue;\n } else if ('timestampValue' in value) {\n return TypeOrder.TimestampValue;\n } else if ('stringValue' in value) {\n return TypeOrder.StringValue;\n } else if ('bytesValue' in value) {\n return TypeOrder.BlobValue;\n } else if ('referenceValue' in value) {\n return TypeOrder.RefValue;\n } else if ('geoPointValue' in value) {\n return TypeOrder.GeoPointValue;\n } else if ('arrayValue' in value) {\n return TypeOrder.ArrayValue;\n } else if ('mapValue' in value) {\n if (isServerTimestamp(value)) {\n return TypeOrder.ServerTimestampValue;\n } else if (isMaxValue(value)) {\n return TypeOrder.MaxValue;\n } else if (isVectorValue(value)) {\n return TypeOrder.VectorValue;\n }\n return TypeOrder.ObjectValue;\n } else {\n return fail(0x6e87, 'Invalid value type', { value });\n }\n}\n\n/** Tests `left` and `right` for equality based on the backend semantics. */\nexport function valueEquals(left: Value, right: Value): boolean {\n if (left === right) {\n return true;\n }\n\n const leftType = typeOrder(left);\n const rightType = typeOrder(right);\n if (leftType !== rightType) {\n return false;\n }\n\n switch (leftType) {\n case TypeOrder.NullValue:\n return true;\n case TypeOrder.BooleanValue:\n return left.booleanValue === right.booleanValue;\n case TypeOrder.ServerTimestampValue:\n return getLocalWriteTime(left).isEqual(getLocalWriteTime(right));\n case TypeOrder.TimestampValue:\n return timestampEquals(left, right);\n case TypeOrder.StringValue:\n return left.stringValue === right.stringValue;\n case TypeOrder.BlobValue:\n return blobEquals(left, right);\n case TypeOrder.RefValue:\n return left.referenceValue === right.referenceValue;\n case TypeOrder.GeoPointValue:\n return geoPointEquals(left, right);\n case TypeOrder.NumberValue:\n return numberEquals(left, right);\n case TypeOrder.ArrayValue:\n return arrayEquals(\n left.arrayValue!.values || [],\n right.arrayValue!.values || [],\n valueEquals\n );\n case TypeOrder.VectorValue:\n case TypeOrder.ObjectValue:\n return objectEquals(left, right);\n case TypeOrder.MaxValue:\n return true;\n default:\n return fail(0xcbf8, 'Unexpected value type', { left });\n }\n}\n\nfunction timestampEquals(left: Value, right: Value): boolean {\n if (\n typeof left.timestampValue === 'string' &&\n typeof right.timestampValue === 'string' &&\n left.timestampValue.length === right.timestampValue.length\n ) {\n // Use string equality for ISO 8601 timestamps\n return left.timestampValue === right.timestampValue;\n }\n\n const leftTimestamp = normalizeTimestamp(left.timestampValue!);\n const rightTimestamp = normalizeTimestamp(right.timestampValue!);\n return (\n leftTimestamp.seconds === rightTimestamp.seconds &&\n leftTimestamp.nanos === rightTimestamp.nanos\n );\n}\n\nfunction geoPointEquals(left: Value, right: Value): boolean {\n return (\n normalizeNumber(left.geoPointValue!.latitude) ===\n normalizeNumber(right.geoPointValue!.latitude) &&\n normalizeNumber(left.geoPointValue!.longitude) ===\n normalizeNumber(right.geoPointValue!.longitude)\n );\n}\n\nfunction blobEquals(left: Value, right: Value): boolean {\n return normalizeByteString(left.bytesValue!).isEqual(\n normalizeByteString(right.bytesValue!)\n );\n}\n\nexport function numberEquals(left: Value, right: Value): boolean {\n if ('integerValue' in left && 'integerValue' in right) {\n return (\n normalizeNumber(left.integerValue) === normalizeNumber(right.integerValue)\n );\n } else if ('doubleValue' in left && 'doubleValue' in right) {\n const n1 = normalizeNumber(left.doubleValue!);\n const n2 = normalizeNumber(right.doubleValue!);\n\n if (n1 === n2) {\n return isNegativeZero(n1) === isNegativeZero(n2);\n } else {\n return isNaN(n1) && isNaN(n2);\n }\n }\n\n return false;\n}\n\nfunction objectEquals(left: Value, right: Value): boolean {\n const leftMap = left.mapValue!.fields || {};\n const rightMap = right.mapValue!.fields || {};\n\n if (objectSize(leftMap) !== objectSize(rightMap)) {\n return false;\n }\n\n for (const key in leftMap) {\n if (leftMap.hasOwnProperty(key)) {\n if (\n rightMap[key] === undefined ||\n !valueEquals(leftMap[key], rightMap[key])\n ) {\n return false;\n }\n }\n }\n return true;\n}\n\n/** Returns true if the ArrayValue contains the specified element. */\nexport function arrayValueContains(\n haystack: ArrayValue,\n needle: Value\n): boolean {\n return (\n (haystack.values || []).find(v => valueEquals(v, needle)) !== undefined\n );\n}\n\nexport function valueCompare(left: Value, right: Value): number {\n if (left === right) {\n return 0;\n }\n\n const leftType = typeOrder(left);\n const rightType = typeOrder(right);\n\n if (leftType !== rightType) {\n return primitiveComparator(leftType, rightType);\n }\n\n switch (leftType) {\n case TypeOrder.NullValue:\n case TypeOrder.MaxValue:\n return 0;\n case TypeOrder.BooleanValue:\n return primitiveComparator(left.booleanValue!, right.booleanValue!);\n case TypeOrder.NumberValue:\n return compareNumbers(left, right);\n case TypeOrder.TimestampValue:\n return compareTimestamps(left.timestampValue!, right.timestampValue!);\n case TypeOrder.ServerTimestampValue:\n return compareTimestamps(\n getLocalWriteTime(left),\n getLocalWriteTime(right)\n );\n case TypeOrder.StringValue:\n return compareUtf8Strings(left.stringValue!, right.stringValue!);\n case TypeOrder.BlobValue:\n return compareBlobs(left.bytesValue!, right.bytesValue!);\n case TypeOrder.RefValue:\n return compareReferences(left.referenceValue!, right.referenceValue!);\n case TypeOrder.GeoPointValue:\n return compareGeoPoints(left.geoPointValue!, right.geoPointValue!);\n case TypeOrder.ArrayValue:\n return compareArrays(left.arrayValue!, right.arrayValue!);\n case TypeOrder.VectorValue:\n return compareVectors(left.mapValue!, right.mapValue!);\n case TypeOrder.ObjectValue:\n return compareMaps(left.mapValue!, right.mapValue!);\n default:\n throw fail(0x5ae0, 'Invalid value type', { leftType });\n }\n}\n\nfunction compareNumbers(left: Value, right: Value): number {\n const leftNumber = normalizeNumber(left.integerValue || left.doubleValue);\n const rightNumber = normalizeNumber(right.integerValue || right.doubleValue);\n\n if (leftNumber < rightNumber) {\n return -1;\n } else if (leftNumber > rightNumber) {\n return 1;\n } else if (leftNumber === rightNumber) {\n return 0;\n } else {\n // one or both are NaN.\n if (isNaN(leftNumber)) {\n return isNaN(rightNumber) ? 0 : -1;\n } else {\n return 1;\n }\n }\n}\n\nfunction compareTimestamps(left: Timestamp, right: Timestamp): number {\n if (\n typeof left === 'string' &&\n typeof right === 'string' &&\n left.length === right.length\n ) {\n return primitiveComparator(left, right);\n }\n\n const leftTimestamp = normalizeTimestamp(left);\n const rightTimestamp = normalizeTimestamp(right);\n\n const comparison = primitiveComparator(\n leftTimestamp.seconds,\n rightTimestamp.seconds\n );\n if (comparison !== 0) {\n return comparison;\n }\n return primitiveComparator(leftTimestamp.nanos, rightTimestamp.nanos);\n}\n\nfunction compareReferences(leftPath: string, rightPath: string): number {\n const leftSegments = leftPath.split('/');\n const rightSegments = rightPath.split('/');\n for (let i = 0; i < leftSegments.length && i < rightSegments.length; i++) {\n const comparison = primitiveComparator(leftSegments[i], rightSegments[i]);\n if (comparison !== 0) {\n return comparison;\n }\n }\n return primitiveComparator(leftSegments.length, rightSegments.length);\n}\n\nfunction compareGeoPoints(left: LatLng, right: LatLng): number {\n const comparison = primitiveComparator(\n normalizeNumber(left.latitude),\n normalizeNumber(right.latitude)\n );\n if (comparison !== 0) {\n return comparison;\n }\n return primitiveComparator(\n normalizeNumber(left.longitude),\n normalizeNumber(right.longitude)\n );\n}\n\nfunction compareBlobs(\n left: string | Uint8Array,\n right: string | Uint8Array\n): number {\n const leftBytes = normalizeByteString(left);\n const rightBytes = normalizeByteString(right);\n return leftBytes.compareTo(rightBytes);\n}\n\nfunction compareArrays(left: ArrayValue, right: ArrayValue): number {\n const leftArray = left.values || [];\n const rightArray = right.values || [];\n\n for (let i = 0; i < leftArray.length && i < rightArray.length; ++i) {\n const compare = valueCompare(leftArray[i], rightArray[i]);\n if (compare) {\n return compare;\n }\n }\n return primitiveComparator(leftArray.length, rightArray.length);\n}\n\nfunction compareVectors(left: MapValue, right: MapValue): number {\n const leftMap = left.fields || {};\n const rightMap = right.fields || {};\n\n // The vector is a map, but only vector value is compared.\n const leftArrayValue = leftMap[VECTOR_MAP_VECTORS_KEY]?.arrayValue;\n const rightArrayValue = rightMap[VECTOR_MAP_VECTORS_KEY]?.arrayValue;\n\n const lengthCompare = primitiveComparator(\n leftArrayValue?.values?.length || 0,\n rightArrayValue?.values?.length || 0\n );\n if (lengthCompare !== 0) {\n return lengthCompare;\n }\n\n return compareArrays(leftArrayValue!, rightArrayValue!);\n}\n\nfunction compareMaps(left: MapValue, right: MapValue): number {\n if (left === MAX_VALUE.mapValue && right === MAX_VALUE.mapValue) {\n return 0;\n } else if (left === MAX_VALUE.mapValue) {\n return 1;\n } else if (right === MAX_VALUE.mapValue) {\n return -1;\n }\n\n const leftMap = left.fields || {};\n const leftKeys = Object.keys(leftMap);\n const rightMap = right.fields || {};\n const rightKeys = Object.keys(rightMap);\n\n // Even though MapValues are likely sorted correctly based on their insertion\n // order (e.g. when received from the backend), local modifications can bring\n // elements out of order. We need to re-sort the elements to ensure that\n // canonical IDs are independent of insertion order.\n leftKeys.sort();\n rightKeys.sort();\n\n for (let i = 0; i < leftKeys.length && i < rightKeys.length; ++i) {\n const keyCompare = compareUtf8Strings(leftKeys[i], rightKeys[i]);\n if (keyCompare !== 0) {\n return keyCompare;\n }\n const compare = valueCompare(leftMap[leftKeys[i]], rightMap[rightKeys[i]]);\n if (compare !== 0) {\n return compare;\n }\n }\n\n return primitiveComparator(leftKeys.length, rightKeys.length);\n}\n\n/**\n * Generates the canonical ID for the provided field value (as used in Target\n * serialization).\n */\nexport function canonicalId(value: Value): string {\n return canonifyValue(value);\n}\n\nfunction canonifyValue(value: Value): string {\n if ('nullValue' in value) {\n return 'null';\n } else if ('booleanValue' in value) {\n return '' + value.booleanValue!;\n } else if ('integerValue' in value) {\n return '' + value.integerValue!;\n } else if ('doubleValue' in value) {\n return '' + value.doubleValue!;\n } else if ('timestampValue' in value) {\n return canonifyTimestamp(value.timestampValue!);\n } else if ('stringValue' in value) {\n return value.stringValue!;\n } else if ('bytesValue' in value) {\n return canonifyByteString(value.bytesValue!);\n } else if ('referenceValue' in value) {\n return canonifyReference(value.referenceValue!);\n } else if ('geoPointValue' in value) {\n return canonifyGeoPoint(value.geoPointValue!);\n } else if ('arrayValue' in value) {\n return canonifyArray(value.arrayValue!);\n } else if ('mapValue' in value) {\n return canonifyMap(value.mapValue!);\n } else {\n return fail(0xee4d, 'Invalid value type', { value });\n }\n}\n\nfunction canonifyByteString(byteString: string | Uint8Array): string {\n return normalizeByteString(byteString).toBase64();\n}\n\nfunction canonifyTimestamp(timestamp: Timestamp): string {\n const normalizedTimestamp = normalizeTimestamp(timestamp);\n return `time(${normalizedTimestamp.seconds},${normalizedTimestamp.nanos})`;\n}\n\nfunction canonifyGeoPoint(geoPoint: LatLng): string {\n return `geo(${geoPoint.latitude},${geoPoint.longitude})`;\n}\n\nfunction canonifyReference(referenceValue: string): string {\n return DocumentKey.fromName(referenceValue).toString();\n}\n\nfunction canonifyMap(mapValue: MapValue): string {\n // Iteration order in JavaScript is not guaranteed. To ensure that we generate\n // matching canonical IDs for identical maps, we need to sort the keys.\n const sortedKeys = Object.keys(mapValue.fields || {}).sort();\n\n let result = '{';\n let first = true;\n for (const key of sortedKeys) {\n if (!first) {\n result += ',';\n } else {\n first = false;\n }\n result += `${key}:${canonifyValue(mapValue.fields![key])}`;\n }\n return result + '}';\n}\n\nfunction canonifyArray(arrayValue: ArrayValue): string {\n let result = '[';\n let first = true;\n for (const value of arrayValue.values || []) {\n if (!first) {\n result += ',';\n } else {\n first = false;\n }\n result += canonifyValue(value);\n }\n return result + ']';\n}\n\n/**\n * Returns an approximate (and wildly inaccurate) in-memory size for the field\n * value.\n *\n * The memory size takes into account only the actual user data as it resides\n * in memory and ignores object overhead.\n */\nexport function estimateByteSize(value: Value): number {\n switch (typeOrder(value)) {\n case TypeOrder.NullValue:\n return 4;\n case TypeOrder.BooleanValue:\n return 4;\n case TypeOrder.NumberValue:\n return 8;\n case TypeOrder.TimestampValue:\n // Timestamps are made up of two distinct numbers (seconds + nanoseconds)\n return 16;\n case TypeOrder.ServerTimestampValue:\n const previousValue = getPreviousValue(value);\n return previousValue ? 16 + estimateByteSize(previousValue) : 16;\n case TypeOrder.StringValue:\n // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures:\n // \"JavaScript's String type is [...] a set of elements of 16-bit unsigned\n // integer values\"\n return value.stringValue!.length * 2;\n case TypeOrder.BlobValue:\n return normalizeByteString(value.bytesValue!).approximateByteSize();\n case TypeOrder.RefValue:\n return value.referenceValue!.length;\n case TypeOrder.GeoPointValue:\n // GeoPoints are made up of two distinct numbers (latitude + longitude)\n return 16;\n case TypeOrder.ArrayValue:\n return estimateArrayByteSize(value.arrayValue!);\n case TypeOrder.VectorValue:\n case TypeOrder.ObjectValue:\n return estimateMapByteSize(value.mapValue!);\n default:\n throw fail(0x34ae, 'Invalid value type', { value });\n }\n}\n\nfunction estimateMapByteSize(mapValue: MapValue): number {\n let size = 0;\n forEach(mapValue.fields, (key, val) => {\n size += key.length + estimateByteSize(val);\n });\n return size;\n}\n\nfunction estimateArrayByteSize(arrayValue: ArrayValue): number {\n return (arrayValue.values || []).reduce(\n (previousSize, value) => previousSize + estimateByteSize(value),\n 0\n );\n}\n\n/** Returns a reference value for the provided database and key. */\nexport function refValue(databaseId: DatabaseId, key: DocumentKey): Value {\n return {\n referenceValue: `projects/${databaseId.projectId}/databases/${\n databaseId.database\n }/documents/${key.path.canonicalString()}`\n };\n}\n\n/** Returns true if `value` is an IntegerValue . */\nexport function isInteger(\n value?: Value | null\n): value is { integerValue: string | number } {\n return !!value && 'integerValue' in value;\n}\n\n/** Returns true if `value` is a DoubleValue. */\nexport function isDouble(\n value?: Value | null\n): value is { doubleValue: string | number } {\n return !!value && 'doubleValue' in value;\n}\n\n/** Returns true if `value` is either an IntegerValue or a DoubleValue. */\nexport function isNumber(value?: Value | null): boolean {\n return isInteger(value) || isDouble(value);\n}\n\n/** Returns true if `value` is an ArrayValue. */\nexport function isArray(\n value?: Value | null\n): value is { arrayValue: ArrayValue } {\n return !!value && 'arrayValue' in value;\n}\n\n/** Returns true if `value` is a ReferenceValue. */\nexport function isReferenceValue(\n value?: Value | null\n): value is { referenceValue: string } {\n return !!value && 'referenceValue' in value;\n}\n\n/** Returns true if `value` is a NullValue. */\nexport function isNullValue(\n value?: Value | null\n): value is { nullValue: 'NULL_VALUE' } {\n return !!value && 'nullValue' in value;\n}\n\n/** Returns true if `value` is NaN. */\nexport function isNanValue(\n value?: Value | null\n): value is { doubleValue: 'NaN' | number } {\n return !!value && 'doubleValue' in value && isNaN(Number(value.doubleValue));\n}\n\n/** Returns true if `value` is a MapValue. */\nexport function isMapValue(\n value?: Value | null\n): value is { mapValue: MapValue } {\n return !!value && 'mapValue' in value;\n}\n\n/** Returns true if `value` is a VetorValue. */\nexport function isVectorValue(value: ProtoValue | null): boolean {\n const type = (value?.mapValue?.fields || {})[TYPE_KEY]?.stringValue;\n return type === VECTOR_VALUE_SENTINEL;\n}\n\n/** Creates a deep copy of `source`. */\nexport function deepClone(source: Value): Value {\n if (source.geoPointValue) {\n return { geoPointValue: { ...source.geoPointValue } };\n } else if (\n source.timestampValue &&\n typeof source.timestampValue === 'object'\n ) {\n return { timestampValue: { ...source.timestampValue } };\n } else if (source.mapValue) {\n const target: Value = { mapValue: { fields: {} } };\n forEach(\n source.mapValue.fields,\n (key, val) => (target.mapValue!.fields![key] = deepClone(val))\n );\n return target;\n } else if (source.arrayValue) {\n const target: Value = { arrayValue: { values: [] } };\n for (let i = 0; i < (source.arrayValue.values || []).length; ++i) {\n target.arrayValue!.values![i] = deepClone(source.arrayValue.values![i]);\n }\n return target;\n } else {\n return { ...source };\n }\n}\n\n/** Returns true if the Value represents the canonical {@link #MAX_VALUE} . */\nexport function isMaxValue(value: Value): boolean {\n return (\n (((value.mapValue || {}).fields || {})['__type__'] || {}).stringValue ===\n MAX_VALUE_TYPE\n );\n}\n\nexport const MIN_VECTOR_VALUE = {\n mapValue: {\n fields: {\n [TYPE_KEY]: { stringValue: VECTOR_VALUE_SENTINEL },\n [VECTOR_MAP_VECTORS_KEY]: {\n arrayValue: {}\n }\n }\n }\n};\n\n/** Returns the lowest value for the given value type (inclusive). */\nexport function valuesGetLowerBound(value: Value): Value {\n if ('nullValue' in value) {\n return MIN_VALUE;\n } else if ('booleanValue' in value) {\n return { booleanValue: false };\n } else if ('integerValue' in value || 'doubleValue' in value) {\n return { doubleValue: NaN };\n } else if ('timestampValue' in value) {\n return { timestampValue: { seconds: Number.MIN_SAFE_INTEGER } };\n } else if ('stringValue' in value) {\n return { stringValue: '' };\n } else if ('bytesValue' in value) {\n return { bytesValue: '' };\n } else if ('referenceValue' in value) {\n return refValue(DatabaseId.empty(), DocumentKey.empty());\n } else if ('geoPointValue' in value) {\n return { geoPointValue: { latitude: -90, longitude: -180 } };\n } else if ('arrayValue' in value) {\n return { arrayValue: {} };\n } else if ('mapValue' in value) {\n if (isVectorValue(value)) {\n return MIN_VECTOR_VALUE;\n }\n return { mapValue: {} };\n } else {\n return fail(0x8c66, 'Invalid value type', { value });\n }\n}\n\n/** Returns the largest value for the given value type (exclusive). */\nexport function valuesGetUpperBound(value: Value): Value {\n if ('nullValue' in value) {\n return { booleanValue: false };\n } else if ('booleanValue' in value) {\n return { doubleValue: NaN };\n } else if ('integerValue' in value || 'doubleValue' in value) {\n return { timestampValue: { seconds: Number.MIN_SAFE_INTEGER } };\n } else if ('timestampValue' in value) {\n return { stringValue: '' };\n } else if ('stringValue' in value) {\n return { bytesValue: '' };\n } else if ('bytesValue' in value) {\n return refValue(DatabaseId.empty(), DocumentKey.empty());\n } else if ('referenceValue' in value) {\n return { geoPointValue: { latitude: -90, longitude: -180 } };\n } else if ('geoPointValue' in value) {\n return { arrayValue: {} };\n } else if ('arrayValue' in value) {\n return MIN_VECTOR_VALUE;\n } else if ('mapValue' in value) {\n if (isVectorValue(value)) {\n return { mapValue: {} };\n }\n return MAX_VALUE;\n } else {\n return fail(0xf207, 'Invalid value type', { value });\n }\n}\n\nexport function lowerBoundCompare(\n left: { value: Value; inclusive: boolean },\n right: { value: Value; inclusive: boolean }\n): number {\n const cmp = valueCompare(left.value, right.value);\n if (cmp !== 0) {\n return cmp;\n }\n\n if (left.inclusive && !right.inclusive) {\n return -1;\n } else if (!left.inclusive && right.inclusive) {\n return 1;\n }\n\n return 0;\n}\n\nexport function upperBoundCompare(\n left: { value: Value; inclusive: boolean },\n right: { value: Value; inclusive: boolean }\n): number {\n const cmp = valueCompare(left.value, right.value);\n if (cmp !== 0) {\n return cmp;\n }\n\n if (left.inclusive && !right.inclusive) {\n return 1;\n } else if (!left.inclusive && right.inclusive) {\n return -1;\n }\n\n return 0;\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { isReferenceValue, valueCompare, valueEquals } from '../model/values';\nimport { Value as ProtoValue } from '../protos/firestore_proto_api';\nimport { debugAssert } from '../util/assert';\n\nimport { Direction, OrderBy } from './order_by';\n\n/**\n * Represents a bound of a query.\n *\n * The bound is specified with the given components representing a position and\n * whether it's just before or just after the position (relative to whatever the\n * query order is).\n *\n * The position represents a logical index position for a query. It's a prefix\n * of values for the (potentially implicit) order by clauses of a query.\n *\n * Bound provides a function to determine whether a document comes before or\n * after a bound. This is influenced by whether the position is just before or\n * just after the provided values.\n */\nexport class Bound {\n constructor(readonly position: ProtoValue[], readonly inclusive: boolean) {}\n}\n\nfunction boundCompareToDocument(\n bound: Bound,\n orderBy: OrderBy[],\n doc: Document\n): number {\n debugAssert(\n bound.position.length <= orderBy.length,\n \"Bound has more components than query's orderBy\"\n );\n let comparison = 0;\n for (let i = 0; i < bound.position.length; i++) {\n const orderByComponent = orderBy[i];\n const component = bound.position[i];\n if (orderByComponent.field.isKeyField()) {\n debugAssert(\n isReferenceValue(component),\n 'Bound has a non-key value where the key path is being used.'\n );\n comparison = DocumentKey.comparator(\n DocumentKey.fromName(component.referenceValue),\n doc.key\n );\n } else {\n const docValue = doc.data.field(orderByComponent.field);\n debugAssert(\n docValue !== null,\n 'Field should exist since document matched the orderBy already.'\n );\n comparison = valueCompare(component, docValue);\n }\n if (orderByComponent.dir === Direction.DESCENDING) {\n comparison = comparison * -1;\n }\n if (comparison !== 0) {\n break;\n }\n }\n return comparison;\n}\n\n/**\n * Returns true if a document sorts after a bound using the provided sort\n * order.\n */\nexport function boundSortsAfterDocument(\n bound: Bound,\n orderBy: OrderBy[],\n doc: Document\n): boolean {\n const comparison = boundCompareToDocument(bound, orderBy, doc);\n return bound.inclusive ? comparison >= 0 : comparison > 0;\n}\n\n/**\n * Returns true if a document sorts before a bound using the provided sort\n * order.\n */\nexport function boundSortsBeforeDocument(\n bound: Bound,\n orderBy: OrderBy[],\n doc: Document\n): boolean {\n const comparison = boundCompareToDocument(bound, orderBy, doc);\n return bound.inclusive ? comparison <= 0 : comparison < 0;\n}\n\nexport function boundEquals(left: Bound | null, right: Bound | null): boolean {\n if (left === null) {\n return right === null;\n } else if (right === null) {\n return false;\n }\n\n if (\n left.inclusive !== right.inclusive ||\n left.position.length !== right.position.length\n ) {\n return false;\n }\n for (let i = 0; i < left.position.length; i++) {\n const leftPosition = left.position[i];\n const rightPosition = right.position[i];\n if (!valueEquals(leftPosition, rightPosition)) {\n return false;\n }\n }\n return true;\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { FieldPath } from '../model/path';\nimport {\n arrayValueContains,\n canonicalId,\n isArray,\n isReferenceValue,\n typeOrder,\n valueCompare,\n valueEquals\n} from '../model/values';\nimport { Value as ProtoValue } from '../protos/firestore_proto_api';\nimport { debugAssert, fail } from '../util/assert';\n\n// The operator of a FieldFilter\nexport const enum Operator {\n LESS_THAN = '<',\n LESS_THAN_OR_EQUAL = '<=',\n EQUAL = '==',\n NOT_EQUAL = '!=',\n GREATER_THAN = '>',\n GREATER_THAN_OR_EQUAL = '>=',\n ARRAY_CONTAINS = 'array-contains',\n IN = 'in',\n NOT_IN = 'not-in',\n ARRAY_CONTAINS_ANY = 'array-contains-any'\n}\n\n// The operator of a CompositeFilter\nexport const enum CompositeOperator {\n OR = 'or',\n AND = 'and'\n}\n\nexport abstract class Filter {\n abstract matches(doc: Document): boolean;\n\n abstract getFlattenedFilters(): readonly FieldFilter[];\n\n abstract getFilters(): Filter[];\n}\n\nexport class FieldFilter extends Filter {\n protected constructor(\n public readonly field: FieldPath,\n public readonly op: Operator,\n public readonly value: ProtoValue\n ) {\n super();\n }\n\n /**\n * Creates a filter based on the provided arguments.\n */\n static create(\n field: FieldPath,\n op: Operator,\n value: ProtoValue\n ): FieldFilter {\n if (field.isKeyField()) {\n if (op === Operator.IN || op === Operator.NOT_IN) {\n return this.createKeyFieldInFilter(field, op, value);\n } else {\n debugAssert(\n isReferenceValue(value),\n 'Comparing on key, but filter value not a RefValue'\n );\n debugAssert(\n op !== Operator.ARRAY_CONTAINS && op !== Operator.ARRAY_CONTAINS_ANY,\n `'${op.toString()}' queries don't make sense on document keys.`\n );\n return new KeyFieldFilter(field, op, value);\n }\n } else if (op === Operator.ARRAY_CONTAINS) {\n return new ArrayContainsFilter(field, value);\n } else if (op === Operator.IN) {\n debugAssert(\n isArray(value),\n 'IN filter has invalid value: ' + value.toString()\n );\n return new InFilter(field, value);\n } else if (op === Operator.NOT_IN) {\n debugAssert(\n isArray(value),\n 'NOT_IN filter has invalid value: ' + value.toString()\n );\n return new NotInFilter(field, value);\n } else if (op === Operator.ARRAY_CONTAINS_ANY) {\n debugAssert(\n isArray(value),\n 'ARRAY_CONTAINS_ANY filter has invalid value: ' + value.toString()\n );\n return new ArrayContainsAnyFilter(field, value);\n } else {\n return new FieldFilter(field, op, value);\n }\n }\n\n private static createKeyFieldInFilter(\n field: FieldPath,\n op: Operator.IN | Operator.NOT_IN,\n value: ProtoValue\n ): FieldFilter {\n debugAssert(\n isArray(value),\n `Comparing on key with ${op.toString()}` +\n ', but filter value not an ArrayValue'\n );\n debugAssert(\n (value.arrayValue.values || []).every(elem => isReferenceValue(elem)),\n `Comparing on key with ${op.toString()}` +\n ', but an array value was not a RefValue'\n );\n\n return op === Operator.IN\n ? new KeyFieldInFilter(field, value)\n : new KeyFieldNotInFilter(field, value);\n }\n\n matches(doc: Document): boolean {\n const other = doc.data.field(this.field);\n // Types do not have to match in NOT_EQUAL filters.\n if (this.op === Operator.NOT_EQUAL) {\n return (\n other !== null &&\n other.nullValue === undefined &&\n this.matchesComparison(valueCompare(other!, this.value))\n );\n }\n\n // Only compare types with matching backend order (such as double and int).\n return (\n other !== null &&\n typeOrder(this.value) === typeOrder(other) &&\n this.matchesComparison(valueCompare(other, this.value))\n );\n }\n\n protected matchesComparison(comparison: number): boolean {\n switch (this.op) {\n case Operator.LESS_THAN:\n return comparison < 0;\n case Operator.LESS_THAN_OR_EQUAL:\n return comparison <= 0;\n case Operator.EQUAL:\n return comparison === 0;\n case Operator.NOT_EQUAL:\n return comparison !== 0;\n case Operator.GREATER_THAN:\n return comparison > 0;\n case Operator.GREATER_THAN_OR_EQUAL:\n return comparison >= 0;\n default:\n return fail(0xb8a2, 'Unknown FieldFilter operator', {\n operator: this.op\n });\n }\n }\n\n isInequality(): boolean {\n return (\n [\n Operator.LESS_THAN,\n Operator.LESS_THAN_OR_EQUAL,\n Operator.GREATER_THAN,\n Operator.GREATER_THAN_OR_EQUAL,\n Operator.NOT_EQUAL,\n Operator.NOT_IN\n ].indexOf(this.op) >= 0\n );\n }\n\n getFlattenedFilters(): readonly FieldFilter[] {\n return [this];\n }\n\n getFilters(): Filter[] {\n return [this];\n }\n}\n\nexport class CompositeFilter extends Filter {\n private memoizedFlattenedFilters: FieldFilter[] | null = null;\n\n protected constructor(\n public readonly filters: readonly Filter[],\n public readonly op: CompositeOperator\n ) {\n super();\n }\n\n /**\n * Creates a filter based on the provided arguments.\n */\n static create(filters: Filter[], op: CompositeOperator): CompositeFilter {\n return new CompositeFilter(filters, op);\n }\n\n matches(doc: Document): boolean {\n if (compositeFilterIsConjunction(this)) {\n // For conjunctions, all filters must match, so return false if any filter doesn't match.\n return this.filters.find(filter => !filter.matches(doc)) === undefined;\n } else {\n // For disjunctions, at least one filter should match.\n return this.filters.find(filter => filter.matches(doc)) !== undefined;\n }\n }\n\n getFlattenedFilters(): readonly FieldFilter[] {\n if (this.memoizedFlattenedFilters !== null) {\n return this.memoizedFlattenedFilters;\n }\n\n this.memoizedFlattenedFilters = this.filters.reduce((result, subfilter) => {\n return result.concat(subfilter.getFlattenedFilters());\n }, [] as FieldFilter[]);\n\n return this.memoizedFlattenedFilters;\n }\n\n // Returns a mutable copy of `this.filters`\n getFilters(): Filter[] {\n return Object.assign([], this.filters);\n }\n}\n\nexport function compositeFilterIsConjunction(\n compositeFilter: CompositeFilter\n): boolean {\n return compositeFilter.op === CompositeOperator.AND;\n}\n\nexport function compositeFilterIsDisjunction(\n compositeFilter: CompositeFilter\n): boolean {\n return compositeFilter.op === CompositeOperator.OR;\n}\n\n/**\n * Returns true if this filter is a conjunction of field filters only. Returns false otherwise.\n */\nexport function compositeFilterIsFlatConjunction(\n compositeFilter: CompositeFilter\n): boolean {\n return (\n compositeFilterIsFlat(compositeFilter) &&\n compositeFilterIsConjunction(compositeFilter)\n );\n}\n\n/**\n * Returns true if this filter does not contain any composite filters. Returns false otherwise.\n */\nexport function compositeFilterIsFlat(\n compositeFilter: CompositeFilter\n): boolean {\n for (const filter of compositeFilter.filters) {\n if (filter instanceof CompositeFilter) {\n return false;\n }\n }\n return true;\n}\n\nexport function canonifyFilter(filter: Filter): string {\n debugAssert(\n filter instanceof FieldFilter || filter instanceof CompositeFilter,\n 'canonifyFilter() only supports FieldFilters and CompositeFilters'\n );\n\n if (filter instanceof FieldFilter) {\n // TODO(b/29183165): Technically, this won't be unique if two values have\n // the same description, such as the int 3 and the string \"3\". So we should\n // add the types in here somehow, too.\n return (\n filter.field.canonicalString() +\n filter.op.toString() +\n canonicalId(filter.value)\n );\n } else if (compositeFilterIsFlatConjunction(filter)) {\n // Older SDK versions use an implicit AND operation between their filters.\n // In the new SDK versions, the developer may use an explicit AND filter.\n // To stay consistent with the old usages, we add a special case to ensure\n // the canonical ID for these two are the same. For example:\n // `col.whereEquals(\"a\", 1).whereEquals(\"b\", 2)` should have the same\n // canonical ID as `col.where(and(equals(\"a\",1), equals(\"b\",2)))`.\n return filter.filters.map(filter => canonifyFilter(filter)).join(',');\n } else {\n // filter instanceof CompositeFilter\n const canonicalIdsString = filter.filters\n .map(filter => canonifyFilter(filter))\n .join(',');\n return `${filter.op}(${canonicalIdsString})`;\n }\n}\n\nexport function filterEquals(f1: Filter, f2: Filter): boolean {\n if (f1 instanceof FieldFilter) {\n return fieldFilterEquals(f1, f2);\n } else if (f1 instanceof CompositeFilter) {\n return compositeFilterEquals(f1, f2);\n } else {\n fail(0x4bef, 'Only FieldFilters and CompositeFilters can be compared');\n }\n}\n\nexport function fieldFilterEquals(f1: FieldFilter, f2: Filter): boolean {\n return (\n f2 instanceof FieldFilter &&\n f1.op === f2.op &&\n f1.field.isEqual(f2.field) &&\n valueEquals(f1.value, f2.value)\n );\n}\n\nexport function compositeFilterEquals(\n f1: CompositeFilter,\n f2: Filter\n): boolean {\n if (\n f2 instanceof CompositeFilter &&\n f1.op === f2.op &&\n f1.filters.length === f2.filters.length\n ) {\n const subFiltersMatch: boolean = f1.filters.reduce(\n (result: boolean, f1Filter: Filter, index: number): boolean =>\n result && filterEquals(f1Filter, f2.filters[index]),\n true\n );\n\n return subFiltersMatch;\n }\n\n return false;\n}\n\n/**\n * Returns a new composite filter that contains all filter from\n * `compositeFilter` plus all the given filters in `otherFilters`.\n */\nexport function compositeFilterWithAddedFilters(\n compositeFilter: CompositeFilter,\n otherFilters: Filter[]\n): CompositeFilter {\n const mergedFilters = compositeFilter.filters.concat(otherFilters);\n return CompositeFilter.create(mergedFilters, compositeFilter.op);\n}\n\n/** Returns a debug description for `filter`. */\nexport function stringifyFilter(filter: Filter): string {\n debugAssert(\n filter instanceof FieldFilter || filter instanceof CompositeFilter,\n 'stringifyFilter() only supports FieldFilters and CompositeFilters'\n );\n if (filter instanceof FieldFilter) {\n return stringifyFieldFilter(filter);\n } else if (filter instanceof CompositeFilter) {\n return stringifyCompositeFilter(filter);\n } else {\n return 'Filter';\n }\n}\n\nexport function stringifyCompositeFilter(filter: CompositeFilter): string {\n return (\n filter.op.toString() +\n ` {` +\n filter.getFilters().map(stringifyFilter).join(' ,') +\n '}'\n );\n}\n\nexport function stringifyFieldFilter(filter: FieldFilter): string {\n return `${filter.field.canonicalString()} ${filter.op} ${canonicalId(\n filter.value\n )}`;\n}\n\n/** Filter that matches on key fields (i.e. '__name__'). */\nexport class KeyFieldFilter extends FieldFilter {\n private readonly key: DocumentKey;\n\n constructor(field: FieldPath, op: Operator, value: ProtoValue) {\n super(field, op, value);\n debugAssert(\n isReferenceValue(value),\n 'KeyFieldFilter expects a ReferenceValue'\n );\n this.key = DocumentKey.fromName(value.referenceValue);\n }\n\n matches(doc: Document): boolean {\n const comparison = DocumentKey.comparator(doc.key, this.key);\n return this.matchesComparison(comparison);\n }\n}\n\n/** Filter that matches on key fields within an array. */\nexport class KeyFieldInFilter extends FieldFilter {\n private readonly keys: DocumentKey[];\n\n constructor(field: FieldPath, value: ProtoValue) {\n super(field, Operator.IN, value);\n this.keys = extractDocumentKeysFromArrayValue(Operator.IN, value);\n }\n\n matches(doc: Document): boolean {\n return this.keys.some(key => key.isEqual(doc.key));\n }\n}\n\n/** Filter that matches on key fields not present within an array. */\nexport class KeyFieldNotInFilter extends FieldFilter {\n private readonly keys: DocumentKey[];\n\n constructor(field: FieldPath, value: ProtoValue) {\n super(field, Operator.NOT_IN, value);\n this.keys = extractDocumentKeysFromArrayValue(Operator.NOT_IN, value);\n }\n\n matches(doc: Document): boolean {\n return !this.keys.some(key => key.isEqual(doc.key));\n }\n}\n\nfunction extractDocumentKeysFromArrayValue(\n op: Operator.IN | Operator.NOT_IN,\n value: ProtoValue\n): DocumentKey[] {\n debugAssert(\n isArray(value),\n 'KeyFieldInFilter/KeyFieldNotInFilter expects an ArrayValue'\n );\n return (value.arrayValue?.values || []).map(v => {\n debugAssert(\n isReferenceValue(v),\n `Comparing on key with ${op.toString()}, but an array value was not ` +\n `a ReferenceValue`\n );\n return DocumentKey.fromName(v.referenceValue);\n });\n}\n\n/** A Filter that implements the array-contains operator. */\nexport class ArrayContainsFilter extends FieldFilter {\n constructor(field: FieldPath, value: ProtoValue) {\n super(field, Operator.ARRAY_CONTAINS, value);\n }\n\n matches(doc: Document): boolean {\n const other = doc.data.field(this.field);\n return isArray(other) && arrayValueContains(other.arrayValue, this.value);\n }\n}\n\n/** A Filter that implements the IN operator. */\nexport class InFilter extends FieldFilter {\n constructor(field: FieldPath, value: ProtoValue) {\n super(field, Operator.IN, value);\n debugAssert(isArray(value), 'InFilter expects an ArrayValue');\n }\n\n matches(doc: Document): boolean {\n const other = doc.data.field(this.field);\n return other !== null && arrayValueContains(this.value.arrayValue!, other);\n }\n}\n\n/** A Filter that implements the not-in operator. */\nexport class NotInFilter extends FieldFilter {\n constructor(field: FieldPath, value: ProtoValue) {\n super(field, Operator.NOT_IN, value);\n debugAssert(isArray(value), 'NotInFilter expects an ArrayValue');\n }\n\n matches(doc: Document): boolean {\n if (\n arrayValueContains(this.value.arrayValue!, { nullValue: 'NULL_VALUE' })\n ) {\n return false;\n }\n const other = doc.data.field(this.field);\n return (\n other !== null &&\n other.nullValue === undefined &&\n !arrayValueContains(this.value.arrayValue!, other)\n );\n }\n}\n\n/** A Filter that implements the array-contains-any operator. */\nexport class ArrayContainsAnyFilter extends FieldFilter {\n constructor(field: FieldPath, value: ProtoValue) {\n super(field, Operator.ARRAY_CONTAINS_ANY, value);\n debugAssert(isArray(value), 'ArrayContainsAnyFilter expects an ArrayValue');\n }\n\n matches(doc: Document): boolean {\n const other = doc.data.field(this.field);\n if (!isArray(other) || !other.arrayValue.values) {\n return false;\n }\n return other.arrayValue.values.some(val =>\n arrayValueContains(this.value.arrayValue!, val)\n );\n }\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FieldPath } from '../model/path';\n\n/**\n * The direction of sorting in an order by.\n */\nexport const enum Direction {\n ASCENDING = 'asc',\n DESCENDING = 'desc'\n}\n\n/**\n * An ordering on a field, in some Direction. Direction defaults to ASCENDING.\n */\nexport class OrderBy {\n constructor(\n readonly field: FieldPath,\n readonly dir: Direction = Direction.ASCENDING\n ) {}\n}\n\nexport function canonifyOrderBy(orderBy: OrderBy): string {\n // TODO(b/29183165): Make this collision robust.\n return orderBy.field.canonicalString() + orderBy.dir;\n}\n\nexport function stringifyOrderBy(orderBy: OrderBy): string {\n return `${orderBy.field.canonicalString()} (${orderBy.dir})`;\n}\n\nexport function orderByEquals(left: OrderBy, right: OrderBy): boolean {\n return left.dir === right.dir && left.field.isEqual(right.field);\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Timestamp } from '../lite-api/timestamp';\n\n/**\n * A version of a document in Firestore. This corresponds to the version\n * timestamp, such as update_time or read_time.\n */\nexport class SnapshotVersion {\n static fromTimestamp(value: Timestamp): SnapshotVersion {\n return new SnapshotVersion(value);\n }\n\n static min(): SnapshotVersion {\n return new SnapshotVersion(new Timestamp(0, 0));\n }\n\n static max(): SnapshotVersion {\n return new SnapshotVersion(new Timestamp(253402300799, 1e9 - 1));\n }\n\n private constructor(private timestamp: Timestamp) {}\n\n compareTo(other: SnapshotVersion): number {\n return this.timestamp._compareTo(other.timestamp);\n }\n\n isEqual(other: SnapshotVersion): boolean {\n return this.timestamp.isEqual(other.timestamp);\n }\n\n /** Returns a number representation of the version for use in spec tests. */\n toMicroseconds(): number {\n // Convert to microseconds.\n return this.timestamp.seconds * 1e6 + this.timestamp.nanoseconds / 1000;\n }\n\n toString(): string {\n return 'SnapshotVersion(' + this.timestamp.toString() + ')';\n }\n\n toTimestamp(): Timestamp {\n return this.timestamp;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { debugAssert, fail } from './assert';\n\n/*\n * Implementation of an immutable SortedMap using a Left-leaning\n * Red-Black Tree, adapted from the implementation in Mugs\n * (http://mads379.github.com/mugs/) by Mads Hartmann Jensen\n * (mads379@gmail.com).\n *\n * Original paper on Left-leaning Red-Black Trees:\n * http://www.cs.princeton.edu/~rs/talks/LLRB/LLRB.pdf\n *\n * Invariant 1: No red node has a red child\n * Invariant 2: Every leaf path has the same number of black nodes\n * Invariant 3: Only the left child can be red (left leaning)\n */\n\nexport type Comparator = (key1: K, key2: K) => number;\n\nexport interface Entry {\n key: K;\n value: V;\n}\n\n// An immutable sorted map implementation, based on a Left-leaning Red-Black\n// tree.\nexport class SortedMap {\n // visible for testing\n root: LLRBNode | LLRBEmptyNode;\n\n constructor(\n public comparator: Comparator,\n root?: LLRBNode | LLRBEmptyNode\n ) {\n this.root = root ? root : LLRBNode.EMPTY;\n }\n\n // Returns a copy of the map, with the specified key/value added or replaced.\n insert(key: K, value: V): SortedMap {\n return new SortedMap(\n this.comparator,\n this.root\n .insert(key, value, this.comparator)\n .copy(null, null, LLRBNode.BLACK, null, null)\n );\n }\n\n // Returns a copy of the map, with the specified key removed.\n remove(key: K): SortedMap {\n return new SortedMap(\n this.comparator,\n this.root\n .remove(key, this.comparator)\n .copy(null, null, LLRBNode.BLACK, null, null)\n );\n }\n\n // Returns the value of the node with the given key, or null.\n get(key: K): V | null {\n let node = this.root;\n while (!node.isEmpty()) {\n const cmp = this.comparator(key, node.key);\n if (cmp === 0) {\n return node.value;\n } else if (cmp < 0) {\n node = node.left;\n } else if (cmp > 0) {\n node = node.right;\n }\n }\n return null;\n }\n\n // Returns the index of the element in this sorted map, or -1 if it doesn't\n // exist.\n indexOf(key: K): number {\n // Number of nodes that were pruned when descending right\n let prunedNodes = 0;\n let node = this.root;\n while (!node.isEmpty()) {\n const cmp = this.comparator(key, node.key);\n if (cmp === 0) {\n return prunedNodes + node.left.size;\n } else if (cmp < 0) {\n node = node.left;\n } else {\n // Count all nodes left of the node plus the node itself\n prunedNodes += node.left.size + 1;\n node = node.right;\n }\n }\n // Node not found\n return -1;\n }\n\n isEmpty(): boolean {\n return this.root.isEmpty();\n }\n\n // Returns the total number of nodes in the map.\n get size(): number {\n return this.root.size;\n }\n\n // Returns the minimum key in the map.\n minKey(): K | null {\n return this.root.minKey();\n }\n\n // Returns the maximum key in the map.\n maxKey(): K | null {\n return this.root.maxKey();\n }\n\n // Traverses the map in key order and calls the specified action function\n // for each key/value pair. If action returns true, traversal is aborted.\n // Returns the first truthy value returned by action, or the last falsey\n // value returned by action.\n inorderTraversal(action: (k: K, v: V) => T): T {\n return (this.root as LLRBNode).inorderTraversal(action);\n }\n\n forEach(fn: (k: K, v: V) => void): void {\n this.inorderTraversal((k, v) => {\n fn(k, v);\n return false;\n });\n }\n\n toString(): string {\n const descriptions: string[] = [];\n this.inorderTraversal((k, v) => {\n descriptions.push(`${k}:${v}`);\n return false;\n });\n return `{${descriptions.join(', ')}}`;\n }\n\n // Traverses the map in reverse key order and calls the specified action\n // function for each key/value pair. If action returns true, traversal is\n // aborted.\n // Returns the first truthy value returned by action, or the last falsey\n // value returned by action.\n reverseTraversal(action: (k: K, v: V) => T): T {\n return (this.root as LLRBNode).reverseTraversal(action);\n }\n\n // Returns an iterator over the SortedMap.\n getIterator(): SortedMapIterator {\n return new SortedMapIterator(this.root, null, this.comparator, false);\n }\n\n getIteratorFrom(key: K): SortedMapIterator {\n return new SortedMapIterator(this.root, key, this.comparator, false);\n }\n\n getReverseIterator(): SortedMapIterator {\n return new SortedMapIterator(this.root, null, this.comparator, true);\n }\n\n getReverseIteratorFrom(key: K): SortedMapIterator {\n return new SortedMapIterator(this.root, key, this.comparator, true);\n }\n} // end SortedMap\n\n// An iterator over an LLRBNode.\nexport class SortedMapIterator {\n private isReverse: boolean;\n private nodeStack: Array | LLRBEmptyNode>;\n\n constructor(\n node: LLRBNode | LLRBEmptyNode,\n startKey: K | null,\n comparator: Comparator,\n isReverse: boolean\n ) {\n this.isReverse = isReverse;\n this.nodeStack = [];\n\n let cmp = 1;\n while (!node.isEmpty()) {\n cmp = startKey ? comparator(node.key, startKey) : 1;\n // flip the comparison if we're going in reverse\n if (startKey && isReverse) {\n cmp *= -1;\n }\n\n if (cmp < 0) {\n // This node is less than our start key. ignore it\n if (this.isReverse) {\n node = node.left;\n } else {\n node = node.right;\n }\n } else if (cmp === 0) {\n // This node is exactly equal to our start key. Push it on the stack,\n // but stop iterating;\n this.nodeStack.push(node);\n break;\n } else {\n // This node is greater than our start key, add it to the stack and move\n // to the next one\n this.nodeStack.push(node);\n if (this.isReverse) {\n node = node.right;\n } else {\n node = node.left;\n }\n }\n }\n }\n\n getNext(): Entry {\n debugAssert(\n this.nodeStack.length > 0,\n 'getNext() called on iterator when hasNext() is false.'\n );\n\n let node = this.nodeStack.pop()!;\n const result = { key: node.key, value: node.value };\n\n if (this.isReverse) {\n node = node.left;\n while (!node.isEmpty()) {\n this.nodeStack.push(node);\n node = node.right;\n }\n } else {\n node = node.right;\n while (!node.isEmpty()) {\n this.nodeStack.push(node);\n node = node.left;\n }\n }\n\n return result;\n }\n\n hasNext(): boolean {\n return this.nodeStack.length > 0;\n }\n\n peek(): Entry | null {\n if (this.nodeStack.length === 0) {\n return null;\n }\n\n const node = this.nodeStack[this.nodeStack.length - 1];\n return { key: node.key, value: node.value };\n }\n} // end SortedMapIterator\n\n// Represents a node in a Left-leaning Red-Black tree.\nexport class LLRBNode {\n readonly color: boolean;\n readonly left: LLRBNode | LLRBEmptyNode;\n readonly right: LLRBNode | LLRBEmptyNode;\n readonly size: number;\n\n // Empty node is shared between all LLRB trees.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n static EMPTY: LLRBEmptyNode = null as any;\n\n static RED = true;\n static BLACK = false;\n\n constructor(\n public key: K,\n public value: V,\n color?: boolean,\n left?: LLRBNode | LLRBEmptyNode,\n right?: LLRBNode | LLRBEmptyNode\n ) {\n this.color = color != null ? color : LLRBNode.RED;\n this.left = left != null ? left : LLRBNode.EMPTY;\n this.right = right != null ? right : LLRBNode.EMPTY;\n this.size = this.left.size + 1 + this.right.size;\n }\n\n // Returns a copy of the current node, optionally replacing pieces of it.\n copy(\n key: K | null,\n value: V | null,\n color: boolean | null,\n left: LLRBNode | LLRBEmptyNode | null,\n right: LLRBNode | LLRBEmptyNode | null\n ): LLRBNode {\n return new LLRBNode(\n key != null ? key : this.key,\n value != null ? value : this.value,\n color != null ? color : this.color,\n left != null ? left : this.left,\n right != null ? right : this.right\n );\n }\n\n isEmpty(): boolean {\n return false;\n }\n\n // Traverses the tree in key order and calls the specified action function\n // for each node. If action returns true, traversal is aborted.\n // Returns the first truthy value returned by action, or the last falsey\n // value returned by action.\n inorderTraversal(action: (k: K, v: V) => T): T {\n return (\n (this.left as LLRBNode).inorderTraversal(action) ||\n action(this.key, this.value) ||\n (this.right as LLRBNode).inorderTraversal(action)\n );\n }\n\n // Traverses the tree in reverse key order and calls the specified action\n // function for each node. If action returns true, traversal is aborted.\n // Returns the first truthy value returned by action, or the last falsey\n // value returned by action.\n reverseTraversal(action: (k: K, v: V) => T): T {\n return (\n (this.right as LLRBNode).reverseTraversal(action) ||\n action(this.key, this.value) ||\n (this.left as LLRBNode).reverseTraversal(action)\n );\n }\n\n // Returns the minimum node in the tree.\n private min(): LLRBNode {\n if (this.left.isEmpty()) {\n return this;\n } else {\n return (this.left as LLRBNode).min();\n }\n }\n\n // Returns the maximum key in the tree.\n minKey(): K | null {\n return this.min().key;\n }\n\n // Returns the maximum key in the tree.\n maxKey(): K | null {\n if (this.right.isEmpty()) {\n return this.key;\n } else {\n return this.right.maxKey();\n }\n }\n\n // Returns new tree, with the key/value added.\n insert(key: K, value: V, comparator: Comparator): LLRBNode {\n let n: LLRBNode = this;\n const cmp = comparator(key, n.key);\n if (cmp < 0) {\n n = n.copy(null, null, null, n.left.insert(key, value, comparator), null);\n } else if (cmp === 0) {\n n = n.copy(null, value, null, null, null);\n } else {\n n = n.copy(\n null,\n null,\n null,\n null,\n n.right.insert(key, value, comparator)\n );\n }\n return n.fixUp();\n }\n\n private removeMin(): LLRBNode | LLRBEmptyNode {\n if (this.left.isEmpty()) {\n return LLRBNode.EMPTY;\n }\n let n: LLRBNode = this;\n if (!n.left.isRed() && !n.left.left.isRed()) {\n n = n.moveRedLeft();\n }\n n = n.copy(null, null, null, (n.left as LLRBNode).removeMin(), null);\n return n.fixUp();\n }\n\n // Returns new tree, with the specified item removed.\n remove(\n key: K,\n comparator: Comparator\n ): LLRBNode | LLRBEmptyNode {\n let smallest: LLRBNode;\n let n: LLRBNode = this;\n if (comparator(key, n.key) < 0) {\n if (!n.left.isEmpty() && !n.left.isRed() && !n.left.left.isRed()) {\n n = n.moveRedLeft();\n }\n n = n.copy(null, null, null, n.left.remove(key, comparator), null);\n } else {\n if (n.left.isRed()) {\n n = n.rotateRight();\n }\n if (!n.right.isEmpty() && !n.right.isRed() && !n.right.left.isRed()) {\n n = n.moveRedRight();\n }\n if (comparator(key, n.key) === 0) {\n if (n.right.isEmpty()) {\n return LLRBNode.EMPTY;\n } else {\n smallest = (n.right as LLRBNode).min();\n n = n.copy(\n smallest.key,\n smallest.value,\n null,\n null,\n (n.right as LLRBNode).removeMin()\n );\n }\n }\n n = n.copy(null, null, null, null, n.right.remove(key, comparator));\n }\n return n.fixUp();\n }\n\n isRed(): boolean {\n return this.color;\n }\n\n // Returns new tree after performing any needed rotations.\n private fixUp(): LLRBNode {\n let n: LLRBNode = this;\n if (n.right.isRed() && !n.left.isRed()) {\n n = n.rotateLeft();\n }\n if (n.left.isRed() && n.left.left.isRed()) {\n n = n.rotateRight();\n }\n if (n.left.isRed() && n.right.isRed()) {\n n = n.colorFlip();\n }\n return n;\n }\n\n private moveRedLeft(): LLRBNode {\n let n = this.colorFlip();\n if (n.right.left.isRed()) {\n n = n.copy(\n null,\n null,\n null,\n null,\n (n.right as LLRBNode).rotateRight()\n );\n n = n.rotateLeft();\n n = n.colorFlip();\n }\n return n;\n }\n\n private moveRedRight(): LLRBNode {\n let n = this.colorFlip();\n if (n.left.left.isRed()) {\n n = n.rotateRight();\n n = n.colorFlip();\n }\n return n;\n }\n\n private rotateLeft(): LLRBNode {\n const nl = this.copy(null, null, LLRBNode.RED, null, this.right.left);\n return (this.right as LLRBNode).copy(\n null,\n null,\n this.color,\n nl,\n null\n );\n }\n\n private rotateRight(): LLRBNode {\n const nr = this.copy(null, null, LLRBNode.RED, this.left.right, null);\n return (this.left as LLRBNode).copy(null, null, this.color, null, nr);\n }\n\n private colorFlip(): LLRBNode {\n const left = this.left.copy(null, null, !this.left.color, null, null);\n const right = this.right.copy(null, null, !this.right.color, null, null);\n return this.copy(null, null, !this.color, left, right);\n }\n\n // For testing.\n checkMaxDepth(): boolean {\n const blackDepth = this.check();\n if (Math.pow(2.0, blackDepth) <= this.size + 1) {\n return true;\n } else {\n return false;\n }\n }\n\n // In a balanced RB tree, the black-depth (number of black nodes) from root to\n // leaves is equal on both sides. This function verifies that or asserts.\n protected check(): number {\n if (this.isRed() && this.left.isRed()) {\n throw fail(0xaad2, 'Red node has red child', {\n key: this.key,\n value: this.value\n });\n }\n if (this.right.isRed()) {\n throw fail(0x3721, 'Right child of (`key`, `value`) is red', {\n key: this.key,\n value: this.value\n });\n }\n const blackDepth = (this.left as LLRBNode).check();\n if (blackDepth !== (this.right as LLRBNode).check()) {\n throw fail(0x6d2d, 'Black depths differ');\n } else {\n return blackDepth + (this.isRed() ? 0 : 1);\n }\n }\n} // end LLRBNode\n\n// Represents an empty node (a leaf node in the Red-Black Tree).\nexport class LLRBEmptyNode {\n get key(): never {\n throw fail(0xe1a6, 'LLRBEmptyNode has no key.');\n }\n get value(): never {\n throw fail(0x3f0d, 'LLRBEmptyNode has no value.');\n }\n get color(): never {\n throw fail(0x4157, 'LLRBEmptyNode has no color.');\n }\n get left(): never {\n throw fail(0x741e, 'LLRBEmptyNode has no left child.');\n }\n get right(): never {\n throw fail(0x901e, 'LLRBEmptyNode has no right child.');\n }\n size = 0;\n\n // Returns a copy of the current node.\n copy(\n key: K | null,\n value: V | null,\n color: boolean | null,\n left: LLRBNode | LLRBEmptyNode | null,\n right: LLRBNode | LLRBEmptyNode | null\n ): LLRBEmptyNode {\n return this;\n }\n\n // Returns a copy of the tree, with the specified key/value added.\n insert(key: K, value: V, comparator: Comparator): LLRBNode {\n return new LLRBNode(key, value);\n }\n\n // Returns a copy of the tree, with the specified key removed.\n remove(key: K, comparator: Comparator): LLRBEmptyNode {\n return this;\n }\n\n isEmpty(): boolean {\n return true;\n }\n\n inorderTraversal(action: (k: K, v: V) => boolean): boolean {\n return false;\n }\n\n reverseTraversal(action: (k: K, v: V) => boolean): boolean {\n return false;\n }\n\n minKey(): K | null {\n return null;\n }\n\n maxKey(): K | null {\n return null;\n }\n\n isRed(): boolean {\n return false;\n }\n\n // For testing.\n checkMaxDepth(): boolean {\n return true;\n }\n\n protected check(): 0 {\n return 0;\n }\n} // end LLRBEmptyNode\n\nLLRBNode.EMPTY = new LLRBEmptyNode();\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SortedMap, SortedMapIterator } from './sorted_map';\n\n/**\n * SortedSet is an immutable (copy-on-write) collection that holds elements\n * in order specified by the provided comparator.\n *\n * NOTE: if provided comparator returns 0 for two elements, we consider them to\n * be equal!\n */\nexport class SortedSet {\n private data: SortedMap;\n\n constructor(private comparator: (left: T, right: T) => number) {\n this.data = new SortedMap(this.comparator);\n }\n\n has(elem: T): boolean {\n return this.data.get(elem) !== null;\n }\n\n first(): T | null {\n return this.data.minKey();\n }\n\n last(): T | null {\n return this.data.maxKey();\n }\n\n get size(): number {\n return this.data.size;\n }\n\n indexOf(elem: T): number {\n return this.data.indexOf(elem);\n }\n\n /** Iterates elements in order defined by \"comparator\" */\n forEach(cb: (elem: T) => void): void {\n this.data.inorderTraversal((k: T, v: boolean) => {\n cb(k);\n return false;\n });\n }\n\n /** Iterates over `elem`s such that: range[0] <= elem < range[1]. */\n forEachInRange(range: [T, T], cb: (elem: T) => void): void {\n const iter = this.data.getIteratorFrom(range[0]);\n while (iter.hasNext()) {\n const elem = iter.getNext();\n if (this.comparator(elem.key, range[1]) >= 0) {\n return;\n }\n cb(elem.key);\n }\n }\n\n /**\n * Iterates over `elem`s such that: start <= elem until false is returned.\n */\n forEachWhile(cb: (elem: T) => boolean, start?: T): void {\n let iter: SortedMapIterator;\n if (start !== undefined) {\n iter = this.data.getIteratorFrom(start);\n } else {\n iter = this.data.getIterator();\n }\n while (iter.hasNext()) {\n const elem = iter.getNext();\n const result = cb(elem.key);\n if (!result) {\n return;\n }\n }\n }\n\n /** Finds the least element greater than or equal to `elem`. */\n firstAfterOrEqual(elem: T): T | null {\n const iter = this.data.getIteratorFrom(elem);\n return iter.hasNext() ? iter.getNext().key : null;\n }\n\n getIterator(): SortedSetIterator {\n return new SortedSetIterator(this.data.getIterator());\n }\n\n getIteratorFrom(key: T): SortedSetIterator {\n return new SortedSetIterator(this.data.getIteratorFrom(key));\n }\n\n /** Inserts or updates an element */\n add(elem: T): SortedSet {\n return this.copy(this.data.remove(elem).insert(elem, true));\n }\n\n /** Deletes an element */\n delete(elem: T): SortedSet {\n if (!this.has(elem)) {\n return this;\n }\n return this.copy(this.data.remove(elem));\n }\n\n isEmpty(): boolean {\n return this.data.isEmpty();\n }\n\n unionWith(other: SortedSet): SortedSet {\n let result: SortedSet = this;\n\n // Make sure `result` always refers to the larger one of the two sets.\n if (result.size < other.size) {\n result = other;\n other = this;\n }\n\n other.forEach(elem => {\n result = result.add(elem);\n });\n return result;\n }\n\n isEqual(other: SortedSet): boolean {\n if (!(other instanceof SortedSet)) {\n return false;\n }\n if (this.size !== other.size) {\n return false;\n }\n\n const thisIt = this.data.getIterator();\n const otherIt = other.data.getIterator();\n while (thisIt.hasNext()) {\n const thisElem = thisIt.getNext().key;\n const otherElem = otherIt.getNext().key;\n if (this.comparator(thisElem, otherElem) !== 0) {\n return false;\n }\n }\n return true;\n }\n\n toArray(): T[] {\n const res: T[] = [];\n this.forEach(targetId => {\n res.push(targetId);\n });\n return res;\n }\n\n toString(): string {\n const result: T[] = [];\n this.forEach(elem => result.push(elem));\n return 'SortedSet(' + result.toString() + ')';\n }\n\n private copy(data: SortedMap): SortedSet {\n const result = new SortedSet(this.comparator);\n result.data = data;\n return result;\n }\n}\n\nexport class SortedSetIterator {\n constructor(private iter: SortedMapIterator) {}\n\n getNext(): T {\n return this.iter.getNext().key;\n }\n\n hasNext(): boolean {\n return this.iter.hasNext();\n }\n}\n\n/**\n * Compares two sorted sets for equality using their natural ordering. The\n * method computes the intersection and invokes `onAdd` for every element that\n * is in `after` but not `before`. `onRemove` is invoked for every element in\n * `before` but missing from `after`.\n *\n * The method creates a copy of both `before` and `after` and runs in O(n log\n * n), where n is the size of the two lists.\n *\n * @param before - The elements that exist in the original set.\n * @param after - The elements to diff against the original set.\n * @param comparator - The comparator for the elements in before and after.\n * @param onAdd - A function to invoke for every element that is part of `\n * after` but not `before`.\n * @param onRemove - A function to invoke for every element that is part of\n * `before` but not `after`.\n */\nexport function diffSortedSets(\n before: SortedSet,\n after: SortedSet,\n comparator: (l: T, r: T) => number,\n onAdd: (entry: T) => void,\n onRemove: (entry: T) => void\n): void {\n const beforeIt = before.getIterator();\n const afterIt = after.getIterator();\n\n let beforeValue = advanceIterator(beforeIt);\n let afterValue = advanceIterator(afterIt);\n\n // Walk through the two sets at the same time, using the ordering defined by\n // `comparator`.\n while (beforeValue || afterValue) {\n let added = false;\n let removed = false;\n\n if (beforeValue && afterValue) {\n const cmp = comparator(beforeValue, afterValue);\n if (cmp < 0) {\n // The element was removed if the next element in our ordered\n // walkthrough is only in `before`.\n removed = true;\n } else if (cmp > 0) {\n // The element was added if the next element in our ordered walkthrough\n // is only in `after`.\n added = true;\n }\n } else if (beforeValue != null) {\n removed = true;\n } else {\n added = true;\n }\n\n if (added) {\n onAdd(afterValue!);\n afterValue = advanceIterator(afterIt);\n } else if (removed) {\n onRemove(beforeValue!);\n beforeValue = advanceIterator(beforeIt);\n } else {\n beforeValue = advanceIterator(beforeIt);\n afterValue = advanceIterator(afterIt);\n }\n }\n}\n\n/**\n * Returns the next element from the iterator or `undefined` if none available.\n */\nfunction advanceIterator(it: SortedSetIterator): T | undefined {\n return it.hasNext() ? it.getNext() : undefined;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { debugAssert } from '../util/assert';\nimport { arrayEquals } from '../util/misc';\nimport { SortedSet } from '../util/sorted_set';\n\nimport { FieldPath } from './path';\n\n/**\n * Provides a set of fields that can be used to partially patch a document.\n * FieldMask is used in conjunction with ObjectValue.\n * Examples:\n * foo - Overwrites foo entirely with the provided value. If foo is not\n * present in the companion ObjectValue, the field is deleted.\n * foo.bar - Overwrites only the field bar of the object foo.\n * If foo is not an object, foo is replaced with an object\n * containing foo\n */\nexport class FieldMask {\n constructor(readonly fields: FieldPath[]) {\n // TODO(dimond): validation of FieldMask\n // Sort the field mask to support `FieldMask.isEqual()` and assert below.\n fields.sort(FieldPath.comparator);\n debugAssert(\n !fields.some((v, i) => i !== 0 && v.isEqual(fields[i - 1])),\n 'FieldMask contains field that is not unique: ' +\n fields.find((v, i) => i !== 0 && v.isEqual(fields[i - 1]))!\n );\n }\n\n static empty(): FieldMask {\n return new FieldMask([]);\n }\n\n /**\n * Returns a new FieldMask object that is the result of adding all the given\n * fields paths to this field mask.\n */\n unionWith(extraFields: FieldPath[]): FieldMask {\n let mergedMaskSet = new SortedSet(FieldPath.comparator);\n for (const fieldPath of this.fields) {\n mergedMaskSet = mergedMaskSet.add(fieldPath);\n }\n for (const fieldPath of extraFields) {\n mergedMaskSet = mergedMaskSet.add(fieldPath);\n }\n return new FieldMask(mergedMaskSet.toArray());\n }\n\n /**\n * Verifies that `fieldPath` is included by at least one field in this field\n * mask.\n *\n * This is an O(n) operation, where `n` is the size of the field mask.\n */\n covers(fieldPath: FieldPath): boolean {\n for (const fieldMaskPath of this.fields) {\n if (fieldMaskPath.isPrefixOf(fieldPath)) {\n return true;\n }\n }\n return false;\n }\n\n isEqual(other: FieldMask): boolean {\n return arrayEquals(this.fields, other.fields, (l, r) => l.isEqual(r));\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n MapValue as ProtoMapValue,\n Value as ProtoValue\n} from '../protos/firestore_proto_api';\nimport { debugAssert } from '../util/assert';\nimport { forEach } from '../util/obj';\n\nimport { FieldMask } from './field_mask';\nimport { FieldPath } from './path';\nimport { isServerTimestamp } from './server_timestamps';\nimport { deepClone, isMapValue, valueEquals } from './values';\n\nexport interface JsonObject {\n [name: string]: T;\n}\n/**\n * An ObjectValue represents a MapValue in the Firestore Proto and offers the\n * ability to add and remove fields (via the ObjectValueBuilder).\n */\nexport class ObjectValue {\n constructor(readonly value: { mapValue: ProtoMapValue }) {\n debugAssert(\n !isServerTimestamp(value),\n 'ServerTimestamps should be converted to ServerTimestampValue'\n );\n }\n\n static empty(): ObjectValue {\n return new ObjectValue({ mapValue: {} });\n }\n\n /**\n * Returns the value at the given path or null.\n *\n * @param path - the path to search\n * @returns The value at the path or null if the path is not set.\n */\n field(path: FieldPath): ProtoValue | null {\n if (path.isEmpty()) {\n return this.value;\n } else {\n let currentLevel: ProtoValue = this.value;\n for (let i = 0; i < path.length - 1; ++i) {\n currentLevel = (currentLevel.mapValue!.fields || {})[path.get(i)];\n if (!isMapValue(currentLevel)) {\n return null;\n }\n }\n currentLevel = (currentLevel.mapValue!.fields! || {})[path.lastSegment()];\n return currentLevel || null;\n }\n }\n\n /**\n * Sets the field to the provided value.\n *\n * @param path - The field path to set.\n * @param value - The value to set.\n */\n set(path: FieldPath, value: ProtoValue): void {\n debugAssert(\n !path.isEmpty(),\n 'Cannot set field for empty path on ObjectValue'\n );\n const fieldsMap = this.getFieldsMap(path.popLast());\n fieldsMap[path.lastSegment()] = deepClone(value);\n }\n\n /**\n * Sets the provided fields to the provided values.\n *\n * @param data - A map of fields to values (or null for deletes).\n */\n setAll(data: Map): void {\n let parent = FieldPath.emptyPath();\n\n let upserts: { [key: string]: ProtoValue } = {};\n let deletes: string[] = [];\n\n data.forEach((value, path) => {\n if (!parent.isImmediateParentOf(path)) {\n // Insert the accumulated changes at this parent location\n const fieldsMap = this.getFieldsMap(parent);\n this.applyChanges(fieldsMap, upserts, deletes);\n upserts = {};\n deletes = [];\n parent = path.popLast();\n }\n\n if (value) {\n upserts[path.lastSegment()] = deepClone(value);\n } else {\n deletes.push(path.lastSegment());\n }\n });\n\n const fieldsMap = this.getFieldsMap(parent);\n this.applyChanges(fieldsMap, upserts, deletes);\n }\n\n /**\n * Removes the field at the specified path. If there is no field at the\n * specified path, nothing is changed.\n *\n * @param path - The field path to remove.\n */\n delete(path: FieldPath): void {\n debugAssert(\n !path.isEmpty(),\n 'Cannot delete field for empty path on ObjectValue'\n );\n const nestedValue = this.field(path.popLast());\n if (isMapValue(nestedValue) && nestedValue.mapValue.fields) {\n delete nestedValue.mapValue.fields[path.lastSegment()];\n }\n }\n\n isEqual(other: ObjectValue): boolean {\n return valueEquals(this.value, other.value);\n }\n\n /**\n * Returns the map that contains the leaf element of `path`. If the parent\n * entry does not yet exist, or if it is not a map, a new map will be created.\n */\n private getFieldsMap(path: FieldPath): Record {\n let current = this.value;\n\n if (!current.mapValue!.fields) {\n current.mapValue = { fields: {} };\n }\n\n for (let i = 0; i < path.length; ++i) {\n let next = current.mapValue!.fields![path.get(i)];\n if (!isMapValue(next) || !next.mapValue.fields) {\n next = { mapValue: { fields: {} } };\n current.mapValue!.fields![path.get(i)] = next;\n }\n current = next as { mapValue: ProtoMapValue };\n }\n\n return current.mapValue!.fields!;\n }\n\n /**\n * Modifies `fieldsMap` by adding, replacing or deleting the specified\n * entries.\n */\n private applyChanges(\n fieldsMap: Record,\n inserts: { [key: string]: ProtoValue },\n deletes: string[]\n ): void {\n forEach(inserts, (key, val) => (fieldsMap[key] = val));\n for (const field of deletes) {\n delete fieldsMap[field];\n }\n }\n\n clone(): ObjectValue {\n return new ObjectValue(\n deepClone(this.value) as { mapValue: ProtoMapValue }\n );\n }\n}\n\n/**\n * Returns a FieldMask built from all fields in a MapValue.\n */\nexport function extractFieldMask(value: ProtoMapValue): FieldMask {\n const fields: FieldPath[] = [];\n forEach(value!.fields, (key, value) => {\n const currentPath = new FieldPath([key]);\n if (isMapValue(value)) {\n const nestedMask = extractFieldMask(value.mapValue!);\n const nestedFields = nestedMask.fields;\n if (nestedFields.length === 0) {\n // Preserve the empty map by adding it to the FieldMask.\n fields.push(currentPath);\n } else {\n // For nested and non-empty ObjectValues, add the FieldPath of the\n // leaf nodes.\n for (const nestedPath of nestedFields) {\n fields.push(currentPath.child(nestedPath));\n }\n }\n } else {\n // For nested and non-empty ObjectValues, add the FieldPath of the leaf\n // nodes.\n fields.push(currentPath);\n }\n });\n return new FieldMask(fields);\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { debugAssert, fail } from '../util/assert';\n\nimport { DocumentKey } from './document_key';\nimport { ObjectValue } from './object_value';\nimport { FieldPath } from './path';\nimport { valueCompare } from './values';\n\n/**\n * Whether the document represents an existing document, a document that is\n * known to exist or a document whose state or existence is unknown.\n */\nconst enum DocumentType {\n /**\n * Represents the initial state of a MutableDocument when only the document\n * key is known. Invalid documents transition to other states as mutations are\n * applied. If a document remains invalid after applying mutations, it should\n * be discarded.\n *\n * Invalid documents can have neither local nor committed mutations.\n */\n INVALID,\n /**\n * Represents a document in Firestore with a key, version, data and whether\n * the data has local mutations applied to it.\n *\n * Found documents can be synced or have or committed mutations applied.\n */\n FOUND_DOCUMENT,\n /**\n * Represents that no documents exists for the key at the given version.\n *\n * Documents that are deleted based on a local mutation do not raise snapshots\n * with `hasPendingWrites`. As such, deleted documents never have\n * `HAS_LOCAL_MUTATIONS` set. Once a delete is committed, we store them with\n * `HAS_COMMITTED_MUTATIONS` until we received the delete from the Watch\n * stream.\n */\n NO_DOCUMENT,\n /**\n * Represents an existing document whose data is unknown (e.g. a document that\n * was updated without a known base document).\n *\n * An unknown document always has `HAS_COMMITTED_MUTATIONS` set, since unknown\n * documents can only be generated by applying a patch mutation from a write\n * acknowledgement.\n */\n UNKNOWN_DOCUMENT\n}\n\n/** Describes whether a document has latency-compensated edits applied. */\nconst enum DocumentState {\n /** No mutations applied. Document was sent to us by Watch. */\n SYNCED,\n /**\n * Local mutations applied via the mutation queue. Document is potentially\n * inconsistent.\n */\n HAS_LOCAL_MUTATIONS,\n /**\n * Mutations applied based on a write acknowledgment. Document is potentially\n * inconsistent.\n */\n HAS_COMMITTED_MUTATIONS\n}\n\n/**\n * Represents a document in Firestore with a key, version, data and whether the\n * data has local mutations applied to it.\n */\nexport interface Document {\n /** The key for this document */\n readonly key: DocumentKey;\n\n /**\n * The version of this document if it exists or a version at which this\n * document was guaranteed to not exist.\n */\n readonly version: SnapshotVersion;\n\n /**\n * The timestamp at which this document was read from the remote server. Uses\n * `SnapshotVersion.min()` for documents created by the user.\n */\n readonly readTime: SnapshotVersion;\n\n /**\n * The timestamp at which the document was created. This value increases\n * monotonically when a document is deleted then recreated. It can also be\n * compared to `createTime` of other documents and the `readTime` of a query.\n */\n readonly createTime: SnapshotVersion;\n\n /** The underlying data of this document or an empty value if no data exists. */\n readonly data: ObjectValue;\n\n /** Returns whether local mutations were applied via the mutation queue. */\n readonly hasLocalMutations: boolean;\n\n /** Returns whether mutations were applied based on a write acknowledgment. */\n readonly hasCommittedMutations: boolean;\n\n /**\n * Whether this document had a local mutation applied that has not yet been\n * acknowledged by Watch.\n */\n readonly hasPendingWrites: boolean;\n\n /**\n * Returns whether this document is valid (i.e. it is an entry in the\n * RemoteDocumentCache, was created by a mutation or read from the backend).\n */\n isValidDocument(): boolean;\n\n /**\n * Returns whether the document exists and its data is known at the current\n * version.\n */\n isFoundDocument(): boolean;\n\n /**\n * Returns whether the document is known to not exist at the current version.\n */\n isNoDocument(): boolean;\n\n /**\n * Returns whether the document exists and its data is unknown at the current\n * version.\n */\n isUnknownDocument(): boolean;\n\n isEqual(other: Document | null | undefined): boolean;\n\n /** Creates a mutable copy of this document. */\n mutableCopy(): MutableDocument;\n\n toString(): string;\n}\n\n/**\n * Represents a document in Firestore with a key, version, data and whether it\n * has local mutations applied to it.\n *\n * Documents can transition between states via `convertToFoundDocument()`,\n * `convertToNoDocument()` and `convertToUnknownDocument()`. If a document does\n * not transition to one of these states even after all mutations have been\n * applied, `isValidDocument()` returns false and the document should be removed\n * from all views.\n */\nexport class MutableDocument implements Document {\n private constructor(\n readonly key: DocumentKey,\n private documentType: DocumentType,\n public version: SnapshotVersion,\n public readTime: SnapshotVersion,\n public createTime: SnapshotVersion,\n public data: ObjectValue,\n private documentState: DocumentState\n ) {}\n\n /**\n * Creates a document with no known version or data, but which can serve as\n * base document for mutations.\n */\n static newInvalidDocument(documentKey: DocumentKey): MutableDocument {\n return new MutableDocument(\n documentKey,\n DocumentType.INVALID,\n /* version */ SnapshotVersion.min(),\n /* readTime */ SnapshotVersion.min(),\n /* createTime */ SnapshotVersion.min(),\n ObjectValue.empty(),\n DocumentState.SYNCED\n );\n }\n\n /**\n * Creates a new document that is known to exist with the given data at the\n * given version.\n */\n static newFoundDocument(\n documentKey: DocumentKey,\n version: SnapshotVersion,\n createTime: SnapshotVersion,\n value: ObjectValue\n ): MutableDocument {\n return new MutableDocument(\n documentKey,\n DocumentType.FOUND_DOCUMENT,\n /* version */ version,\n /* readTime */ SnapshotVersion.min(),\n /* createTime */ createTime,\n value,\n DocumentState.SYNCED\n );\n }\n\n /** Creates a new document that is known to not exist at the given version. */\n static newNoDocument(\n documentKey: DocumentKey,\n version: SnapshotVersion\n ): MutableDocument {\n return new MutableDocument(\n documentKey,\n DocumentType.NO_DOCUMENT,\n /* version */ version,\n /* readTime */ SnapshotVersion.min(),\n /* createTime */ SnapshotVersion.min(),\n ObjectValue.empty(),\n DocumentState.SYNCED\n );\n }\n\n /**\n * Creates a new document that is known to exist at the given version but\n * whose data is not known (e.g. a document that was updated without a known\n * base document).\n */\n static newUnknownDocument(\n documentKey: DocumentKey,\n version: SnapshotVersion\n ): MutableDocument {\n return new MutableDocument(\n documentKey,\n DocumentType.UNKNOWN_DOCUMENT,\n /* version */ version,\n /* readTime */ SnapshotVersion.min(),\n /* createTime */ SnapshotVersion.min(),\n ObjectValue.empty(),\n DocumentState.HAS_COMMITTED_MUTATIONS\n );\n }\n\n /**\n * Changes the document type to indicate that it exists and that its version\n * and data are known.\n */\n convertToFoundDocument(\n version: SnapshotVersion,\n value: ObjectValue\n ): MutableDocument {\n // If a document is switching state from being an invalid or deleted\n // document to a valid (FOUND_DOCUMENT) document, either due to receiving an\n // update from Watch or due to applying a local set mutation on top\n // of a deleted document, our best guess about its createTime would be the\n // version at which the document transitioned to a FOUND_DOCUMENT.\n if (\n this.createTime.isEqual(SnapshotVersion.min()) &&\n (this.documentType === DocumentType.NO_DOCUMENT ||\n this.documentType === DocumentType.INVALID)\n ) {\n this.createTime = version;\n }\n this.version = version;\n this.documentType = DocumentType.FOUND_DOCUMENT;\n this.data = value;\n this.documentState = DocumentState.SYNCED;\n return this;\n }\n\n /**\n * Changes the document type to indicate that it doesn't exist at the given\n * version.\n */\n convertToNoDocument(version: SnapshotVersion): MutableDocument {\n this.version = version;\n this.documentType = DocumentType.NO_DOCUMENT;\n this.data = ObjectValue.empty();\n this.documentState = DocumentState.SYNCED;\n return this;\n }\n\n /**\n * Changes the document type to indicate that it exists at a given version but\n * that its data is not known (e.g. a document that was updated without a known\n * base document).\n */\n convertToUnknownDocument(version: SnapshotVersion): MutableDocument {\n this.version = version;\n this.documentType = DocumentType.UNKNOWN_DOCUMENT;\n this.data = ObjectValue.empty();\n this.documentState = DocumentState.HAS_COMMITTED_MUTATIONS;\n return this;\n }\n\n setHasCommittedMutations(): MutableDocument {\n debugAssert(\n this.isValidDocument(),\n 'Invalid documents cannot have committed mutations'\n );\n this.documentState = DocumentState.HAS_COMMITTED_MUTATIONS;\n return this;\n }\n\n setHasLocalMutations(): MutableDocument {\n this.documentState = DocumentState.HAS_LOCAL_MUTATIONS;\n this.version = SnapshotVersion.min();\n return this;\n }\n\n setReadTime(readTime: SnapshotVersion): MutableDocument {\n this.readTime = readTime;\n return this;\n }\n\n get hasLocalMutations(): boolean {\n return this.documentState === DocumentState.HAS_LOCAL_MUTATIONS;\n }\n\n get hasCommittedMutations(): boolean {\n return this.documentState === DocumentState.HAS_COMMITTED_MUTATIONS;\n }\n\n get hasPendingWrites(): boolean {\n return this.hasLocalMutations || this.hasCommittedMutations;\n }\n\n isValidDocument(): boolean {\n return this.documentType !== DocumentType.INVALID;\n }\n\n isFoundDocument(): boolean {\n return this.documentType === DocumentType.FOUND_DOCUMENT;\n }\n\n isNoDocument(): boolean {\n return this.documentType === DocumentType.NO_DOCUMENT;\n }\n\n isUnknownDocument(): boolean {\n return this.documentType === DocumentType.UNKNOWN_DOCUMENT;\n }\n\n isEqual(other: Document | null | undefined): boolean {\n return (\n other instanceof MutableDocument &&\n this.key.isEqual(other.key) &&\n this.version.isEqual(other.version) &&\n this.documentType === other.documentType &&\n this.documentState === other.documentState &&\n this.data.isEqual(other.data)\n );\n }\n\n mutableCopy(): MutableDocument {\n return new MutableDocument(\n this.key,\n this.documentType,\n this.version,\n this.readTime,\n this.createTime,\n this.data.clone(),\n this.documentState\n );\n }\n\n toString(): string {\n return (\n `Document(${this.key}, ${this.version}, ${JSON.stringify(\n this.data.value\n )}, ` +\n `{createTime: ${this.createTime}}), ` +\n `{documentType: ${this.documentType}}), ` +\n `{documentState: ${this.documentState}})`\n );\n }\n}\n\n/**\n * Compares the value for field `field` in the provided documents. Throws if\n * the field does not exist in both documents.\n */\nexport function compareDocumentsByField(\n field: FieldPath,\n d1: Document,\n d2: Document\n): number {\n const v1 = d1.data.field(field);\n const v2 = d2.data.field(field);\n if (v1 !== null && v2 !== null) {\n return valueCompare(v1, v2);\n } else {\n return fail(\n 0xa786,\n \"Trying to compare documents on fields that don't exist\"\n );\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DocumentKey } from '../model/document_key';\nimport {\n FieldIndex,\n fieldIndexGetArraySegment,\n fieldIndexGetDirectionalSegments,\n IndexKind\n} from '../model/field_index';\nimport { FieldPath, ResourcePath } from '../model/path';\nimport {\n canonicalId,\n MAX_VALUE,\n MIN_VALUE,\n lowerBoundCompare,\n upperBoundCompare,\n valuesGetLowerBound,\n valuesGetUpperBound\n} from '../model/values';\nimport { Value as ProtoValue } from '../protos/firestore_proto_api';\nimport { debugCast } from '../util/assert';\nimport { SortedSet } from '../util/sorted_set';\nimport { isNullOrUndefined } from '../util/types';\n\nimport { Bound, boundEquals } from './bound';\nimport {\n Filter,\n FieldFilter,\n canonifyFilter,\n stringifyFilter,\n filterEquals,\n Operator\n} from './filter';\nimport {\n canonifyOrderBy,\n OrderBy,\n orderByEquals,\n stringifyOrderBy\n} from './order_by';\n\n/**\n * A Target represents the WatchTarget representation of a Query, which is used\n * by the LocalStore and the RemoteStore to keep track of and to execute\n * backend queries. While a Query can represent multiple Targets, each Targets\n * maps to a single WatchTarget in RemoteStore and a single TargetData entry\n * in persistence.\n */\nexport interface Target {\n readonly path: ResourcePath;\n readonly collectionGroup: string | null;\n readonly orderBy: OrderBy[];\n readonly filters: Filter[];\n readonly limit: number | null;\n readonly startAt: Bound | null;\n readonly endAt: Bound | null;\n}\n\n// Visible for testing\nexport class TargetImpl implements Target {\n memoizedCanonicalId: string | null = null;\n constructor(\n readonly path: ResourcePath,\n readonly collectionGroup: string | null = null,\n readonly orderBy: OrderBy[] = [],\n readonly filters: Filter[] = [],\n readonly limit: number | null = null,\n readonly startAt: Bound | null = null,\n readonly endAt: Bound | null = null\n ) {}\n}\n\n/**\n * Initializes a Target with a path and optional additional query constraints.\n * Path must currently be empty if this is a collection group query.\n *\n * NOTE: you should always construct `Target` from `Query.toTarget` instead of\n * using this factory method, because `Query` provides an implicit `orderBy`\n * property.\n */\nexport function newTarget(\n path: ResourcePath,\n collectionGroup: string | null = null,\n orderBy: OrderBy[] = [],\n filters: Filter[] = [],\n limit: number | null = null,\n startAt: Bound | null = null,\n endAt: Bound | null = null\n): Target {\n return new TargetImpl(\n path,\n collectionGroup,\n orderBy,\n filters,\n limit,\n startAt,\n endAt\n );\n}\n\nexport function canonifyTarget(target: Target): string {\n const targetImpl = debugCast(target, TargetImpl);\n\n if (targetImpl.memoizedCanonicalId === null) {\n let str = targetImpl.path.canonicalString();\n if (targetImpl.collectionGroup !== null) {\n str += '|cg:' + targetImpl.collectionGroup;\n }\n str += '|f:';\n str += targetImpl.filters.map(f => canonifyFilter(f)).join(',');\n str += '|ob:';\n str += targetImpl.orderBy.map(o => canonifyOrderBy(o)).join(',');\n\n if (!isNullOrUndefined(targetImpl.limit)) {\n str += '|l:';\n str += targetImpl.limit!;\n }\n if (targetImpl.startAt) {\n str += '|lb:';\n str += targetImpl.startAt.inclusive ? 'b:' : 'a:';\n str += targetImpl.startAt.position.map(p => canonicalId(p)).join(',');\n }\n if (targetImpl.endAt) {\n str += '|ub:';\n str += targetImpl.endAt.inclusive ? 'a:' : 'b:';\n str += targetImpl.endAt.position.map(p => canonicalId(p)).join(',');\n }\n targetImpl.memoizedCanonicalId = str;\n }\n return targetImpl.memoizedCanonicalId;\n}\n\nexport function stringifyTarget(target: Target): string {\n let str = target.path.canonicalString();\n if (target.collectionGroup !== null) {\n str += ' collectionGroup=' + target.collectionGroup;\n }\n if (target.filters.length > 0) {\n str += `, filters: [${target.filters\n .map(f => stringifyFilter(f))\n .join(', ')}]`;\n }\n if (!isNullOrUndefined(target.limit)) {\n str += ', limit: ' + target.limit;\n }\n if (target.orderBy.length > 0) {\n str += `, orderBy: [${target.orderBy\n .map(o => stringifyOrderBy(o))\n .join(', ')}]`;\n }\n if (target.startAt) {\n str += ', startAt: ';\n str += target.startAt.inclusive ? 'b:' : 'a:';\n str += target.startAt.position.map(p => canonicalId(p)).join(',');\n }\n if (target.endAt) {\n str += ', endAt: ';\n str += target.endAt.inclusive ? 'a:' : 'b:';\n str += target.endAt.position.map(p => canonicalId(p)).join(',');\n }\n return `Target(${str})`;\n}\n\nexport function targetEquals(left: Target, right: Target): boolean {\n if (left.limit !== right.limit) {\n return false;\n }\n\n if (left.orderBy.length !== right.orderBy.length) {\n return false;\n }\n\n for (let i = 0; i < left.orderBy.length; i++) {\n if (!orderByEquals(left.orderBy[i], right.orderBy[i])) {\n return false;\n }\n }\n\n if (left.filters.length !== right.filters.length) {\n return false;\n }\n\n for (let i = 0; i < left.filters.length; i++) {\n if (!filterEquals(left.filters[i], right.filters[i])) {\n return false;\n }\n }\n\n if (left.collectionGroup !== right.collectionGroup) {\n return false;\n }\n\n if (!left.path.isEqual(right.path)) {\n return false;\n }\n\n if (!boundEquals(left.startAt, right.startAt)) {\n return false;\n }\n\n return boundEquals(left.endAt, right.endAt);\n}\n\nexport function targetIsDocumentTarget(target: Target): boolean {\n return (\n DocumentKey.isDocumentKey(target.path) &&\n target.collectionGroup === null &&\n target.filters.length === 0\n );\n}\n\n/** Returns the field filters that target the given field path. */\nexport function targetGetFieldFiltersForPath(\n target: Target,\n path: FieldPath\n): FieldFilter[] {\n return target.filters.filter(\n f => f instanceof FieldFilter && f.field.isEqual(path)\n ) as FieldFilter[];\n}\n\n/**\n * Returns the values that are used in ARRAY_CONTAINS or ARRAY_CONTAINS_ANY\n * filters. Returns `null` if there are no such filters.\n */\nexport function targetGetArrayValues(\n target: Target,\n fieldIndex: FieldIndex\n): ProtoValue[] | null {\n const segment = fieldIndexGetArraySegment(fieldIndex);\n if (segment === undefined) {\n return null;\n }\n\n for (const fieldFilter of targetGetFieldFiltersForPath(\n target,\n segment.fieldPath\n )) {\n switch (fieldFilter.op) {\n case Operator.ARRAY_CONTAINS_ANY:\n return fieldFilter.value.arrayValue!.values || [];\n case Operator.ARRAY_CONTAINS:\n return [fieldFilter.value];\n default:\n // Remaining filters are not array filters.\n }\n }\n return null;\n}\n\n/**\n * Returns the list of values that are used in != or NOT_IN filters. Returns\n * `null` if there are no such filters.\n */\nexport function targetGetNotInValues(\n target: Target,\n fieldIndex: FieldIndex\n): ProtoValue[] | null {\n const values = new Map();\n\n for (const segment of fieldIndexGetDirectionalSegments(fieldIndex)) {\n for (const fieldFilter of targetGetFieldFiltersForPath(\n target,\n segment.fieldPath\n )) {\n switch (fieldFilter.op) {\n case Operator.EQUAL:\n case Operator.IN:\n // Encode equality prefix, which is encoded in the index value before\n // the inequality (e.g. `a == 'a' && b != 'b'` is encoded to\n // `value != 'ab'`).\n values.set(segment.fieldPath.canonicalString(), fieldFilter.value);\n break;\n case Operator.NOT_IN:\n case Operator.NOT_EQUAL:\n // NotIn/NotEqual is always a suffix. There cannot be any remaining\n // segments and hence we can return early here.\n values.set(segment.fieldPath.canonicalString(), fieldFilter.value);\n return Array.from(values.values());\n default:\n // Remaining filters cannot be used as notIn bounds.\n }\n }\n }\n\n return null;\n}\n\n/**\n * Returns a lower bound of field values that can be used as a starting point to\n * scan the index defined by `fieldIndex`. Returns `MIN_VALUE` if no lower bound\n * exists.\n */\nexport function targetGetLowerBound(\n target: Target,\n fieldIndex: FieldIndex\n): Bound {\n const values: ProtoValue[] = [];\n let inclusive = true;\n\n // For each segment, retrieve a lower bound if there is a suitable filter or\n // startAt.\n for (const segment of fieldIndexGetDirectionalSegments(fieldIndex)) {\n const segmentBound =\n segment.kind === IndexKind.ASCENDING\n ? targetGetAscendingBound(target, segment.fieldPath, target.startAt)\n : targetGetDescendingBound(target, segment.fieldPath, target.startAt);\n\n values.push(segmentBound.value);\n inclusive &&= segmentBound.inclusive;\n }\n return new Bound(values, inclusive);\n}\n\n/**\n * Returns an upper bound of field values that can be used as an ending point\n * when scanning the index defined by `fieldIndex`. Returns `MAX_VALUE` if no\n * upper bound exists.\n */\nexport function targetGetUpperBound(\n target: Target,\n fieldIndex: FieldIndex\n): Bound {\n const values: ProtoValue[] = [];\n let inclusive = true;\n\n // For each segment, retrieve an upper bound if there is a suitable filter or\n // endAt.\n for (const segment of fieldIndexGetDirectionalSegments(fieldIndex)) {\n const segmentBound =\n segment.kind === IndexKind.ASCENDING\n ? targetGetDescendingBound(target, segment.fieldPath, target.endAt)\n : targetGetAscendingBound(target, segment.fieldPath, target.endAt);\n\n values.push(segmentBound.value);\n inclusive &&= segmentBound.inclusive;\n }\n\n return new Bound(values, inclusive);\n}\n\n/**\n * Returns the value to use as the lower bound for ascending index segment at\n * the provided `fieldPath` (or the upper bound for an descending segment).\n */\nfunction targetGetAscendingBound(\n target: Target,\n fieldPath: FieldPath,\n bound: Bound | null\n): { value: ProtoValue; inclusive: boolean } {\n let value: ProtoValue = MIN_VALUE;\n\n let inclusive = true;\n\n // Process all filters to find a value for the current field segment\n for (const fieldFilter of targetGetFieldFiltersForPath(target, fieldPath)) {\n let filterValue: ProtoValue = MIN_VALUE;\n let filterInclusive = true;\n\n switch (fieldFilter.op) {\n case Operator.LESS_THAN:\n case Operator.LESS_THAN_OR_EQUAL:\n filterValue = valuesGetLowerBound(fieldFilter.value);\n break;\n case Operator.EQUAL:\n case Operator.IN:\n case Operator.GREATER_THAN_OR_EQUAL:\n filterValue = fieldFilter.value;\n break;\n case Operator.GREATER_THAN:\n filterValue = fieldFilter.value;\n filterInclusive = false;\n break;\n case Operator.NOT_EQUAL:\n case Operator.NOT_IN:\n filterValue = MIN_VALUE;\n break;\n default:\n // Remaining filters cannot be used as lower bounds.\n }\n\n if (\n lowerBoundCompare(\n { value, inclusive },\n { value: filterValue, inclusive: filterInclusive }\n ) < 0\n ) {\n value = filterValue;\n inclusive = filterInclusive;\n }\n }\n\n // If there is an additional bound, compare the values against the existing\n // range to see if we can narrow the scope.\n if (bound !== null) {\n for (let i = 0; i < target.orderBy.length; ++i) {\n const orderBy = target.orderBy[i];\n if (orderBy.field.isEqual(fieldPath)) {\n const cursorValue = bound.position[i];\n if (\n lowerBoundCompare(\n { value, inclusive },\n { value: cursorValue, inclusive: bound.inclusive }\n ) < 0\n ) {\n value = cursorValue;\n inclusive = bound.inclusive;\n }\n break;\n }\n }\n }\n\n return { value, inclusive };\n}\n\n/**\n * Returns the value to use as the upper bound for ascending index segment at\n * the provided `fieldPath` (or the lower bound for a descending segment).\n */\nfunction targetGetDescendingBound(\n target: Target,\n fieldPath: FieldPath,\n bound: Bound | null\n): { value: ProtoValue; inclusive: boolean } {\n let value: ProtoValue = MAX_VALUE;\n let inclusive = true;\n\n // Process all filters to find a value for the current field segment\n for (const fieldFilter of targetGetFieldFiltersForPath(target, fieldPath)) {\n let filterValue: ProtoValue = MAX_VALUE;\n let filterInclusive = true;\n\n switch (fieldFilter.op) {\n case Operator.GREATER_THAN_OR_EQUAL:\n case Operator.GREATER_THAN:\n filterValue = valuesGetUpperBound(fieldFilter.value);\n filterInclusive = false;\n break;\n case Operator.EQUAL:\n case Operator.IN:\n case Operator.LESS_THAN_OR_EQUAL:\n filterValue = fieldFilter.value;\n break;\n case Operator.LESS_THAN:\n filterValue = fieldFilter.value;\n filterInclusive = false;\n break;\n case Operator.NOT_EQUAL:\n case Operator.NOT_IN:\n filterValue = MAX_VALUE;\n break;\n default:\n // Remaining filters cannot be used as upper bounds.\n }\n\n if (\n upperBoundCompare(\n { value, inclusive },\n { value: filterValue, inclusive: filterInclusive }\n ) > 0\n ) {\n value = filterValue;\n inclusive = filterInclusive;\n }\n }\n\n // If there is an additional bound, compare the values against the existing\n // range to see if we can narrow the scope.\n if (bound !== null) {\n for (let i = 0; i < target.orderBy.length; ++i) {\n const orderBy = target.orderBy[i];\n if (orderBy.field.isEqual(fieldPath)) {\n const cursorValue = bound.position[i];\n if (\n upperBoundCompare(\n { value, inclusive },\n { value: cursorValue, inclusive: bound.inclusive }\n ) > 0\n ) {\n value = cursorValue;\n inclusive = bound.inclusive;\n }\n break;\n }\n }\n }\n\n return { value, inclusive };\n}\n\n/** Returns the number of segments of a perfect index for this target. */\nexport function targetGetSegmentCount(target: Target): number {\n let fields = new SortedSet(FieldPath.comparator);\n let hasArraySegment = false;\n\n for (const filter of target.filters) {\n for (const subFilter of filter.getFlattenedFilters()) {\n // __name__ is not an explicit segment of any index, so we don't need to\n // count it.\n if (subFilter.field.isKeyField()) {\n continue;\n }\n\n // ARRAY_CONTAINS or ARRAY_CONTAINS_ANY filters must be counted separately.\n // For instance, it is possible to have an index for \"a ARRAY a ASC\". Even\n // though these are on the same field, they should be counted as two\n // separate segments in an index.\n if (\n subFilter.op === Operator.ARRAY_CONTAINS ||\n subFilter.op === Operator.ARRAY_CONTAINS_ANY\n ) {\n hasArraySegment = true;\n } else {\n fields = fields.add(subFilter.field);\n }\n }\n }\n\n for (const orderBy of target.orderBy) {\n // __name__ is not an explicit segment of any index, so we don't need to\n // count it.\n if (!orderBy.field.isKeyField()) {\n fields = fields.add(orderBy.field);\n }\n }\n\n return fields.size + (hasArraySegment ? 1 : 0);\n}\n\nexport function targetHasLimit(target: Target): boolean {\n return target.limit !== null;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { compareDocumentsByField, Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { FieldPath, ResourcePath } from '../model/path';\nimport { debugAssert, debugCast, fail } from '../util/assert';\nimport { SortedSet } from '../util/sorted_set';\n\nimport {\n Bound,\n boundSortsAfterDocument,\n boundSortsBeforeDocument\n} from './bound';\nimport { FieldFilter, Filter } from './filter';\nimport { Direction, OrderBy } from './order_by';\nimport {\n canonifyTarget,\n newTarget,\n stringifyTarget,\n Target,\n targetEquals\n} from './target';\n\nexport const enum LimitType {\n First = 'F',\n Last = 'L'\n}\n\n/**\n * The Query interface defines all external properties of a query.\n *\n * QueryImpl implements this interface to provide memoization for `queryNormalizedOrderBy`\n * and `queryToTarget`.\n */\nexport interface Query {\n readonly path: ResourcePath;\n readonly collectionGroup: string | null;\n readonly explicitOrderBy: OrderBy[];\n readonly filters: Filter[];\n readonly limit: number | null;\n readonly limitType: LimitType;\n readonly startAt: Bound | null;\n readonly endAt: Bound | null;\n}\n\n/**\n * Query encapsulates all the query attributes we support in the SDK. It can\n * be run against the LocalStore, as well as be converted to a `Target` to\n * query the RemoteStore results.\n *\n * Visible for testing.\n */\nexport class QueryImpl implements Query {\n memoizedNormalizedOrderBy: OrderBy[] | null = null;\n\n // The corresponding `Target` of this `Query` instance, for use with\n // non-aggregate queries.\n memoizedTarget: Target | null = null;\n\n // The corresponding `Target` of this `Query` instance, for use with\n // aggregate queries. Unlike targets for non-aggregate queries,\n // aggregate query targets do not contain normalized order-bys, they only\n // contain explicit order-bys.\n memoizedAggregateTarget: Target | null = null;\n\n /**\n * Initializes a Query with a path and optional additional query constraints.\n * Path must currently be empty if this is a collection group query.\n */\n constructor(\n readonly path: ResourcePath,\n readonly collectionGroup: string | null = null,\n readonly explicitOrderBy: OrderBy[] = [],\n readonly filters: Filter[] = [],\n readonly limit: number | null = null,\n readonly limitType: LimitType = LimitType.First,\n readonly startAt: Bound | null = null,\n readonly endAt: Bound | null = null\n ) {\n if (this.startAt) {\n debugAssert(\n this.startAt.position.length <= queryNormalizedOrderBy(this).length,\n 'Bound is longer than orderBy'\n );\n }\n if (this.endAt) {\n debugAssert(\n this.endAt.position.length <= queryNormalizedOrderBy(this).length,\n 'Bound is longer than orderBy'\n );\n }\n }\n}\n\n/** Creates a new Query instance with the options provided. */\nexport function newQuery(\n path: ResourcePath,\n collectionGroup: string | null,\n explicitOrderBy: OrderBy[],\n filters: Filter[],\n limit: number | null,\n limitType: LimitType,\n startAt: Bound | null,\n endAt: Bound | null\n): Query {\n return new QueryImpl(\n path,\n collectionGroup,\n explicitOrderBy,\n filters,\n limit,\n limitType,\n startAt,\n endAt\n );\n}\n\n/** Creates a new Query for a query that matches all documents at `path` */\nexport function newQueryForPath(path: ResourcePath): Query {\n return new QueryImpl(path);\n}\n\n/**\n * Helper to convert a collection group query into a collection query at a\n * specific path. This is used when executing collection group queries, since\n * we have to split the query into a set of collection queries at multiple\n * paths.\n */\nexport function asCollectionQueryAtPath(\n query: Query,\n path: ResourcePath\n): Query {\n return new QueryImpl(\n path,\n /*collectionGroup=*/ null,\n query.explicitOrderBy.slice(),\n query.filters.slice(),\n query.limit,\n query.limitType,\n query.startAt,\n query.endAt\n );\n}\n\n/**\n * Returns true if this query does not specify any query constraints that\n * could remove results.\n */\nexport function queryMatchesAllDocuments(query: Query): boolean {\n return (\n query.filters.length === 0 &&\n query.limit === null &&\n query.startAt == null &&\n query.endAt == null &&\n (query.explicitOrderBy.length === 0 ||\n (query.explicitOrderBy.length === 1 &&\n query.explicitOrderBy[0].field.isKeyField()))\n );\n}\n\n// Returns the sorted set of inequality filter fields used in this query.\nexport function getInequalityFilterFields(query: Query): SortedSet {\n let result = new SortedSet(FieldPath.comparator);\n query.filters.forEach((filter: Filter) => {\n const subFilters = filter.getFlattenedFilters();\n subFilters.forEach((filter: FieldFilter) => {\n if (filter.isInequality()) {\n result = result.add(filter.field);\n }\n });\n });\n return result;\n}\n\n/**\n * Creates a new Query for a collection group query that matches all documents\n * within the provided collection group.\n */\nexport function newQueryForCollectionGroup(collectionId: string): Query {\n return new QueryImpl(ResourcePath.emptyPath(), collectionId);\n}\n\n/**\n * Returns whether the query matches a single document by path (rather than a\n * collection).\n */\nexport function isDocumentQuery(query: Query): boolean {\n return (\n DocumentKey.isDocumentKey(query.path) &&\n query.collectionGroup === null &&\n query.filters.length === 0\n );\n}\n\n/**\n * Returns whether the query matches a collection group rather than a specific\n * collection.\n */\nexport function isCollectionGroupQuery(query: Query): boolean {\n return query.collectionGroup !== null;\n}\n\n/**\n * Returns the normalized order-by constraint that is used to execute the Query,\n * which can be different from the order-by constraints the user provided (e.g.\n * the SDK and backend always orders by `__name__`). The normalized order-by\n * includes implicit order-bys in addition to the explicit user provided\n * order-bys.\n */\nexport function queryNormalizedOrderBy(query: Query): OrderBy[] {\n const queryImpl = debugCast(query, QueryImpl);\n if (queryImpl.memoizedNormalizedOrderBy === null) {\n queryImpl.memoizedNormalizedOrderBy = [];\n const fieldsNormalized = new Set();\n\n // Any explicit order by fields should be added as is.\n for (const orderBy of queryImpl.explicitOrderBy) {\n queryImpl.memoizedNormalizedOrderBy.push(orderBy);\n fieldsNormalized.add(orderBy.field.canonicalString());\n }\n\n // The order of the implicit ordering always matches the last explicit order by.\n const lastDirection =\n queryImpl.explicitOrderBy.length > 0\n ? queryImpl.explicitOrderBy[queryImpl.explicitOrderBy.length - 1].dir\n : Direction.ASCENDING;\n\n // Any inequality fields not explicitly ordered should be implicitly ordered in a lexicographical\n // order. When there are multiple inequality filters on the same field, the field should be added\n // only once.\n // Note: `SortedSet` sorts the key field before other fields. However, we want the key\n // field to be sorted last.\n const inequalityFields: SortedSet =\n getInequalityFilterFields(queryImpl);\n inequalityFields.forEach(field => {\n if (\n !fieldsNormalized.has(field.canonicalString()) &&\n !field.isKeyField()\n ) {\n queryImpl.memoizedNormalizedOrderBy!.push(\n new OrderBy(field, lastDirection)\n );\n }\n });\n\n // Add the document key field to the last if it is not explicitly ordered.\n if (!fieldsNormalized.has(FieldPath.keyField().canonicalString())) {\n queryImpl.memoizedNormalizedOrderBy.push(\n new OrderBy(FieldPath.keyField(), lastDirection)\n );\n }\n }\n return queryImpl.memoizedNormalizedOrderBy;\n}\n\n/**\n * Converts this `Query` instance to its corresponding `Target` representation.\n */\nexport function queryToTarget(query: Query): Target {\n const queryImpl = debugCast(query, QueryImpl);\n if (!queryImpl.memoizedTarget) {\n queryImpl.memoizedTarget = _queryToTarget(\n queryImpl,\n queryNormalizedOrderBy(query)\n );\n }\n\n return queryImpl.memoizedTarget;\n}\n\n/**\n * Converts this `Query` instance to its corresponding `Target` representation,\n * for use within an aggregate query. Unlike targets for non-aggregate queries,\n * aggregate query targets do not contain normalized order-bys, they only\n * contain explicit order-bys.\n */\nexport function queryToAggregateTarget(query: Query): Target {\n const queryImpl = debugCast(query, QueryImpl);\n\n if (!queryImpl.memoizedAggregateTarget) {\n // Do not include implicit order-bys for aggregate queries.\n queryImpl.memoizedAggregateTarget = _queryToTarget(\n queryImpl,\n query.explicitOrderBy\n );\n }\n\n return queryImpl.memoizedAggregateTarget;\n}\n\nfunction _queryToTarget(queryImpl: QueryImpl, orderBys: OrderBy[]): Target {\n if (queryImpl.limitType === LimitType.First) {\n return newTarget(\n queryImpl.path,\n queryImpl.collectionGroup,\n orderBys,\n queryImpl.filters,\n queryImpl.limit,\n queryImpl.startAt,\n queryImpl.endAt\n );\n } else {\n // Flip the orderBy directions since we want the last results\n orderBys = orderBys.map(orderBy => {\n const dir =\n orderBy.dir === Direction.DESCENDING\n ? Direction.ASCENDING\n : Direction.DESCENDING;\n return new OrderBy(orderBy.field, dir);\n });\n\n // We need to swap the cursors to match the now-flipped query ordering.\n const startAt = queryImpl.endAt\n ? new Bound(queryImpl.endAt.position, queryImpl.endAt.inclusive)\n : null;\n const endAt = queryImpl.startAt\n ? new Bound(queryImpl.startAt.position, queryImpl.startAt.inclusive)\n : null;\n\n // Now return as a LimitType.First query.\n return newTarget(\n queryImpl.path,\n queryImpl.collectionGroup,\n orderBys,\n queryImpl.filters,\n queryImpl.limit,\n startAt,\n endAt\n );\n }\n}\n\nexport function queryWithAddedFilter(query: Query, filter: Filter): Query {\n debugAssert(\n !isDocumentQuery(query),\n 'No filtering allowed for document query'\n );\n\n const newFilters = query.filters.concat([filter]);\n return new QueryImpl(\n query.path,\n query.collectionGroup,\n query.explicitOrderBy.slice(),\n newFilters,\n query.limit,\n query.limitType,\n query.startAt,\n query.endAt\n );\n}\n\nexport function queryWithAddedOrderBy(query: Query, orderBy: OrderBy): Query {\n debugAssert(\n !query.startAt && !query.endAt,\n 'Bounds must be set after orderBy'\n );\n // TODO(dimond): validate that orderBy does not list the same key twice.\n const newOrderBy = query.explicitOrderBy.concat([orderBy]);\n return new QueryImpl(\n query.path,\n query.collectionGroup,\n newOrderBy,\n query.filters.slice(),\n query.limit,\n query.limitType,\n query.startAt,\n query.endAt\n );\n}\n\nexport function queryWithLimit(\n query: Query,\n limit: number | null,\n limitType: LimitType\n): Query {\n return new QueryImpl(\n query.path,\n query.collectionGroup,\n query.explicitOrderBy.slice(),\n query.filters.slice(),\n limit,\n limitType,\n query.startAt,\n query.endAt\n );\n}\n\nexport function queryWithStartAt(query: Query, bound: Bound): Query {\n return new QueryImpl(\n query.path,\n query.collectionGroup,\n query.explicitOrderBy.slice(),\n query.filters.slice(),\n query.limit,\n query.limitType,\n bound,\n query.endAt\n );\n}\n\nexport function queryWithEndAt(query: Query, bound: Bound): Query {\n return new QueryImpl(\n query.path,\n query.collectionGroup,\n query.explicitOrderBy.slice(),\n query.filters.slice(),\n query.limit,\n query.limitType,\n query.startAt,\n bound\n );\n}\n\nexport function queryEquals(left: Query, right: Query): boolean {\n return (\n targetEquals(queryToTarget(left), queryToTarget(right)) &&\n left.limitType === right.limitType\n );\n}\n\n// TODO(b/29183165): This is used to get a unique string from a query to, for\n// example, use as a dictionary key, but the implementation is subject to\n// collisions. Make it collision-free.\nexport function canonifyQuery(query: Query): string {\n return `${canonifyTarget(queryToTarget(query))}|lt:${query.limitType}`;\n}\n\nexport function stringifyQuery(query: Query): string {\n return `Query(target=${stringifyTarget(queryToTarget(query))}; limitType=${\n query.limitType\n })`;\n}\n\n/** Returns whether `doc` matches the constraints of `query`. */\nexport function queryMatches(query: Query, doc: Document): boolean {\n return (\n doc.isFoundDocument() &&\n queryMatchesPathAndCollectionGroup(query, doc) &&\n queryMatchesOrderBy(query, doc) &&\n queryMatchesFilters(query, doc) &&\n queryMatchesBounds(query, doc)\n );\n}\n\nfunction queryMatchesPathAndCollectionGroup(\n query: Query,\n doc: Document\n): boolean {\n const docPath = doc.key.path;\n if (query.collectionGroup !== null) {\n // NOTE: this.path is currently always empty since we don't expose Collection\n // Group queries rooted at a document path yet.\n return (\n doc.key.hasCollectionId(query.collectionGroup) &&\n query.path.isPrefixOf(docPath)\n );\n } else if (DocumentKey.isDocumentKey(query.path)) {\n // exact match for document queries\n return query.path.isEqual(docPath);\n } else {\n // shallow ancestor queries by default\n return query.path.isImmediateParentOf(docPath);\n }\n}\n\n/**\n * A document must have a value for every ordering clause in order to show up\n * in the results.\n */\nfunction queryMatchesOrderBy(query: Query, doc: Document): boolean {\n // We must use `queryNormalizedOrderBy()` to get the list of all orderBys (both implicit and explicit).\n // Note that for OR queries, orderBy applies to all disjunction terms and implicit orderBys must\n // be taken into account. For example, the query \"a > 1 || b==1\" has an implicit \"orderBy a\" due\n // to the inequality, and is evaluated as \"a > 1 orderBy a || b==1 orderBy a\".\n // A document with content of {b:1} matches the filters, but does not match the orderBy because\n // it's missing the field 'a'.\n for (const orderBy of queryNormalizedOrderBy(query)) {\n // order-by key always matches\n if (!orderBy.field.isKeyField() && doc.data.field(orderBy.field) === null) {\n return false;\n }\n }\n return true;\n}\n\nfunction queryMatchesFilters(query: Query, doc: Document): boolean {\n for (const filter of query.filters) {\n if (!filter.matches(doc)) {\n return false;\n }\n }\n return true;\n}\n\n/** Makes sure a document is within the bounds, if provided. */\nfunction queryMatchesBounds(query: Query, doc: Document): boolean {\n if (\n query.startAt &&\n !boundSortsBeforeDocument(query.startAt, queryNormalizedOrderBy(query), doc)\n ) {\n return false;\n }\n if (\n query.endAt &&\n !boundSortsAfterDocument(query.endAt, queryNormalizedOrderBy(query), doc)\n ) {\n return false;\n }\n return true;\n}\n\n/**\n * Returns the collection group that this query targets.\n *\n * PORTING NOTE: This is only used in the Web SDK to facilitate multi-tab\n * synchronization for query results.\n */\nexport function queryCollectionGroup(query: Query): string {\n return (\n query.collectionGroup ||\n (query.path.length % 2 === 1\n ? query.path.lastSegment()\n : query.path.get(query.path.length - 2))\n );\n}\n\n/**\n * Returns a new comparator function that can be used to compare two documents\n * based on the Query's ordering constraint.\n */\nexport function newQueryComparator(\n query: Query\n): (d1: Document, d2: Document) => number {\n return (d1: Document, d2: Document): number => {\n let comparedOnKeyField = false;\n for (const orderBy of queryNormalizedOrderBy(query)) {\n const comp = compareDocs(orderBy, d1, d2);\n if (comp !== 0) {\n return comp;\n }\n comparedOnKeyField = comparedOnKeyField || orderBy.field.isKeyField();\n }\n // Assert that we actually compared by key\n debugAssert(\n comparedOnKeyField,\n \"orderBy used that doesn't compare on key field\"\n );\n return 0;\n };\n}\n\nexport function compareDocs(\n orderBy: OrderBy,\n d1: Document,\n d2: Document\n): number {\n const comparison = orderBy.field.isKeyField()\n ? DocumentKey.comparator(d1.key, d2.key)\n : compareDocumentsByField(orderBy.field, d1, d2);\n switch (orderBy.dir) {\n case Direction.ASCENDING:\n return comparison;\n case Direction.DESCENDING:\n return -1 * comparison;\n default:\n return fail(0x4d4e, 'Unknown direction', { direction: orderBy.dir });\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Value as ProtoValue } from '../protos/firestore_proto_api';\nimport { isNegativeZero, isSafeInteger } from '../util/types';\n\n/** Base interface for the Serializer implementation. */\nexport interface Serializer {\n readonly useProto3Json: boolean;\n}\n\n/**\n * Returns an DoubleValue for `value` that is encoded based the serializer's\n * `useProto3Json` setting.\n */\nexport function toDouble(serializer: Serializer, value: number): ProtoValue {\n if (serializer.useProto3Json) {\n if (isNaN(value)) {\n return { doubleValue: 'NaN' };\n } else if (value === Infinity) {\n return { doubleValue: 'Infinity' };\n } else if (value === -Infinity) {\n return { doubleValue: '-Infinity' };\n }\n }\n return { doubleValue: isNegativeZero(value) ? '-0' : value };\n}\n\n/**\n * Returns an IntegerValue for `value`.\n */\nexport function toInteger(value: number): ProtoValue {\n return { integerValue: '' + value };\n}\n\n/**\n * Returns a value for a number that's appropriate to put into a proto.\n * The return value is an IntegerValue if it can safely represent the value,\n * otherwise a DoubleValue is returned.\n */\nexport function toNumber(serializer: Serializer, value: number): ProtoValue {\n return isSafeInteger(value) ? toInteger(value) : toDouble(serializer, value);\n}\n","/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Timestamp } from '../lite-api/timestamp';\nimport { Value as ProtoValue } from '../protos/firestore_proto_api';\nimport { Serializer, toDouble, toInteger } from '../remote/number_serializer';\nimport { debugAssert } from '../util/assert';\nimport { arrayEquals } from '../util/misc';\n\nimport { normalizeNumber } from './normalize';\nimport { serverTimestamp } from './server_timestamps';\nimport { isArray, isInteger, isNumber, valueEquals } from './values';\n\n/** Used to represent a field transform on a mutation. */\nexport class TransformOperation {\n // Make sure that the structural type of `TransformOperation` is unique.\n // See https://github.com/microsoft/TypeScript/issues/5451\n private _ = undefined;\n}\n\n/**\n * Computes the local transform result against the provided `previousValue`,\n * optionally using the provided localWriteTime.\n */\nexport function applyTransformOperationToLocalView(\n transform: TransformOperation,\n previousValue: ProtoValue | null,\n localWriteTime: Timestamp\n): ProtoValue {\n if (transform instanceof ServerTimestampTransform) {\n return serverTimestamp(localWriteTime, previousValue);\n } else if (transform instanceof ArrayUnionTransformOperation) {\n return applyArrayUnionTransformOperation(transform, previousValue);\n } else if (transform instanceof ArrayRemoveTransformOperation) {\n return applyArrayRemoveTransformOperation(transform, previousValue);\n } else {\n debugAssert(\n transform instanceof NumericIncrementTransformOperation,\n 'Expected NumericIncrementTransformOperation but was: ' + transform\n );\n return applyNumericIncrementTransformOperationToLocalView(\n transform,\n previousValue\n );\n }\n}\n\n/**\n * Computes a final transform result after the transform has been acknowledged\n * by the server, potentially using the server-provided transformResult.\n */\nexport function applyTransformOperationToRemoteDocument(\n transform: TransformOperation,\n previousValue: ProtoValue | null,\n transformResult: ProtoValue | null\n): ProtoValue {\n // The server just sends null as the transform result for array operations,\n // so we have to calculate a result the same as we do for local\n // applications.\n if (transform instanceof ArrayUnionTransformOperation) {\n return applyArrayUnionTransformOperation(transform, previousValue);\n } else if (transform instanceof ArrayRemoveTransformOperation) {\n return applyArrayRemoveTransformOperation(transform, previousValue);\n }\n\n debugAssert(\n transformResult !== null,\n \"Didn't receive transformResult for non-array transform\"\n );\n return transformResult;\n}\n\n/**\n * If this transform operation is not idempotent, returns the base value to\n * persist for this transform. If a base value is returned, the transform\n * operation is always applied to this base value, even if document has\n * already been updated.\n *\n * Base values provide consistent behavior for non-idempotent transforms and\n * allow us to return the same latency-compensated value even if the backend\n * has already applied the transform operation. The base value is null for\n * idempotent transforms, as they can be re-played even if the backend has\n * already applied them.\n *\n * @returns a base value to store along with the mutation, or null for\n * idempotent transforms.\n */\nexport function computeTransformOperationBaseValue(\n transform: TransformOperation,\n previousValue: ProtoValue | null\n): ProtoValue | null {\n if (transform instanceof NumericIncrementTransformOperation) {\n return isNumber(previousValue) ? previousValue! : { integerValue: 0 };\n }\n return null;\n}\n\nexport function transformOperationEquals(\n left: TransformOperation,\n right: TransformOperation\n): boolean {\n if (\n left instanceof ArrayUnionTransformOperation &&\n right instanceof ArrayUnionTransformOperation\n ) {\n return arrayEquals(left.elements, right.elements, valueEquals);\n } else if (\n left instanceof ArrayRemoveTransformOperation &&\n right instanceof ArrayRemoveTransformOperation\n ) {\n return arrayEquals(left.elements, right.elements, valueEquals);\n } else if (\n left instanceof NumericIncrementTransformOperation &&\n right instanceof NumericIncrementTransformOperation\n ) {\n return valueEquals(left.operand, right.operand);\n }\n\n return (\n left instanceof ServerTimestampTransform &&\n right instanceof ServerTimestampTransform\n );\n}\n\n/** Transforms a value into a server-generated timestamp. */\nexport class ServerTimestampTransform extends TransformOperation {}\n\n/** Transforms an array value via a union operation. */\nexport class ArrayUnionTransformOperation extends TransformOperation {\n constructor(readonly elements: ProtoValue[]) {\n super();\n }\n}\n\nfunction applyArrayUnionTransformOperation(\n transform: ArrayUnionTransformOperation,\n previousValue: ProtoValue | null\n): ProtoValue {\n const values = coercedFieldValuesArray(previousValue);\n for (const toUnion of transform.elements) {\n if (!values.some(element => valueEquals(element, toUnion))) {\n values.push(toUnion);\n }\n }\n return { arrayValue: { values } };\n}\n\n/** Transforms an array value via a remove operation. */\nexport class ArrayRemoveTransformOperation extends TransformOperation {\n constructor(readonly elements: ProtoValue[]) {\n super();\n }\n}\n\nfunction applyArrayRemoveTransformOperation(\n transform: ArrayRemoveTransformOperation,\n previousValue: ProtoValue | null\n): ProtoValue {\n let values = coercedFieldValuesArray(previousValue);\n for (const toRemove of transform.elements) {\n values = values.filter(element => !valueEquals(element, toRemove));\n }\n return { arrayValue: { values } };\n}\n\n/**\n * Implements the backend semantics for locally computed NUMERIC_ADD (increment)\n * transforms. Converts all field values to integers or doubles, but unlike the\n * backend does not cap integer values at 2^63. Instead, JavaScript number\n * arithmetic is used and precision loss can occur for values greater than 2^53.\n */\nexport class NumericIncrementTransformOperation extends TransformOperation {\n constructor(readonly serializer: Serializer, readonly operand: ProtoValue) {\n super();\n debugAssert(\n isNumber(operand),\n 'NumericIncrementTransform transform requires a NumberValue'\n );\n }\n}\n\nexport function applyNumericIncrementTransformOperationToLocalView(\n transform: NumericIncrementTransformOperation,\n previousValue: ProtoValue | null\n): ProtoValue {\n // PORTING NOTE: Since JavaScript's integer arithmetic is limited to 53 bit\n // precision and resolves overflows by reducing precision, we do not\n // manually cap overflows at 2^63.\n const baseValue = computeTransformOperationBaseValue(\n transform,\n previousValue\n )!;\n const sum = asNumber(baseValue) + asNumber(transform.operand);\n if (isInteger(baseValue) && isInteger(transform.operand)) {\n return toInteger(sum);\n } else {\n return toDouble(transform.serializer, sum);\n }\n}\n\nfunction asNumber(value: ProtoValue): number {\n return normalizeNumber(value.integerValue || value.doubleValue);\n}\n\nfunction coercedFieldValuesArray(value: ProtoValue | null): ProtoValue[] {\n return isArray(value) && value.arrayValue.values\n ? value.arrayValue.values.slice()\n : [];\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { Timestamp } from '../lite-api/timestamp';\nimport { Value as ProtoValue } from '../protos/firestore_proto_api';\nimport { debugAssert, hardAssert } from '../util/assert';\nimport { arrayEquals } from '../util/misc';\nimport { SortedSet } from '../util/sorted_set';\n\nimport { Document, MutableDocument } from './document';\nimport { DocumentKey } from './document_key';\nimport { FieldMask } from './field_mask';\nimport { ObjectValue } from './object_value';\nimport { FieldPath } from './path';\nimport {\n applyTransformOperationToLocalView,\n applyTransformOperationToRemoteDocument,\n computeTransformOperationBaseValue,\n TransformOperation,\n transformOperationEquals\n} from './transform_operation';\n\n/** A field path and the TransformOperation to perform upon it. */\nexport class FieldTransform {\n constructor(\n readonly field: FieldPath,\n readonly transform: TransformOperation\n ) {}\n}\n\nexport function fieldTransformEquals(\n left: FieldTransform,\n right: FieldTransform\n): boolean {\n return (\n left.field.isEqual(right.field) &&\n transformOperationEquals(left.transform, right.transform)\n );\n}\n\nexport function fieldTransformsAreEqual(\n left?: FieldTransform[],\n right?: FieldTransform[]\n): boolean {\n if (left === undefined && right === undefined) {\n return true;\n }\n\n if (left && right) {\n return arrayEquals(left, right, (l, r) => fieldTransformEquals(l, r));\n }\n\n return false;\n}\n\n/** The result of successfully applying a mutation to the backend. */\nexport class MutationResult {\n constructor(\n /**\n * The version at which the mutation was committed:\n *\n * - For most operations, this is the updateTime in the WriteResult.\n * - For deletes, the commitTime of the WriteResponse (because deletes are\n * not stored and have no updateTime).\n *\n * Note that these versions can be different: No-op writes will not change\n * the updateTime even though the commitTime advances.\n */\n readonly version: SnapshotVersion,\n /**\n * The resulting fields returned from the backend after a mutation\n * containing field transforms has been committed. Contains one FieldValue\n * for each FieldTransform that was in the mutation.\n *\n * Will be empty if the mutation did not contain any field transforms.\n */\n readonly transformResults: Array\n ) {}\n}\n\nexport const enum MutationType {\n Set,\n Patch,\n Delete,\n Verify\n}\n\n/**\n * Encodes a precondition for a mutation. This follows the model that the\n * backend accepts with the special case of an explicit \"empty\" precondition\n * (meaning no precondition).\n */\nexport class Precondition {\n private constructor(\n readonly updateTime?: SnapshotVersion,\n readonly exists?: boolean\n ) {\n debugAssert(\n updateTime === undefined || exists === undefined,\n 'Precondition can specify \"exists\" or \"updateTime\" but not both'\n );\n }\n\n /** Creates a new empty Precondition. */\n static none(): Precondition {\n return new Precondition();\n }\n\n /** Creates a new Precondition with an exists flag. */\n static exists(exists: boolean): Precondition {\n return new Precondition(undefined, exists);\n }\n\n /** Creates a new Precondition based on a version a document exists at. */\n static updateTime(version: SnapshotVersion): Precondition {\n return new Precondition(version);\n }\n\n /** Returns whether this Precondition is empty. */\n get isNone(): boolean {\n return this.updateTime === undefined && this.exists === undefined;\n }\n\n isEqual(other: Precondition): boolean {\n return (\n this.exists === other.exists &&\n (this.updateTime\n ? !!other.updateTime && this.updateTime.isEqual(other.updateTime)\n : !other.updateTime)\n );\n }\n}\n\n/** Returns true if the preconditions is valid for the given document. */\nexport function preconditionIsValidForDocument(\n precondition: Precondition,\n document: MutableDocument\n): boolean {\n if (precondition.updateTime !== undefined) {\n return (\n document.isFoundDocument() &&\n document.version.isEqual(precondition.updateTime)\n );\n } else if (precondition.exists !== undefined) {\n return precondition.exists === document.isFoundDocument();\n } else {\n debugAssert(precondition.isNone, 'Precondition should be empty');\n return true;\n }\n}\n\n/**\n * A mutation describes a self-contained change to a document. Mutations can\n * create, replace, delete, and update subsets of documents.\n *\n * Mutations not only act on the value of the document but also its version.\n *\n * For local mutations (mutations that haven't been committed yet), we preserve\n * the existing version for Set and Patch mutations. For Delete mutations, we\n * reset the version to 0.\n *\n * Here's the expected transition table.\n *\n * MUTATION APPLIED TO RESULTS IN\n *\n * SetMutation Document(v3) Document(v3)\n * SetMutation NoDocument(v3) Document(v0)\n * SetMutation InvalidDocument(v0) Document(v0)\n * PatchMutation Document(v3) Document(v3)\n * PatchMutation NoDocument(v3) NoDocument(v3)\n * PatchMutation InvalidDocument(v0) UnknownDocument(v3)\n * DeleteMutation Document(v3) NoDocument(v0)\n * DeleteMutation NoDocument(v3) NoDocument(v0)\n * DeleteMutation InvalidDocument(v0) NoDocument(v0)\n *\n * For acknowledged mutations, we use the updateTime of the WriteResponse as\n * the resulting version for Set and Patch mutations. As deletes have no\n * explicit update time, we use the commitTime of the WriteResponse for\n * Delete mutations.\n *\n * If a mutation is acknowledged by the backend but fails the precondition check\n * locally, we transition to an `UnknownDocument` and rely on Watch to send us\n * the updated version.\n *\n * Field transforms are used only with Patch and Set Mutations. We use the\n * `updateTransforms` message to store transforms, rather than the `transforms`s\n * messages.\n *\n * ## Subclassing Notes\n *\n * Every type of mutation needs to implement its own applyToRemoteDocument() and\n * applyToLocalView() to implement the actual behavior of applying the mutation\n * to some source document (see `setMutationApplyToRemoteDocument()` for an\n * example).\n */\nexport abstract class Mutation {\n abstract readonly type: MutationType;\n abstract readonly key: DocumentKey;\n abstract readonly precondition: Precondition;\n abstract readonly fieldTransforms: FieldTransform[];\n /**\n * Returns a `FieldMask` representing the fields that will be changed by\n * applying this mutation. Returns `null` if the mutation will overwrite the\n * entire document.\n */\n abstract getFieldMask(): FieldMask | null;\n}\n\n/**\n * A utility method to calculate a `Mutation` representing the overlay from the\n * final state of the document, and a `FieldMask` representing the fields that\n * are mutated by the local mutations.\n */\nexport function calculateOverlayMutation(\n doc: MutableDocument,\n mask: FieldMask | null\n): Mutation | null {\n if (!doc.hasLocalMutations || (mask && mask!.fields.length === 0)) {\n return null;\n }\n\n // mask is null when sets or deletes are applied to the current document.\n if (mask === null) {\n if (doc.isNoDocument()) {\n return new DeleteMutation(doc.key, Precondition.none());\n } else {\n return new SetMutation(doc.key, doc.data, Precondition.none());\n }\n } else {\n const docValue = doc.data;\n const patchValue = ObjectValue.empty();\n let maskSet = new SortedSet(FieldPath.comparator);\n for (let path of mask.fields) {\n if (!maskSet.has(path)) {\n let value = docValue.field(path);\n // If we are deleting a nested field, we take the immediate parent as\n // the mask used to construct the resulting mutation.\n // Justification: Nested fields can create parent fields implicitly. If\n // only a leaf entry is deleted in later mutations, the parent field\n // should still remain, but we may have lost this information.\n // Consider mutation (foo.bar 1), then mutation (foo.bar delete()).\n // This leaves the final result (foo, {}). Despite the fact that `doc`\n // has the correct result, `foo` is not in `mask`, and the resulting\n // mutation would miss `foo`.\n if (value === null && path.length > 1) {\n path = path.popLast();\n value = docValue.field(path);\n }\n if (value === null) {\n patchValue.delete(path);\n } else {\n patchValue.set(path, value);\n }\n maskSet = maskSet.add(path);\n }\n }\n return new PatchMutation(\n doc.key,\n patchValue,\n new FieldMask(maskSet.toArray()),\n Precondition.none()\n );\n }\n}\n\n/**\n * Applies this mutation to the given document for the purposes of computing a\n * new remote document. If the input document doesn't match the expected state\n * (e.g. it is invalid or outdated), the document type may transition to\n * unknown.\n *\n * @param mutation - The mutation to apply.\n * @param document - The document to mutate. The input document can be an\n * invalid document if the client has no knowledge of the pre-mutation state\n * of the document.\n * @param mutationResult - The result of applying the mutation from the backend.\n */\nexport function mutationApplyToRemoteDocument(\n mutation: Mutation,\n document: MutableDocument,\n mutationResult: MutationResult\n): void {\n mutationVerifyKeyMatches(mutation, document);\n if (mutation instanceof SetMutation) {\n setMutationApplyToRemoteDocument(mutation, document, mutationResult);\n } else if (mutation instanceof PatchMutation) {\n patchMutationApplyToRemoteDocument(mutation, document, mutationResult);\n } else {\n debugAssert(\n mutation instanceof DeleteMutation,\n 'Unexpected mutation type: ' + mutation\n );\n deleteMutationApplyToRemoteDocument(mutation, document, mutationResult);\n }\n}\n\n/**\n * Applies this mutation to the given document for the purposes of computing\n * the new local view of a document. If the input document doesn't match the\n * expected state, the document is not modified.\n *\n * @param mutation - The mutation to apply.\n * @param document - The document to mutate. The input document can be an\n * invalid document if the client has no knowledge of the pre-mutation state\n * of the document.\n * @param previousMask - The fields that have been updated before applying this mutation.\n * @param localWriteTime - A timestamp indicating the local write time of the\n * batch this mutation is a part of.\n * @returns A `FieldMask` representing the fields that are changed by applying this mutation.\n */\nexport function mutationApplyToLocalView(\n mutation: Mutation,\n document: MutableDocument,\n previousMask: FieldMask | null,\n localWriteTime: Timestamp\n): FieldMask | null {\n mutationVerifyKeyMatches(mutation, document);\n\n if (mutation instanceof SetMutation) {\n return setMutationApplyToLocalView(\n mutation,\n document,\n previousMask,\n localWriteTime\n );\n } else if (mutation instanceof PatchMutation) {\n return patchMutationApplyToLocalView(\n mutation,\n document,\n previousMask,\n localWriteTime\n );\n } else {\n debugAssert(\n mutation instanceof DeleteMutation,\n 'Unexpected mutation type: ' + mutation\n );\n return deleteMutationApplyToLocalView(mutation, document, previousMask);\n }\n}\n\n/**\n * If this mutation is not idempotent, returns the base value to persist with\n * this mutation. If a base value is returned, the mutation is always applied\n * to this base value, even if document has already been updated.\n *\n * The base value is a sparse object that consists of only the document\n * fields for which this mutation contains a non-idempotent transformation\n * (e.g. a numeric increment). The provided value guarantees consistent\n * behavior for non-idempotent transforms and allow us to return the same\n * latency-compensated value even if the backend has already applied the\n * mutation. The base value is null for idempotent mutations, as they can be\n * re-played even if the backend has already applied them.\n *\n * @returns a base value to store along with the mutation, or null for\n * idempotent mutations.\n */\nexport function mutationExtractBaseValue(\n mutation: Mutation,\n document: Document\n): ObjectValue | null {\n let baseObject: ObjectValue | null = null;\n for (const fieldTransform of mutation.fieldTransforms) {\n const existingValue = document.data.field(fieldTransform.field);\n const coercedValue = computeTransformOperationBaseValue(\n fieldTransform.transform,\n existingValue || null\n );\n\n if (coercedValue != null) {\n if (baseObject === null) {\n baseObject = ObjectValue.empty();\n }\n baseObject.set(fieldTransform.field, coercedValue);\n }\n }\n return baseObject ? baseObject : null;\n}\n\nexport function mutationEquals(left: Mutation, right: Mutation): boolean {\n if (left.type !== right.type) {\n return false;\n }\n\n if (!left.key.isEqual(right.key)) {\n return false;\n }\n\n if (!left.precondition.isEqual(right.precondition)) {\n return false;\n }\n\n if (!fieldTransformsAreEqual(left.fieldTransforms, right.fieldTransforms)) {\n return false;\n }\n\n if (left.type === MutationType.Set) {\n return (left as SetMutation).value.isEqual((right as SetMutation).value);\n }\n\n if (left.type === MutationType.Patch) {\n return (\n (left as PatchMutation).data.isEqual((right as PatchMutation).data) &&\n (left as PatchMutation).fieldMask.isEqual(\n (right as PatchMutation).fieldMask\n )\n );\n }\n\n return true;\n}\n\nfunction mutationVerifyKeyMatches(\n mutation: Mutation,\n document: MutableDocument\n): void {\n debugAssert(\n document.key.isEqual(mutation.key),\n 'Can only apply a mutation to a document with the same key'\n );\n}\n\n/**\n * A mutation that creates or replaces the document at the given key with the\n * object value contents.\n */\nexport class SetMutation extends Mutation {\n constructor(\n readonly key: DocumentKey,\n readonly value: ObjectValue,\n readonly precondition: Precondition,\n readonly fieldTransforms: FieldTransform[] = []\n ) {\n super();\n }\n\n readonly type: MutationType = MutationType.Set;\n\n getFieldMask(): FieldMask | null {\n return null;\n }\n}\n\nfunction setMutationApplyToRemoteDocument(\n mutation: SetMutation,\n document: MutableDocument,\n mutationResult: MutationResult\n): void {\n // Unlike setMutationApplyToLocalView, if we're applying a mutation to a\n // remote document the server has accepted the mutation so the precondition\n // must have held.\n const newData = mutation.value.clone();\n const transformResults = serverTransformResults(\n mutation.fieldTransforms,\n document,\n mutationResult.transformResults\n );\n newData.setAll(transformResults);\n document\n .convertToFoundDocument(mutationResult.version, newData)\n .setHasCommittedMutations();\n}\n\nfunction setMutationApplyToLocalView(\n mutation: SetMutation,\n document: MutableDocument,\n previousMask: FieldMask | null,\n localWriteTime: Timestamp\n): FieldMask | null {\n if (!preconditionIsValidForDocument(mutation.precondition, document)) {\n // The mutation failed to apply (e.g. a document ID created with add()\n // caused a name collision).\n return previousMask;\n }\n\n const newData = mutation.value.clone();\n const transformResults = localTransformResults(\n mutation.fieldTransforms,\n localWriteTime,\n document\n );\n newData.setAll(transformResults);\n document\n .convertToFoundDocument(document.version, newData)\n .setHasLocalMutations();\n return null; // SetMutation overwrites all fields.\n}\n\n/**\n * A mutation that modifies fields of the document at the given key with the\n * given values. The values are applied through a field mask:\n *\n * * When a field is in both the mask and the values, the corresponding field\n * is updated.\n * * When a field is in neither the mask nor the values, the corresponding\n * field is unmodified.\n * * When a field is in the mask but not in the values, the corresponding field\n * is deleted.\n * * When a field is not in the mask but is in the values, the values map is\n * ignored.\n */\nexport class PatchMutation extends Mutation {\n constructor(\n readonly key: DocumentKey,\n readonly data: ObjectValue,\n readonly fieldMask: FieldMask,\n readonly precondition: Precondition,\n readonly fieldTransforms: FieldTransform[] = []\n ) {\n super();\n }\n\n readonly type: MutationType = MutationType.Patch;\n\n getFieldMask(): FieldMask | null {\n return this.fieldMask;\n }\n}\n\nfunction patchMutationApplyToRemoteDocument(\n mutation: PatchMutation,\n document: MutableDocument,\n mutationResult: MutationResult\n): void {\n if (!preconditionIsValidForDocument(mutation.precondition, document)) {\n // Since the mutation was not rejected, we know that the precondition\n // matched on the backend. We therefore must not have the expected version\n // of the document in our cache and convert to an UnknownDocument with a\n // known updateTime.\n document.convertToUnknownDocument(mutationResult.version);\n return;\n }\n\n const transformResults = serverTransformResults(\n mutation.fieldTransforms,\n document,\n mutationResult.transformResults\n );\n const newData = document.data;\n newData.setAll(getPatch(mutation));\n newData.setAll(transformResults);\n document\n .convertToFoundDocument(mutationResult.version, newData)\n .setHasCommittedMutations();\n}\n\nfunction patchMutationApplyToLocalView(\n mutation: PatchMutation,\n document: MutableDocument,\n previousMask: FieldMask | null,\n localWriteTime: Timestamp\n): FieldMask | null {\n if (!preconditionIsValidForDocument(mutation.precondition, document)) {\n return previousMask;\n }\n\n const transformResults = localTransformResults(\n mutation.fieldTransforms,\n localWriteTime,\n document\n );\n const newData = document.data;\n newData.setAll(getPatch(mutation));\n newData.setAll(transformResults);\n document\n .convertToFoundDocument(document.version, newData)\n .setHasLocalMutations();\n\n if (previousMask === null) {\n return null;\n }\n\n return previousMask\n .unionWith(mutation.fieldMask.fields)\n .unionWith(mutation.fieldTransforms.map(transform => transform.field));\n}\n\n/**\n * Returns a FieldPath/Value map with the content of the PatchMutation.\n */\nfunction getPatch(mutation: PatchMutation): Map {\n const result = new Map();\n mutation.fieldMask.fields.forEach(fieldPath => {\n if (!fieldPath.isEmpty()) {\n const newValue = mutation.data.field(fieldPath);\n result.set(fieldPath, newValue);\n }\n });\n return result;\n}\n\n/**\n * Creates a list of \"transform results\" (a transform result is a field value\n * representing the result of applying a transform) for use after a mutation\n * containing transforms has been acknowledged by the server.\n *\n * @param fieldTransforms - The field transforms to apply the result to.\n * @param mutableDocument - The current state of the document after applying all\n * previous mutations.\n * @param serverTransformResults - The transform results received by the server.\n * @returns The transform results list.\n */\nfunction serverTransformResults(\n fieldTransforms: FieldTransform[],\n mutableDocument: MutableDocument,\n serverTransformResults: Array\n): Map {\n const transformResults = new Map();\n hardAssert(\n fieldTransforms.length === serverTransformResults.length,\n 0x7f90,\n 'server transform result count should match field transform count',\n {\n serverTransformResultCount: serverTransformResults.length,\n fieldTransformCount: fieldTransforms.length\n }\n );\n\n for (let i = 0; i < serverTransformResults.length; i++) {\n const fieldTransform = fieldTransforms[i];\n const transform = fieldTransform.transform;\n const previousValue = mutableDocument.data.field(fieldTransform.field);\n transformResults.set(\n fieldTransform.field,\n applyTransformOperationToRemoteDocument(\n transform,\n previousValue,\n serverTransformResults[i]\n )\n );\n }\n return transformResults;\n}\n\n/**\n * Creates a list of \"transform results\" (a transform result is a field value\n * representing the result of applying a transform) for use when applying a\n * transform locally.\n *\n * @param fieldTransforms - The field transforms to apply the result to.\n * @param localWriteTime - The local time of the mutation (used to\n * generate ServerTimestampValues).\n * @param mutableDocument - The document to apply transforms on.\n * @returns The transform results list.\n */\nfunction localTransformResults(\n fieldTransforms: FieldTransform[],\n localWriteTime: Timestamp,\n mutableDocument: MutableDocument\n): Map {\n const transformResults = new Map();\n for (const fieldTransform of fieldTransforms) {\n const transform = fieldTransform.transform;\n\n const previousValue = mutableDocument.data.field(fieldTransform.field);\n transformResults.set(\n fieldTransform.field,\n applyTransformOperationToLocalView(\n transform,\n previousValue,\n localWriteTime\n )\n );\n }\n return transformResults;\n}\n\n/** A mutation that deletes the document at the given key. */\nexport class DeleteMutation extends Mutation {\n constructor(readonly key: DocumentKey, readonly precondition: Precondition) {\n super();\n }\n\n readonly type: MutationType = MutationType.Delete;\n readonly fieldTransforms: FieldTransform[] = [];\n\n getFieldMask(): FieldMask | null {\n return null;\n }\n}\n\nfunction deleteMutationApplyToRemoteDocument(\n mutation: DeleteMutation,\n document: MutableDocument,\n mutationResult: MutationResult\n): void {\n debugAssert(\n mutationResult.transformResults.length === 0,\n 'Transform results received by DeleteMutation.'\n );\n\n // Unlike applyToLocalView, if we're applying a mutation to a remote\n // document the server has accepted the mutation so the precondition must\n // have held.\n document\n .convertToNoDocument(mutationResult.version)\n .setHasCommittedMutations();\n}\n\nfunction deleteMutationApplyToLocalView(\n mutation: DeleteMutation,\n document: MutableDocument,\n previousMask: FieldMask | null\n): FieldMask | null {\n debugAssert(\n document.key.isEqual(mutation.key),\n 'Can only apply mutation to document with same key'\n );\n if (preconditionIsValidForDocument(mutation.precondition, document)) {\n document.convertToNoDocument(document.version).setHasLocalMutations();\n return null;\n }\n return previousMask;\n}\n\n/**\n * A mutation that verifies the existence of the document at the given key with\n * the provided precondition.\n *\n * The `verify` operation is only used in Transactions, and this class serves\n * primarily to facilitate serialization into protos.\n */\nexport class VerifyMutation extends Mutation {\n constructor(readonly key: DocumentKey, readonly precondition: Precondition) {\n super();\n }\n\n readonly type: MutationType = MutationType.Verify;\n readonly fieldTransforms: FieldTransform[] = [];\n\n getFieldMask(): FieldMask | null {\n return null;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Aggregate } from '../core/aggregate';\nimport { Bound } from '../core/bound';\nimport { DatabaseId } from '../core/database_info';\nimport {\n CompositeFilter,\n compositeFilterIsFlatConjunction,\n CompositeOperator,\n FieldFilter,\n Filter,\n Operator\n} from '../core/filter';\nimport { Direction, OrderBy } from '../core/order_by';\nimport {\n LimitType,\n newQuery,\n newQueryForPath,\n Query,\n queryToTarget\n} from '../core/query';\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { targetIsDocumentTarget, Target } from '../core/target';\nimport { TargetId } from '../core/types';\nimport { Timestamp } from '../lite-api/timestamp';\nimport { TargetData, TargetPurpose } from '../local/target_data';\nimport { MutableDocument } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { FieldMask } from '../model/field_mask';\nimport {\n DeleteMutation,\n FieldTransform,\n Mutation,\n MutationResult,\n PatchMutation,\n Precondition,\n SetMutation,\n VerifyMutation\n} from '../model/mutation';\nimport { normalizeTimestamp } from '../model/normalize';\nimport { ObjectValue } from '../model/object_value';\nimport { FieldPath, ResourcePath } from '../model/path';\nimport {\n ArrayRemoveTransformOperation,\n ArrayUnionTransformOperation,\n NumericIncrementTransformOperation,\n ServerTimestampTransform,\n TransformOperation\n} from '../model/transform_operation';\nimport { isNanValue, isNullValue } from '../model/values';\nimport {\n ApiClientObjectMap as ProtoApiClientObjectMap,\n BatchGetDocumentsResponse as ProtoBatchGetDocumentsResponse,\n CompositeFilterOp as ProtoCompositeFilterOp,\n Cursor as ProtoCursor,\n Document as ProtoDocument,\n DocumentMask as ProtoDocumentMask,\n DocumentsTarget as ProtoDocumentsTarget,\n FieldFilterOp as ProtoFieldFilterOp,\n FieldReference as ProtoFieldReference,\n FieldTransform as ProtoFieldTransform,\n Filter as ProtoFilter,\n ListenResponse as ProtoListenResponse,\n Order as ProtoOrder,\n OrderDirection as ProtoOrderDirection,\n Precondition as ProtoPrecondition,\n QueryTarget as ProtoQueryTarget,\n RunAggregationQueryRequest as ProtoRunAggregationQueryRequest,\n Aggregation as ProtoAggregation,\n Status as ProtoStatus,\n Target as ProtoTarget,\n TargetChangeTargetChangeType as ProtoTargetChangeTargetChangeType,\n Timestamp as ProtoTimestamp,\n Write as ProtoWrite,\n WriteResult as ProtoWriteResult\n} from '../protos/firestore_proto_api';\nimport { debugAssert, fail, hardAssert } from '../util/assert';\nimport { ByteString } from '../util/byte_string';\nimport { Code, FirestoreError } from '../util/error';\nimport { isNullOrUndefined } from '../util/types';\n\nimport { ExistenceFilter } from './existence_filter';\nimport { Serializer } from './number_serializer';\nimport { mapCodeFromRpcCode } from './rpc_error';\nimport {\n DocumentWatchChange,\n ExistenceFilterChange,\n WatchChange,\n WatchTargetChange,\n WatchTargetChangeState\n} from './watch_change';\n\nconst DIRECTIONS = (() => {\n const dirs: { [dir: string]: ProtoOrderDirection } = {};\n dirs[Direction.ASCENDING] = 'ASCENDING';\n dirs[Direction.DESCENDING] = 'DESCENDING';\n return dirs;\n})();\n\nconst OPERATORS = (() => {\n const ops: { [op: string]: ProtoFieldFilterOp } = {};\n ops[Operator.LESS_THAN] = 'LESS_THAN';\n ops[Operator.LESS_THAN_OR_EQUAL] = 'LESS_THAN_OR_EQUAL';\n ops[Operator.GREATER_THAN] = 'GREATER_THAN';\n ops[Operator.GREATER_THAN_OR_EQUAL] = 'GREATER_THAN_OR_EQUAL';\n ops[Operator.EQUAL] = 'EQUAL';\n ops[Operator.NOT_EQUAL] = 'NOT_EQUAL';\n ops[Operator.ARRAY_CONTAINS] = 'ARRAY_CONTAINS';\n ops[Operator.IN] = 'IN';\n ops[Operator.NOT_IN] = 'NOT_IN';\n ops[Operator.ARRAY_CONTAINS_ANY] = 'ARRAY_CONTAINS_ANY';\n return ops;\n})();\n\nconst COMPOSITE_OPERATORS = (() => {\n const ops: { [op: string]: ProtoCompositeFilterOp } = {};\n ops[CompositeOperator.AND] = 'AND';\n ops[CompositeOperator.OR] = 'OR';\n return ops;\n})();\n\nfunction assertPresent(value: unknown, description: string): asserts value {\n debugAssert(!isNullOrUndefined(value), description + ' is missing');\n}\n\n/**\n * This class generates JsonObject values for the Datastore API suitable for\n * sending to either GRPC stub methods or via the JSON/HTTP REST API.\n *\n * The serializer supports both Protobuf.js and Proto3 JSON formats. By\n * setting `useProto3Json` to true, the serializer will use the Proto3 JSON\n * format.\n *\n * For a description of the Proto3 JSON format check\n * https://developers.google.com/protocol-buffers/docs/proto3#json\n *\n * TODO(klimt): We can remove the databaseId argument if we keep the full\n * resource name in documents.\n */\nexport class JsonProtoSerializer implements Serializer {\n constructor(\n readonly databaseId: DatabaseId,\n readonly useProto3Json: boolean\n ) {}\n}\n\nfunction fromRpcStatus(status: ProtoStatus): FirestoreError {\n const code =\n status.code === undefined ? Code.UNKNOWN : mapCodeFromRpcCode(status.code);\n return new FirestoreError(code, status.message || '');\n}\n\n/**\n * Returns a value for a number (or null) that's appropriate to put into\n * a google.protobuf.Int32Value proto.\n * DO NOT USE THIS FOR ANYTHING ELSE.\n * This method cheats. It's typed as returning \"number\" because that's what\n * our generated proto interfaces say Int32Value must be. But GRPC actually\n * expects a { value: } struct.\n */\nfunction toInt32Proto(\n serializer: JsonProtoSerializer,\n val: number | null\n): number | { value: number } | null {\n if (serializer.useProto3Json || isNullOrUndefined(val)) {\n return val;\n } else {\n return { value: val };\n }\n}\n\n/**\n * Returns a number (or null) from a google.protobuf.Int32Value proto.\n */\nfunction fromInt32Proto(\n val: number | { value: number } | undefined\n): number | null {\n let result;\n if (typeof val === 'object') {\n result = val.value;\n } else {\n result = val;\n }\n return isNullOrUndefined(result) ? null : result;\n}\n\n/**\n * Returns a value for a Date that's appropriate to put into a proto.\n */\nexport function toTimestamp(\n serializer: JsonProtoSerializer,\n timestamp: Timestamp\n): ProtoTimestamp {\n if (serializer.useProto3Json) {\n // Serialize to ISO-8601 date format, but with full nano resolution.\n // Since JS Date has only millis, let's only use it for the seconds and\n // then manually add the fractions to the end.\n const jsDateStr = new Date(timestamp.seconds * 1000).toISOString();\n // Remove .xxx frac part and Z in the end.\n const strUntilSeconds = jsDateStr.replace(/\\.\\d*/, '').replace('Z', '');\n // Pad the fraction out to 9 digits (nanos).\n const nanoStr = ('000000000' + timestamp.nanoseconds).slice(-9);\n\n return `${strUntilSeconds}.${nanoStr}Z`;\n } else {\n return {\n seconds: '' + timestamp.seconds,\n nanos: timestamp.nanoseconds\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } as any;\n }\n}\n\n/**\n * Returns a Timestamp typed object given protobuf timestamp value.\n */\nexport function fromTimestamp(date: ProtoTimestamp): Timestamp {\n const timestamp = normalizeTimestamp(date);\n return new Timestamp(timestamp.seconds, timestamp.nanos);\n}\n\n/**\n * Returns a value for bytes that's appropriate to put in a proto.\n *\n * Visible for testing.\n */\nexport function toBytes(\n serializer: JsonProtoSerializer,\n bytes: ByteString\n): string | Uint8Array {\n if (serializer.useProto3Json) {\n return bytes.toBase64();\n } else {\n return bytes.toUint8Array();\n }\n}\n\n/**\n * Returns a ByteString based on the proto string value.\n */\nexport function fromBytes(\n serializer: JsonProtoSerializer,\n value: string | Uint8Array | undefined\n): ByteString {\n if (serializer.useProto3Json) {\n hardAssert(\n value === undefined || typeof value === 'string',\n 0xe30b,\n 'value must be undefined or a string when using proto3 Json'\n );\n return ByteString.fromBase64String(value ? value : '');\n } else {\n hardAssert(\n value === undefined ||\n // Check if the value is an instance of both Buffer and Uint8Array,\n // despite the fact that Buffer extends Uint8Array. In some\n // environments, such as jsdom, the prototype chain of Buffer\n // does not indicate that it extends Uint8Array.\n value instanceof Buffer ||\n value instanceof Uint8Array,\n 0x3f41,\n 'value must be undefined, Buffer, or Uint8Array'\n );\n return ByteString.fromUint8Array(value ? value : new Uint8Array());\n }\n}\n\nexport function toVersion(\n serializer: JsonProtoSerializer,\n version: SnapshotVersion\n): ProtoTimestamp {\n return toTimestamp(serializer, version.toTimestamp());\n}\n\nexport function fromVersion(version: ProtoTimestamp): SnapshotVersion {\n hardAssert(!!version, 0xc050, \"Trying to deserialize version that isn't set\");\n return SnapshotVersion.fromTimestamp(fromTimestamp(version));\n}\n\nexport function toResourceName(\n databaseId: DatabaseId,\n path: ResourcePath\n): string {\n return toResourcePath(databaseId, path).canonicalString();\n}\n\nexport function toResourcePath(\n databaseId: DatabaseId,\n path?: ResourcePath\n): ResourcePath {\n const resourcePath = fullyQualifiedPrefixPath(databaseId).child('documents');\n return path === undefined ? resourcePath : resourcePath.child(path);\n}\n\nfunction fromResourceName(name: string): ResourcePath {\n const resource = ResourcePath.fromString(name);\n hardAssert(\n isValidResourceName(resource),\n 0x27ce,\n 'Tried to deserialize invalid key',\n { key: resource.toString() }\n );\n return resource;\n}\n\nexport function toName(\n serializer: JsonProtoSerializer,\n key: DocumentKey\n): string {\n return toResourceName(serializer.databaseId, key.path);\n}\n\nexport function fromName(\n serializer: JsonProtoSerializer,\n name: string\n): DocumentKey {\n const resource = fromResourceName(name);\n\n if (resource.get(1) !== serializer.databaseId.projectId) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Tried to deserialize key from different project: ' +\n resource.get(1) +\n ' vs ' +\n serializer.databaseId.projectId\n );\n }\n\n if (resource.get(3) !== serializer.databaseId.database) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Tried to deserialize key from different database: ' +\n resource.get(3) +\n ' vs ' +\n serializer.databaseId.database\n );\n }\n return new DocumentKey(extractLocalPathFromResourceName(resource));\n}\n\nfunction toQueryPath(\n serializer: JsonProtoSerializer,\n path: ResourcePath\n): string {\n return toResourceName(serializer.databaseId, path);\n}\n\nfunction fromQueryPath(name: string): ResourcePath {\n const resourceName = fromResourceName(name);\n // In v1beta1 queries for collections at the root did not have a trailing\n // \"/documents\". In v1 all resource paths contain \"/documents\". Preserve the\n // ability to read the v1beta1 form for compatibility with queries persisted\n // in the local target cache.\n if (resourceName.length === 4) {\n return ResourcePath.emptyPath();\n }\n return extractLocalPathFromResourceName(resourceName);\n}\n\nexport function getEncodedDatabaseId(serializer: JsonProtoSerializer): string {\n const path = new ResourcePath([\n 'projects',\n serializer.databaseId.projectId,\n 'databases',\n serializer.databaseId.database\n ]);\n return path.canonicalString();\n}\n\nfunction fullyQualifiedPrefixPath(databaseId: DatabaseId): ResourcePath {\n return new ResourcePath([\n 'projects',\n databaseId.projectId,\n 'databases',\n databaseId.database\n ]);\n}\n\nfunction extractLocalPathFromResourceName(\n resourceName: ResourcePath\n): ResourcePath {\n hardAssert(\n resourceName.length > 4 && resourceName.get(4) === 'documents',\n 0x71a3,\n 'tried to deserialize invalid key',\n { key: resourceName.toString() }\n );\n return resourceName.popFirst(5);\n}\n\n/** Creates a Document proto from key and fields (but no create/update time) */\nexport function toMutationDocument(\n serializer: JsonProtoSerializer,\n key: DocumentKey,\n fields: ObjectValue\n): ProtoDocument {\n return {\n name: toName(serializer, key),\n fields: fields.value.mapValue.fields\n };\n}\n\nexport function toDocument(\n serializer: JsonProtoSerializer,\n document: MutableDocument\n): ProtoDocument {\n debugAssert(\n !document.hasLocalMutations,\n \"Can't serialize documents with mutations.\"\n );\n return {\n name: toName(serializer, document.key),\n fields: document.data.value.mapValue.fields,\n updateTime: toTimestamp(serializer, document.version.toTimestamp()),\n createTime: toTimestamp(serializer, document.createTime.toTimestamp())\n };\n}\n\nexport function fromDocument(\n serializer: JsonProtoSerializer,\n document: ProtoDocument,\n hasCommittedMutations?: boolean\n): MutableDocument {\n const key = fromName(serializer, document.name!);\n const version = fromVersion(document.updateTime!);\n // If we read a document from persistence that is missing createTime, it's due\n // to older SDK versions not storing this information. In such cases, we'll\n // set the createTime to zero. This can be removed in the long term.\n const createTime = document.createTime\n ? fromVersion(document.createTime)\n : SnapshotVersion.min();\n const data = new ObjectValue({ mapValue: { fields: document.fields } });\n const result = MutableDocument.newFoundDocument(\n key,\n version,\n createTime,\n data\n );\n if (hasCommittedMutations) {\n result.setHasCommittedMutations();\n }\n return hasCommittedMutations ? result.setHasCommittedMutations() : result;\n}\n\nfunction fromFound(\n serializer: JsonProtoSerializer,\n doc: ProtoBatchGetDocumentsResponse\n): MutableDocument {\n hardAssert(\n !!doc.found,\n 0xaa33,\n 'Tried to deserialize a found document from a missing document.'\n );\n assertPresent(doc.found.name, 'doc.found.name');\n assertPresent(doc.found.updateTime, 'doc.found.updateTime');\n const key = fromName(serializer, doc.found.name);\n const version = fromVersion(doc.found.updateTime);\n const createTime = doc.found.createTime\n ? fromVersion(doc.found.createTime)\n : SnapshotVersion.min();\n const data = new ObjectValue({ mapValue: { fields: doc.found.fields } });\n return MutableDocument.newFoundDocument(key, version, createTime, data);\n}\n\nfunction fromMissing(\n serializer: JsonProtoSerializer,\n result: ProtoBatchGetDocumentsResponse\n): MutableDocument {\n hardAssert(\n !!result.missing,\n 0x0f36,\n 'Tried to deserialize a missing document from a found document.'\n );\n hardAssert(\n !!result.readTime,\n 0x5995,\n 'Tried to deserialize a missing document without a read time.'\n );\n const key = fromName(serializer, result.missing);\n const version = fromVersion(result.readTime);\n return MutableDocument.newNoDocument(key, version);\n}\n\nexport function fromBatchGetDocumentsResponse(\n serializer: JsonProtoSerializer,\n result: ProtoBatchGetDocumentsResponse\n): MutableDocument {\n if ('found' in result) {\n return fromFound(serializer, result);\n } else if ('missing' in result) {\n return fromMissing(serializer, result);\n }\n return fail(0x1c42, 'invalid batch get response', { result });\n}\n\nexport function fromWatchChange(\n serializer: JsonProtoSerializer,\n change: ProtoListenResponse\n): WatchChange {\n let watchChange: WatchChange;\n if ('targetChange' in change) {\n assertPresent(change.targetChange, 'targetChange');\n // proto3 default value is unset in JSON (undefined), so use 'NO_CHANGE'\n // if unset\n const state = fromWatchTargetChangeState(\n change.targetChange.targetChangeType || 'NO_CHANGE'\n );\n const targetIds: TargetId[] = change.targetChange.targetIds || [];\n\n const resumeToken = fromBytes(serializer, change.targetChange.resumeToken);\n const causeProto = change.targetChange!.cause;\n const cause = causeProto && fromRpcStatus(causeProto);\n watchChange = new WatchTargetChange(\n state,\n targetIds,\n resumeToken,\n cause || null\n );\n } else if ('documentChange' in change) {\n assertPresent(change.documentChange, 'documentChange');\n const entityChange = change.documentChange;\n assertPresent(entityChange.document, 'documentChange.name');\n assertPresent(entityChange.document.name, 'documentChange.document.name');\n assertPresent(\n entityChange.document.updateTime,\n 'documentChange.document.updateTime'\n );\n const key = fromName(serializer, entityChange.document.name);\n const version = fromVersion(entityChange.document.updateTime);\n const createTime = entityChange.document.createTime\n ? fromVersion(entityChange.document.createTime)\n : SnapshotVersion.min();\n const data = new ObjectValue({\n mapValue: { fields: entityChange.document.fields }\n });\n const doc = MutableDocument.newFoundDocument(\n key,\n version,\n createTime,\n data\n );\n const updatedTargetIds = entityChange.targetIds || [];\n const removedTargetIds = entityChange.removedTargetIds || [];\n watchChange = new DocumentWatchChange(\n updatedTargetIds,\n removedTargetIds,\n doc.key,\n doc\n );\n } else if ('documentDelete' in change) {\n assertPresent(change.documentDelete, 'documentDelete');\n const docDelete = change.documentDelete;\n assertPresent(docDelete.document, 'documentDelete.document');\n const key = fromName(serializer, docDelete.document);\n const version = docDelete.readTime\n ? fromVersion(docDelete.readTime)\n : SnapshotVersion.min();\n const doc = MutableDocument.newNoDocument(key, version);\n const removedTargetIds = docDelete.removedTargetIds || [];\n watchChange = new DocumentWatchChange([], removedTargetIds, doc.key, doc);\n } else if ('documentRemove' in change) {\n assertPresent(change.documentRemove, 'documentRemove');\n const docRemove = change.documentRemove;\n assertPresent(docRemove.document, 'documentRemove');\n const key = fromName(serializer, docRemove.document);\n const removedTargetIds = docRemove.removedTargetIds || [];\n watchChange = new DocumentWatchChange([], removedTargetIds, key, null);\n } else if ('filter' in change) {\n // TODO(dimond): implement existence filter parsing with strategy.\n assertPresent(change.filter, 'filter');\n const filter = change.filter;\n assertPresent(filter.targetId, 'filter.targetId');\n const { count = 0, unchangedNames } = filter;\n const existenceFilter = new ExistenceFilter(count, unchangedNames);\n const targetId = filter.targetId;\n watchChange = new ExistenceFilterChange(targetId, existenceFilter);\n } else {\n return fail(0x2d51, 'Unknown change type', { change });\n }\n return watchChange;\n}\n\nfunction fromWatchTargetChangeState(\n state: ProtoTargetChangeTargetChangeType\n): WatchTargetChangeState {\n if (state === 'NO_CHANGE') {\n return WatchTargetChangeState.NoChange;\n } else if (state === 'ADD') {\n return WatchTargetChangeState.Added;\n } else if (state === 'REMOVE') {\n return WatchTargetChangeState.Removed;\n } else if (state === 'CURRENT') {\n return WatchTargetChangeState.Current;\n } else if (state === 'RESET') {\n return WatchTargetChangeState.Reset;\n } else {\n return fail(0x9991, 'Got unexpected TargetChange.state', { state });\n }\n}\n\nexport function versionFromListenResponse(\n change: ProtoListenResponse\n): SnapshotVersion {\n // We have only reached a consistent snapshot for the entire stream if there\n // is a read_time set and it applies to all targets (i.e. the list of\n // targets is empty). The backend is guaranteed to send such responses.\n if (!('targetChange' in change)) {\n return SnapshotVersion.min();\n }\n const targetChange = change.targetChange!;\n if (targetChange.targetIds && targetChange.targetIds.length) {\n return SnapshotVersion.min();\n }\n if (!targetChange.readTime) {\n return SnapshotVersion.min();\n }\n return fromVersion(targetChange.readTime);\n}\n\nexport function toMutation(\n serializer: JsonProtoSerializer,\n mutation: Mutation\n): ProtoWrite {\n let result: ProtoWrite;\n if (mutation instanceof SetMutation) {\n result = {\n update: toMutationDocument(serializer, mutation.key, mutation.value)\n };\n } else if (mutation instanceof DeleteMutation) {\n result = { delete: toName(serializer, mutation.key) };\n } else if (mutation instanceof PatchMutation) {\n result = {\n update: toMutationDocument(serializer, mutation.key, mutation.data),\n updateMask: toDocumentMask(mutation.fieldMask)\n };\n } else if (mutation instanceof VerifyMutation) {\n result = {\n verify: toName(serializer, mutation.key)\n };\n } else {\n return fail(0x40d7, 'Unknown mutation type', {\n mutationType: mutation.type\n });\n }\n\n if (mutation.fieldTransforms.length > 0) {\n result.updateTransforms = mutation.fieldTransforms.map(transform =>\n toFieldTransform(serializer, transform)\n );\n }\n\n if (!mutation.precondition.isNone) {\n result.currentDocument = toPrecondition(serializer, mutation.precondition);\n }\n\n return result;\n}\n\nexport function fromMutation(\n serializer: JsonProtoSerializer,\n proto: ProtoWrite\n): Mutation {\n const precondition = proto.currentDocument\n ? fromPrecondition(proto.currentDocument)\n : Precondition.none();\n\n const fieldTransforms = proto.updateTransforms\n ? proto.updateTransforms.map(transform =>\n fromFieldTransform(serializer, transform)\n )\n : [];\n\n if (proto.update) {\n assertPresent(proto.update.name, 'name');\n const key = fromName(serializer, proto.update.name);\n const value = new ObjectValue({\n mapValue: { fields: proto.update.fields }\n });\n\n if (proto.updateMask) {\n const fieldMask = fromDocumentMask(proto.updateMask);\n return new PatchMutation(\n key,\n value,\n fieldMask,\n precondition,\n fieldTransforms\n );\n } else {\n return new SetMutation(key, value, precondition, fieldTransforms);\n }\n } else if (proto.delete) {\n const key = fromName(serializer, proto.delete);\n return new DeleteMutation(key, precondition);\n } else if (proto.verify) {\n const key = fromName(serializer, proto.verify);\n return new VerifyMutation(key, precondition);\n } else {\n return fail(0x05b7, 'unknown mutation proto', { proto });\n }\n}\n\nfunction toPrecondition(\n serializer: JsonProtoSerializer,\n precondition: Precondition\n): ProtoPrecondition {\n debugAssert(!precondition.isNone, \"Can't serialize an empty precondition\");\n if (precondition.updateTime !== undefined) {\n return {\n updateTime: toVersion(serializer, precondition.updateTime)\n };\n } else if (precondition.exists !== undefined) {\n return { exists: precondition.exists };\n } else {\n return fail(0x6b69, 'Unknown precondition');\n }\n}\n\nfunction fromPrecondition(precondition: ProtoPrecondition): Precondition {\n if (precondition.updateTime !== undefined) {\n return Precondition.updateTime(fromVersion(precondition.updateTime));\n } else if (precondition.exists !== undefined) {\n return Precondition.exists(precondition.exists);\n } else {\n return Precondition.none();\n }\n}\n\nfunction fromWriteResult(\n proto: ProtoWriteResult,\n commitTime: ProtoTimestamp\n): MutationResult {\n // NOTE: Deletes don't have an updateTime.\n let version = proto.updateTime\n ? fromVersion(proto.updateTime)\n : fromVersion(commitTime);\n\n if (version.isEqual(SnapshotVersion.min())) {\n // The Firestore Emulator currently returns an update time of 0 for\n // deletes of non-existing documents (rather than null). This breaks the\n // test \"get deleted doc while offline with source=cache\" as NoDocuments\n // with version 0 are filtered by IndexedDb's RemoteDocumentCache.\n // TODO(#2149): Remove this when Emulator is fixed\n version = fromVersion(commitTime);\n }\n\n return new MutationResult(version, proto.transformResults || []);\n}\n\nexport function fromWriteResults(\n protos: ProtoWriteResult[] | undefined,\n commitTime?: ProtoTimestamp\n): MutationResult[] {\n if (protos && protos.length > 0) {\n hardAssert(\n commitTime !== undefined,\n 0x3811,\n 'Received a write result without a commit time'\n );\n return protos.map(proto => fromWriteResult(proto, commitTime));\n } else {\n return [];\n }\n}\n\nfunction toFieldTransform(\n serializer: JsonProtoSerializer,\n fieldTransform: FieldTransform\n): ProtoFieldTransform {\n const transform = fieldTransform.transform;\n if (transform instanceof ServerTimestampTransform) {\n return {\n fieldPath: fieldTransform.field.canonicalString(),\n setToServerValue: 'REQUEST_TIME'\n };\n } else if (transform instanceof ArrayUnionTransformOperation) {\n return {\n fieldPath: fieldTransform.field.canonicalString(),\n appendMissingElements: {\n values: transform.elements\n }\n };\n } else if (transform instanceof ArrayRemoveTransformOperation) {\n return {\n fieldPath: fieldTransform.field.canonicalString(),\n removeAllFromArray: {\n values: transform.elements\n }\n };\n } else if (transform instanceof NumericIncrementTransformOperation) {\n return {\n fieldPath: fieldTransform.field.canonicalString(),\n increment: transform.operand\n };\n } else {\n throw fail(0x51c2, 'Unknown transform', {\n transform: fieldTransform.transform\n });\n }\n}\n\nfunction fromFieldTransform(\n serializer: JsonProtoSerializer,\n proto: ProtoFieldTransform\n): FieldTransform {\n let transform: TransformOperation | null = null;\n if ('setToServerValue' in proto) {\n hardAssert(\n proto.setToServerValue === 'REQUEST_TIME',\n 0x40f6,\n 'Unknown server value transform proto',\n { proto }\n );\n transform = new ServerTimestampTransform();\n } else if ('appendMissingElements' in proto) {\n const values = proto.appendMissingElements!.values || [];\n transform = new ArrayUnionTransformOperation(values);\n } else if ('removeAllFromArray' in proto) {\n const values = proto.removeAllFromArray!.values || [];\n transform = new ArrayRemoveTransformOperation(values);\n } else if ('increment' in proto) {\n transform = new NumericIncrementTransformOperation(\n serializer,\n proto.increment!\n );\n } else {\n fail(0x40c8, 'Unknown transform proto', { proto });\n }\n const fieldPath = FieldPath.fromServerFormat(proto.fieldPath!);\n return new FieldTransform(fieldPath, transform!);\n}\n\nexport function toDocumentsTarget(\n serializer: JsonProtoSerializer,\n target: Target\n): ProtoDocumentsTarget {\n return { documents: [toQueryPath(serializer, target.path)] };\n}\n\nexport function fromDocumentsTarget(\n documentsTarget: ProtoDocumentsTarget\n): Target {\n const count = documentsTarget.documents!.length;\n hardAssert(\n count === 1,\n 0x07ae,\n 'DocumentsTarget contained other than 1 document',\n {\n count\n }\n );\n const name = documentsTarget.documents![0];\n return queryToTarget(newQueryForPath(fromQueryPath(name)));\n}\n\nexport function toQueryTarget(\n serializer: JsonProtoSerializer,\n target: Target\n): { queryTarget: ProtoQueryTarget; parent: ResourcePath } {\n // Dissect the path into parent, collectionId, and optional key filter.\n const queryTarget: ProtoQueryTarget = { structuredQuery: {} };\n const path = target.path;\n let parent: ResourcePath;\n if (target.collectionGroup !== null) {\n debugAssert(\n path.length % 2 === 0,\n 'Collection Group queries should be within a document path or root.'\n );\n parent = path;\n queryTarget.structuredQuery!.from = [\n {\n collectionId: target.collectionGroup,\n allDescendants: true\n }\n ];\n } else {\n debugAssert(\n path.length % 2 !== 0,\n 'Document queries with filters are not supported.'\n );\n parent = path.popLast();\n queryTarget.structuredQuery!.from = [{ collectionId: path.lastSegment() }];\n }\n queryTarget.parent = toQueryPath(serializer, parent);\n\n const where = toFilters(target.filters);\n if (where) {\n queryTarget.structuredQuery!.where = where;\n }\n\n const orderBy = toOrder(target.orderBy);\n if (orderBy) {\n queryTarget.structuredQuery!.orderBy = orderBy;\n }\n\n const limit = toInt32Proto(serializer, target.limit);\n if (limit !== null) {\n queryTarget.structuredQuery!.limit = limit;\n }\n\n if (target.startAt) {\n queryTarget.structuredQuery!.startAt = toStartAtCursor(target.startAt);\n }\n if (target.endAt) {\n queryTarget.structuredQuery!.endAt = toEndAtCursor(target.endAt);\n }\n\n return { queryTarget, parent };\n}\n\nexport function toRunAggregationQueryRequest(\n serializer: JsonProtoSerializer,\n target: Target,\n aggregates: Aggregate[],\n skipAliasing?: boolean\n): {\n request: ProtoRunAggregationQueryRequest;\n aliasMap: Record;\n parent: ResourcePath;\n} {\n const { queryTarget, parent } = toQueryTarget(serializer, target);\n const aliasMap: Record = {};\n\n const aggregations: ProtoAggregation[] = [];\n let aggregationNum = 0;\n\n aggregates.forEach(aggregate => {\n // Map all client-side aliases to a unique short-form\n // alias. This avoids issues with client-side aliases that\n // exceed the 1500-byte string size limit.\n const serverAlias = skipAliasing\n ? aggregate.alias\n : `aggregate_${aggregationNum++}`;\n aliasMap[serverAlias] = aggregate.alias;\n\n if (aggregate.aggregateType === 'count') {\n aggregations.push({\n alias: serverAlias,\n count: {}\n });\n } else if (aggregate.aggregateType === 'avg') {\n aggregations.push({\n alias: serverAlias,\n avg: {\n field: toFieldPathReference(aggregate.fieldPath!)\n }\n });\n } else if (aggregate.aggregateType === 'sum') {\n aggregations.push({\n alias: serverAlias,\n sum: {\n field: toFieldPathReference(aggregate.fieldPath!)\n }\n });\n }\n });\n\n return {\n request: {\n structuredAggregationQuery: {\n aggregations,\n structuredQuery: queryTarget.structuredQuery\n },\n parent: queryTarget.parent\n },\n aliasMap,\n parent\n };\n}\n\nexport function convertQueryTargetToQuery(target: ProtoQueryTarget): Query {\n let path = fromQueryPath(target.parent!);\n\n const query = target.structuredQuery!;\n const fromCount = query.from ? query.from.length : 0;\n let collectionGroup: string | null = null;\n if (fromCount > 0) {\n hardAssert(\n fromCount === 1,\n 0xfe26,\n 'StructuredQuery.from with more than one collection is not supported.'\n );\n const from = query.from![0];\n if (from.allDescendants) {\n collectionGroup = from.collectionId!;\n } else {\n path = path.child(from.collectionId!);\n }\n }\n\n let filterBy: Filter[] = [];\n if (query.where) {\n filterBy = fromFilters(query.where);\n }\n\n let orderBy: OrderBy[] = [];\n if (query.orderBy) {\n orderBy = fromOrder(query.orderBy);\n }\n\n let limit: number | null = null;\n if (query.limit) {\n limit = fromInt32Proto(query.limit);\n }\n\n let startAt: Bound | null = null;\n if (query.startAt) {\n startAt = fromStartAtCursor(query.startAt);\n }\n\n let endAt: Bound | null = null;\n if (query.endAt) {\n endAt = fromEndAtCursor(query.endAt);\n }\n\n return newQuery(\n path,\n collectionGroup,\n orderBy,\n filterBy,\n limit,\n LimitType.First,\n startAt,\n endAt\n );\n}\n\nexport function fromQueryTarget(target: ProtoQueryTarget): Target {\n return queryToTarget(convertQueryTargetToQuery(target));\n}\n\nexport function toListenRequestLabels(\n serializer: JsonProtoSerializer,\n targetData: TargetData\n): ProtoApiClientObjectMap | null {\n const value = toLabel(targetData.purpose);\n if (value == null) {\n return null;\n } else {\n return {\n 'goog-listen-tags': value\n };\n }\n}\n\nexport function toLabel(purpose: TargetPurpose): string | null {\n switch (purpose) {\n case TargetPurpose.Listen:\n return null;\n case TargetPurpose.ExistenceFilterMismatch:\n return 'existence-filter-mismatch';\n case TargetPurpose.ExistenceFilterMismatchBloom:\n return 'existence-filter-mismatch-bloom';\n case TargetPurpose.LimboResolution:\n return 'limbo-document';\n default:\n return fail(0x713b, 'Unrecognized query purpose', { purpose });\n }\n}\n\nexport function toTarget(\n serializer: JsonProtoSerializer,\n targetData: TargetData\n): ProtoTarget {\n let result: ProtoTarget;\n const target = targetData.target;\n\n if (targetIsDocumentTarget(target)) {\n result = { documents: toDocumentsTarget(serializer, target) };\n } else {\n result = { query: toQueryTarget(serializer, target).queryTarget };\n }\n\n result.targetId = targetData.targetId;\n\n if (targetData.resumeToken.approximateByteSize() > 0) {\n result.resumeToken = toBytes(serializer, targetData.resumeToken);\n const expectedCount = toInt32Proto(serializer, targetData.expectedCount);\n if (expectedCount !== null) {\n result.expectedCount = expectedCount;\n }\n } else if (targetData.snapshotVersion.compareTo(SnapshotVersion.min()) > 0) {\n // TODO(wuandy): Consider removing above check because it is most likely true.\n // Right now, many tests depend on this behaviour though (leaving min() out\n // of serialization).\n result.readTime = toTimestamp(\n serializer,\n targetData.snapshotVersion.toTimestamp()\n );\n const expectedCount = toInt32Proto(serializer, targetData.expectedCount);\n if (expectedCount !== null) {\n result.expectedCount = expectedCount;\n }\n }\n\n return result;\n}\n\nfunction toFilters(filters: Filter[]): ProtoFilter | undefined {\n if (filters.length === 0) {\n return;\n }\n\n return toFilter(CompositeFilter.create(filters, CompositeOperator.AND));\n}\n\nfunction fromFilters(filter: ProtoFilter): Filter[] {\n const result = fromFilter(filter);\n\n if (\n result instanceof CompositeFilter &&\n compositeFilterIsFlatConjunction(result)\n ) {\n return result.getFilters();\n }\n\n return [result];\n}\n\nfunction fromFilter(filter: ProtoFilter): Filter {\n if (filter.unaryFilter !== undefined) {\n return fromUnaryFilter(filter);\n } else if (filter.fieldFilter !== undefined) {\n return fromFieldFilter(filter);\n } else if (filter.compositeFilter !== undefined) {\n return fromCompositeFilter(filter);\n } else {\n return fail(0x7591, 'Unknown filter', { filter });\n }\n}\n\nfunction toOrder(orderBys: OrderBy[]): ProtoOrder[] | undefined {\n if (orderBys.length === 0) {\n return;\n }\n return orderBys.map(order => toPropertyOrder(order));\n}\n\nfunction fromOrder(orderBys: ProtoOrder[]): OrderBy[] {\n return orderBys.map(order => fromPropertyOrder(order));\n}\n\nfunction toStartAtCursor(cursor: Bound): ProtoCursor {\n return {\n before: cursor.inclusive,\n values: cursor.position\n };\n}\n\nfunction toEndAtCursor(cursor: Bound): ProtoCursor {\n return {\n before: !cursor.inclusive,\n values: cursor.position\n };\n}\n\nfunction fromStartAtCursor(cursor: ProtoCursor): Bound {\n const inclusive = !!cursor.before;\n const position = cursor.values || [];\n return new Bound(position, inclusive);\n}\n\nfunction fromEndAtCursor(cursor: ProtoCursor): Bound {\n const inclusive = !cursor.before;\n const position = cursor.values || [];\n return new Bound(position, inclusive);\n}\n\n// visible for testing\nexport function toDirection(dir: Direction): ProtoOrderDirection {\n return DIRECTIONS[dir];\n}\n\n// visible for testing\nexport function fromDirection(\n dir: ProtoOrderDirection | undefined\n): Direction | undefined {\n switch (dir) {\n case 'ASCENDING':\n return Direction.ASCENDING;\n case 'DESCENDING':\n return Direction.DESCENDING;\n default:\n return undefined;\n }\n}\n\n// visible for testing\nexport function toOperatorName(op: Operator): ProtoFieldFilterOp {\n return OPERATORS[op];\n}\n\nexport function toCompositeOperatorName(\n op: CompositeOperator\n): ProtoCompositeFilterOp {\n return COMPOSITE_OPERATORS[op];\n}\n\nexport function fromOperatorName(op: ProtoFieldFilterOp): Operator {\n switch (op) {\n case 'EQUAL':\n return Operator.EQUAL;\n case 'NOT_EQUAL':\n return Operator.NOT_EQUAL;\n case 'GREATER_THAN':\n return Operator.GREATER_THAN;\n case 'GREATER_THAN_OR_EQUAL':\n return Operator.GREATER_THAN_OR_EQUAL;\n case 'LESS_THAN':\n return Operator.LESS_THAN;\n case 'LESS_THAN_OR_EQUAL':\n return Operator.LESS_THAN_OR_EQUAL;\n case 'ARRAY_CONTAINS':\n return Operator.ARRAY_CONTAINS;\n case 'IN':\n return Operator.IN;\n case 'NOT_IN':\n return Operator.NOT_IN;\n case 'ARRAY_CONTAINS_ANY':\n return Operator.ARRAY_CONTAINS_ANY;\n case 'OPERATOR_UNSPECIFIED':\n return fail(0xe2fe, 'Unspecified operator');\n default:\n return fail(0xc54a, 'Unknown operator');\n }\n}\n\nexport function fromCompositeOperatorName(\n op: ProtoCompositeFilterOp\n): CompositeOperator {\n switch (op) {\n case 'AND':\n return CompositeOperator.AND;\n case 'OR':\n return CompositeOperator.OR;\n default:\n return fail(0x0402, 'Unknown operator');\n }\n}\n\nexport function toFieldPathReference(path: FieldPath): ProtoFieldReference {\n return { fieldPath: path.canonicalString() };\n}\n\nexport function fromFieldPathReference(\n fieldReference: ProtoFieldReference\n): FieldPath {\n return FieldPath.fromServerFormat(fieldReference.fieldPath!);\n}\n\n// visible for testing\nexport function toPropertyOrder(orderBy: OrderBy): ProtoOrder {\n return {\n field: toFieldPathReference(orderBy.field),\n direction: toDirection(orderBy.dir)\n };\n}\n\nexport function fromPropertyOrder(orderBy: ProtoOrder): OrderBy {\n return new OrderBy(\n fromFieldPathReference(orderBy.field!),\n fromDirection(orderBy.direction)\n );\n}\n\n// visible for testing\nexport function toFilter(filter: Filter): ProtoFilter {\n if (filter instanceof FieldFilter) {\n return toUnaryOrFieldFilter(filter);\n } else if (filter instanceof CompositeFilter) {\n return toCompositeFilter(filter);\n } else {\n return fail(0xd65d, 'Unrecognized filter type', { filter });\n }\n}\n\nexport function toCompositeFilter(filter: CompositeFilter): ProtoFilter {\n const protos = filter.getFilters().map(filter => toFilter(filter));\n\n if (protos.length === 1) {\n return protos[0];\n }\n\n return {\n compositeFilter: {\n op: toCompositeOperatorName(filter.op),\n filters: protos\n }\n };\n}\n\nexport function toUnaryOrFieldFilter(filter: FieldFilter): ProtoFilter {\n if (filter.op === Operator.EQUAL) {\n if (isNanValue(filter.value)) {\n return {\n unaryFilter: {\n field: toFieldPathReference(filter.field),\n op: 'IS_NAN'\n }\n };\n } else if (isNullValue(filter.value)) {\n return {\n unaryFilter: {\n field: toFieldPathReference(filter.field),\n op: 'IS_NULL'\n }\n };\n }\n } else if (filter.op === Operator.NOT_EQUAL) {\n if (isNanValue(filter.value)) {\n return {\n unaryFilter: {\n field: toFieldPathReference(filter.field),\n op: 'IS_NOT_NAN'\n }\n };\n } else if (isNullValue(filter.value)) {\n return {\n unaryFilter: {\n field: toFieldPathReference(filter.field),\n op: 'IS_NOT_NULL'\n }\n };\n }\n }\n return {\n fieldFilter: {\n field: toFieldPathReference(filter.field),\n op: toOperatorName(filter.op),\n value: filter.value\n }\n };\n}\n\nexport function fromUnaryFilter(filter: ProtoFilter): Filter {\n switch (filter.unaryFilter!.op!) {\n case 'IS_NAN':\n const nanField = fromFieldPathReference(filter.unaryFilter!.field!);\n return FieldFilter.create(nanField, Operator.EQUAL, {\n doubleValue: NaN\n });\n case 'IS_NULL':\n const nullField = fromFieldPathReference(filter.unaryFilter!.field!);\n return FieldFilter.create(nullField, Operator.EQUAL, {\n nullValue: 'NULL_VALUE'\n });\n case 'IS_NOT_NAN':\n const notNanField = fromFieldPathReference(filter.unaryFilter!.field!);\n return FieldFilter.create(notNanField, Operator.NOT_EQUAL, {\n doubleValue: NaN\n });\n case 'IS_NOT_NULL':\n const notNullField = fromFieldPathReference(filter.unaryFilter!.field!);\n return FieldFilter.create(notNullField, Operator.NOT_EQUAL, {\n nullValue: 'NULL_VALUE'\n });\n case 'OPERATOR_UNSPECIFIED':\n return fail(0xef81, 'Unspecified filter');\n default:\n return fail(0xed36, 'Unknown filter');\n }\n}\n\nexport function fromFieldFilter(filter: ProtoFilter): FieldFilter {\n return FieldFilter.create(\n fromFieldPathReference(filter.fieldFilter!.field!),\n fromOperatorName(filter.fieldFilter!.op!),\n filter.fieldFilter!.value!\n );\n}\n\nexport function fromCompositeFilter(filter: ProtoFilter): CompositeFilter {\n return CompositeFilter.create(\n filter.compositeFilter!.filters!.map(filter => fromFilter(filter)),\n fromCompositeOperatorName(filter.compositeFilter!.op!)\n );\n}\n\nexport function toDocumentMask(fieldMask: FieldMask): ProtoDocumentMask {\n const canonicalFields: string[] = [];\n fieldMask.fields.forEach(field =>\n canonicalFields.push(field.canonicalString())\n );\n return {\n fieldPaths: canonicalFields\n };\n}\n\nexport function fromDocumentMask(proto: ProtoDocumentMask): FieldMask {\n const paths = proto.fieldPaths || [];\n return new FieldMask(paths.map(path => FieldPath.fromServerFormat(path)));\n}\n\nexport function isValidResourceName(path: ResourcePath): boolean {\n // Resource names have at least 4 components (project ID, database ID)\n return (\n path.length >= 4 &&\n path.get(0) === 'projects' &&\n path.get(2) === 'databases'\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** Return the Platform-specific serializer monitor. */\nimport { DatabaseId } from '../../core/database_info';\nimport { JsonProtoSerializer } from '../../remote/serializer';\n\nexport function newSerializer(databaseId: DatabaseId): JsonProtoSerializer {\n return new JsonProtoSerializer(databaseId, /* useProto3Json= */ true);\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { AsyncQueue, DelayedOperation, TimerId } from '../util/async_queue';\nimport { logDebug } from '../util/log';\n\nconst LOG_TAG = 'ExponentialBackoff';\n\n/**\n * Initial backoff time in milliseconds after an error.\n * Set to 1s according to https://cloud.google.com/apis/design/errors.\n */\nconst DEFAULT_BACKOFF_INITIAL_DELAY_MS = 1000;\n\nconst DEFAULT_BACKOFF_FACTOR = 1.5;\n\n/** Maximum backoff time in milliseconds */\nconst DEFAULT_BACKOFF_MAX_DELAY_MS = 60 * 1000;\n\n/**\n * A helper for running delayed tasks following an exponential backoff curve\n * between attempts.\n *\n * Each delay is made up of a \"base\" delay which follows the exponential\n * backoff curve, and a +/- 50% \"jitter\" that is calculated and added to the\n * base delay. This prevents clients from accidentally synchronizing their\n * delays causing spikes of load to the backend.\n */\nexport class ExponentialBackoff {\n private currentBaseMs: number = 0;\n private timerPromise: DelayedOperation | null = null;\n /** The last backoff attempt, as epoch milliseconds. */\n private lastAttemptTime = Date.now();\n\n constructor(\n /**\n * The AsyncQueue to run backoff operations on.\n */\n private readonly queue: AsyncQueue,\n /**\n * The ID to use when scheduling backoff operations on the AsyncQueue.\n */\n private readonly timerId: TimerId,\n /**\n * The initial delay (used as the base delay on the first retry attempt).\n * Note that jitter will still be applied, so the actual delay could be as\n * little as 0.5*initialDelayMs.\n */\n private readonly initialDelayMs: number = DEFAULT_BACKOFF_INITIAL_DELAY_MS,\n /**\n * The multiplier to use to determine the extended base delay after each\n * attempt.\n */\n private readonly backoffFactor: number = DEFAULT_BACKOFF_FACTOR,\n /**\n * The maximum base delay after which no further backoff is performed.\n * Note that jitter will still be applied, so the actual delay could be as\n * much as 1.5*maxDelayMs.\n */\n private readonly maxDelayMs: number = DEFAULT_BACKOFF_MAX_DELAY_MS\n ) {\n this.reset();\n }\n\n /**\n * Resets the backoff delay.\n *\n * The very next backoffAndWait() will have no delay. If it is called again\n * (i.e. due to an error), initialDelayMs (plus jitter) will be used, and\n * subsequent ones will increase according to the backoffFactor.\n */\n reset(): void {\n this.currentBaseMs = 0;\n }\n\n /**\n * Resets the backoff delay to the maximum delay (e.g. for use after a\n * RESOURCE_EXHAUSTED error).\n */\n resetToMax(): void {\n this.currentBaseMs = this.maxDelayMs;\n }\n\n /**\n * Returns a promise that resolves after currentDelayMs, and increases the\n * delay for any subsequent attempts. If there was a pending backoff operation\n * already, it will be canceled.\n */\n backoffAndRun(op: () => Promise): void {\n // Cancel any pending backoff operation.\n this.cancel();\n\n // First schedule using the current base (which may be 0 and should be\n // honored as such).\n const desiredDelayWithJitterMs = Math.floor(\n this.currentBaseMs + this.jitterDelayMs()\n );\n\n // Guard against lastAttemptTime being in the future due to a clock change.\n const delaySoFarMs = Math.max(0, Date.now() - this.lastAttemptTime);\n\n // Guard against the backoff delay already being past.\n const remainingDelayMs = Math.max(\n 0,\n desiredDelayWithJitterMs - delaySoFarMs\n );\n\n if (remainingDelayMs > 0) {\n logDebug(\n LOG_TAG,\n `Backing off for ${remainingDelayMs} ms ` +\n `(base delay: ${this.currentBaseMs} ms, ` +\n `delay with jitter: ${desiredDelayWithJitterMs} ms, ` +\n `last attempt: ${delaySoFarMs} ms ago)`\n );\n }\n\n this.timerPromise = this.queue.enqueueAfterDelay(\n this.timerId,\n remainingDelayMs,\n () => {\n this.lastAttemptTime = Date.now();\n return op();\n }\n );\n\n // Apply backoff factor to determine next delay and ensure it is within\n // bounds.\n this.currentBaseMs *= this.backoffFactor;\n if (this.currentBaseMs < this.initialDelayMs) {\n this.currentBaseMs = this.initialDelayMs;\n }\n if (this.currentBaseMs > this.maxDelayMs) {\n this.currentBaseMs = this.maxDelayMs;\n }\n }\n\n skipBackoff(): void {\n if (this.timerPromise !== null) {\n this.timerPromise.skipDelay();\n this.timerPromise = null;\n }\n }\n\n cancel(): void {\n if (this.timerPromise !== null) {\n this.timerPromise.cancel();\n this.timerPromise = null;\n }\n }\n\n /** Returns a random value in the range [-currentBaseMs/2, currentBaseMs/2] */\n private jitterDelayMs(): number {\n return (Math.random() - 0.5) * this.currentBaseMs;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { CredentialsProvider } from '../api/credentials';\nimport { User } from '../auth/user';\nimport { Aggregate } from '../core/aggregate';\nimport { DatabaseId } from '../core/database_info';\nimport { queryToAggregateTarget, Query, queryToTarget } from '../core/query';\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { Mutation } from '../model/mutation';\nimport { ResourcePath } from '../model/path';\nimport {\n ApiClientObjectMap,\n BatchGetDocumentsRequest as ProtoBatchGetDocumentsRequest,\n BatchGetDocumentsResponse as ProtoBatchGetDocumentsResponse,\n RunAggregationQueryRequest as ProtoRunAggregationQueryRequest,\n RunAggregationQueryResponse as ProtoRunAggregationQueryResponse,\n RunQueryRequest as ProtoRunQueryRequest,\n RunQueryResponse as ProtoRunQueryResponse,\n Value\n} from '../protos/firestore_proto_api';\nimport { debugAssert, debugCast, hardAssert } from '../util/assert';\nimport { AsyncQueue } from '../util/async_queue';\nimport { Code, FirestoreError } from '../util/error';\nimport { isNullOrUndefined } from '../util/types';\n\nimport { Connection } from './connection';\nimport {\n PersistentListenStream,\n PersistentWriteStream,\n WatchStreamListener,\n WriteStreamListener\n} from './persistent_stream';\nimport {\n fromDocument,\n fromBatchGetDocumentsResponse,\n JsonProtoSerializer,\n toMutation,\n toName,\n toQueryTarget,\n toResourcePath,\n toRunAggregationQueryRequest\n} from './serializer';\n\n/**\n * Datastore and its related methods are a wrapper around the external Google\n * Cloud Datastore grpc API, which provides an interface that is more convenient\n * for the rest of the client SDK architecture to consume.\n */\nexport abstract class Datastore {\n abstract terminate(): void;\n abstract serializer: JsonProtoSerializer;\n}\n\n/**\n * An implementation of Datastore that exposes additional state for internal\n * consumption.\n */\nclass DatastoreImpl extends Datastore {\n terminated = false;\n\n constructor(\n readonly authCredentials: CredentialsProvider,\n readonly appCheckCredentials: CredentialsProvider,\n readonly connection: Connection,\n readonly serializer: JsonProtoSerializer\n ) {\n super();\n }\n\n verifyInitialized(): void {\n debugAssert(!!this.connection, 'Datastore.start() not called');\n if (this.terminated) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'The client has already been terminated.'\n );\n }\n }\n\n /** Invokes the provided RPC with auth and AppCheck tokens. */\n invokeRPC(\n rpcName: string,\n databaseId: DatabaseId,\n resourcePath: ResourcePath,\n request: Req\n ): Promise {\n this.verifyInitialized();\n return Promise.all([\n this.authCredentials.getToken(),\n this.appCheckCredentials.getToken()\n ])\n .then(([authToken, appCheckToken]) => {\n return this.connection.invokeRPC(\n rpcName,\n toResourcePath(databaseId, resourcePath),\n request,\n authToken,\n appCheckToken\n );\n })\n .catch((error: FirestoreError) => {\n if (error.name === 'FirebaseError') {\n if (error.code === Code.UNAUTHENTICATED) {\n this.authCredentials.invalidateToken();\n this.appCheckCredentials.invalidateToken();\n }\n throw error;\n } else {\n throw new FirestoreError(Code.UNKNOWN, error.toString());\n }\n });\n }\n\n /** Invokes the provided RPC with streamed results with auth and AppCheck tokens. */\n invokeStreamingRPC(\n rpcName: string,\n databaseId: DatabaseId,\n resourcePath: ResourcePath,\n request: Req,\n expectedResponseCount?: number\n ): Promise {\n this.verifyInitialized();\n return Promise.all([\n this.authCredentials.getToken(),\n this.appCheckCredentials.getToken()\n ])\n .then(([authToken, appCheckToken]) => {\n return this.connection.invokeStreamingRPC(\n rpcName,\n toResourcePath(databaseId, resourcePath),\n request,\n authToken,\n appCheckToken,\n expectedResponseCount\n );\n })\n .catch((error: FirestoreError) => {\n if (error.name === 'FirebaseError') {\n if (error.code === Code.UNAUTHENTICATED) {\n this.authCredentials.invalidateToken();\n this.appCheckCredentials.invalidateToken();\n }\n throw error;\n } else {\n throw new FirestoreError(Code.UNKNOWN, error.toString());\n }\n });\n }\n\n terminate(): void {\n this.terminated = true;\n this.connection.terminate();\n }\n}\n\n// TODO(firestorexp): Make sure there is only one Datastore instance per\n// firestore-exp client.\nexport function newDatastore(\n authCredentials: CredentialsProvider,\n appCheckCredentials: CredentialsProvider,\n connection: Connection,\n serializer: JsonProtoSerializer\n): Datastore {\n return new DatastoreImpl(\n authCredentials,\n appCheckCredentials,\n connection,\n serializer\n );\n}\n\nexport async function invokeCommitRpc(\n datastore: Datastore,\n mutations: Mutation[]\n): Promise {\n const datastoreImpl = debugCast(datastore, DatastoreImpl);\n const request = {\n writes: mutations.map(m => toMutation(datastoreImpl.serializer, m))\n };\n await datastoreImpl.invokeRPC(\n 'Commit',\n datastoreImpl.serializer.databaseId,\n ResourcePath.emptyPath(),\n request\n );\n}\n\nexport async function invokeBatchGetDocumentsRpc(\n datastore: Datastore,\n keys: DocumentKey[]\n): Promise {\n const datastoreImpl = debugCast(datastore, DatastoreImpl);\n const request = {\n documents: keys.map(k => toName(datastoreImpl.serializer, k))\n };\n const response = await datastoreImpl.invokeStreamingRPC<\n ProtoBatchGetDocumentsRequest,\n ProtoBatchGetDocumentsResponse\n >(\n 'BatchGetDocuments',\n datastoreImpl.serializer.databaseId,\n ResourcePath.emptyPath(),\n request,\n keys.length\n );\n\n const docs = new Map();\n response.forEach(proto => {\n const doc = fromBatchGetDocumentsResponse(datastoreImpl.serializer, proto);\n docs.set(doc.key.toString(), doc);\n });\n const result: Document[] = [];\n keys.forEach(key => {\n const doc = docs.get(key.toString());\n hardAssert(!!doc, 0xd7c2, 'Missing entity in write response for `key`', {\n key\n });\n result.push(doc);\n });\n return result;\n}\n\nexport async function invokeRunQueryRpc(\n datastore: Datastore,\n query: Query\n): Promise {\n const datastoreImpl = debugCast(datastore, DatastoreImpl);\n const { queryTarget, parent } = toQueryTarget(\n datastoreImpl.serializer,\n queryToTarget(query)\n );\n const response = await datastoreImpl.invokeStreamingRPC<\n ProtoRunQueryRequest,\n ProtoRunQueryResponse\n >('RunQuery', datastoreImpl.serializer.databaseId, parent, {\n structuredQuery: queryTarget.structuredQuery\n });\n return (\n response\n // Omit RunQueryResponses that only contain readTimes.\n .filter(proto => !!proto.document)\n .map(proto =>\n fromDocument(datastoreImpl.serializer, proto.document!, undefined)\n )\n );\n}\n\nexport async function invokeRunAggregationQueryRpc(\n datastore: Datastore,\n query: Query,\n aggregates: Aggregate[]\n): Promise> {\n const datastoreImpl = debugCast(datastore, DatastoreImpl);\n const { request, aliasMap, parent } = toRunAggregationQueryRequest(\n datastoreImpl.serializer,\n queryToAggregateTarget(query),\n aggregates\n );\n\n if (!datastoreImpl.connection.shouldResourcePathBeIncludedInRequest) {\n delete request.parent;\n }\n const response = await datastoreImpl.invokeStreamingRPC<\n ProtoRunAggregationQueryRequest,\n ProtoRunAggregationQueryResponse\n >(\n 'RunAggregationQuery',\n datastoreImpl.serializer.databaseId,\n parent,\n request,\n /*expectedResponseCount=*/ 1\n );\n\n // Omit RunAggregationQueryResponse that only contain readTimes.\n const filteredResult = response.filter(proto => !!proto.result);\n\n hardAssert(\n filteredResult.length === 1,\n 0xfcd7,\n 'Aggregation fields are missing from result.'\n );\n debugAssert(\n !isNullOrUndefined(filteredResult[0].result),\n 'aggregationQueryResponse.result'\n );\n debugAssert(\n !isNullOrUndefined(filteredResult[0].result.aggregateFields),\n 'aggregationQueryResponse.result.aggregateFields'\n );\n\n // Remap the short-form aliases that were sent to the server\n // to the client-side aliases. Users will access the results\n // using the client-side alias.\n const unmappedAggregateFields = filteredResult[0].result?.aggregateFields;\n const remappedFields = Object.keys(unmappedAggregateFields).reduce<\n ApiClientObjectMap\n >((accumulator, key) => {\n debugAssert(\n !isNullOrUndefined(aliasMap[key]),\n `'${key}' not present in aliasMap result`\n );\n accumulator[aliasMap[key]] = unmappedAggregateFields[key]!;\n return accumulator;\n }, {});\n\n return remappedFields;\n}\n\nexport function newPersistentWriteStream(\n datastore: Datastore,\n queue: AsyncQueue,\n listener: WriteStreamListener\n): PersistentWriteStream {\n const datastoreImpl = debugCast(datastore, DatastoreImpl);\n datastoreImpl.verifyInitialized();\n return new PersistentWriteStream(\n queue,\n datastoreImpl.connection,\n datastoreImpl.authCredentials,\n datastoreImpl.appCheckCredentials,\n datastoreImpl.serializer,\n listener\n );\n}\n\nexport function newPersistentWatchStream(\n datastore: Datastore,\n queue: AsyncQueue,\n listener: WatchStreamListener\n): PersistentListenStream {\n const datastoreImpl = debugCast(datastore, DatastoreImpl);\n datastoreImpl.verifyInitialized();\n return new PersistentListenStream(\n queue,\n datastoreImpl.connection,\n datastoreImpl.authCredentials,\n datastoreImpl.appCheckCredentials,\n datastoreImpl.serializer,\n listener\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport { _FirebaseService } from '@firebase/app';\n\nimport { CredentialsProvider } from '../api/credentials';\nimport { cloneLongPollingOptions } from '../api/long_polling_options';\nimport { User } from '../auth/user';\nimport { DatabaseId, DatabaseInfo } from '../core/database_info';\nimport { newConnection } from '../platform/connection';\nimport { newSerializer } from '../platform/serializer';\nimport { Datastore, newDatastore } from '../remote/datastore';\nimport { Code, FirestoreError } from '../util/error';\nimport { logDebug } from '../util/log';\n\nimport { FirestoreSettingsImpl } from './settings';\n\nexport const LOG_TAG = 'ComponentProvider';\n\n// The components module manages the lifetime of dependencies of the Firestore\n// client. Dependencies can be lazily constructed and only one exists per\n// Firestore instance.\n\n/**\n * An interface implemented by FirebaseFirestore that provides compatibility\n * with the usage in this file.\n *\n * This interface mainly exists to remove a cyclic dependency.\n */\nexport interface FirestoreService extends _FirebaseService {\n _authCredentials: CredentialsProvider;\n _appCheckCredentials: CredentialsProvider;\n _persistenceKey: string;\n _databaseId: DatabaseId;\n _terminated: boolean;\n\n _freezeSettings(): FirestoreSettingsImpl;\n}\n/**\n * An instance map that ensures only one Datastore exists per Firestore\n * instance.\n */\nconst datastoreInstances = new Map();\n\n/**\n * Returns an initialized and started Datastore for the given Firestore\n * instance. Callers must invoke removeComponents() when the Firestore\n * instance is terminated.\n */\nexport function getDatastore(firestore: FirestoreService): Datastore {\n if (firestore._terminated) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'The client has already been terminated.'\n );\n }\n if (!datastoreInstances.has(firestore)) {\n logDebug(LOG_TAG, 'Initializing Datastore');\n const databaseInfo = makeDatabaseInfo(\n firestore._databaseId,\n firestore.app.options.appId || '',\n firestore._persistenceKey,\n firestore._freezeSettings()\n );\n const connection = newConnection(databaseInfo);\n const serializer = newSerializer(firestore._databaseId);\n const datastore = newDatastore(\n firestore._authCredentials,\n firestore._appCheckCredentials,\n connection,\n serializer\n );\n\n datastoreInstances.set(firestore, datastore);\n }\n return datastoreInstances.get(firestore)!;\n}\n\n/**\n * Removes all components associated with the provided instance. Must be called\n * when the `Firestore` instance is terminated.\n */\nexport function removeComponents(firestore: FirestoreService): void {\n const datastore = datastoreInstances.get(firestore);\n if (datastore) {\n logDebug(LOG_TAG, 'Removing Datastore');\n datastoreInstances.delete(firestore);\n datastore.terminate();\n }\n}\n\nexport function makeDatabaseInfo(\n databaseId: DatabaseId,\n appId: string,\n persistenceKey: string,\n settings: FirestoreSettingsImpl\n): DatabaseInfo {\n return new DatabaseInfo(\n databaseId,\n appId,\n persistenceKey,\n settings.host,\n settings.ssl,\n settings.experimentalForceLongPolling,\n settings.experimentalAutoDetectLongPolling,\n cloneLongPollingOptions(settings.experimentalLongPollingOptions),\n settings.useFetchStreams,\n settings.isUsingEmulator\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DatabaseInfo } from '../../core/database_info';\nimport { Connection } from '../../remote/connection';\n\nimport { FetchConnection } from './fetch_connection';\n\nexport { newConnectivityMonitor } from '../browser/connection';\n\n/** Initializes the HTTP connection for the REST API. */\nexport function newConnection(databaseInfo: DatabaseInfo): Connection {\n return new FetchConnection(databaseInfo);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirestoreError } from '../api';\nimport { ListenSequence } from '../core/listen_sequence';\nimport { ListenSequenceNumber } from '../core/types';\nimport { debugAssert } from '../util/assert';\nimport { AsyncQueue, DelayedOperation, TimerId } from '../util/async_queue';\nimport { getLogLevel, logDebug, LogLevel } from '../util/log';\nimport { primitiveComparator } from '../util/misc';\nimport { SortedSet } from '../util/sorted_set';\n\nimport { ignoreIfPrimaryLeaseLoss, LocalStore } from './local_store';\nimport {\n ActiveTargets,\n GC_DID_NOT_RUN,\n LRU_COLLECTION_DISABLED,\n LruDelegate,\n LruGarbageCollector,\n LruParams,\n LruResults\n} from './lru_garbage_collector';\nimport { Scheduler } from './persistence';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { isIndexedDbTransactionError } from './simple_db';\n\nconst LOG_TAG = 'LruGarbageCollector';\n\nexport const LRU_MINIMUM_CACHE_SIZE_BYTES = 1 * 1024 * 1024;\n\n/** How long we wait to try running LRU GC after SDK initialization. */\nconst INITIAL_GC_DELAY_MS = 1 * 60 * 1000;\n/** Minimum amount of time between GC checks, after the first one. */\nconst REGULAR_GC_DELAY_MS = 5 * 60 * 1000;\n\n// The type and comparator for the items contained in the SortedSet used in\n// place of a priority queue for the RollingSequenceNumberBuffer.\ntype BufferEntry = [ListenSequenceNumber, number];\n\nfunction bufferEntryComparator(\n [aSequence, aIndex]: BufferEntry,\n [bSequence, bIndex]: BufferEntry\n): number {\n const seqCmp = primitiveComparator(aSequence, bSequence);\n if (seqCmp === 0) {\n // This order doesn't matter, but we can bias against churn by sorting\n // entries created earlier as less than newer entries.\n return primitiveComparator(aIndex, bIndex);\n } else {\n return seqCmp;\n }\n}\n\n/**\n * Used to calculate the nth sequence number. Keeps a rolling buffer of the\n * lowest n values passed to `addElement`, and finally reports the largest of\n * them in `maxValue`.\n */\nclass RollingSequenceNumberBuffer {\n private buffer: SortedSet = new SortedSet(\n bufferEntryComparator\n );\n\n private previousIndex = 0;\n\n constructor(private readonly maxElements: number) {}\n\n private nextIndex(): number {\n return ++this.previousIndex;\n }\n\n addElement(sequenceNumber: ListenSequenceNumber): void {\n const entry: BufferEntry = [sequenceNumber, this.nextIndex()];\n if (this.buffer.size < this.maxElements) {\n this.buffer = this.buffer.add(entry);\n } else {\n const highestValue = this.buffer.last()!;\n if (bufferEntryComparator(entry, highestValue) < 0) {\n this.buffer = this.buffer.delete(highestValue).add(entry);\n }\n }\n }\n\n get maxValue(): ListenSequenceNumber {\n // Guaranteed to be non-empty. If we decide we are not collecting any\n // sequence numbers, nthSequenceNumber below short-circuits. If we have\n // decided that we are collecting n sequence numbers, it's because n is some\n // percentage of the existing sequence numbers. That means we should never\n // be in a situation where we are collecting sequence numbers but don't\n // actually have any.\n return this.buffer.last()![0];\n }\n}\n\n/**\n * This class is responsible for the scheduling of LRU garbage collection. It handles checking\n * whether or not GC is enabled, as well as which delay to use before the next run.\n */\nexport class LruScheduler implements Scheduler {\n private gcTask: DelayedOperation | null;\n\n constructor(\n private readonly garbageCollector: LruGarbageCollector,\n private readonly asyncQueue: AsyncQueue,\n private readonly localStore: LocalStore\n ) {\n this.gcTask = null;\n }\n\n start(): void {\n debugAssert(\n this.gcTask === null,\n 'Cannot start an already started LruScheduler'\n );\n if (\n this.garbageCollector.params.cacheSizeCollectionThreshold !==\n LRU_COLLECTION_DISABLED\n ) {\n this.scheduleGC(INITIAL_GC_DELAY_MS);\n }\n }\n\n stop(): void {\n if (this.gcTask) {\n this.gcTask.cancel();\n this.gcTask = null;\n }\n }\n\n get started(): boolean {\n return this.gcTask !== null;\n }\n\n private scheduleGC(delay: number): void {\n debugAssert(\n this.gcTask === null,\n 'Cannot schedule GC while a task is pending'\n );\n logDebug(LOG_TAG, `Garbage collection scheduled in ${delay}ms`);\n this.gcTask = this.asyncQueue.enqueueAfterDelay(\n TimerId.LruGarbageCollection,\n delay,\n async () => {\n this.gcTask = null;\n try {\n await this.localStore.collectGarbage(this.garbageCollector);\n } catch (e) {\n if (isIndexedDbTransactionError(e as Error)) {\n logDebug(\n LOG_TAG,\n 'Ignoring IndexedDB error during garbage collection: ',\n e\n );\n } else {\n await ignoreIfPrimaryLeaseLoss(e as FirestoreError);\n }\n }\n await this.scheduleGC(REGULAR_GC_DELAY_MS);\n }\n );\n }\n}\n\n/**\n * Implements the steps for LRU garbage collection.\n */\nclass LruGarbageCollectorImpl implements LruGarbageCollector {\n constructor(\n private readonly delegate: LruDelegate,\n readonly params: LruParams\n ) {}\n\n calculateTargetCount(\n txn: PersistenceTransaction,\n percentile: number\n ): PersistencePromise {\n return this.delegate.getSequenceNumberCount(txn).next(targetCount => {\n return Math.floor((percentile / 100.0) * targetCount);\n });\n }\n\n nthSequenceNumber(\n txn: PersistenceTransaction,\n n: number\n ): PersistencePromise {\n if (n === 0) {\n return PersistencePromise.resolve(ListenSequence.INVALID);\n }\n\n const buffer = new RollingSequenceNumberBuffer(n);\n return this.delegate\n .forEachTarget(txn, target => buffer.addElement(target.sequenceNumber))\n .next(() => {\n return this.delegate.forEachOrphanedDocumentSequenceNumber(\n txn,\n sequenceNumber => buffer.addElement(sequenceNumber)\n );\n })\n .next(() => buffer.maxValue);\n }\n\n removeTargets(\n txn: PersistenceTransaction,\n upperBound: ListenSequenceNumber,\n activeTargetIds: ActiveTargets\n ): PersistencePromise {\n return this.delegate.removeTargets(txn, upperBound, activeTargetIds);\n }\n\n removeOrphanedDocuments(\n txn: PersistenceTransaction,\n upperBound: ListenSequenceNumber\n ): PersistencePromise {\n return this.delegate.removeOrphanedDocuments(txn, upperBound);\n }\n\n collect(\n txn: PersistenceTransaction,\n activeTargetIds: ActiveTargets\n ): PersistencePromise {\n if (this.params.cacheSizeCollectionThreshold === LRU_COLLECTION_DISABLED) {\n logDebug('LruGarbageCollector', 'Garbage collection skipped; disabled');\n return PersistencePromise.resolve(GC_DID_NOT_RUN);\n }\n\n return this.getCacheSize(txn).next(cacheSize => {\n if (cacheSize < this.params.cacheSizeCollectionThreshold) {\n logDebug(\n 'LruGarbageCollector',\n `Garbage collection skipped; Cache size ${cacheSize} ` +\n `is lower than threshold ${this.params.cacheSizeCollectionThreshold}`\n );\n return GC_DID_NOT_RUN;\n } else {\n return this.runGarbageCollection(txn, activeTargetIds);\n }\n });\n }\n\n getCacheSize(txn: PersistenceTransaction): PersistencePromise {\n return this.delegate.getCacheSize(txn);\n }\n\n private runGarbageCollection(\n txn: PersistenceTransaction,\n activeTargetIds: ActiveTargets\n ): PersistencePromise {\n let upperBoundSequenceNumber: number;\n let sequenceNumbersToCollect: number, targetsRemoved: number;\n // Timestamps for various pieces of the process\n let countedTargetsTs: number,\n foundUpperBoundTs: number,\n removedTargetsTs: number,\n removedDocumentsTs: number;\n const startTs = Date.now();\n return this.calculateTargetCount(txn, this.params.percentileToCollect)\n .next(sequenceNumbers => {\n // Cap at the configured max\n if (sequenceNumbers > this.params.maximumSequenceNumbersToCollect) {\n logDebug(\n 'LruGarbageCollector',\n 'Capping sequence numbers to collect down ' +\n `to the maximum of ${this.params.maximumSequenceNumbersToCollect} ` +\n `from ${sequenceNumbers}`\n );\n sequenceNumbersToCollect =\n this.params.maximumSequenceNumbersToCollect;\n } else {\n sequenceNumbersToCollect = sequenceNumbers;\n }\n countedTargetsTs = Date.now();\n\n return this.nthSequenceNumber(txn, sequenceNumbersToCollect);\n })\n .next(upperBound => {\n upperBoundSequenceNumber = upperBound;\n foundUpperBoundTs = Date.now();\n\n return this.removeTargets(\n txn,\n upperBoundSequenceNumber,\n activeTargetIds\n );\n })\n .next(numTargetsRemoved => {\n targetsRemoved = numTargetsRemoved;\n removedTargetsTs = Date.now();\n\n return this.removeOrphanedDocuments(txn, upperBoundSequenceNumber);\n })\n .next(documentsRemoved => {\n removedDocumentsTs = Date.now();\n\n if (getLogLevel() <= LogLevel.DEBUG) {\n const desc =\n 'LRU Garbage Collection\\n' +\n `\\tCounted targets in ${countedTargetsTs - startTs}ms\\n` +\n `\\tDetermined least recently used ${sequenceNumbersToCollect} in ` +\n `${foundUpperBoundTs - countedTargetsTs}ms\\n` +\n `\\tRemoved ${targetsRemoved} targets in ` +\n `${removedTargetsTs - foundUpperBoundTs}ms\\n` +\n `\\tRemoved ${documentsRemoved} documents in ` +\n `${removedDocumentsTs - removedTargetsTs}ms\\n` +\n `Total Duration: ${removedDocumentsTs - startTs}ms`;\n logDebug('LruGarbageCollector', desc);\n }\n\n return PersistencePromise.resolve({\n didRun: true,\n sequenceNumbersCollected: sequenceNumbersToCollect,\n targetsRemoved,\n documentsRemoved\n });\n });\n }\n}\n\nexport function newLruGarbageCollector(\n delegate: LruDelegate,\n params: LruParams\n): LruGarbageCollector {\n return new LruGarbageCollectorImpl(delegate, params);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { EmulatorMockTokenOptions } from '@firebase/util';\n\nimport { FirestoreLocalCache } from '../api/cache_config';\nimport { CredentialsSettings } from '../api/credentials';\nimport {\n ExperimentalLongPollingOptions,\n cloneLongPollingOptions,\n longPollingOptionsEqual\n} from '../api/long_polling_options';\nimport {\n LRU_COLLECTION_DISABLED,\n LRU_DEFAULT_CACHE_SIZE_BYTES\n} from '../local/lru_garbage_collector';\nimport { LRU_MINIMUM_CACHE_SIZE_BYTES } from '../local/lru_garbage_collector_impl';\nimport { Code, FirestoreError } from '../util/error';\nimport { validateIsNotUsedTogether } from '../util/input_validation';\n\n// settings() defaults:\nexport const DEFAULT_HOST = 'firestore.googleapis.com';\nexport const DEFAULT_SSL = true;\n\n// The minimum long-polling timeout is hardcoded on the server. The value here\n// should be kept in sync with the value used by the server, as the server will\n// silently ignore a value below the minimum and fall back to the default.\n// Googlers see b/266868871 for relevant discussion.\nconst MIN_LONG_POLLING_TIMEOUT_SECONDS = 5;\n\n// No maximum long-polling timeout is configured in the server, and defaults to\n// 30 seconds, which is what Watch appears to use.\n// Googlers see b/266868871 for relevant discussion.\nconst MAX_LONG_POLLING_TIMEOUT_SECONDS = 30;\n\n// Whether long-polling auto-detected is enabled by default.\nconst DEFAULT_AUTO_DETECT_LONG_POLLING = true;\n\n/**\n * Specifies custom configurations for your Cloud Firestore instance.\n * You must set these before invoking any other methods.\n */\nexport interface FirestoreSettings {\n /** The hostname to connect to. */\n host?: string;\n\n /** Whether to use SSL when connecting. */\n ssl?: boolean;\n\n /**\n * Whether to skip nested properties that are set to `undefined` during\n * object serialization. If set to `true`, these properties are skipped\n * and not written to Firestore. If set to `false` or omitted, the SDK\n * throws an exception when it encounters properties of type `undefined`.\n */\n ignoreUndefinedProperties?: boolean;\n}\n\n/**\n * @internal\n * Undocumented, private additional settings not exposed in our public API.\n */\nexport interface PrivateSettings extends FirestoreSettings {\n // Can be a google-auth-library or gapi client.\n credentials?: CredentialsSettings;\n cacheSizeBytes?: number;\n experimentalForceLongPolling?: boolean;\n experimentalAutoDetectLongPolling?: boolean;\n experimentalLongPollingOptions?: ExperimentalLongPollingOptions;\n useFetchStreams?: boolean;\n emulatorOptions?: { mockUserToken?: EmulatorMockTokenOptions | string };\n\n localCache?: FirestoreLocalCache;\n}\n\n/**\n * A concrete type describing all the values that can be applied via a\n * user-supplied `FirestoreSettings` object. This is a separate type so that\n * defaults can be supplied and the value can be checked for equality.\n */\nexport class FirestoreSettingsImpl {\n /** The hostname to connect to. */\n readonly host: string;\n\n /** Whether to use SSL when connecting. */\n readonly ssl: boolean;\n\n readonly cacheSizeBytes: number;\n\n readonly experimentalForceLongPolling: boolean;\n\n readonly experimentalAutoDetectLongPolling: boolean;\n\n readonly experimentalLongPollingOptions: ExperimentalLongPollingOptions;\n\n readonly ignoreUndefinedProperties: boolean;\n\n readonly useFetchStreams: boolean;\n readonly localCache?: FirestoreLocalCache;\n\n readonly isUsingEmulator: boolean;\n\n // Can be a google-auth-library or gapi client.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n credentials?: any;\n\n constructor(settings: PrivateSettings) {\n if (settings.host === undefined) {\n if (settings.ssl !== undefined) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n \"Can't provide ssl option if host option is not set\"\n );\n }\n this.host = DEFAULT_HOST;\n this.ssl = DEFAULT_SSL;\n } else {\n this.host = settings.host;\n this.ssl = settings.ssl ?? DEFAULT_SSL;\n }\n this.isUsingEmulator = settings.emulatorOptions !== undefined;\n\n this.credentials = settings.credentials;\n this.ignoreUndefinedProperties = !!settings.ignoreUndefinedProperties;\n this.localCache = settings.localCache;\n\n if (settings.cacheSizeBytes === undefined) {\n this.cacheSizeBytes = LRU_DEFAULT_CACHE_SIZE_BYTES;\n } else {\n if (\n settings.cacheSizeBytes !== LRU_COLLECTION_DISABLED &&\n settings.cacheSizeBytes < LRU_MINIMUM_CACHE_SIZE_BYTES\n ) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `cacheSizeBytes must be at least ${LRU_MINIMUM_CACHE_SIZE_BYTES}`\n );\n } else {\n this.cacheSizeBytes = settings.cacheSizeBytes;\n }\n }\n\n validateIsNotUsedTogether(\n 'experimentalForceLongPolling',\n settings.experimentalForceLongPolling,\n 'experimentalAutoDetectLongPolling',\n settings.experimentalAutoDetectLongPolling\n );\n\n this.experimentalForceLongPolling = !!settings.experimentalForceLongPolling;\n\n if (this.experimentalForceLongPolling) {\n this.experimentalAutoDetectLongPolling = false;\n } else if (settings.experimentalAutoDetectLongPolling === undefined) {\n this.experimentalAutoDetectLongPolling = DEFAULT_AUTO_DETECT_LONG_POLLING;\n } else {\n // For backwards compatibility, coerce the value to boolean even though\n // the TypeScript compiler has narrowed the type to boolean already.\n // noinspection PointlessBooleanExpressionJS\n this.experimentalAutoDetectLongPolling =\n !!settings.experimentalAutoDetectLongPolling;\n }\n\n this.experimentalLongPollingOptions = cloneLongPollingOptions(\n settings.experimentalLongPollingOptions ?? {}\n );\n validateLongPollingOptions(this.experimentalLongPollingOptions);\n\n this.useFetchStreams = !!settings.useFetchStreams;\n }\n\n isEqual(other: FirestoreSettingsImpl): boolean {\n return (\n this.host === other.host &&\n this.ssl === other.ssl &&\n this.credentials === other.credentials &&\n this.cacheSizeBytes === other.cacheSizeBytes &&\n this.experimentalForceLongPolling ===\n other.experimentalForceLongPolling &&\n this.experimentalAutoDetectLongPolling ===\n other.experimentalAutoDetectLongPolling &&\n longPollingOptionsEqual(\n this.experimentalLongPollingOptions,\n other.experimentalLongPollingOptions\n ) &&\n this.ignoreUndefinedProperties === other.ignoreUndefinedProperties &&\n this.useFetchStreams === other.useFetchStreams\n );\n }\n}\n\nfunction validateLongPollingOptions(\n options: ExperimentalLongPollingOptions\n): void {\n if (options.timeoutSeconds !== undefined) {\n if (isNaN(options.timeoutSeconds)) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `invalid long polling timeout: ` +\n `${options.timeoutSeconds} (must not be NaN)`\n );\n }\n if (options.timeoutSeconds < MIN_LONG_POLLING_TIMEOUT_SECONDS) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `invalid long polling timeout: ${options.timeoutSeconds} ` +\n `(minimum allowed value is ${MIN_LONG_POLLING_TIMEOUT_SECONDS})`\n );\n }\n if (options.timeoutSeconds > MAX_LONG_POLLING_TIMEOUT_SECONDS) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `invalid long polling timeout: ${options.timeoutSeconds} ` +\n `(maximum allowed value is ${MAX_LONG_POLLING_TIMEOUT_SECONDS})`\n );\n }\n }\n}\n","/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ListenSequenceNumber, TargetId } from '../core/types';\nimport { SortedMap } from '../util/sorted_map';\n\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { TargetData } from './target_data';\n\n/**\n * Describes a map whose keys are active target ids. We do not care about the type of the\n * values.\n */\nexport type ActiveTargets = SortedMap;\n\nexport const GC_DID_NOT_RUN: LruResults = {\n didRun: false,\n sequenceNumbersCollected: 0,\n targetsRemoved: 0,\n documentsRemoved: 0\n};\n\nexport const LRU_COLLECTION_DISABLED = -1;\nexport const LRU_DEFAULT_CACHE_SIZE_BYTES = 40 * 1024 * 1024;\n\nexport class LruParams {\n private static readonly DEFAULT_COLLECTION_PERCENTILE = 10;\n private static readonly DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT = 1000;\n\n static withCacheSize(cacheSize: number): LruParams {\n return new LruParams(\n cacheSize,\n LruParams.DEFAULT_COLLECTION_PERCENTILE,\n LruParams.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT\n );\n }\n\n static readonly DEFAULT: LruParams = new LruParams(\n LRU_DEFAULT_CACHE_SIZE_BYTES,\n LruParams.DEFAULT_COLLECTION_PERCENTILE,\n LruParams.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT\n );\n\n static readonly DISABLED: LruParams = new LruParams(\n LRU_COLLECTION_DISABLED,\n 0,\n 0\n );\n\n constructor(\n // When we attempt to collect, we will only do so if the cache size is greater than this\n // threshold. Passing `COLLECTION_DISABLED` here will cause collection to always be skipped.\n readonly cacheSizeCollectionThreshold: number,\n // The percentage of sequence numbers that we will attempt to collect\n readonly percentileToCollect: number,\n // A cap on the total number of sequence numbers that will be collected. This prevents\n // us from collecting a huge number of sequence numbers if the cache has grown very large.\n readonly maximumSequenceNumbersToCollect: number\n ) {}\n}\n\nexport interface LruGarbageCollector {\n readonly params: LruParams;\n\n collect(\n txn: PersistenceTransaction,\n activeTargetIds: ActiveTargets\n ): PersistencePromise;\n\n /** Given a percentile of target to collect, returns the number of targets to collect. */\n calculateTargetCount(\n txn: PersistenceTransaction,\n percentile: number\n ): PersistencePromise;\n\n /** Returns the nth sequence number, counting in order from the smallest. */\n nthSequenceNumber(\n txn: PersistenceTransaction,\n n: number\n ): PersistencePromise;\n\n /**\n * Removes documents that have a sequence number equal to or less than the\n * upper bound and are not otherwise pinned.\n */\n removeOrphanedDocuments(\n txn: PersistenceTransaction,\n upperBound: ListenSequenceNumber\n ): PersistencePromise;\n\n getCacheSize(txn: PersistenceTransaction): PersistencePromise;\n\n /**\n * Removes targets with a sequence number equal to or less than the given\n * upper bound, and removes document associations with those targets.\n */\n removeTargets(\n txn: PersistenceTransaction,\n upperBound: ListenSequenceNumber,\n activeTargetIds: ActiveTargets\n ): PersistencePromise;\n}\n\n/**\n * Describes the results of a garbage collection run. `didRun` will be set to\n * `false` if collection was skipped (either it is disabled or the cache size\n * has not hit the threshold). If collection ran, the other fields will be\n * filled in with the details of the results.\n */\nexport interface LruResults {\n readonly didRun: boolean;\n readonly sequenceNumbersCollected: number;\n readonly targetsRemoved: number;\n readonly documentsRemoved: number;\n}\n\n/**\n * Persistence layers intending to use LRU Garbage collection should have\n * reference delegates that implement this interface. This interface defines the\n * operations that the LRU garbage collector needs from the persistence layer.\n */\nexport interface LruDelegate {\n readonly garbageCollector: LruGarbageCollector;\n\n /** Enumerates all the targets in the TargetCache. */\n forEachTarget(\n txn: PersistenceTransaction,\n f: (target: TargetData) => void\n ): PersistencePromise;\n\n getSequenceNumberCount(\n txn: PersistenceTransaction\n ): PersistencePromise;\n\n /**\n * Enumerates sequence numbers for documents not associated with a target.\n * Note that this may include duplicate sequence numbers.\n */\n forEachOrphanedDocumentSequenceNumber(\n txn: PersistenceTransaction,\n f: (sequenceNumber: ListenSequenceNumber) => void\n ): PersistencePromise;\n\n /**\n * Removes all targets that have a sequence number less than or equal to\n * `upperBound`, and are not present in the `activeTargetIds` set.\n *\n * @returns the number of targets removed.\n */\n removeTargets(\n txn: PersistenceTransaction,\n upperBound: ListenSequenceNumber,\n activeTargetIds: ActiveTargets\n ): PersistencePromise;\n\n /**\n * Removes all unreferenced documents from the cache that have a sequence\n * number less than or equal to the given `upperBound`.\n *\n * @returns the number of documents removed.\n */\n removeOrphanedDocuments(\n txn: PersistenceTransaction,\n upperBound: ListenSequenceNumber\n ): PersistencePromise;\n\n getCacheSize(txn: PersistenceTransaction): PersistencePromise;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport {\n _getProvider,\n _removeServiceInstance,\n FirebaseApp,\n getApp\n} from '@firebase/app';\nimport {\n createMockUserToken,\n deepEqual,\n EmulatorMockTokenOptions,\n getDefaultEmulatorHostnameAndPort,\n isCloudWorkstation,\n pingServer,\n updateEmulatorBanner\n} from '@firebase/util';\n\nimport {\n CredentialsProvider,\n EmulatorAuthCredentialsProvider,\n makeAuthCredentialsProvider,\n OAuthToken\n} from '../api/credentials';\nimport { User } from '../auth/user';\nimport { DatabaseId, DEFAULT_DATABASE_NAME } from '../core/database_info';\nimport { Code, FirestoreError } from '../util/error';\nimport { cast } from '../util/input_validation';\nimport { logWarn } from '../util/log';\n\nimport { FirestoreService, removeComponents } from './components';\nimport {\n DEFAULT_HOST,\n FirestoreSettingsImpl,\n PrivateSettings,\n FirestoreSettings\n} from './settings';\n\nexport { EmulatorMockTokenOptions } from '@firebase/util';\n\ndeclare module '@firebase/component' {\n interface NameServiceMapping {\n 'firestore/lite': Firestore;\n }\n}\n\n/**\n * The Cloud Firestore service interface.\n *\n * Do not call this constructor directly. Instead, use {@link (getFirestore:1)}.\n */\nexport class Firestore implements FirestoreService {\n /**\n * Whether it's a Firestore or Firestore Lite instance.\n */\n type: 'firestore-lite' | 'firestore' = 'firestore-lite';\n\n readonly _persistenceKey: string = '(lite)';\n\n private _settings = new FirestoreSettingsImpl({});\n private _settingsFrozen = false;\n private _emulatorOptions: {\n mockUserToken?: EmulatorMockTokenOptions | string;\n } = {};\n\n // A task that is assigned when the terminate() is invoked and resolved when\n // all components have shut down. Otherwise, Firestore is not terminated,\n // which can mean either the FirestoreClient is in the process of starting,\n // or restarting.\n private _terminateTask: Promise | 'notTerminated' = 'notTerminated';\n\n /** @hideconstructor */\n constructor(\n public _authCredentials: CredentialsProvider,\n public _appCheckCredentials: CredentialsProvider,\n readonly _databaseId: DatabaseId,\n readonly _app?: FirebaseApp\n ) {}\n\n /**\n * The {@link @firebase/app#FirebaseApp} associated with this `Firestore` service\n * instance.\n */\n get app(): FirebaseApp {\n if (!this._app) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n \"Firestore was not initialized using the Firebase SDK. 'app' is \" +\n 'not available'\n );\n }\n return this._app;\n }\n\n get _initialized(): boolean {\n return this._settingsFrozen;\n }\n\n get _terminated(): boolean {\n return this._terminateTask !== 'notTerminated';\n }\n\n _setSettings(settings: PrivateSettings): void {\n if (this._settingsFrozen) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'Firestore has already been started and its settings can no longer ' +\n 'be changed. You can only modify settings before calling any other ' +\n 'methods on a Firestore object.'\n );\n }\n this._settings = new FirestoreSettingsImpl(settings);\n this._emulatorOptions = settings.emulatorOptions || {};\n\n if (settings.credentials !== undefined) {\n this._authCredentials = makeAuthCredentialsProvider(settings.credentials);\n }\n }\n\n _getSettings(): FirestoreSettingsImpl {\n return this._settings;\n }\n\n _getEmulatorOptions(): { mockUserToken?: EmulatorMockTokenOptions | string } {\n return this._emulatorOptions;\n }\n\n _freezeSettings(): FirestoreSettingsImpl {\n this._settingsFrozen = true;\n return this._settings;\n }\n\n _delete(): Promise {\n // The `_terminateTask` must be assigned future that completes when\n // terminate is complete. The existence of this future puts SDK in state\n // that will not accept further API interaction.\n if (this._terminateTask === 'notTerminated') {\n this._terminateTask = this._terminate();\n }\n return this._terminateTask;\n }\n\n async _restart(): Promise {\n // The `_terminateTask` must equal 'notTerminated' after restart to\n // signal that client is in a state that accepts API calls.\n if (this._terminateTask === 'notTerminated') {\n await this._terminate();\n } else {\n this._terminateTask = 'notTerminated';\n }\n }\n\n /** Returns a JSON-serializable representation of this `Firestore` instance. */\n toJSON(): object {\n return {\n app: this._app,\n databaseId: this._databaseId,\n settings: this._settings\n };\n }\n\n /**\n * Terminates all components used by this client. Subclasses can override\n * this method to clean up their own dependencies, but must also call this\n * method.\n *\n * Only ever called once.\n */\n protected _terminate(): Promise {\n removeComponents(this);\n return Promise.resolve();\n }\n}\n\n/**\n * Initializes a new instance of Cloud Firestore with the provided settings.\n * Can only be called before any other functions, including\n * {@link (getFirestore:1)}. If the custom settings are empty, this function is\n * equivalent to calling {@link (getFirestore:1)}.\n *\n * @param app - The {@link @firebase/app#FirebaseApp} with which the `Firestore` instance will\n * be associated.\n * @param settings - A settings object to configure the `Firestore` instance.\n * @returns A newly initialized `Firestore` instance.\n */\nexport function initializeFirestore(\n app: FirebaseApp,\n settings: FirestoreSettings\n): Firestore;\n/**\n * Initializes a new instance of Cloud Firestore with the provided settings.\n * Can only be called before any other functions, including\n * {@link (getFirestore:1)}. If the custom settings are empty, this function is\n * equivalent to calling {@link (getFirestore:1)}.\n *\n * @param app - The {@link @firebase/app#FirebaseApp} with which the `Firestore` instance will\n * be associated.\n * @param settings - A settings object to configure the `Firestore` instance.\n * @param databaseId - The name of the database.\n * @returns A newly initialized `Firestore` instance.\n * @beta\n */\nexport function initializeFirestore(\n app: FirebaseApp,\n settings: FirestoreSettings,\n databaseId?: string\n): Firestore;\nexport function initializeFirestore(\n app: FirebaseApp,\n settings: FirestoreSettings,\n databaseId?: string\n): Firestore {\n if (!databaseId) {\n databaseId = DEFAULT_DATABASE_NAME;\n }\n const provider = _getProvider(app, 'firestore/lite');\n\n if (provider.isInitialized(databaseId)) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'Firestore can only be initialized once per app.'\n );\n }\n\n return provider.initialize({\n options: settings,\n instanceIdentifier: databaseId\n });\n}\n\n/**\n * Returns the existing default {@link Firestore} instance that is associated with the\n * default {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new\n * instance with default settings.\n *\n * @returns The {@link Firestore} instance of the provided app.\n */\nexport function getFirestore(): Firestore;\n/**\n * Returns the existing default {@link Firestore} instance that is associated with the\n * provided {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new\n * instance with default settings.\n *\n * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned {@link Firestore}\n * instance is associated with.\n * @returns The {@link Firestore} instance of the provided app.\n */\nexport function getFirestore(app: FirebaseApp): Firestore;\n/**\n * Returns the existing {@link Firestore} instance that is associated with the\n * default {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new\n * instance with default settings.\n *\n * @param databaseId - The name of the database.\n * @returns The {@link Firestore} instance of the provided app.\n * @beta\n */\nexport function getFirestore(databaseId: string): Firestore;\n/**\n * Returns the existing {@link Firestore} instance that is associated with the\n * provided {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new\n * instance with default settings.\n *\n * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned {@link Firestore}\n * instance is associated with.\n * @param databaseId - The name of the database.\n * @returns The {@link Firestore} instance of the provided app.\n * @beta\n */\nexport function getFirestore(app: FirebaseApp, databaseId: string): Firestore;\nexport function getFirestore(\n appOrDatabaseId?: FirebaseApp | string,\n optionalDatabaseId?: string\n): Firestore {\n const app: FirebaseApp =\n typeof appOrDatabaseId === 'object' ? appOrDatabaseId : getApp();\n const databaseId =\n typeof appOrDatabaseId === 'string'\n ? appOrDatabaseId\n : optionalDatabaseId || '(default)';\n const db = _getProvider(app, 'firestore/lite').getImmediate({\n identifier: databaseId\n }) as Firestore;\n if (!db._initialized) {\n const emulator = getDefaultEmulatorHostnameAndPort('firestore');\n if (emulator) {\n connectFirestoreEmulator(db, ...emulator);\n }\n }\n return db;\n}\n\n/**\n * Modify this instance to communicate with the Cloud Firestore emulator.\n *\n * Note: This must be called before this instance has been used to do any\n * operations.\n *\n * @param firestore - The `Firestore` instance to configure to connect to the\n * emulator.\n * @param host - the emulator host (ex: localhost).\n * @param port - the emulator port (ex: 9000).\n * @param options.mockUserToken - the mock auth token to use for unit testing\n * Security Rules.\n */\nexport function connectFirestoreEmulator(\n firestore: Firestore,\n host: string,\n port: number,\n options: {\n mockUserToken?: EmulatorMockTokenOptions | string;\n } = {}\n): void {\n firestore = cast(firestore, Firestore);\n const useSsl = isCloudWorkstation(host);\n const settings = firestore._getSettings();\n const existingConfig = {\n ...settings,\n emulatorOptions: firestore._getEmulatorOptions()\n };\n const newHostSetting = `${host}:${port}`;\n if (useSsl) {\n void pingServer(`https://${newHostSetting}`);\n updateEmulatorBanner('Firestore', true);\n }\n if (settings.host !== DEFAULT_HOST && settings.host !== newHostSetting) {\n logWarn(\n 'Host has been set in both settings() and connectFirestoreEmulator(), emulator host ' +\n 'will be used.'\n );\n }\n const newConfig = {\n ...settings,\n host: newHostSetting,\n ssl: useSsl,\n emulatorOptions: options\n };\n // No-op if the new configuration matches the current configuration. This supports SSR\n // enviornments which might call `connectFirestoreEmulator` multiple times as a standard practice.\n if (deepEqual(newConfig, existingConfig)) {\n return;\n }\n\n firestore._setSettings(newConfig);\n\n if (options.mockUserToken) {\n let token: string;\n let user: User;\n if (typeof options.mockUserToken === 'string') {\n token = options.mockUserToken;\n user = User.MOCK_USER;\n } else {\n // Let createMockUserToken validate first (catches common mistakes like\n // invalid field \"uid\" and missing field \"sub\" / \"user_id\".)\n token = createMockUserToken(\n options.mockUserToken,\n firestore._app?.options.projectId\n );\n const uid = options.mockUserToken.sub || options.mockUserToken.user_id;\n if (!uid) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n \"mockUserToken must contain 'sub' or 'user_id' field!\"\n );\n }\n user = new User(uid);\n }\n\n firestore._authCredentials = new EmulatorAuthCredentialsProvider(\n new OAuthToken(token, user)\n );\n }\n}\n\n/**\n * Terminates the provided `Firestore` instance.\n *\n * After calling `terminate()` only the `clearIndexedDbPersistence()` functions\n * may be used. Any other function will throw a `FirestoreError`. Termination\n * does not cancel any pending writes, and any promises that are awaiting a\n * response from the server will not be resolved.\n *\n * To restart after termination, create a new instance of `Firestore` with\n * {@link (getFirestore:1)}.\n *\n * Note: Under normal circumstances, calling `terminate()` is not required. This\n * function is useful only when you want to force this instance to release all of\n * its resources or in combination with {@link clearIndexedDbPersistence} to\n * ensure that all local state is destroyed between test runs.\n *\n * @param firestore - The `Firestore` instance to terminate.\n * @returns A `Promise` that is resolved when the instance has been successfully\n * terminated.\n */\nexport function terminate(firestore: Firestore): Promise {\n firestore = cast(firestore, Firestore);\n _removeServiceInstance(firestore.app, 'firestore/lite');\n return firestore._delete();\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { AggregateType } from '../core/aggregate';\nimport { FieldPath as InternalFieldPath } from '../model/path';\nimport { ApiClientObjectMap, Value } from '../protos/firestore_proto_api';\n\nimport { average, count, sum } from './aggregate';\nimport { DocumentData, Query } from './reference';\nimport { AbstractUserDataWriter } from './user_data_writer';\n\nexport { AggregateType };\n\n/**\n * Represents an aggregation that can be performed by Firestore.\n */\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport class AggregateField {\n /** A type string to uniquely identify instances of this class. */\n readonly type = 'AggregateField';\n\n /** Indicates the aggregation operation of this AggregateField. */\n readonly aggregateType: AggregateType;\n\n /**\n * Create a new AggregateField\n * @param aggregateType Specifies the type of aggregation operation to perform.\n * @param _internalFieldPath Optionally specifies the field that is aggregated.\n * @internal\n */\n constructor(\n aggregateType: AggregateType = 'count',\n readonly _internalFieldPath?: InternalFieldPath\n ) {\n this.aggregateType = aggregateType;\n }\n}\n\n/**\n * The union of all `AggregateField` types that are supported by Firestore.\n */\nexport type AggregateFieldType =\n | ReturnType\n | ReturnType\n | ReturnType;\n\n/**\n * Specifies a set of aggregations and their aliases.\n */\nexport interface AggregateSpec {\n [field: string]: AggregateFieldType;\n}\n\n/**\n * A type whose keys are taken from an `AggregateSpec`, and whose values are the\n * result of the aggregation performed by the corresponding `AggregateField`\n * from the input `AggregateSpec`.\n */\nexport type AggregateSpecData = {\n [P in keyof T]: T[P] extends AggregateField ? U : never;\n};\n\n/**\n * The results of executing an aggregation query.\n */\nexport class AggregateQuerySnapshot<\n AggregateSpecType extends AggregateSpec,\n AppModelType = DocumentData,\n DbModelType extends DocumentData = DocumentData\n> {\n /** A type string to uniquely identify instances of this class. */\n readonly type = 'AggregateQuerySnapshot';\n\n /**\n * The underlying query over which the aggregations recorded in this\n * `AggregateQuerySnapshot` were performed.\n */\n readonly query: Query;\n\n /** @hideconstructor */\n constructor(\n query: Query,\n private readonly _userDataWriter: AbstractUserDataWriter,\n private readonly _data: ApiClientObjectMap\n ) {\n this.query = query;\n }\n\n /**\n * Returns the results of the aggregations performed over the underlying\n * query.\n *\n * The keys of the returned object will be the same as those of the\n * `AggregateSpec` object specified to the aggregation method, and the values\n * will be the corresponding aggregation result.\n *\n * @returns The results of the aggregations performed over the underlying\n * query.\n */\n data(): AggregateSpecData {\n return this._userDataWriter.convertObjectMap(\n this._data\n ) as AggregateSpecData;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getModularInstance } from '@firebase/util';\n\nimport {\n newQueryForCollectionGroup,\n newQueryForPath,\n Query as InternalQuery,\n queryEquals\n} from '../core/query';\nimport { DocumentKey } from '../model/document_key';\nimport { ResourcePath } from '../model/path';\nimport { Code, FirestoreError } from '../util/error';\nimport {\n cast,\n validateCollectionPath,\n validateDocumentPath,\n validateNonEmptyArgument\n} from '../util/input_validation';\n// API extractor fails importing property unless we also explicitly import Property.\n// eslint-disable-next-line @typescript-eslint/no-unused-vars, unused-imports/no-unused-imports-ts\nimport { Property, property, validateJSON } from '../util/json_validation';\nimport { AutoId } from '../util/misc';\n\nimport { Firestore } from './database';\nimport { FieldPath } from './field_path';\nimport { FieldValue } from './field_value';\nimport { FirestoreDataConverter } from './snapshot';\nimport { NestedUpdateFields, Primitive } from './types';\n\n/**\n * Document data (for use with {@link @firebase/firestore/lite#(setDoc:1)}) consists of fields mapped to\n * values.\n */\nexport interface DocumentData {\n /** A mapping between a field and its value. */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [field: string]: any;\n}\n\n/**\n * Similar to TypeScript's `Partial`, but allows nested fields to be\n * omitted and FieldValues to be passed in as property values.\n */\nexport type PartialWithFieldValue =\n | Partial\n | (T extends Primitive\n ? T\n : T extends {}\n ? { [K in keyof T]?: PartialWithFieldValue | FieldValue }\n : never);\n\n/**\n * Allows FieldValues to be passed in as a property value while maintaining\n * type safety.\n */\nexport type WithFieldValue =\n | T\n | (T extends Primitive\n ? T\n : T extends {}\n ? { [K in keyof T]: WithFieldValue | FieldValue }\n : never);\n\n/**\n * Update data (for use with {@link (updateDoc:1)}) that consists of field paths\n * (e.g. 'foo' or 'foo.baz') mapped to values. Fields that contain dots\n * reference nested fields within the document. FieldValues can be passed in\n * as property values.\n */\nexport type UpdateData = T extends Primitive\n ? T\n : T extends {}\n ? { [K in keyof T]?: UpdateData | FieldValue } & NestedUpdateFields\n : Partial;\n/**\n * An options object that configures the behavior of {@link @firebase/firestore/lite#(setDoc:1)}, {@link\n * @firebase/firestore/lite#(WriteBatch.set:1)} and {@link @firebase/firestore/lite#(Transaction.set:1)} calls. These calls can be\n * configured to perform granular merges instead of overwriting the target\n * documents in their entirety by providing a `SetOptions` with `merge: true`.\n *\n * @param merge - Changes the behavior of a `setDoc()` call to only replace the\n * values specified in its data argument. Fields omitted from the `setDoc()`\n * call remain untouched. If your input sets any field to an empty map, all\n * nested fields are overwritten.\n * @param mergeFields - Changes the behavior of `setDoc()` calls to only replace\n * the specified field paths. Any field path that is not specified is ignored\n * and remains untouched. If your input sets any field to an empty map, all\n * nested fields are overwritten.\n */\nexport type SetOptions =\n | {\n readonly merge?: boolean;\n }\n | {\n readonly mergeFields?: Array;\n };\n\n/**\n * A `Query` refers to a query which you can read or listen to. You can also\n * construct refined `Query` objects by adding filters and ordering.\n */\nexport class Query<\n AppModelType = DocumentData,\n DbModelType extends DocumentData = DocumentData\n> {\n /** The type of this Firestore reference. */\n readonly type: 'query' | 'collection' = 'query';\n\n /**\n * The `Firestore` instance for the Firestore database (useful for performing\n * transactions, etc.).\n */\n readonly firestore: Firestore;\n\n // This is the lite version of the Query class in the main SDK.\n\n /** @hideconstructor protected */\n constructor(\n firestore: Firestore,\n /**\n * If provided, the `FirestoreDataConverter` associated with this instance.\n */\n readonly converter: FirestoreDataConverter<\n AppModelType,\n DbModelType\n > | null,\n readonly _query: InternalQuery\n ) {\n this.firestore = firestore;\n }\n\n /**\n * Removes the current converter.\n *\n * @param converter - `null` removes the current converter.\n * @returns A `Query` that does not use a\n * converter.\n */\n withConverter(converter: null): Query;\n /**\n * Applies a custom data converter to this query, allowing you to use your own\n * custom model objects with Firestore. When you call {@link getDocs} with\n * the returned query, the provided converter will convert between Firestore\n * data of type `NewDbModelType` and your custom type `NewAppModelType`.\n *\n * @param converter - Converts objects to and from Firestore.\n * @returns A `Query` that uses the provided converter.\n */\n withConverter<\n NewAppModelType,\n NewDbModelType extends DocumentData = DocumentData\n >(\n converter: FirestoreDataConverter\n ): Query;\n withConverter<\n NewAppModelType,\n NewDbModelType extends DocumentData = DocumentData\n >(\n converter: FirestoreDataConverter | null\n ): Query {\n return new Query(\n this.firestore,\n converter,\n this._query\n );\n }\n}\n\n/**\n * A `DocumentReference` refers to a document location in a Firestore database\n * and can be used to write, read, or listen to the location. The document at\n * the referenced location may or may not exist.\n */\nexport class DocumentReference<\n AppModelType = DocumentData,\n DbModelType extends DocumentData = DocumentData\n> {\n /** The type of this Firestore reference. */\n readonly type = 'document';\n\n /**\n * The {@link Firestore} instance the document is in.\n * This is useful for performing transactions, for example.\n */\n readonly firestore: Firestore;\n\n /** @hideconstructor */\n constructor(\n firestore: Firestore,\n /**\n * If provided, the `FirestoreDataConverter` associated with this instance.\n */\n readonly converter: FirestoreDataConverter<\n AppModelType,\n DbModelType\n > | null,\n readonly _key: DocumentKey\n ) {\n this.firestore = firestore;\n }\n\n get _path(): ResourcePath {\n return this._key.path;\n }\n\n /**\n * The document's identifier within its collection.\n */\n get id(): string {\n return this._key.path.lastSegment();\n }\n\n /**\n * A string representing the path of the referenced document (relative\n * to the root of the database).\n */\n get path(): string {\n return this._key.path.canonicalString();\n }\n\n /**\n * The collection this `DocumentReference` belongs to.\n */\n get parent(): CollectionReference {\n return new CollectionReference(\n this.firestore,\n this.converter,\n this._key.path.popLast()\n );\n }\n\n /**\n * Applies a custom data converter to this `DocumentReference`, allowing you\n * to use your own custom model objects with Firestore. When you call {@link\n * @firebase/firestore/lite#(setDoc:1)}, {@link @firebase/firestore/lite#getDoc}, etc. with the returned `DocumentReference`\n * instance, the provided converter will convert between Firestore data of\n * type `NewDbModelType` and your custom type `NewAppModelType`.\n *\n * @param converter - Converts objects to and from Firestore.\n * @returns A `DocumentReference` that uses the provided converter.\n */\n withConverter<\n NewAppModelType,\n NewDbModelType extends DocumentData = DocumentData\n >(\n converter: FirestoreDataConverter\n ): DocumentReference;\n /**\n * Removes the current converter.\n *\n * @param converter - `null` removes the current converter.\n * @returns A `DocumentReference` that does not\n * use a converter.\n */\n withConverter(converter: null): DocumentReference;\n withConverter<\n NewAppModelType,\n NewDbModelType extends DocumentData = DocumentData\n >(\n converter: FirestoreDataConverter | null\n ): DocumentReference {\n return new DocumentReference(\n this.firestore,\n converter,\n this._key\n );\n }\n\n static _jsonSchemaVersion: string = 'firestore/documentReference/1.0';\n static _jsonSchema = {\n type: property('string', DocumentReference._jsonSchemaVersion),\n referencePath: property('string')\n };\n\n /**\n * Returns a JSON-serializable representation of this `DocumentReference` instance.\n *\n * @returns a JSON representation of this object.\n */\n toJSON(): object {\n return {\n type: DocumentReference._jsonSchemaVersion,\n referencePath: this._key.toString()\n };\n }\n\n /**\n * Builds a `DocumentReference` instance from a JSON object created by\n * {@link DocumentReference.toJSON}.\n *\n * @param firestore - The {@link Firestore} instance the snapshot should be loaded for.\n * @param json a JSON object represention of a `DocumentReference` instance\n * @returns an instance of {@link DocumentReference} if the JSON object could be parsed. Throws a\n * {@link FirestoreError} if an error occurs.\n */\n static fromJSON(firestore: Firestore, json: object): DocumentReference;\n /**\n * Builds a `DocumentReference` instance from a JSON object created by\n * {@link DocumentReference.toJSON}.\n *\n * @param firestore - The {@link Firestore} instance the snapshot should be loaded for.\n * @param json a JSON object represention of a `DocumentReference` instance\n * @param converter - Converts objects to and from Firestore.\n * @returns an instance of {@link DocumentReference} if the JSON object could be parsed. Throws a\n * {@link FirestoreError} if an error occurs.\n */\n static fromJSON<\n NewAppModelType = DocumentData,\n NewDbModelType extends DocumentData = DocumentData\n >(\n firestore: Firestore,\n json: object,\n converter: FirestoreDataConverter\n ): DocumentReference;\n static fromJSON<\n NewAppModelType = DocumentData,\n NewDbModelType extends DocumentData = DocumentData\n >(\n firestore: Firestore,\n json: object,\n converter?: FirestoreDataConverter\n ): DocumentReference {\n if (validateJSON(json, DocumentReference._jsonSchema)) {\n return new DocumentReference(\n firestore,\n converter ? converter : null,\n new DocumentKey(ResourcePath.fromString(json.referencePath))\n );\n }\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Unexpected error creating Bytes from JSON.'\n );\n }\n}\n\n/**\n * A `CollectionReference` object can be used for adding documents, getting\n * document references, and querying for documents (using {@link (query:1)}).\n */\nexport class CollectionReference<\n AppModelType = DocumentData,\n DbModelType extends DocumentData = DocumentData\n> extends Query {\n /** The type of this Firestore reference. */\n readonly type = 'collection';\n\n /** @hideconstructor */\n constructor(\n firestore: Firestore,\n converter: FirestoreDataConverter | null,\n readonly _path: ResourcePath\n ) {\n super(firestore, converter, newQueryForPath(_path));\n }\n\n /** The collection's identifier. */\n get id(): string {\n return this._query.path.lastSegment();\n }\n\n /**\n * A string representing the path of the referenced collection (relative\n * to the root of the database).\n */\n get path(): string {\n return this._query.path.canonicalString();\n }\n\n /**\n * A reference to the containing `DocumentReference` if this is a\n * subcollection. If this isn't a subcollection, the reference is null.\n */\n get parent(): DocumentReference | null {\n const parentPath = this._path.popLast();\n if (parentPath.isEmpty()) {\n return null;\n } else {\n return new DocumentReference(\n this.firestore,\n /* converter= */ null,\n new DocumentKey(parentPath)\n );\n }\n }\n\n /**\n * Applies a custom data converter to this `CollectionReference`, allowing you\n * to use your own custom model objects with Firestore. When you call {@link\n * addDoc} with the returned `CollectionReference` instance, the provided\n * converter will convert between Firestore data of type `NewDbModelType` and\n * your custom type `NewAppModelType`.\n *\n * @param converter - Converts objects to and from Firestore.\n * @returns A `CollectionReference` that uses the provided converter.\n */\n withConverter<\n NewAppModelType,\n NewDbModelType extends DocumentData = DocumentData\n >(\n converter: FirestoreDataConverter\n ): CollectionReference;\n /**\n * Removes the current converter.\n *\n * @param converter - `null` removes the current converter.\n * @returns A `CollectionReference` that does not\n * use a converter.\n */\n withConverter(\n converter: null\n ): CollectionReference;\n withConverter<\n NewAppModelType,\n NewDbModelType extends DocumentData = DocumentData\n >(\n converter: FirestoreDataConverter | null\n ): CollectionReference {\n return new CollectionReference(\n this.firestore,\n converter,\n this._path\n );\n }\n}\n\n/**\n * Gets a `CollectionReference` instance that refers to the collection at\n * the specified absolute path.\n *\n * @param firestore - A reference to the root `Firestore` instance.\n * @param path - A slash-separated path to a collection.\n * @param pathSegments - Additional path segments to apply relative to the first\n * argument.\n * @throws If the final path has an even number of segments and does not point\n * to a collection.\n * @returns The `CollectionReference` instance.\n */\nexport function collection(\n firestore: Firestore,\n path: string,\n ...pathSegments: string[]\n): CollectionReference;\n/**\n * Gets a `CollectionReference` instance that refers to a subcollection of\n * `reference` at the specified relative path.\n *\n * @param reference - A reference to a collection.\n * @param path - A slash-separated path to a collection.\n * @param pathSegments - Additional path segments to apply relative to the first\n * argument.\n * @throws If the final path has an even number of segments and does not point\n * to a collection.\n * @returns The `CollectionReference` instance.\n */\nexport function collection(\n reference: CollectionReference,\n path: string,\n ...pathSegments: string[]\n): CollectionReference;\n/**\n * Gets a `CollectionReference` instance that refers to a subcollection of\n * `reference` at the specified relative path.\n *\n * @param reference - A reference to a Firestore document.\n * @param path - A slash-separated path to a collection.\n * @param pathSegments - Additional path segments that will be applied relative\n * to the first argument.\n * @throws If the final path has an even number of segments and does not point\n * to a collection.\n * @returns The `CollectionReference` instance.\n */\nexport function collection(\n reference: DocumentReference,\n path: string,\n ...pathSegments: string[]\n): CollectionReference;\nexport function collection(\n parent:\n | Firestore\n | DocumentReference\n | CollectionReference,\n path: string,\n ...pathSegments: string[]\n): CollectionReference {\n parent = getModularInstance(parent);\n\n validateNonEmptyArgument('collection', 'path', path);\n if (parent instanceof Firestore) {\n const absolutePath = ResourcePath.fromString(path, ...pathSegments);\n validateCollectionPath(absolutePath);\n return new CollectionReference(parent, /* converter= */ null, absolutePath);\n } else {\n if (\n !(parent instanceof DocumentReference) &&\n !(parent instanceof CollectionReference)\n ) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Expected first argument to collection() to be a CollectionReference, ' +\n 'a DocumentReference or FirebaseFirestore'\n );\n }\n const absolutePath = parent._path.child(\n ResourcePath.fromString(path, ...pathSegments)\n );\n validateCollectionPath(absolutePath);\n return new CollectionReference(\n parent.firestore,\n /* converter= */ null,\n absolutePath\n );\n }\n}\n\n// TODO(firestorelite): Consider using ErrorFactory -\n// https://github.com/firebase/firebase-js-sdk/blob/0131e1f/packages/util/src/errors.ts#L106\n\n/**\n * Creates and returns a new `Query` instance that includes all documents in the\n * database that are contained in a collection or subcollection with the\n * given `collectionId`.\n *\n * @param firestore - A reference to the root `Firestore` instance.\n * @param collectionId - Identifies the collections to query over. Every\n * collection or subcollection with this ID as the last segment of its path\n * will be included. Cannot contain a slash.\n * @returns The created `Query`.\n */\nexport function collectionGroup(\n firestore: Firestore,\n collectionId: string\n): Query {\n firestore = cast(firestore, Firestore);\n\n validateNonEmptyArgument('collectionGroup', 'collection id', collectionId);\n if (collectionId.indexOf('/') >= 0) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid collection ID '${collectionId}' passed to function ` +\n `collectionGroup(). Collection IDs must not contain '/'.`\n );\n }\n\n return new Query(\n firestore,\n /* converter= */ null,\n newQueryForCollectionGroup(collectionId)\n );\n}\n\n/**\n * Gets a `DocumentReference` instance that refers to the document at the\n * specified absolute path.\n *\n * @param firestore - A reference to the root `Firestore` instance.\n * @param path - A slash-separated path to a document.\n * @param pathSegments - Additional path segments that will be applied relative\n * to the first argument.\n * @throws If the final path has an odd number of segments and does not point to\n * a document.\n * @returns The `DocumentReference` instance.\n */\nexport function doc(\n firestore: Firestore,\n path: string,\n ...pathSegments: string[]\n): DocumentReference;\n/**\n * Gets a `DocumentReference` instance that refers to a document within\n * `reference` at the specified relative path. If no path is specified, an\n * automatically-generated unique ID will be used for the returned\n * `DocumentReference`.\n *\n * @param reference - A reference to a collection.\n * @param path - A slash-separated path to a document. Has to be omitted to use\n * auto-generated IDs.\n * @param pathSegments - Additional path segments that will be applied relative\n * to the first argument.\n * @throws If the final path has an odd number of segments and does not point to\n * a document.\n * @returns The `DocumentReference` instance.\n */\nexport function doc(\n reference: CollectionReference,\n path?: string,\n ...pathSegments: string[]\n): DocumentReference;\n/**\n * Gets a `DocumentReference` instance that refers to a document within\n * `reference` at the specified relative path.\n *\n * @param reference - A reference to a Firestore document.\n * @param path - A slash-separated path to a document.\n * @param pathSegments - Additional path segments that will be applied relative\n * to the first argument.\n * @throws If the final path has an odd number of segments and does not point to\n * a document.\n * @returns The `DocumentReference` instance.\n */\nexport function doc(\n reference: DocumentReference,\n path: string,\n ...pathSegments: string[]\n): DocumentReference;\nexport function doc(\n parent:\n | Firestore\n | CollectionReference\n | DocumentReference,\n path?: string,\n ...pathSegments: string[]\n): DocumentReference {\n parent = getModularInstance(parent);\n\n // We allow omission of 'pathString' but explicitly prohibit passing in both\n // 'undefined' and 'null'.\n if (arguments.length === 1) {\n path = AutoId.newId();\n }\n validateNonEmptyArgument('doc', 'path', path);\n\n if (parent instanceof Firestore) {\n const absolutePath = ResourcePath.fromString(path, ...pathSegments);\n validateDocumentPath(absolutePath);\n return new DocumentReference(\n parent,\n /* converter= */ null,\n new DocumentKey(absolutePath)\n );\n } else {\n if (\n !(parent instanceof DocumentReference) &&\n !(parent instanceof CollectionReference)\n ) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Expected first argument to collection() to be a CollectionReference, ' +\n 'a DocumentReference or FirebaseFirestore'\n );\n }\n const absolutePath = parent._path.child(\n ResourcePath.fromString(path, ...pathSegments)\n );\n validateDocumentPath(absolutePath);\n return new DocumentReference(\n parent.firestore,\n parent instanceof CollectionReference ? parent.converter : null,\n new DocumentKey(absolutePath)\n );\n }\n}\n\n/**\n * Returns true if the provided references are equal.\n *\n * @param left - A reference to compare.\n * @param right - A reference to compare.\n * @returns true if the references point to the same location in the same\n * Firestore database.\n */\nexport function refEqual(\n left:\n | DocumentReference\n | CollectionReference,\n right:\n | DocumentReference\n | CollectionReference\n): boolean {\n left = getModularInstance(left);\n right = getModularInstance(right);\n\n if (\n (left instanceof DocumentReference ||\n left instanceof CollectionReference) &&\n (right instanceof DocumentReference || right instanceof CollectionReference)\n ) {\n return (\n left.firestore === right.firestore &&\n left.path === right.path &&\n left.converter === right.converter\n );\n }\n return false;\n}\n\n/**\n * Returns true if the provided queries point to the same collection and apply\n * the same constraints.\n *\n * @param left - A `Query` to compare.\n * @param right - A `Query` to compare.\n * @returns true if the references point to the same location in the same\n * Firestore database.\n */\nexport function queryEqual(\n left: Query,\n right: Query\n): boolean {\n left = getModularInstance(left);\n right = getModularInstance(right);\n\n if (left instanceof Query && right instanceof Query) {\n return (\n left.firestore === right.firestore &&\n queryEquals(left._query, right._query) &&\n left.converter === right.converter\n );\n }\n return false;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ByteString } from '../util/byte_string';\nimport { Code, FirestoreError } from '../util/error';\n// API extractor fails importing property unless we also explicitly import Property.\n// eslint-disable-next-line @typescript-eslint/no-unused-vars, unused-imports/no-unused-imports-ts\nimport { Property, property, validateJSON } from '../util/json_validation';\n\n/**\n * An immutable object representing an array of bytes.\n */\nexport class Bytes {\n _byteString: ByteString;\n\n /** @hideconstructor */\n constructor(byteString: ByteString) {\n this._byteString = byteString;\n }\n\n /**\n * Creates a new `Bytes` object from the given Base64 string, converting it to\n * bytes.\n *\n * @param base64 - The Base64 string used to create the `Bytes` object.\n */\n static fromBase64String(base64: string): Bytes {\n try {\n return new Bytes(ByteString.fromBase64String(base64));\n } catch (e) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Failed to construct data from Base64 string: ' + e\n );\n }\n }\n\n /**\n * Creates a new `Bytes` object from the given Uint8Array.\n *\n * @param array - The Uint8Array used to create the `Bytes` object.\n */\n static fromUint8Array(array: Uint8Array): Bytes {\n return new Bytes(ByteString.fromUint8Array(array));\n }\n\n /**\n * Returns the underlying bytes as a Base64-encoded string.\n *\n * @returns The Base64-encoded string created from the `Bytes` object.\n */\n toBase64(): string {\n return this._byteString.toBase64();\n }\n\n /**\n * Returns the underlying bytes in a new `Uint8Array`.\n *\n * @returns The Uint8Array created from the `Bytes` object.\n */\n toUint8Array(): Uint8Array {\n return this._byteString.toUint8Array();\n }\n\n /**\n * Returns a string representation of the `Bytes` object.\n *\n * @returns A string representation of the `Bytes` object.\n */\n toString(): string {\n return 'Bytes(base64: ' + this.toBase64() + ')';\n }\n\n /**\n * Returns true if this `Bytes` object is equal to the provided one.\n *\n * @param other - The `Bytes` object to compare against.\n * @returns true if this `Bytes` object is equal to the provided one.\n */\n isEqual(other: Bytes): boolean {\n return this._byteString.isEqual(other._byteString);\n }\n\n static _jsonSchemaVersion: string = 'firestore/bytes/1.0';\n static _jsonSchema = {\n type: property('string', Bytes._jsonSchemaVersion),\n bytes: property('string')\n };\n\n /**\n * Returns a JSON-serializable representation of this `Bytes` instance.\n *\n * @returns a JSON representation of this object.\n */\n toJSON(): object {\n return {\n type: Bytes._jsonSchemaVersion,\n bytes: this.toBase64()\n };\n }\n\n /**\n * Builds a `Bytes` instance from a JSON object created by {@link Bytes.toJSON}.\n *\n * @param json a JSON object represention of a `Bytes` instance\n * @returns an instance of {@link Bytes} if the JSON object could be parsed. Throws a\n * {@link FirestoreError} if an error occurs.\n */\n static fromJSON(json: object): Bytes {\n if (validateJSON(json, Bytes._jsonSchema)) {\n return Bytes.fromBase64String(json.bytes);\n }\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Unexpected error creating Bytes from JSON.'\n );\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n DOCUMENT_KEY_NAME,\n FieldPath as InternalFieldPath\n} from '../model/path';\nimport { Code, FirestoreError } from '../util/error';\n\n/**\n * A `FieldPath` refers to a field in a document. The path may consist of a\n * single field name (referring to a top-level field in the document), or a\n * list of field names (referring to a nested field in the document).\n *\n * Create a `FieldPath` by providing field names. If more than one field\n * name is provided, the path will point to a nested field in a document.\n */\nexport class FieldPath {\n /** Internal representation of a Firestore field path. */\n readonly _internalPath: InternalFieldPath;\n\n /**\n * Creates a `FieldPath` from the provided field names. If more than one field\n * name is provided, the path will point to a nested field in a document.\n *\n * @param fieldNames - A list of field names.\n */\n constructor(...fieldNames: string[]) {\n for (let i = 0; i < fieldNames.length; ++i) {\n if (fieldNames[i].length === 0) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid field name at argument $(i + 1). ` +\n 'Field names must not be empty.'\n );\n }\n }\n\n this._internalPath = new InternalFieldPath(fieldNames);\n }\n\n /**\n * Returns true if this `FieldPath` is equal to the provided one.\n *\n * @param other - The `FieldPath` to compare against.\n * @returns true if this `FieldPath` is equal to the provided one.\n */\n isEqual(other: FieldPath): boolean {\n return this._internalPath.isEqual(other._internalPath);\n }\n}\n\n/**\n * Returns a special sentinel `FieldPath` to refer to the ID of a document.\n * It can be used in queries to sort or filter by the document ID.\n */\nexport function documentId(): FieldPath {\n return new FieldPath(DOCUMENT_KEY_NAME);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ParseContext } from '../api/parse_context';\nimport { FieldTransform } from '../model/mutation';\n\n/**\n * Sentinel values that can be used when writing document fields with `set()`\n * or `update()`.\n */\nexport abstract class FieldValue {\n /**\n * @param _methodName - The public API endpoint that returns this class.\n * @hideconstructor\n */\n constructor(public _methodName: string) {}\n\n /** Compares `FieldValue`s for equality. */\n abstract isEqual(other: FieldValue): boolean;\n abstract _toFieldTransform(context: ParseContext): FieldTransform | null;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Code, FirestoreError } from '../util/error';\n// API extractor fails importing 'property' unless we also explicitly import 'Property'.\n// eslint-disable-next-line @typescript-eslint/no-unused-vars, unused-imports/no-unused-imports-ts\nimport { Property, property, validateJSON } from '../util/json_validation';\nimport { primitiveComparator } from '../util/misc';\n\n/**\n * An immutable object representing a geographic location in Firestore. The\n * location is represented as latitude/longitude pair.\n *\n * Latitude values are in the range of [-90, 90].\n * Longitude values are in the range of [-180, 180].\n */\nexport class GeoPoint {\n // Prefix with underscore to signal this is a private variable in JS and\n // prevent it showing up for autocompletion when typing latitude or longitude.\n private _lat: number;\n private _long: number;\n\n /**\n * Creates a new immutable `GeoPoint` object with the provided latitude and\n * longitude values.\n * @param latitude - The latitude as number between -90 and 90.\n * @param longitude - The longitude as number between -180 and 180.\n */\n constructor(latitude: number, longitude: number) {\n if (!isFinite(latitude) || latitude < -90 || latitude > 90) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Latitude must be a number between -90 and 90, but was: ' + latitude\n );\n }\n if (!isFinite(longitude) || longitude < -180 || longitude > 180) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Longitude must be a number between -180 and 180, but was: ' + longitude\n );\n }\n\n this._lat = latitude;\n this._long = longitude;\n }\n\n /**\n * The latitude of this `GeoPoint` instance.\n */\n get latitude(): number {\n return this._lat;\n }\n\n /**\n * The longitude of this `GeoPoint` instance.\n */\n get longitude(): number {\n return this._long;\n }\n\n /**\n * Returns true if this `GeoPoint` is equal to the provided one.\n *\n * @param other - The `GeoPoint` to compare against.\n * @returns true if this `GeoPoint` is equal to the provided one.\n */\n isEqual(other: GeoPoint): boolean {\n return this._lat === other._lat && this._long === other._long;\n }\n\n /**\n * Actually private to JS consumers of our API, so this function is prefixed\n * with an underscore.\n */\n _compareTo(other: GeoPoint): number {\n return (\n primitiveComparator(this._lat, other._lat) ||\n primitiveComparator(this._long, other._long)\n );\n }\n\n static _jsonSchemaVersion: string = 'firestore/geoPoint/1.0';\n static _jsonSchema = {\n type: property('string', GeoPoint._jsonSchemaVersion),\n latitude: property('number'),\n longitude: property('number')\n };\n\n /**\n * Returns a JSON-serializable representation of this `GeoPoint` instance.\n *\n * @returns a JSON representation of this object.\n */\n toJSON(): { latitude: number; longitude: number; type: string } {\n return {\n latitude: this._lat,\n longitude: this._long,\n type: GeoPoint._jsonSchemaVersion\n };\n }\n\n /**\n * Builds a `GeoPoint` instance from a JSON object created by {@link GeoPoint.toJSON}.\n *\n * @param json a JSON object represention of a `GeoPoint` instance\n * @returns an instance of {@link GeoPoint} if the JSON object could be parsed. Throws a\n * {@link FirestoreError} if an error occurs.\n */\n static fromJSON(json: object): GeoPoint {\n if (validateJSON(json, GeoPoint._jsonSchema)) {\n return new GeoPoint(json.latitude, json.longitude);\n }\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Unexpected error creating GeoPoint from JSON.'\n );\n }\n}\n","/**\n * @license\n * Copyright 2024 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isPrimitiveArrayEqual } from '../util/array';\nimport { Code, FirestoreError } from '../util/error';\n// API extractor fails importing 'property' unless we also explicitly import 'Property'.\n// eslint-disable-next-line @typescript-eslint/no-unused-vars, unused-imports/no-unused-imports-ts\nimport { Property, property, validateJSON } from '../util/json_validation';\n\n/**\n * Represents a vector type in Firestore documents.\n * Create an instance with {@link vector}.\n *\n * @class VectorValue\n */\nexport class VectorValue {\n private readonly _values: number[];\n\n /**\n * @private\n * @internal\n */\n constructor(values: number[] | undefined) {\n // Making a copy of the parameter.\n this._values = (values || []).map(n => n);\n }\n\n /**\n * Returns a copy of the raw number array form of the vector.\n */\n toArray(): number[] {\n return this._values.map(n => n);\n }\n\n /**\n * Returns `true` if the two `VectorValue` values have the same raw number arrays, returns `false` otherwise.\n */\n isEqual(other: VectorValue): boolean {\n return isPrimitiveArrayEqual(this._values, other._values);\n }\n\n static _jsonSchemaVersion: string = 'firestore/vectorValue/1.0';\n static _jsonSchema = {\n type: property('string', VectorValue._jsonSchemaVersion),\n vectorValues: property('object')\n };\n\n /**\n * Returns a JSON-serializable representation of this `VectorValue` instance.\n *\n * @returns a JSON representation of this object.\n */\n toJSON(): object {\n return {\n type: VectorValue._jsonSchemaVersion,\n vectorValues: this._values\n };\n }\n\n /**\n * Builds a `VectorValue` instance from a JSON object created by {@link VectorValue.toJSON}.\n *\n * @param json a JSON object represention of a `VectorValue` instance.\n * @returns an instance of {@link VectorValue} if the JSON object could be parsed. Throws a\n * {@link FirestoreError} if an error occurs.\n */\n static fromJSON(json: object): VectorValue {\n if (validateJSON(json, VectorValue._jsonSchema)) {\n if (\n Array.isArray(json.vectorValues) &&\n json.vectorValues.every(element => typeof element === 'number')\n ) {\n return new VectorValue(json.vectorValues);\n }\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n \"Expected 'vectorValues' field to be a number array\"\n );\n }\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Unexpected error creating Timestamp from JSON.'\n );\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Returns true iff the array contains the value using strong equality.\n */\nexport function includes(array: T[], value: T): boolean {\n for (let i = 0; i < array.length; i++) {\n if (array[i] === value) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * Returns true iff the array contains any value matching the predicate\n */\nexport function some(array: T[], predicate: (t: T) => boolean): boolean {\n for (let i = 0; i < array.length; i++) {\n if (predicate(array[i])) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * Calls predicate function for each item in the array until the predicate\n * returns true, at which point the index of that item is returned. If the\n * predicate does not return true for any item, null is returned.\n */\nexport function findIndex
(\n array: A[],\n predicate: (value: A) => boolean\n): number | null {\n for (let i = 0; i < array.length; i++) {\n if (predicate(array[i])) {\n return i;\n }\n }\n return null;\n}\n\n/**\n * Compares two array for equality using comparator. The method computes the\n * intersection and invokes `onAdd` for every element that is in `after` but not\n * `before`. `onRemove` is invoked for every element in `before` but missing\n * from `after`.\n *\n * The method creates a copy of both `before` and `after` and runs in O(n log\n * n), where n is the size of the two lists.\n *\n * @param before - The elements that exist in the original array.\n * @param after - The elements to diff against the original array.\n * @param comparator - The comparator for the elements in before and after.\n * @param onAdd - A function to invoke for every element that is part of `\n * after` but not `before`.\n * @param onRemove - A function to invoke for every element that is part of\n * `before` but not `after`.\n */\nexport function diffArrays(\n before: T[],\n after: T[],\n comparator: (l: T, r: T) => number,\n onAdd: (entry: T) => void,\n onRemove: (entry: T) => void\n): void {\n before = [...before];\n after = [...after];\n before.sort(comparator);\n after.sort(comparator);\n\n const bLen = before.length;\n const aLen = after.length;\n let a = 0;\n let b = 0;\n while (a < aLen && b < bLen) {\n const cmp = comparator(before[b], after[a]);\n if (cmp < 0) {\n // The element was removed if the next element in our ordered\n // walkthrough is only in `before`.\n onRemove(before[b++]);\n } else if (cmp > 0) {\n // The element was added if the next element in our ordered walkthrough\n // is only in `after`.\n onAdd(after[a++]);\n } else {\n a++;\n b++;\n }\n }\n while (a < aLen) {\n onAdd(after[a++]);\n }\n while (b < bLen) {\n onRemove(before[b++]);\n }\n}\n\n/**\n * Verifies equality for an array of objects using the `isEqual` interface.\n *\n * @private\n * @internal\n * @param left Array of objects supporting `isEqual`.\n * @param right Array of objects supporting `isEqual`.\n * @return True if arrays are equal.\n */\nexport function isArrayEqual boolean }>(\n left: T[],\n right: T[]\n): boolean {\n if (left.length !== right.length) {\n return false;\n }\n\n for (let i = 0; i < left.length; ++i) {\n if (!left[i].isEqual(right[i])) {\n return false;\n }\n }\n\n return true;\n}\n\n/**\n * Verifies equality for an array of primitives.\n *\n * @private\n * @internal\n * @param left Array of primitives.\n * @param right Array of primitives.\n * @return True if arrays are equal.\n */\nexport function isPrimitiveArrayEqual(\n left: T[],\n right: T[]\n): boolean {\n if (left.length !== right.length) {\n return false;\n }\n\n for (let i = 0; i < left.length; ++i) {\n if (left[i] !== right[i]) {\n return false;\n }\n }\n\n return true;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n DocumentData,\n FieldPath as PublicFieldPath,\n SetOptions\n} from '@firebase/firestore-types';\nimport { Compat, deepEqual, getModularInstance } from '@firebase/util';\n\nimport { ParseContext } from '../api/parse_context';\nimport { DatabaseId } from '../core/database_info';\nimport { DocumentKey } from '../model/document_key';\nimport { FieldMask } from '../model/field_mask';\nimport {\n FieldTransform,\n Mutation,\n PatchMutation,\n Precondition,\n SetMutation\n} from '../model/mutation';\nimport { ObjectValue } from '../model/object_value';\nimport { FieldPath as InternalFieldPath } from '../model/path';\nimport {\n ArrayRemoveTransformOperation,\n ArrayUnionTransformOperation,\n NumericIncrementTransformOperation,\n ServerTimestampTransform\n} from '../model/transform_operation';\nimport {\n TYPE_KEY,\n VECTOR_MAP_VECTORS_KEY,\n VECTOR_VALUE_SENTINEL\n} from '../model/values';\nimport { newSerializer } from '../platform/serializer';\nimport {\n MapValue as ProtoMapValue,\n Value as ProtoValue\n} from '../protos/firestore_proto_api';\nimport { toDouble, toNumber } from '../remote/number_serializer';\nimport {\n JsonProtoSerializer,\n toBytes,\n toResourceName,\n toTimestamp\n} from '../remote/serializer';\nimport { debugAssert, fail } from '../util/assert';\nimport { Code, FirestoreError } from '../util/error';\nimport { isPlainObject, valueDescription } from '../util/input_validation';\nimport { Dict, forEach, isEmpty } from '../util/obj';\n\nimport { Bytes } from './bytes';\nimport { Firestore } from './database';\nimport { FieldPath } from './field_path';\nimport { FieldValue } from './field_value';\nimport { GeoPoint } from './geo_point';\nimport {\n DocumentReference,\n PartialWithFieldValue,\n WithFieldValue\n} from './reference';\nimport { Timestamp } from './timestamp';\nimport { VectorValue } from './vector_value';\n\nconst RESERVED_FIELD_REGEX = /^__.*__$/;\n\n/**\n * An untyped Firestore Data Converter interface that is shared between the\n * lite, firestore-exp and classic SDK.\n */\nexport interface UntypedFirestoreDataConverter<\n AppModelType,\n DbModelType extends DocumentData = DocumentData\n> {\n toFirestore(\n modelObject: WithFieldValue\n ): WithFieldValue;\n toFirestore(\n modelObject: PartialWithFieldValue,\n options: SetOptions\n ): PartialWithFieldValue;\n fromFirestore(snapshot: unknown, options?: unknown): AppModelType;\n}\n\n/** The result of parsing document data (e.g. for a setData call). */\nexport class ParsedSetData {\n constructor(\n readonly data: ObjectValue,\n readonly fieldMask: FieldMask | null,\n readonly fieldTransforms: FieldTransform[]\n ) {}\n\n toMutation(key: DocumentKey, precondition: Precondition): Mutation {\n if (this.fieldMask !== null) {\n return new PatchMutation(\n key,\n this.data,\n this.fieldMask,\n precondition,\n this.fieldTransforms\n );\n } else {\n return new SetMutation(\n key,\n this.data,\n precondition,\n this.fieldTransforms\n );\n }\n }\n}\n\n/** The result of parsing \"update\" data (i.e. for an updateData call). */\nexport class ParsedUpdateData {\n constructor(\n readonly data: ObjectValue,\n // The fieldMask does not include document transforms.\n readonly fieldMask: FieldMask,\n readonly fieldTransforms: FieldTransform[]\n ) {}\n\n toMutation(key: DocumentKey, precondition: Precondition): Mutation {\n return new PatchMutation(\n key,\n this.data,\n this.fieldMask,\n precondition,\n this.fieldTransforms\n );\n }\n}\n\n/*\n * Represents what type of API method provided the data being parsed; useful\n * for determining which error conditions apply during parsing and providing\n * better error messages.\n */\nexport const enum UserDataSource {\n Set,\n Update,\n MergeSet,\n /**\n * Indicates the source is a where clause, cursor bound, arrayUnion()\n * element, etc. Of note, isWrite(source) will return false.\n */\n Argument,\n /**\n * Indicates that the source is an Argument that may directly contain nested\n * arrays (e.g. the operand of an `in` query).\n */\n ArrayArgument\n}\n\nfunction isWrite(dataSource: UserDataSource): boolean {\n switch (dataSource) {\n case UserDataSource.Set: // fall through\n case UserDataSource.MergeSet: // fall through\n case UserDataSource.Update:\n return true;\n case UserDataSource.Argument:\n case UserDataSource.ArrayArgument:\n return false;\n default:\n throw fail(0x9c4b, 'Unexpected case for UserDataSource', {\n dataSource\n });\n }\n}\n\n/** Contains the settings that are mutated as we parse user data. */\ninterface ContextSettings {\n /** Indicates what kind of API method this data came from. */\n readonly dataSource: UserDataSource;\n /** The name of the method the user called to create the ParseContext. */\n readonly methodName: string;\n /** The document the user is attempting to modify, if that applies. */\n readonly targetDoc?: DocumentKey;\n /**\n * A path within the object being parsed. This could be an empty path (in\n * which case the context represents the root of the data being parsed), or a\n * nonempty path (indicating the context represents a nested location within\n * the data).\n */\n readonly path?: InternalFieldPath;\n /**\n * Whether or not this context corresponds to an element of an array.\n * If not set, elements are treated as if they were outside of arrays.\n */\n readonly arrayElement?: boolean;\n /**\n * Whether or not a converter was specified in this context. If true, error\n * messages will reference the converter when invalid data is provided.\n */\n readonly hasConverter?: boolean;\n}\n\n/** A \"context\" object passed around while parsing user data. */\nclass ParseContextImpl implements ParseContext {\n readonly fieldTransforms: FieldTransform[];\n readonly fieldMask: InternalFieldPath[];\n /**\n * Initializes a ParseContext with the given source and path.\n *\n * @param settings - The settings for the parser.\n * @param databaseId - The database ID of the Firestore instance.\n * @param serializer - The serializer to use to generate the Value proto.\n * @param ignoreUndefinedProperties - Whether to ignore undefined properties\n * rather than throw.\n * @param fieldTransforms - A mutable list of field transforms encountered\n * while parsing the data.\n * @param fieldMask - A mutable list of field paths encountered while parsing\n * the data.\n *\n * TODO(b/34871131): We don't support array paths right now, so path can be\n * null to indicate the context represents any location within an array (in\n * which case certain features will not work and errors will be somewhat\n * compromised).\n */\n constructor(\n readonly settings: ContextSettings,\n readonly databaseId: DatabaseId,\n readonly serializer: JsonProtoSerializer,\n readonly ignoreUndefinedProperties: boolean,\n fieldTransforms?: FieldTransform[],\n fieldMask?: InternalFieldPath[]\n ) {\n // Minor hack: If fieldTransforms is undefined, we assume this is an\n // external call and we need to validate the entire path.\n if (fieldTransforms === undefined) {\n this.validatePath();\n }\n this.fieldTransforms = fieldTransforms || [];\n this.fieldMask = fieldMask || [];\n }\n\n get path(): InternalFieldPath | undefined {\n return this.settings.path;\n }\n\n get dataSource(): UserDataSource {\n return this.settings.dataSource;\n }\n\n /** Returns a new context with the specified settings overwritten. */\n contextWith(configuration: Partial): ParseContextImpl {\n return new ParseContextImpl(\n { ...this.settings, ...configuration },\n this.databaseId,\n this.serializer,\n this.ignoreUndefinedProperties,\n this.fieldTransforms,\n this.fieldMask\n );\n }\n\n childContextForField(field: string): ParseContextImpl {\n const childPath = this.path?.child(field);\n const context = this.contextWith({ path: childPath, arrayElement: false });\n context.validatePathSegment(field);\n return context;\n }\n\n childContextForFieldPath(field: InternalFieldPath): ParseContextImpl {\n const childPath = this.path?.child(field);\n const context = this.contextWith({ path: childPath, arrayElement: false });\n context.validatePath();\n return context;\n }\n\n childContextForArray(index: number): ParseContextImpl {\n // TODO(b/34871131): We don't support array paths right now; so make path\n // undefined.\n return this.contextWith({ path: undefined, arrayElement: true });\n }\n\n createError(reason: string): FirestoreError {\n return createError(\n reason,\n this.settings.methodName,\n this.settings.hasConverter || false,\n this.path,\n this.settings.targetDoc\n );\n }\n\n /** Returns 'true' if 'fieldPath' was traversed when creating this context. */\n contains(fieldPath: InternalFieldPath): boolean {\n return (\n this.fieldMask.find(field => fieldPath.isPrefixOf(field)) !== undefined ||\n this.fieldTransforms.find(transform =>\n fieldPath.isPrefixOf(transform.field)\n ) !== undefined\n );\n }\n\n private validatePath(): void {\n // TODO(b/34871131): Remove null check once we have proper paths for fields\n // within arrays.\n if (!this.path) {\n return;\n }\n for (let i = 0; i < this.path.length; i++) {\n this.validatePathSegment(this.path.get(i));\n }\n }\n\n private validatePathSegment(segment: string): void {\n if (segment.length === 0) {\n throw this.createError('Document fields must not be empty');\n }\n if (isWrite(this.dataSource) && RESERVED_FIELD_REGEX.test(segment)) {\n throw this.createError('Document fields cannot begin and end with \"__\"');\n }\n }\n}\n\n/**\n * Helper for parsing raw user input (provided via the API) into internal model\n * classes.\n */\nexport class UserDataReader {\n private readonly serializer: JsonProtoSerializer;\n\n constructor(\n private readonly databaseId: DatabaseId,\n private readonly ignoreUndefinedProperties: boolean,\n serializer?: JsonProtoSerializer\n ) {\n this.serializer = serializer || newSerializer(databaseId);\n }\n\n /** Creates a new top-level parse context. */\n createContext(\n dataSource: UserDataSource,\n methodName: string,\n targetDoc?: DocumentKey,\n hasConverter = false\n ): ParseContextImpl {\n return new ParseContextImpl(\n {\n dataSource,\n methodName,\n targetDoc,\n path: InternalFieldPath.emptyPath(),\n arrayElement: false,\n hasConverter\n },\n this.databaseId,\n this.serializer,\n this.ignoreUndefinedProperties\n );\n }\n}\n\nexport function newUserDataReader(firestore: Firestore): UserDataReader {\n const settings = firestore._freezeSettings();\n const serializer = newSerializer(firestore._databaseId);\n return new UserDataReader(\n firestore._databaseId,\n !!settings.ignoreUndefinedProperties,\n serializer\n );\n}\n\n/** Parse document data from a set() call. */\nexport function parseSetData(\n userDataReader: UserDataReader,\n methodName: string,\n targetDoc: DocumentKey,\n input: unknown,\n hasConverter: boolean,\n options: SetOptions = {}\n): ParsedSetData {\n const context = userDataReader.createContext(\n options.merge || options.mergeFields\n ? UserDataSource.MergeSet\n : UserDataSource.Set,\n methodName,\n targetDoc,\n hasConverter\n );\n validatePlainObject('Data must be an object, but it was:', context, input);\n const updateData = parseObject(input, context)!;\n\n let fieldMask: FieldMask | null;\n let fieldTransforms: FieldTransform[];\n\n if (options.merge) {\n fieldMask = new FieldMask(context.fieldMask);\n fieldTransforms = context.fieldTransforms;\n } else if (options.mergeFields) {\n const validatedFieldPaths: InternalFieldPath[] = [];\n\n for (const stringOrFieldPath of options.mergeFields) {\n const fieldPath = fieldPathFromArgument(\n methodName,\n stringOrFieldPath,\n targetDoc\n );\n if (!context.contains(fieldPath)) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Field '${fieldPath}' is specified in your field mask but missing from your input data.`\n );\n }\n\n if (!fieldMaskContains(validatedFieldPaths, fieldPath)) {\n validatedFieldPaths.push(fieldPath);\n }\n }\n\n fieldMask = new FieldMask(validatedFieldPaths);\n fieldTransforms = context.fieldTransforms.filter(transform =>\n fieldMask!.covers(transform.field)\n );\n } else {\n fieldMask = null;\n fieldTransforms = context.fieldTransforms;\n }\n\n return new ParsedSetData(\n new ObjectValue(updateData),\n fieldMask,\n fieldTransforms\n );\n}\n\nexport class DeleteFieldValueImpl extends FieldValue {\n _toFieldTransform(context: ParseContextImpl): null {\n if (context.dataSource === UserDataSource.MergeSet) {\n // No transform to add for a delete, but we need to add it to our\n // fieldMask so it gets deleted.\n context.fieldMask.push(context.path!);\n } else if (context.dataSource === UserDataSource.Update) {\n debugAssert(\n context.path!.length > 0,\n `${this._methodName}() at the top level should have already ` +\n 'been handled.'\n );\n throw context.createError(\n `${this._methodName}() can only appear at the top level ` +\n 'of your update data'\n );\n } else {\n // We shouldn't encounter delete sentinels for queries or non-merge set() calls.\n throw context.createError(\n `${this._methodName}() cannot be used with set() unless you pass ` +\n '{merge:true}'\n );\n }\n return null;\n }\n\n isEqual(other: FieldValue): boolean {\n return other instanceof DeleteFieldValueImpl;\n }\n}\n\n/**\n * Creates a child context for parsing SerializableFieldValues.\n *\n * This is different than calling `ParseContext.contextWith` because it keeps\n * the fieldTransforms and fieldMask separate.\n *\n * The created context has its `dataSource` set to `UserDataSource.Argument`.\n * Although these values are used with writes, any elements in these FieldValues\n * are not considered writes since they cannot contain any FieldValue sentinels,\n * etc.\n *\n * @param fieldValue - The sentinel FieldValue for which to create a child\n * context.\n * @param context - The parent context.\n * @param arrayElement - Whether or not the FieldValue has an array.\n */\nfunction createSentinelChildContext(\n fieldValue: FieldValue,\n context: ParseContextImpl,\n arrayElement: boolean\n): ParseContextImpl {\n return new ParseContextImpl(\n {\n dataSource: UserDataSource.Argument,\n targetDoc: context.settings.targetDoc,\n methodName: fieldValue._methodName,\n arrayElement\n },\n context.databaseId,\n context.serializer,\n context.ignoreUndefinedProperties\n );\n}\n\nexport class ServerTimestampFieldValueImpl extends FieldValue {\n _toFieldTransform(context: ParseContextImpl): FieldTransform {\n return new FieldTransform(context.path!, new ServerTimestampTransform());\n }\n\n isEqual(other: FieldValue): boolean {\n return other instanceof ServerTimestampFieldValueImpl;\n }\n}\n\nexport class ArrayUnionFieldValueImpl extends FieldValue {\n constructor(methodName: string, private readonly _elements: unknown[]) {\n super(methodName);\n }\n\n _toFieldTransform(context: ParseContextImpl): FieldTransform {\n const parseContext = createSentinelChildContext(\n this,\n context,\n /*array=*/ true\n );\n const parsedElements = this._elements.map(\n element => parseData(element, parseContext)!\n );\n const arrayUnion = new ArrayUnionTransformOperation(parsedElements);\n return new FieldTransform(context.path!, arrayUnion);\n }\n\n isEqual(other: FieldValue): boolean {\n return (\n other instanceof ArrayUnionFieldValueImpl &&\n deepEqual(this._elements, other._elements)\n );\n }\n}\n\nexport class ArrayRemoveFieldValueImpl extends FieldValue {\n constructor(methodName: string, private readonly _elements: unknown[]) {\n super(methodName);\n }\n\n _toFieldTransform(context: ParseContextImpl): FieldTransform {\n const parseContext = createSentinelChildContext(\n this,\n context,\n /*array=*/ true\n );\n const parsedElements = this._elements.map(\n element => parseData(element, parseContext)!\n );\n const arrayUnion = new ArrayRemoveTransformOperation(parsedElements);\n return new FieldTransform(context.path!, arrayUnion);\n }\n\n isEqual(other: FieldValue): boolean {\n return (\n other instanceof ArrayRemoveFieldValueImpl &&\n deepEqual(this._elements, other._elements)\n );\n }\n}\n\nexport class NumericIncrementFieldValueImpl extends FieldValue {\n constructor(methodName: string, private readonly _operand: number) {\n super(methodName);\n }\n\n _toFieldTransform(context: ParseContextImpl): FieldTransform {\n const numericIncrement = new NumericIncrementTransformOperation(\n context.serializer,\n toNumber(context.serializer, this._operand)\n );\n return new FieldTransform(context.path!, numericIncrement);\n }\n\n isEqual(other: FieldValue): boolean {\n return (\n other instanceof NumericIncrementFieldValueImpl &&\n this._operand === other._operand\n );\n }\n}\n\n/** Parse update data from an update() call. */\nexport function parseUpdateData(\n userDataReader: UserDataReader,\n methodName: string,\n targetDoc: DocumentKey,\n input: unknown\n): ParsedUpdateData {\n const context = userDataReader.createContext(\n UserDataSource.Update,\n methodName,\n targetDoc\n );\n validatePlainObject('Data must be an object, but it was:', context, input);\n\n const fieldMaskPaths: InternalFieldPath[] = [];\n const updateData = ObjectValue.empty();\n forEach(input as Dict, (key, value) => {\n const path = fieldPathFromDotSeparatedString(methodName, key, targetDoc);\n\n // For Compat types, we have to \"extract\" the underlying types before\n // performing validation.\n value = getModularInstance(value);\n\n const childContext = context.childContextForFieldPath(path);\n if (value instanceof DeleteFieldValueImpl) {\n // Add it to the field mask, but don't add anything to updateData.\n fieldMaskPaths.push(path);\n } else {\n const parsedValue = parseData(value, childContext);\n if (parsedValue != null) {\n fieldMaskPaths.push(path);\n updateData.set(path, parsedValue);\n }\n }\n });\n\n const mask = new FieldMask(fieldMaskPaths);\n return new ParsedUpdateData(updateData, mask, context.fieldTransforms);\n}\n\n/** Parse update data from a list of field/value arguments. */\nexport function parseUpdateVarargs(\n userDataReader: UserDataReader,\n methodName: string,\n targetDoc: DocumentKey,\n field: string | PublicFieldPath | Compat,\n value: unknown,\n moreFieldsAndValues: unknown[]\n): ParsedUpdateData {\n const context = userDataReader.createContext(\n UserDataSource.Update,\n methodName,\n targetDoc\n );\n const keys = [fieldPathFromArgument(methodName, field, targetDoc)];\n const values = [value];\n\n if (moreFieldsAndValues.length % 2 !== 0) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Function ${methodName}() needs to be called with an even number ` +\n 'of arguments that alternate between field names and values.'\n );\n }\n\n for (let i = 0; i < moreFieldsAndValues.length; i += 2) {\n keys.push(\n fieldPathFromArgument(\n methodName,\n moreFieldsAndValues[i] as string | PublicFieldPath\n )\n );\n values.push(moreFieldsAndValues[i + 1]);\n }\n\n const fieldMaskPaths: InternalFieldPath[] = [];\n const updateData = ObjectValue.empty();\n\n // We iterate in reverse order to pick the last value for a field if the\n // user specified the field multiple times.\n for (let i = keys.length - 1; i >= 0; --i) {\n if (!fieldMaskContains(fieldMaskPaths, keys[i])) {\n const path = keys[i];\n let value = values[i];\n\n // For Compat types, we have to \"extract\" the underlying types before\n // performing validation.\n value = getModularInstance(value);\n\n const childContext = context.childContextForFieldPath(path);\n if (value instanceof DeleteFieldValueImpl) {\n // Add it to the field mask, but don't add anything to updateData.\n fieldMaskPaths.push(path);\n } else {\n const parsedValue = parseData(value, childContext);\n if (parsedValue != null) {\n fieldMaskPaths.push(path);\n updateData.set(path, parsedValue);\n }\n }\n }\n }\n\n const mask = new FieldMask(fieldMaskPaths);\n return new ParsedUpdateData(updateData, mask, context.fieldTransforms);\n}\n\n/**\n * Parse a \"query value\" (e.g. value in a where filter or a value in a cursor\n * bound).\n *\n * @param allowArrays - Whether the query value is an array that may directly\n * contain additional arrays (e.g. the operand of an `in` query).\n */\nexport function parseQueryValue(\n userDataReader: UserDataReader,\n methodName: string,\n input: unknown,\n allowArrays = false\n): ProtoValue {\n const context = userDataReader.createContext(\n allowArrays ? UserDataSource.ArrayArgument : UserDataSource.Argument,\n methodName\n );\n const parsed = parseData(input, context);\n debugAssert(parsed != null, 'Parsed data should not be null.');\n debugAssert(\n context.fieldTransforms.length === 0,\n 'Field transforms should have been disallowed.'\n );\n return parsed;\n}\n\n/**\n * Parses user data to Protobuf Values.\n *\n * @param input - Data to be parsed.\n * @param context - A context object representing the current path being parsed,\n * the source of the data being parsed, etc.\n * @returns The parsed value, or null if the value was a FieldValue sentinel\n * that should not be included in the resulting parsed data.\n */\nexport function parseData(\n input: unknown,\n context: ParseContextImpl\n): ProtoValue | null {\n // Unwrap the API type from the Compat SDK. This will return the API type\n // from firestore-exp.\n input = getModularInstance(input);\n\n if (looksLikeJsonObject(input)) {\n validatePlainObject('Unsupported field value:', context, input);\n return parseObject(input, context);\n } else if (input instanceof FieldValue) {\n // FieldValues usually parse into transforms (except deleteField())\n // in which case we do not want to include this field in our parsed data\n // (as doing so will overwrite the field directly prior to the transform\n // trying to transform it). So we don't add this location to\n // context.fieldMask and we return null as our parsing result.\n parseSentinelFieldValue(input, context);\n return null;\n } else if (input === undefined && context.ignoreUndefinedProperties) {\n // If the input is undefined it can never participate in the fieldMask, so\n // don't handle this below. If `ignoreUndefinedProperties` is false,\n // `parseScalarValue` will reject an undefined value.\n return null;\n } else {\n // If context.path is null we are inside an array and we don't support\n // field mask paths more granular than the top-level array.\n if (context.path) {\n context.fieldMask.push(context.path);\n }\n\n if (input instanceof Array) {\n // TODO(b/34871131): Include the path containing the array in the error\n // message.\n // In the case of IN queries, the parsed data is an array (representing\n // the set of values to be included for the IN query) that may directly\n // contain additional arrays (each representing an individual field\n // value), so we disable this validation.\n if (\n context.settings.arrayElement &&\n context.dataSource !== UserDataSource.ArrayArgument\n ) {\n throw context.createError('Nested arrays are not supported');\n }\n return parseArray(input as unknown[], context);\n } else {\n return parseScalarValue(input, context);\n }\n }\n}\n\nexport function parseObject(\n obj: Dict,\n context: ParseContextImpl\n): { mapValue: ProtoMapValue } {\n const fields: Dict = {};\n\n if (isEmpty(obj)) {\n // If we encounter an empty object, we explicitly add it to the update\n // mask to ensure that the server creates a map entry.\n if (context.path && context.path.length > 0) {\n context.fieldMask.push(context.path);\n }\n } else {\n forEach(obj, (key: string, val: unknown) => {\n const parsedValue = parseData(val, context.childContextForField(key));\n if (parsedValue != null) {\n fields[key] = parsedValue;\n }\n });\n }\n\n return { mapValue: { fields } };\n}\n\nfunction parseArray(array: unknown[], context: ParseContextImpl): ProtoValue {\n const values: ProtoValue[] = [];\n let entryIndex = 0;\n for (const entry of array) {\n let parsedEntry = parseData(\n entry,\n context.childContextForArray(entryIndex)\n );\n if (parsedEntry == null) {\n // Just include nulls in the array for fields being replaced with a\n // sentinel.\n parsedEntry = { nullValue: 'NULL_VALUE' };\n }\n values.push(parsedEntry);\n entryIndex++;\n }\n return { arrayValue: { values } };\n}\n\n/**\n * \"Parses\" the provided FieldValueImpl, adding any necessary transforms to\n * context.fieldTransforms.\n */\nfunction parseSentinelFieldValue(\n value: FieldValue,\n context: ParseContextImpl\n): void {\n // Sentinels are only supported with writes, and not within arrays.\n if (!isWrite(context.dataSource)) {\n throw context.createError(\n `${value._methodName}() can only be used with update() and set()`\n );\n }\n if (!context.path) {\n throw context.createError(\n `${value._methodName}() is not currently supported inside arrays`\n );\n }\n\n const fieldTransform = value._toFieldTransform(context);\n if (fieldTransform) {\n context.fieldTransforms.push(fieldTransform);\n }\n}\n\n/**\n * Helper to parse a scalar value (i.e. not an Object, Array, or FieldValue)\n *\n * @returns The parsed value\n */\nfunction parseScalarValue(\n value: unknown,\n context: ParseContextImpl\n): ProtoValue | null {\n value = getModularInstance(value);\n\n if (value === null) {\n return { nullValue: 'NULL_VALUE' };\n } else if (typeof value === 'number') {\n return toNumber(context.serializer, value);\n } else if (typeof value === 'boolean') {\n return { booleanValue: value };\n } else if (typeof value === 'string') {\n return { stringValue: value };\n } else if (value instanceof Date) {\n const timestamp = Timestamp.fromDate(value);\n return {\n timestampValue: toTimestamp(context.serializer, timestamp)\n };\n } else if (value instanceof Timestamp) {\n // Firestore backend truncates precision down to microseconds. To ensure\n // offline mode works the same with regards to truncation, perform the\n // truncation immediately without waiting for the backend to do that.\n const timestamp = new Timestamp(\n value.seconds,\n Math.floor(value.nanoseconds / 1000) * 1000\n );\n return {\n timestampValue: toTimestamp(context.serializer, timestamp)\n };\n } else if (value instanceof GeoPoint) {\n return {\n geoPointValue: {\n latitude: value.latitude,\n longitude: value.longitude\n }\n };\n } else if (value instanceof Bytes) {\n return { bytesValue: toBytes(context.serializer, value._byteString) };\n } else if (value instanceof DocumentReference) {\n const thisDb = context.databaseId;\n const otherDb = value.firestore._databaseId;\n if (!otherDb.isEqual(thisDb)) {\n throw context.createError(\n 'Document reference is for database ' +\n `${otherDb.projectId}/${otherDb.database} but should be ` +\n `for database ${thisDb.projectId}/${thisDb.database}`\n );\n }\n return {\n referenceValue: toResourceName(\n value.firestore._databaseId || context.databaseId,\n value._key.path\n )\n };\n } else if (value instanceof VectorValue) {\n return parseVectorValue(value, context);\n } else {\n throw context.createError(\n `Unsupported field value: ${valueDescription(value)}`\n );\n }\n}\n\n/**\n * Creates a new VectorValue proto value (using the internal format).\n */\nexport function parseVectorValue(\n value: VectorValue,\n context: ParseContextImpl\n): ProtoValue {\n const mapValue: ProtoMapValue = {\n fields: {\n [TYPE_KEY]: {\n stringValue: VECTOR_VALUE_SENTINEL\n },\n [VECTOR_MAP_VECTORS_KEY]: {\n arrayValue: {\n values: value.toArray().map(value => {\n if (typeof value !== 'number') {\n throw context.createError(\n 'VectorValues must only contain numeric values.'\n );\n }\n\n return toDouble(context.serializer, value);\n })\n }\n }\n }\n };\n\n return { mapValue };\n}\n\n/**\n * Checks whether an object looks like a JSON object that should be converted\n * into a struct. Normal class/prototype instances are considered to look like\n * JSON objects since they should be converted to a struct value. Arrays, Dates,\n * GeoPoints, etc. are not considered to look like JSON objects since they map\n * to specific FieldValue types other than ObjectValue.\n */\nfunction looksLikeJsonObject(input: unknown): boolean {\n return (\n typeof input === 'object' &&\n input !== null &&\n !(input instanceof Array) &&\n !(input instanceof Date) &&\n !(input instanceof Timestamp) &&\n !(input instanceof GeoPoint) &&\n !(input instanceof Bytes) &&\n !(input instanceof DocumentReference) &&\n !(input instanceof FieldValue) &&\n !(input instanceof VectorValue)\n );\n}\n\nfunction validatePlainObject(\n message: string,\n context: ParseContextImpl,\n input: unknown\n): asserts input is Dict {\n if (!looksLikeJsonObject(input) || !isPlainObject(input)) {\n const description = valueDescription(input);\n if (description === 'an object') {\n // Massage the error if it was an object.\n throw context.createError(message + ' a custom object');\n } else {\n throw context.createError(message + ' ' + description);\n }\n }\n}\n\n/**\n * Helper that calls fromDotSeparatedString() but wraps any error thrown.\n */\nexport function fieldPathFromArgument(\n methodName: string,\n path: string | PublicFieldPath | Compat,\n targetDoc?: DocumentKey\n): InternalFieldPath {\n // If required, replace the FieldPath Compat class with the firestore-exp\n // FieldPath.\n path = getModularInstance(path);\n\n if (path instanceof FieldPath) {\n return path._internalPath;\n } else if (typeof path === 'string') {\n return fieldPathFromDotSeparatedString(methodName, path);\n } else {\n const message = 'Field path arguments must be of type string or ';\n throw createError(\n message,\n methodName,\n /* hasConverter= */ false,\n /* path= */ undefined,\n targetDoc\n );\n }\n}\n\n/**\n * Matches any characters in a field path string that are reserved.\n */\nconst FIELD_PATH_RESERVED = new RegExp('[~\\\\*/\\\\[\\\\]]');\n\n/**\n * Wraps fromDotSeparatedString with an error message about the method that\n * was thrown.\n * @param methodName - The publicly visible method name\n * @param path - The dot-separated string form of a field path which will be\n * split on dots.\n * @param targetDoc - The document against which the field path will be\n * evaluated.\n */\nexport function fieldPathFromDotSeparatedString(\n methodName: string,\n path: string,\n targetDoc?: DocumentKey\n): InternalFieldPath {\n const found = path.search(FIELD_PATH_RESERVED);\n if (found >= 0) {\n throw createError(\n `Invalid field path (${path}). Paths must not contain ` +\n `'~', '*', '/', '[', or ']'`,\n methodName,\n /* hasConverter= */ false,\n /* path= */ undefined,\n targetDoc\n );\n }\n\n try {\n return new FieldPath(...path.split('.'))._internalPath;\n } catch (e) {\n throw createError(\n `Invalid field path (${path}). Paths must not be empty, ` +\n `begin with '.', end with '.', or contain '..'`,\n methodName,\n /* hasConverter= */ false,\n /* path= */ undefined,\n targetDoc\n );\n }\n}\n\nfunction createError(\n reason: string,\n methodName: string,\n hasConverter: boolean,\n path?: InternalFieldPath,\n targetDoc?: DocumentKey\n): FirestoreError {\n const hasPath = path && !path.isEmpty();\n const hasDocument = targetDoc !== undefined;\n let message = `Function ${methodName}() called with invalid data`;\n if (hasConverter) {\n message += ' (via `toFirestore()`)';\n }\n message += '. ';\n\n let description = '';\n if (hasPath || hasDocument) {\n description += ' (found';\n\n if (hasPath) {\n description += ` in field ${path}`;\n }\n if (hasDocument) {\n description += ` in document ${targetDoc}`;\n }\n description += ')';\n }\n\n return new FirestoreError(\n Code.INVALID_ARGUMENT,\n message + reason + description\n );\n}\n\n/** Checks `haystack` if FieldPath `needle` is present. Runs in O(n). */\nfunction fieldMaskContains(\n haystack: InternalFieldPath[],\n needle: InternalFieldPath\n): boolean {\n return haystack.some(v => v.isEqual(needle));\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Compat, getModularInstance } from '@firebase/util';\n\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { FieldPath as InternalFieldPath } from '../model/path';\nimport { arrayEquals } from '../util/misc';\n\nimport { Firestore } from './database';\nimport { FieldPath } from './field_path';\nimport {\n DocumentData,\n DocumentReference,\n PartialWithFieldValue,\n Query,\n queryEqual,\n SetOptions,\n WithFieldValue\n} from './reference';\nimport {\n fieldPathFromDotSeparatedString,\n UntypedFirestoreDataConverter\n} from './user_data_reader';\nimport { AbstractUserDataWriter } from './user_data_writer';\n\n/**\n * Converter used by `withConverter()` to transform user objects of type\n * `AppModelType` into Firestore data of type `DbModelType`.\n *\n * Using the converter allows you to specify generic type arguments when\n * storing and retrieving objects from Firestore.\n *\n * In this context, an \"AppModel\" is a class that is used in an application to\n * package together related information and functionality. Such a class could,\n * for example, have properties with complex, nested data types, properties used\n * for memoization, properties of types not supported by Firestore (such as\n * `symbol` and `bigint`), and helper functions that perform compound\n * operations. Such classes are not suitable and/or possible to store into a\n * Firestore database. Instead, instances of such classes need to be converted\n * to \"plain old JavaScript objects\" (POJOs) with exclusively primitive\n * properties, potentially nested inside other POJOs or arrays of POJOs. In this\n * context, this type is referred to as the \"DbModel\" and would be an object\n * suitable for persisting into Firestore. For convenience, applications can\n * implement `FirestoreDataConverter` and register the converter with Firestore\n * objects, such as `DocumentReference` or `Query`, to automatically convert\n * `AppModel` to `DbModel` when storing into Firestore, and convert `DbModel`\n * to `AppModel` when retrieving from Firestore.\n *\n * @example\n *\n * Simple Example\n *\n * ```typescript\n * const numberConverter = {\n * toFirestore(value: WithFieldValue) {\n * return { value };\n * },\n * fromFirestore(snapshot: QueryDocumentSnapshot, options: SnapshotOptions) {\n * return snapshot.data(options).value as number;\n * }\n * };\n *\n * async function simpleDemo(db: Firestore): Promise {\n * const documentRef = doc(db, 'values/value123').withConverter(numberConverter);\n *\n * // converters are used with `setDoc`, `addDoc`, and `getDoc`\n * await setDoc(documentRef, 42);\n * const snapshot1 = await getDoc(documentRef);\n * assertEqual(snapshot1.data(), 42);\n *\n * // converters are not used when writing data with `updateDoc`\n * await updateDoc(documentRef, { value: 999 });\n * const snapshot2 = await getDoc(documentRef);\n * assertEqual(snapshot2.data(), 999);\n * }\n * ```\n *\n * Advanced Example\n *\n * ```typescript\n * // The Post class is a model that is used by our application.\n * // This class may have properties and methods that are specific\n * // to our application execution, which do not need to be persisted\n * // to Firestore.\n * class Post {\n * constructor(\n * readonly title: string,\n * readonly author: string,\n * readonly lastUpdatedMillis: number\n * ) {}\n * toString(): string {\n * return `${this.title} by ${this.author}`;\n * }\n * }\n *\n * // The PostDbModel represents how we want our posts to be stored\n * // in Firestore. This DbModel has different properties (`ttl`,\n * // `aut`, and `lut`) from the Post class we use in our application.\n * interface PostDbModel {\n * ttl: string;\n * aut: { firstName: string; lastName: string };\n * lut: Timestamp;\n * }\n *\n * // The `PostConverter` implements `FirestoreDataConverter` and specifies\n * // how the Firestore SDK can convert `Post` objects to `PostDbModel`\n * // objects and vice versa.\n * class PostConverter implements FirestoreDataConverter {\n * toFirestore(post: WithFieldValue): WithFieldValue {\n * return {\n * ttl: post.title,\n * aut: this._autFromAuthor(post.author),\n * lut: this._lutFromLastUpdatedMillis(post.lastUpdatedMillis)\n * };\n * }\n *\n * fromFirestore(snapshot: QueryDocumentSnapshot, options: SnapshotOptions): Post {\n * const data = snapshot.data(options) as PostDbModel;\n * const author = `${data.aut.firstName} ${data.aut.lastName}`;\n * return new Post(data.ttl, author, data.lut.toMillis());\n * }\n *\n * _autFromAuthor(\n * author: string | FieldValue\n * ): { firstName: string; lastName: string } | FieldValue {\n * if (typeof author !== 'string') {\n * // `author` is a FieldValue, so just return it.\n * return author;\n * }\n * const [firstName, lastName] = author.split(' ');\n * return {firstName, lastName};\n * }\n *\n * _lutFromLastUpdatedMillis(\n * lastUpdatedMillis: number | FieldValue\n * ): Timestamp | FieldValue {\n * if (typeof lastUpdatedMillis !== 'number') {\n * // `lastUpdatedMillis` must be a FieldValue, so just return it.\n * return lastUpdatedMillis;\n * }\n * return Timestamp.fromMillis(lastUpdatedMillis);\n * }\n * }\n *\n * async function advancedDemo(db: Firestore): Promise {\n * // Create a `DocumentReference` with a `FirestoreDataConverter`.\n * const documentRef = doc(db, 'posts/post123').withConverter(new PostConverter());\n *\n * // The `data` argument specified to `setDoc()` is type checked by the\n * // TypeScript compiler to be compatible with `Post`. Since the `data`\n * // argument is typed as `WithFieldValue` rather than just `Post`,\n * // this allows properties of the `data` argument to also be special\n * // Firestore values that perform server-side mutations, such as\n * // `arrayRemove()`, `deleteField()`, and `serverTimestamp()`.\n * await setDoc(documentRef, {\n * title: 'My Life',\n * author: 'Foo Bar',\n * lastUpdatedMillis: serverTimestamp()\n * });\n *\n * // The TypeScript compiler will fail to compile if the `data` argument to\n * // `setDoc()` is _not_ compatible with `WithFieldValue`. This\n * // type checking prevents the caller from specifying objects with incorrect\n * // properties or property values.\n * // @ts-expect-error \"Argument of type { ttl: string; } is not assignable\n * // to parameter of type WithFieldValue\"\n * await setDoc(documentRef, { ttl: 'The Title' });\n *\n * // When retrieving a document with `getDoc()` the `DocumentSnapshot`\n * // object's `data()` method returns a `Post`, rather than a generic object,\n * // which would have been returned if the `DocumentReference` did _not_ have a\n * // `FirestoreDataConverter` attached to it.\n * const snapshot1: DocumentSnapshot = await getDoc(documentRef);\n * const post1: Post = snapshot1.data()!;\n * if (post1) {\n * assertEqual(post1.title, 'My Life');\n * assertEqual(post1.author, 'Foo Bar');\n * }\n *\n * // The `data` argument specified to `updateDoc()` is type checked by the\n * // TypeScript compiler to be compatible with `PostDbModel`. Note that\n * // unlike `setDoc()`, whose `data` argument must be compatible with `Post`,\n * // the `data` argument to `updateDoc()` must be compatible with\n * // `PostDbModel`. Similar to `setDoc()`, since the `data` argument is typed\n * // as `WithFieldValue` rather than just `PostDbModel`, this\n * // allows properties of the `data` argument to also be those special\n * // Firestore values, like `arrayRemove()`, `deleteField()`, and\n * // `serverTimestamp()`.\n * await updateDoc(documentRef, {\n * 'aut.firstName': 'NewFirstName',\n * lut: serverTimestamp()\n * });\n *\n * // The TypeScript compiler will fail to compile if the `data` argument to\n * // `updateDoc()` is _not_ compatible with `WithFieldValue`.\n * // This type checking prevents the caller from specifying objects with\n * // incorrect properties or property values.\n * // @ts-expect-error \"Argument of type { title: string; } is not assignable\n * // to parameter of type WithFieldValue\"\n * await updateDoc(documentRef, { title: 'New Title' });\n * const snapshot2: DocumentSnapshot = await getDoc(documentRef);\n * const post2: Post = snapshot2.data()!;\n * if (post2) {\n * assertEqual(post2.title, 'My Life');\n * assertEqual(post2.author, 'NewFirstName Bar');\n * }\n * }\n * ```\n */\nexport interface FirestoreDataConverter<\n AppModelType,\n DbModelType extends DocumentData = DocumentData\n> {\n /**\n * Called by the Firestore SDK to convert a custom model object of type\n * `AppModelType` into a plain JavaScript object (suitable for writing\n * directly to the Firestore database) of type `DbModelType`. Used with\n * {@link @firebase/firestore/lite#(setDoc:1)},\n * {@link @firebase/firestore/lite#(WriteBatch.set:1)} and\n * {@link @firebase/firestore/lite#(Transaction.set:1)}.\n *\n * The `WithFieldValue` type extends `T` to also allow FieldValues such as\n * {@link (deleteField:1)} to be used as property values.\n */\n toFirestore(\n modelObject: WithFieldValue\n ): WithFieldValue;\n\n /**\n * Called by the Firestore SDK to convert a custom model object of type\n * `AppModelType` into a plain JavaScript object (suitable for writing\n * directly to the Firestore database) of type `DbModelType`. Used with\n * {@link @firebase/firestore/lite#(setDoc:1)},\n * {@link @firebase/firestore/lite#(WriteBatch.set:1)} and\n * {@link @firebase/firestore/lite#(Transaction.set:1)} with `merge:true`\n * or `mergeFields`.\n *\n * The `PartialWithFieldValue` type extends `Partial` to allow\n * FieldValues such as {@link (arrayUnion:1)} to be used as property values.\n * It also supports nested `Partial` by allowing nested fields to be\n * omitted.\n */\n toFirestore(\n modelObject: PartialWithFieldValue,\n options: SetOptions\n ): PartialWithFieldValue;\n\n /**\n * Called by the Firestore SDK to convert Firestore data into an object of\n * type `AppModelType`. You can access your data by calling:\n * `snapshot.data()`.\n *\n *\n * Generally, the data returned from `snapshot.data()` can be cast to\n * `DbModelType`; however, this is not guaranteed because Firestore does not\n * enforce a schema on the database. For example, writes from a previous\n * version of the application or writes from another client that did not use a\n * type converter could have written data with different properties and/or\n * property types. The implementation will need to choose whether to\n * gracefully recover from non-conforming data or throw an error.\n *\n * @param snapshot - A `QueryDocumentSnapshot` containing your data and\n * metadata.\n */\n fromFirestore(\n snapshot: QueryDocumentSnapshot\n ): AppModelType;\n}\n\n/**\n * A `DocumentSnapshot` contains data read from a document in your Firestore\n * database. The data can be extracted with `.data()` or `.get()` to\n * get a specific field.\n *\n * For a `DocumentSnapshot` that points to a non-existing document, any data\n * access will return 'undefined'. You can use the `exists()` method to\n * explicitly verify a document's existence.\n */\nexport class DocumentSnapshot<\n AppModelType = DocumentData,\n DbModelType extends DocumentData = DocumentData\n> {\n // Note: This class is stripped down version of the DocumentSnapshot in\n // the legacy SDK. The changes are:\n // - No support for SnapshotMetadata.\n // - No support for SnapshotOptions.\n\n /** @hideconstructor protected */\n constructor(\n public _firestore: Firestore,\n public _userDataWriter: AbstractUserDataWriter,\n public _key: DocumentKey,\n public _document: Document | null,\n public _converter: UntypedFirestoreDataConverter<\n AppModelType,\n DbModelType\n > | null\n ) {}\n\n /** Property of the `DocumentSnapshot` that provides the document's ID. */\n get id(): string {\n return this._key.path.lastSegment();\n }\n\n /**\n * The `DocumentReference` for the document included in the `DocumentSnapshot`.\n */\n get ref(): DocumentReference {\n return new DocumentReference(\n this._firestore,\n this._converter,\n this._key\n );\n }\n\n /**\n * Signals whether or not the document at the snapshot's location exists.\n *\n * @returns true if the document exists.\n */\n exists(): this is QueryDocumentSnapshot {\n return this._document !== null;\n }\n\n /**\n * Retrieves all fields in the document as an `Object`. Returns `undefined` if\n * the document doesn't exist.\n *\n * @returns An `Object` containing all fields in the document or `undefined`\n * if the document doesn't exist.\n */\n data(): AppModelType | undefined {\n if (!this._document) {\n return undefined;\n } else if (this._converter) {\n // We only want to use the converter and create a new DocumentSnapshot\n // if a converter has been provided.\n const snapshot = new QueryDocumentSnapshot(\n this._firestore,\n this._userDataWriter,\n this._key,\n this._document,\n /* converter= */ null\n );\n return this._converter.fromFirestore(snapshot);\n } else {\n return this._userDataWriter.convertValue(\n this._document.data.value\n ) as AppModelType;\n }\n }\n\n /**\n * Retrieves the field specified by `fieldPath`. Returns `undefined` if the\n * document or field doesn't exist.\n *\n * @param fieldPath - The path (for example 'foo' or 'foo.bar') to a specific\n * field.\n * @returns The data at the specified field location or undefined if no such\n * field exists in the document.\n */\n // We are using `any` here to avoid an explicit cast by our users.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n get(fieldPath: string | FieldPath): any {\n if (this._document) {\n const value = this._document.data.field(\n fieldPathFromArgument('DocumentSnapshot.get', fieldPath)\n );\n if (value !== null) {\n return this._userDataWriter.convertValue(value);\n }\n }\n return undefined;\n }\n}\n\n/**\n * A `QueryDocumentSnapshot` contains data read from a document in your\n * Firestore database as part of a query. The document is guaranteed to exist\n * and its data can be extracted with `.data()` or `.get()` to get a\n * specific field.\n *\n * A `QueryDocumentSnapshot` offers the same API surface as a\n * `DocumentSnapshot`. Since query results contain only existing documents, the\n * `exists` property will always be true and `data()` will never return\n * 'undefined'.\n */\nexport class QueryDocumentSnapshot<\n AppModelType = DocumentData,\n DbModelType extends DocumentData = DocumentData\n> extends DocumentSnapshot {\n /**\n * Retrieves all fields in the document as an `Object`.\n *\n * @override\n * @returns An `Object` containing all fields in the document.\n */\n data(): AppModelType {\n return super.data() as AppModelType;\n }\n}\n\n/**\n * A `QuerySnapshot` contains zero or more `DocumentSnapshot` objects\n * representing the results of a query. The documents can be accessed as an\n * array via the `docs` property or enumerated using the `forEach` method. The\n * number of documents can be determined via the `empty` and `size`\n * properties.\n */\nexport class QuerySnapshot<\n AppModelType = DocumentData,\n DbModelType extends DocumentData = DocumentData\n> {\n /**\n * The query on which you called {@link getDocs} in order to get this\n * `QuerySnapshot`.\n */\n readonly query: Query;\n\n /** @hideconstructor */\n constructor(\n _query: Query,\n readonly _docs: Array>\n ) {\n this.query = _query;\n }\n\n /** An array of all the documents in the `QuerySnapshot`. */\n get docs(): Array> {\n return [...this._docs];\n }\n\n /** The number of documents in the `QuerySnapshot`. */\n get size(): number {\n return this.docs.length;\n }\n\n /** True if there are no documents in the `QuerySnapshot`. */\n get empty(): boolean {\n return this.docs.length === 0;\n }\n\n /**\n * Enumerates all of the documents in the `QuerySnapshot`.\n *\n * @param callback - A callback to be called with a `QueryDocumentSnapshot` for\n * each document in the snapshot.\n * @param thisArg - The `this` binding for the callback.\n */\n forEach(\n callback: (\n result: QueryDocumentSnapshot\n ) => void,\n thisArg?: unknown\n ): void {\n this._docs.forEach(callback, thisArg);\n }\n}\n\n/**\n * Returns true if the provided snapshots are equal.\n *\n * @param left - A snapshot to compare.\n * @param right - A snapshot to compare.\n * @returns true if the snapshots are equal.\n */\nexport function snapshotEqual(\n left:\n | DocumentSnapshot\n | QuerySnapshot,\n right:\n | DocumentSnapshot\n | QuerySnapshot\n): boolean {\n left = getModularInstance(left);\n right = getModularInstance(right);\n\n if (left instanceof DocumentSnapshot && right instanceof DocumentSnapshot) {\n return (\n left._firestore === right._firestore &&\n left._key.isEqual(right._key) &&\n (left._document === null\n ? right._document === null\n : left._document.isEqual(right._document)) &&\n left._converter === right._converter\n );\n } else if (left instanceof QuerySnapshot && right instanceof QuerySnapshot) {\n return (\n queryEqual(left.query, right.query) &&\n arrayEquals(left.docs, right.docs, snapshotEqual)\n );\n }\n\n return false;\n}\n\n/**\n * Helper that calls `fromDotSeparatedString()` but wraps any error thrown.\n */\nexport function fieldPathFromArgument(\n methodName: string,\n arg: string | FieldPath | Compat\n): InternalFieldPath {\n if (typeof arg === 'string') {\n return fieldPathFromDotSeparatedString(methodName, arg);\n } else if (arg instanceof FieldPath) {\n return arg._internalPath;\n } else {\n return arg._delegate._internalPath;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getModularInstance } from '@firebase/util';\n\nimport { Bound } from '../core/bound';\nimport { DatabaseId } from '../core/database_info';\nimport {\n CompositeFilter,\n CompositeOperator,\n FieldFilter,\n Filter,\n Operator\n} from '../core/filter';\nimport { Direction, OrderBy } from '../core/order_by';\nimport {\n isCollectionGroupQuery,\n LimitType,\n Query as InternalQuery,\n queryNormalizedOrderBy,\n queryWithAddedFilter,\n queryWithAddedOrderBy,\n queryWithEndAt,\n queryWithLimit,\n queryWithStartAt\n} from '../core/query';\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { FieldPath as InternalFieldPath, ResourcePath } from '../model/path';\nimport { isServerTimestamp } from '../model/server_timestamps';\nimport { refValue } from '../model/values';\nimport { Value as ProtoValue } from '../protos/firestore_proto_api';\nimport { Code, FirestoreError } from '../util/error';\nimport {\n validatePositiveNumber,\n valueDescription\n} from '../util/input_validation';\n\nimport { FieldPath } from './field_path';\nimport { DocumentData, DocumentReference, Query } from './reference';\nimport { DocumentSnapshot, fieldPathFromArgument } from './snapshot';\nimport {\n newUserDataReader,\n parseQueryValue,\n UserDataReader\n} from './user_data_reader';\n\nexport function validateHasExplicitOrderByForLimitToLast(\n query: InternalQuery\n): void {\n if (\n query.limitType === LimitType.Last &&\n query.explicitOrderBy.length === 0\n ) {\n throw new FirestoreError(\n Code.UNIMPLEMENTED,\n 'limitToLast() queries require specifying at least one orderBy() clause'\n );\n }\n}\n\n/** Describes the different query constraints available in this SDK. */\nexport type QueryConstraintType =\n | 'where'\n | 'orderBy'\n | 'limit'\n | 'limitToLast'\n | 'startAt'\n | 'startAfter'\n | 'endAt'\n | 'endBefore';\n\n/**\n * An `AppliableConstraint` is an abstraction of a constraint that can be applied\n * to a Firestore query.\n */\nexport abstract class AppliableConstraint {\n /**\n * Takes the provided {@link Query} and returns a copy of the {@link Query} with this\n * {@link AppliableConstraint} applied.\n */\n abstract _apply(\n query: Query\n ): Query;\n}\n\n/**\n * A `QueryConstraint` is used to narrow the set of documents returned by a\n * Firestore query. `QueryConstraint`s are created by invoking {@link where},\n * {@link orderBy}, {@link (startAt:1)}, {@link (startAfter:1)}, {@link\n * (endBefore:1)}, {@link (endAt:1)}, {@link limit}, {@link limitToLast} and\n * can then be passed to {@link (query:1)} to create a new query instance that\n * also contains this `QueryConstraint`.\n */\nexport abstract class QueryConstraint extends AppliableConstraint {\n /** The type of this query constraint */\n abstract readonly type: QueryConstraintType;\n\n /**\n * Takes the provided {@link Query} and returns a copy of the {@link Query} with this\n * {@link AppliableConstraint} applied.\n */\n abstract _apply(\n query: Query\n ): Query;\n}\n\n/**\n * Creates a new immutable instance of {@link Query} that is extended to also\n * include additional query constraints.\n *\n * @param query - The {@link Query} instance to use as a base for the new\n * constraints.\n * @param compositeFilter - The {@link QueryCompositeFilterConstraint} to\n * apply. Create {@link QueryCompositeFilterConstraint} using {@link and} or\n * {@link or}.\n * @param queryConstraints - Additional {@link QueryNonFilterConstraint}s to\n * apply (e.g. {@link orderBy}, {@link limit}).\n * @throws if any of the provided query constraints cannot be combined with the\n * existing or new constraints.\n */\nexport function query(\n query: Query,\n compositeFilter: QueryCompositeFilterConstraint,\n ...queryConstraints: QueryNonFilterConstraint[]\n): Query;\n\n/**\n * Creates a new immutable instance of {@link Query} that is extended to also\n * include additional query constraints.\n *\n * @param query - The {@link Query} instance to use as a base for the new\n * constraints.\n * @param queryConstraints - The list of {@link QueryConstraint}s to apply.\n * @throws if any of the provided query constraints cannot be combined with the\n * existing or new constraints.\n */\nexport function query(\n query: Query,\n ...queryConstraints: QueryConstraint[]\n): Query;\n\nexport function query(\n query: Query,\n queryConstraint: QueryCompositeFilterConstraint | QueryConstraint | undefined,\n ...additionalQueryConstraints: Array<\n QueryConstraint | QueryNonFilterConstraint\n >\n): Query {\n let queryConstraints: AppliableConstraint[] = [];\n\n if (queryConstraint instanceof AppliableConstraint) {\n queryConstraints.push(queryConstraint);\n }\n\n queryConstraints = queryConstraints.concat(additionalQueryConstraints);\n\n validateQueryConstraintArray(queryConstraints);\n\n for (const constraint of queryConstraints) {\n query = constraint._apply(query);\n }\n return query;\n}\n\n/**\n * A `QueryFieldFilterConstraint` is used to narrow the set of documents returned by\n * a Firestore query by filtering on one or more document fields.\n * `QueryFieldFilterConstraint`s are created by invoking {@link where} and can then\n * be passed to {@link (query:1)} to create a new query instance that also contains\n * this `QueryFieldFilterConstraint`.\n */\nexport class QueryFieldFilterConstraint extends QueryConstraint {\n /** The type of this query constraint */\n readonly type = 'where';\n\n /**\n * @internal\n */\n protected constructor(\n private readonly _field: InternalFieldPath,\n private _op: Operator,\n private _value: unknown\n ) {\n super();\n }\n\n static _create(\n _field: InternalFieldPath,\n _op: Operator,\n _value: unknown\n ): QueryFieldFilterConstraint {\n return new QueryFieldFilterConstraint(_field, _op, _value);\n }\n\n _apply(\n query: Query\n ): Query {\n const filter = this._parse(query);\n validateNewFieldFilter(query._query, filter);\n return new Query(\n query.firestore,\n query.converter,\n queryWithAddedFilter(query._query, filter)\n );\n }\n\n _parse(\n query: Query\n ): FieldFilter {\n const reader = newUserDataReader(query.firestore);\n const filter = newQueryFilter(\n query._query,\n 'where',\n reader,\n query.firestore._databaseId,\n this._field,\n this._op,\n this._value\n );\n return filter;\n }\n}\n\n/**\n * Filter conditions in a {@link where} clause are specified using the\n * strings '<', '<=', '==', '!=', '>=', '>', 'array-contains', 'in',\n * 'array-contains-any', and 'not-in'.\n */\nexport type WhereFilterOp =\n | '<'\n | '<='\n | '=='\n | '!='\n | '>='\n | '>'\n | 'array-contains'\n | 'in'\n | 'array-contains-any'\n | 'not-in';\n\n/**\n * Creates a {@link QueryFieldFilterConstraint} that enforces that documents\n * must contain the specified field and that the value should satisfy the\n * relation constraint provided.\n *\n * @param fieldPath - The path to compare\n * @param opStr - The operation string (e.g \"<\", \"<=\", \"==\", \"<\",\n * \"<=\", \"!=\").\n * @param value - The value for comparison\n * @returns The created {@link QueryFieldFilterConstraint}.\n */\nexport function where(\n fieldPath: string | FieldPath,\n opStr: WhereFilterOp,\n value: unknown\n): QueryFieldFilterConstraint {\n const op = opStr as Operator;\n const field = fieldPathFromArgument('where', fieldPath);\n return QueryFieldFilterConstraint._create(field, op, value);\n}\n\n/**\n * A `QueryCompositeFilterConstraint` is used to narrow the set of documents\n * returned by a Firestore query by performing the logical OR or AND of multiple\n * {@link QueryFieldFilterConstraint}s or {@link QueryCompositeFilterConstraint}s.\n * `QueryCompositeFilterConstraint`s are created by invoking {@link or} or\n * {@link and} and can then be passed to {@link (query:1)} to create a new query\n * instance that also contains the `QueryCompositeFilterConstraint`.\n */\nexport class QueryCompositeFilterConstraint extends AppliableConstraint {\n /**\n * @internal\n */\n protected constructor(\n /** The type of this query constraint */\n readonly type: 'or' | 'and',\n private readonly _queryConstraints: QueryFilterConstraint[]\n ) {\n super();\n }\n\n static _create(\n type: 'or' | 'and',\n _queryConstraints: QueryFilterConstraint[]\n ): QueryCompositeFilterConstraint {\n return new QueryCompositeFilterConstraint(type, _queryConstraints);\n }\n\n _parse(\n query: Query\n ): Filter {\n const parsedFilters = this._queryConstraints\n .map(queryConstraint => {\n return queryConstraint._parse(query);\n })\n .filter(parsedFilter => parsedFilter.getFilters().length > 0);\n\n if (parsedFilters.length === 1) {\n return parsedFilters[0];\n }\n\n return CompositeFilter.create(parsedFilters, this._getOperator());\n }\n\n _apply(\n query: Query\n ): Query {\n const parsedFilter = this._parse(query);\n if (parsedFilter.getFilters().length === 0) {\n // Return the existing query if not adding any more filters (e.g. an empty\n // composite filter).\n return query;\n }\n validateNewFilter(query._query, parsedFilter);\n\n return new Query(\n query.firestore,\n query.converter,\n queryWithAddedFilter(query._query, parsedFilter)\n );\n }\n\n _getQueryConstraints(): readonly AppliableConstraint[] {\n return this._queryConstraints;\n }\n\n _getOperator(): CompositeOperator {\n return this.type === 'and' ? CompositeOperator.AND : CompositeOperator.OR;\n }\n}\n\n/**\n * `QueryNonFilterConstraint` is a helper union type that represents\n * QueryConstraints which are used to narrow or order the set of documents,\n * but that do not explicitly filter on a document field.\n * `QueryNonFilterConstraint`s are created by invoking {@link orderBy},\n * {@link (startAt:1)}, {@link (startAfter:1)}, {@link (endBefore:1)}, {@link (endAt:1)},\n * {@link limit} or {@link limitToLast} and can then be passed to {@link (query:1)}\n * to create a new query instance that also contains the `QueryConstraint`.\n */\nexport type QueryNonFilterConstraint =\n | QueryOrderByConstraint\n | QueryLimitConstraint\n | QueryStartAtConstraint\n | QueryEndAtConstraint;\n\n/**\n * `QueryFilterConstraint` is a helper union type that represents\n * {@link QueryFieldFilterConstraint} and {@link QueryCompositeFilterConstraint}.\n */\nexport type QueryFilterConstraint =\n | QueryFieldFilterConstraint\n | QueryCompositeFilterConstraint;\n\n/**\n * Creates a new {@link QueryCompositeFilterConstraint} that is a disjunction of\n * the given filter constraints. A disjunction filter includes a document if it\n * satisfies any of the given filters.\n *\n * @param queryConstraints - Optional. The list of\n * {@link QueryFilterConstraint}s to perform a disjunction for. These must be\n * created with calls to {@link where}, {@link or}, or {@link and}.\n * @returns The newly created {@link QueryCompositeFilterConstraint}.\n */\nexport function or(\n ...queryConstraints: QueryFilterConstraint[]\n): QueryCompositeFilterConstraint {\n // Only support QueryFilterConstraints\n queryConstraints.forEach(queryConstraint =>\n validateQueryFilterConstraint('or', queryConstraint)\n );\n\n return QueryCompositeFilterConstraint._create(\n CompositeOperator.OR,\n queryConstraints as QueryFilterConstraint[]\n );\n}\n\n/**\n * Creates a new {@link QueryCompositeFilterConstraint} that is a conjunction of\n * the given filter constraints. A conjunction filter includes a document if it\n * satisfies all of the given filters.\n *\n * @param queryConstraints - Optional. The list of\n * {@link QueryFilterConstraint}s to perform a conjunction for. These must be\n * created with calls to {@link where}, {@link or}, or {@link and}.\n * @returns The newly created {@link QueryCompositeFilterConstraint}.\n */\nexport function and(\n ...queryConstraints: QueryFilterConstraint[]\n): QueryCompositeFilterConstraint {\n // Only support QueryFilterConstraints\n queryConstraints.forEach(queryConstraint =>\n validateQueryFilterConstraint('and', queryConstraint)\n );\n\n return QueryCompositeFilterConstraint._create(\n CompositeOperator.AND,\n queryConstraints as QueryFilterConstraint[]\n );\n}\n\n/**\n * A `QueryOrderByConstraint` is used to sort the set of documents returned by a\n * Firestore query. `QueryOrderByConstraint`s are created by invoking\n * {@link orderBy} and can then be passed to {@link (query:1)} to create a new query\n * instance that also contains this `QueryOrderByConstraint`.\n *\n * Note: Documents that do not contain the orderBy field will not be present in\n * the query result.\n */\nexport class QueryOrderByConstraint extends QueryConstraint {\n /** The type of this query constraint */\n readonly type = 'orderBy';\n\n /**\n * @internal\n */\n protected constructor(\n private readonly _field: InternalFieldPath,\n private _direction: Direction\n ) {\n super();\n }\n\n static _create(\n _field: InternalFieldPath,\n _direction: Direction\n ): QueryOrderByConstraint {\n return new QueryOrderByConstraint(_field, _direction);\n }\n\n _apply(\n query: Query\n ): Query {\n const orderBy = newQueryOrderBy(query._query, this._field, this._direction);\n return new Query(\n query.firestore,\n query.converter,\n queryWithAddedOrderBy(query._query, orderBy)\n );\n }\n}\n\n/**\n * The direction of a {@link orderBy} clause is specified as 'desc' or 'asc'\n * (descending or ascending).\n */\nexport type OrderByDirection = 'desc' | 'asc';\n\n/**\n * Creates a {@link QueryOrderByConstraint} that sorts the query result by the\n * specified field, optionally in descending order instead of ascending.\n *\n * Note: Documents that do not contain the specified field will not be present\n * in the query result.\n *\n * @param fieldPath - The field to sort by.\n * @param directionStr - Optional direction to sort by ('asc' or 'desc'). If\n * not specified, order will be ascending.\n * @returns The created {@link QueryOrderByConstraint}.\n */\nexport function orderBy(\n fieldPath: string | FieldPath,\n directionStr: OrderByDirection = 'asc'\n): QueryOrderByConstraint {\n const direction = directionStr as Direction;\n const path = fieldPathFromArgument('orderBy', fieldPath);\n return QueryOrderByConstraint._create(path, direction);\n}\n\n/**\n * A `QueryLimitConstraint` is used to limit the number of documents returned by\n * a Firestore query.\n * `QueryLimitConstraint`s are created by invoking {@link limit} or\n * {@link limitToLast} and can then be passed to {@link (query:1)} to create a new\n * query instance that also contains this `QueryLimitConstraint`.\n */\nexport class QueryLimitConstraint extends QueryConstraint {\n /**\n * @internal\n */\n protected constructor(\n /** The type of this query constraint */\n readonly type: 'limit' | 'limitToLast',\n private readonly _limit: number,\n private readonly _limitType: LimitType\n ) {\n super();\n }\n\n static _create(\n type: 'limit' | 'limitToLast',\n _limit: number,\n _limitType: LimitType\n ): QueryLimitConstraint {\n return new QueryLimitConstraint(type, _limit, _limitType);\n }\n\n _apply(\n query: Query\n ): Query {\n return new Query(\n query.firestore,\n query.converter,\n queryWithLimit(query._query, this._limit, this._limitType)\n );\n }\n}\n\n/**\n * Creates a {@link QueryLimitConstraint} that only returns the first matching\n * documents.\n *\n * @param limit - The maximum number of items to return.\n * @returns The created {@link QueryLimitConstraint}.\n */\nexport function limit(limit: number): QueryLimitConstraint {\n validatePositiveNumber('limit', limit);\n return QueryLimitConstraint._create('limit', limit, LimitType.First);\n}\n\n/**\n * Creates a {@link QueryLimitConstraint} that only returns the last matching\n * documents.\n *\n * You must specify at least one `orderBy` clause for `limitToLast` queries,\n * otherwise an exception will be thrown during execution.\n *\n * @param limit - The maximum number of items to return.\n * @returns The created {@link QueryLimitConstraint}.\n */\nexport function limitToLast(limit: number): QueryLimitConstraint {\n validatePositiveNumber('limitToLast', limit);\n return QueryLimitConstraint._create('limitToLast', limit, LimitType.Last);\n}\n\n/**\n * A `QueryStartAtConstraint` is used to exclude documents from the start of a\n * result set returned by a Firestore query.\n * `QueryStartAtConstraint`s are created by invoking {@link (startAt:1)} or\n * {@link (startAfter:1)} and can then be passed to {@link (query:1)} to create a\n * new query instance that also contains this `QueryStartAtConstraint`.\n */\nexport class QueryStartAtConstraint extends QueryConstraint {\n /**\n * @internal\n */\n protected constructor(\n /** The type of this query constraint */\n readonly type: 'startAt' | 'startAfter',\n private readonly _docOrFields: Array>,\n private readonly _inclusive: boolean\n ) {\n super();\n }\n\n static _create(\n type: 'startAt' | 'startAfter',\n _docOrFields: Array>,\n _inclusive: boolean\n ): QueryStartAtConstraint {\n return new QueryStartAtConstraint(type, _docOrFields, _inclusive);\n }\n\n _apply(\n query: Query\n ): Query {\n const bound = newQueryBoundFromDocOrFields(\n query,\n this.type,\n this._docOrFields,\n this._inclusive\n );\n return new Query(\n query.firestore,\n query.converter,\n queryWithStartAt(query._query, bound)\n );\n }\n}\n\n/**\n * Creates a {@link QueryStartAtConstraint} that modifies the result set to\n * start at the provided document (inclusive). The starting position is relative\n * to the order of the query. The document must contain all of the fields\n * provided in the `orderBy` of this query.\n *\n * @param snapshot - The snapshot of the document to start at.\n * @returns A {@link QueryStartAtConstraint} to pass to `query()`.\n */\nexport function startAt(\n snapshot: DocumentSnapshot\n): QueryStartAtConstraint;\n/**\n * Creates a {@link QueryStartAtConstraint} that modifies the result set to\n * start at the provided fields relative to the order of the query. The order of\n * the field values must match the order of the order by clauses of the query.\n *\n * @param fieldValues - The field values to start this query at, in order\n * of the query's order by.\n * @returns A {@link QueryStartAtConstraint} to pass to `query()`.\n */\nexport function startAt(...fieldValues: unknown[]): QueryStartAtConstraint;\nexport function startAt(\n ...docOrFields: Array>\n): QueryStartAtConstraint {\n return QueryStartAtConstraint._create(\n 'startAt',\n docOrFields,\n /*inclusive=*/ true\n );\n}\n\n/**\n * Creates a {@link QueryStartAtConstraint} that modifies the result set to\n * start after the provided document (exclusive). The starting position is\n * relative to the order of the query. The document must contain all of the\n * fields provided in the orderBy of the query.\n *\n * @param snapshot - The snapshot of the document to start after.\n * @returns A {@link QueryStartAtConstraint} to pass to `query()`\n */\nexport function startAfter(\n snapshot: DocumentSnapshot\n): QueryStartAtConstraint;\n/**\n * Creates a {@link QueryStartAtConstraint} that modifies the result set to\n * start after the provided fields relative to the order of the query. The order\n * of the field values must match the order of the order by clauses of the query.\n *\n * @param fieldValues - The field values to start this query after, in order\n * of the query's order by.\n * @returns A {@link QueryStartAtConstraint} to pass to `query()`\n */\nexport function startAfter(...fieldValues: unknown[]): QueryStartAtConstraint;\nexport function startAfter(\n ...docOrFields: Array>\n): QueryStartAtConstraint {\n return QueryStartAtConstraint._create(\n 'startAfter',\n docOrFields,\n /*inclusive=*/ false\n );\n}\n\n/**\n * A `QueryEndAtConstraint` is used to exclude documents from the end of a\n * result set returned by a Firestore query.\n * `QueryEndAtConstraint`s are created by invoking {@link (endAt:1)} or\n * {@link (endBefore:1)} and can then be passed to {@link (query:1)} to create a new\n * query instance that also contains this `QueryEndAtConstraint`.\n */\nexport class QueryEndAtConstraint extends QueryConstraint {\n /**\n * @internal\n */\n protected constructor(\n /** The type of this query constraint */\n readonly type: 'endBefore' | 'endAt',\n private readonly _docOrFields: Array>,\n private readonly _inclusive: boolean\n ) {\n super();\n }\n\n static _create(\n type: 'endBefore' | 'endAt',\n _docOrFields: Array>,\n _inclusive: boolean\n ): QueryEndAtConstraint {\n return new QueryEndAtConstraint(type, _docOrFields, _inclusive);\n }\n\n _apply(\n query: Query\n ): Query {\n const bound = newQueryBoundFromDocOrFields(\n query,\n this.type,\n this._docOrFields,\n this._inclusive\n );\n return new Query(\n query.firestore,\n query.converter,\n queryWithEndAt(query._query, bound)\n );\n }\n}\n\n/**\n * Creates a {@link QueryEndAtConstraint} that modifies the result set to end\n * before the provided document (exclusive). The end position is relative to the\n * order of the query. The document must contain all of the fields provided in\n * the orderBy of the query.\n *\n * @param snapshot - The snapshot of the document to end before.\n * @returns A {@link QueryEndAtConstraint} to pass to `query()`\n */\nexport function endBefore(\n snapshot: DocumentSnapshot\n): QueryEndAtConstraint;\n/**\n * Creates a {@link QueryEndAtConstraint} that modifies the result set to end\n * before the provided fields relative to the order of the query. The order of\n * the field values must match the order of the order by clauses of the query.\n *\n * @param fieldValues - The field values to end this query before, in order\n * of the query's order by.\n * @returns A {@link QueryEndAtConstraint} to pass to `query()`\n */\nexport function endBefore(...fieldValues: unknown[]): QueryEndAtConstraint;\nexport function endBefore(\n ...docOrFields: Array>\n): QueryEndAtConstraint {\n return QueryEndAtConstraint._create(\n 'endBefore',\n docOrFields,\n /*inclusive=*/ false\n );\n}\n\n/**\n * Creates a {@link QueryEndAtConstraint} that modifies the result set to end at\n * the provided document (inclusive). The end position is relative to the order\n * of the query. The document must contain all of the fields provided in the\n * orderBy of the query.\n *\n * @param snapshot - The snapshot of the document to end at.\n * @returns A {@link QueryEndAtConstraint} to pass to `query()`\n */\nexport function endAt(\n snapshot: DocumentSnapshot\n): QueryEndAtConstraint;\n/**\n * Creates a {@link QueryEndAtConstraint} that modifies the result set to end at\n * the provided fields relative to the order of the query. The order of the field\n * values must match the order of the order by clauses of the query.\n *\n * @param fieldValues - The field values to end this query at, in order\n * of the query's order by.\n * @returns A {@link QueryEndAtConstraint} to pass to `query()`\n */\nexport function endAt(...fieldValues: unknown[]): QueryEndAtConstraint;\nexport function endAt(\n ...docOrFields: Array>\n): QueryEndAtConstraint {\n return QueryEndAtConstraint._create(\n 'endAt',\n docOrFields,\n /*inclusive=*/ true\n );\n}\n\n/** Helper function to create a bound from a document or fields */\nfunction newQueryBoundFromDocOrFields<\n AppModelType,\n DbModelType extends DocumentData\n>(\n query: Query,\n methodName: string,\n docOrFields: Array>,\n inclusive: boolean\n): Bound {\n docOrFields[0] = getModularInstance(docOrFields[0]);\n\n if (docOrFields[0] instanceof DocumentSnapshot) {\n return newQueryBoundFromDocument(\n query._query,\n query.firestore._databaseId,\n methodName,\n docOrFields[0]._document,\n inclusive\n );\n } else {\n const reader = newUserDataReader(query.firestore);\n return newQueryBoundFromFields(\n query._query,\n query.firestore._databaseId,\n reader,\n methodName,\n docOrFields,\n inclusive\n );\n }\n}\n\nexport function newQueryFilter(\n query: InternalQuery,\n methodName: string,\n dataReader: UserDataReader,\n databaseId: DatabaseId,\n fieldPath: InternalFieldPath,\n op: Operator,\n value: unknown\n): FieldFilter {\n let fieldValue: ProtoValue;\n if (fieldPath.isKeyField()) {\n if (op === Operator.ARRAY_CONTAINS || op === Operator.ARRAY_CONTAINS_ANY) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid Query. You can't perform '${op}' queries on documentId().`\n );\n } else if (op === Operator.IN || op === Operator.NOT_IN) {\n validateDisjunctiveFilterElements(value, op);\n const referenceList: ProtoValue[] = [];\n for (const arrayValue of value as ProtoValue[]) {\n referenceList.push(parseDocumentIdValue(databaseId, query, arrayValue));\n }\n fieldValue = { arrayValue: { values: referenceList } };\n } else {\n fieldValue = parseDocumentIdValue(databaseId, query, value);\n }\n } else {\n if (\n op === Operator.IN ||\n op === Operator.NOT_IN ||\n op === Operator.ARRAY_CONTAINS_ANY\n ) {\n validateDisjunctiveFilterElements(value, op);\n }\n fieldValue = parseQueryValue(\n dataReader,\n methodName,\n value,\n /* allowArrays= */ op === Operator.IN || op === Operator.NOT_IN\n );\n }\n const filter = FieldFilter.create(fieldPath, op, fieldValue);\n return filter;\n}\n\nexport function newQueryOrderBy(\n query: InternalQuery,\n fieldPath: InternalFieldPath,\n direction: Direction\n): OrderBy {\n if (query.startAt !== null) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Invalid query. You must not call startAt() or startAfter() before ' +\n 'calling orderBy().'\n );\n }\n if (query.endAt !== null) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Invalid query. You must not call endAt() or endBefore() before ' +\n 'calling orderBy().'\n );\n }\n const orderBy = new OrderBy(fieldPath, direction);\n return orderBy;\n}\n\n/**\n * Create a `Bound` from a query and a document.\n *\n * Note that the `Bound` will always include the key of the document\n * and so only the provided document will compare equal to the returned\n * position.\n *\n * Will throw if the document does not contain all fields of the order by\n * of the query or if any of the fields in the order by are an uncommitted\n * server timestamp.\n */\nexport function newQueryBoundFromDocument(\n query: InternalQuery,\n databaseId: DatabaseId,\n methodName: string,\n doc: Document | null,\n inclusive: boolean\n): Bound {\n if (!doc) {\n throw new FirestoreError(\n Code.NOT_FOUND,\n `Can't use a DocumentSnapshot that doesn't exist for ` +\n `${methodName}().`\n );\n }\n\n const components: ProtoValue[] = [];\n\n // Because people expect to continue/end a query at the exact document\n // provided, we need to use the implicit sort order rather than the explicit\n // sort order, because it's guaranteed to contain the document key. That way\n // the position becomes unambiguous and the query continues/ends exactly at\n // the provided document. Without the key (by using the explicit sort\n // orders), multiple documents could match the position, yielding duplicate\n // results.\n for (const orderBy of queryNormalizedOrderBy(query)) {\n if (orderBy.field.isKeyField()) {\n components.push(refValue(databaseId, doc.key));\n } else {\n const value = doc.data.field(orderBy.field);\n if (isServerTimestamp(value)) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Invalid query. You are trying to start or end a query using a ' +\n 'document for which the field \"' +\n orderBy.field +\n '\" is an uncommitted server timestamp. (Since the value of ' +\n 'this field is unknown, you cannot start/end a query with it.)'\n );\n } else if (value !== null) {\n components.push(value);\n } else {\n const field = orderBy.field.canonicalString();\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid query. You are trying to start or end a query using a ` +\n `document for which the field '${field}' (used as the ` +\n `orderBy) does not exist.`\n );\n }\n }\n }\n return new Bound(components, inclusive);\n}\n\n/**\n * Converts a list of field values to a `Bound` for the given query.\n */\nexport function newQueryBoundFromFields(\n query: InternalQuery,\n databaseId: DatabaseId,\n dataReader: UserDataReader,\n methodName: string,\n values: unknown[],\n inclusive: boolean\n): Bound {\n // Use explicit order by's because it has to match the query the user made\n const orderBy = query.explicitOrderBy;\n if (values.length > orderBy.length) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Too many arguments provided to ${methodName}(). ` +\n `The number of arguments must be less than or equal to the ` +\n `number of orderBy() clauses`\n );\n }\n\n const components: ProtoValue[] = [];\n for (let i = 0; i < values.length; i++) {\n const rawValue = values[i];\n const orderByComponent = orderBy[i];\n if (orderByComponent.field.isKeyField()) {\n if (typeof rawValue !== 'string') {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid query. Expected a string for document ID in ` +\n `${methodName}(), but got a ${typeof rawValue}`\n );\n }\n if (!isCollectionGroupQuery(query) && rawValue.indexOf('/') !== -1) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid query. When querying a collection and ordering by documentId(), ` +\n `the value passed to ${methodName}() must be a plain document ID, but ` +\n `'${rawValue}' contains a slash.`\n );\n }\n const path = query.path.child(ResourcePath.fromString(rawValue));\n if (!DocumentKey.isDocumentKey(path)) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid query. When querying a collection group and ordering by ` +\n `documentId(), the value passed to ${methodName}() must result in a ` +\n `valid document path, but '${path}' is not because it contains an odd number ` +\n `of segments.`\n );\n }\n const key = new DocumentKey(path);\n components.push(refValue(databaseId, key));\n } else {\n const wrapped = parseQueryValue(dataReader, methodName, rawValue);\n components.push(wrapped);\n }\n }\n\n return new Bound(components, inclusive);\n}\n\n/**\n * Parses the given `documentIdValue` into a `ReferenceValue`, throwing\n * appropriate errors if the value is anything other than a `DocumentReference`\n * or `string`, or if the string is malformed.\n */\nfunction parseDocumentIdValue(\n databaseId: DatabaseId,\n query: InternalQuery,\n documentIdValue: unknown\n): ProtoValue {\n documentIdValue = getModularInstance(documentIdValue);\n\n if (typeof documentIdValue === 'string') {\n if (documentIdValue === '') {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Invalid query. When querying with documentId(), you ' +\n 'must provide a valid document ID, but it was an empty string.'\n );\n }\n if (!isCollectionGroupQuery(query) && documentIdValue.indexOf('/') !== -1) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid query. When querying a collection by ` +\n `documentId(), you must provide a plain document ID, but ` +\n `'${documentIdValue}' contains a '/' character.`\n );\n }\n const path = query.path.child(ResourcePath.fromString(documentIdValue));\n if (!DocumentKey.isDocumentKey(path)) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid query. When querying a collection group by ` +\n `documentId(), the value provided must result in a valid document path, ` +\n `but '${path}' is not because it has an odd number of segments (${path.length}).`\n );\n }\n return refValue(databaseId, new DocumentKey(path));\n } else if (documentIdValue instanceof DocumentReference) {\n return refValue(databaseId, documentIdValue._key);\n } else {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid query. When querying with documentId(), you must provide a valid ` +\n `string or a DocumentReference, but it was: ` +\n `${valueDescription(documentIdValue)}.`\n );\n }\n}\n\n/**\n * Validates that the value passed into a disjunctive filter satisfies all\n * array requirements.\n */\nfunction validateDisjunctiveFilterElements(\n value: unknown,\n operator: Operator\n): void {\n if (!Array.isArray(value) || value.length === 0) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Invalid Query. A non-empty array is required for ' +\n `'${operator.toString()}' filters.`\n );\n }\n}\n\n/**\n * Given an operator, returns the set of operators that cannot be used with it.\n *\n * This is not a comprehensive check, and this function should be removed in the\n * long term. Validations should occur in the Firestore backend.\n *\n * Operators in a query must adhere to the following set of rules:\n * 1. Only one inequality per query.\n * 2. `NOT_IN` cannot be used with array, disjunctive, or `NOT_EQUAL` operators.\n */\nfunction conflictingOps(op: Operator): Operator[] {\n switch (op) {\n case Operator.NOT_EQUAL:\n return [Operator.NOT_EQUAL, Operator.NOT_IN];\n case Operator.ARRAY_CONTAINS_ANY:\n case Operator.IN:\n return [Operator.NOT_IN];\n case Operator.NOT_IN:\n return [\n Operator.ARRAY_CONTAINS_ANY,\n Operator.IN,\n Operator.NOT_IN,\n Operator.NOT_EQUAL\n ];\n default:\n return [];\n }\n}\n\nfunction validateNewFieldFilter(\n query: InternalQuery,\n fieldFilter: FieldFilter\n): void {\n const conflictingOp = findOpInsideFilters(\n query.filters,\n conflictingOps(fieldFilter.op)\n );\n if (conflictingOp !== null) {\n // Special case when it's a duplicate op to give a slightly clearer error message.\n if (conflictingOp === fieldFilter.op) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Invalid query. You cannot use more than one ' +\n `'${fieldFilter.op.toString()}' filter.`\n );\n } else {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid query. You cannot use '${fieldFilter.op.toString()}' filters ` +\n `with '${conflictingOp.toString()}' filters.`\n );\n }\n }\n}\n\nfunction validateNewFilter(query: InternalQuery, filter: Filter): void {\n let testQuery = query;\n const subFilters = filter.getFlattenedFilters();\n for (const subFilter of subFilters) {\n validateNewFieldFilter(testQuery, subFilter);\n testQuery = queryWithAddedFilter(testQuery, subFilter);\n }\n}\n\n// Checks if any of the provided filter operators are included in the given list of filters and\n// returns the first one that is, or null if none are.\nfunction findOpInsideFilters(\n filters: Filter[],\n operators: Operator[]\n): Operator | null {\n for (const filter of filters) {\n for (const fieldFilter of filter.getFlattenedFilters()) {\n if (operators.indexOf(fieldFilter.op) >= 0) {\n return fieldFilter.op;\n }\n }\n }\n return null;\n}\n\nexport function validateQueryFilterConstraint(\n functionName: string,\n queryConstraint: AppliableConstraint\n): void {\n if (\n !(queryConstraint instanceof QueryFieldFilterConstraint) &&\n !(queryConstraint instanceof QueryCompositeFilterConstraint)\n ) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Function ${functionName}() requires AppliableConstraints created with a call to 'where(...)', 'or(...)', or 'and(...)'.`\n );\n }\n}\n\nfunction validateQueryConstraintArray(\n queryConstraint: AppliableConstraint[]\n): void {\n const compositeFilterCount = queryConstraint.filter(\n filter => filter instanceof QueryCompositeFilterConstraint\n ).length;\n const fieldFilterCount = queryConstraint.filter(\n filter => filter instanceof QueryFieldFilterConstraint\n ).length;\n\n if (\n compositeFilterCount > 1 ||\n (compositeFilterCount > 0 && fieldFilterCount > 0)\n ) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'InvalidQuery. When using composite filters, you cannot use ' +\n 'more than one filter at the top level. Consider nesting the multiple ' +\n 'filters within an `and(...)` statement. For example: ' +\n 'change `query(query, where(...), or(...))` to ' +\n '`query(query, and(where(...), or(...)))`.'\n );\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DocumentData } from '@firebase/firestore-types';\n\nimport { DatabaseId } from '../core/database_info';\nimport { DocumentKey } from '../model/document_key';\nimport {\n normalizeByteString,\n normalizeNumber,\n normalizeTimestamp\n} from '../model/normalize';\nimport { ResourcePath } from '../model/path';\nimport {\n getLocalWriteTime,\n getPreviousValue\n} from '../model/server_timestamps';\nimport { TypeOrder } from '../model/type_order';\nimport { VECTOR_MAP_VECTORS_KEY, typeOrder } from '../model/values';\nimport {\n ApiClientObjectMap,\n ArrayValue as ProtoArrayValue,\n LatLng as ProtoLatLng,\n MapValue as ProtoMapValue,\n Timestamp as ProtoTimestamp,\n Value,\n Value as ProtoValue\n} from '../protos/firestore_proto_api';\nimport { isValidResourceName } from '../remote/serializer';\nimport { fail, hardAssert } from '../util/assert';\nimport { ByteString } from '../util/byte_string';\nimport { logError } from '../util/log';\nimport { forEach } from '../util/obj';\n\nimport { GeoPoint } from './geo_point';\nimport { Timestamp } from './timestamp';\nimport { VectorValue } from './vector_value';\n\nexport type ServerTimestampBehavior = 'estimate' | 'previous' | 'none';\n\n/**\n * Converts Firestore's internal types to the JavaScript types that we expose\n * to the user.\n *\n * @internal\n */\nexport abstract class AbstractUserDataWriter {\n convertValue(\n value: ProtoValue,\n serverTimestampBehavior: ServerTimestampBehavior = 'none'\n ): unknown {\n switch (typeOrder(value)) {\n case TypeOrder.NullValue:\n return null;\n case TypeOrder.BooleanValue:\n return value.booleanValue!;\n case TypeOrder.NumberValue:\n return normalizeNumber(value.integerValue || value.doubleValue);\n case TypeOrder.TimestampValue:\n return this.convertTimestamp(value.timestampValue!);\n case TypeOrder.ServerTimestampValue:\n return this.convertServerTimestamp(value, serverTimestampBehavior);\n case TypeOrder.StringValue:\n return value.stringValue!;\n case TypeOrder.BlobValue:\n return this.convertBytes(normalizeByteString(value.bytesValue!));\n case TypeOrder.RefValue:\n return this.convertReference(value.referenceValue!);\n case TypeOrder.GeoPointValue:\n return this.convertGeoPoint(value.geoPointValue!);\n case TypeOrder.ArrayValue:\n return this.convertArray(value.arrayValue!, serverTimestampBehavior);\n case TypeOrder.ObjectValue:\n return this.convertObject(value.mapValue!, serverTimestampBehavior);\n case TypeOrder.VectorValue:\n return this.convertVectorValue(value.mapValue!);\n default:\n throw fail(0xf2a2, 'Invalid value type', {\n value\n });\n }\n }\n\n private convertObject(\n mapValue: ProtoMapValue,\n serverTimestampBehavior: ServerTimestampBehavior\n ): DocumentData {\n return this.convertObjectMap(mapValue.fields, serverTimestampBehavior);\n }\n\n /**\n * @internal\n */\n convertObjectMap(\n fields: ApiClientObjectMap | undefined,\n serverTimestampBehavior: ServerTimestampBehavior = 'none'\n ): DocumentData {\n const result: DocumentData = {};\n forEach(fields, (key, value) => {\n result[key] = this.convertValue(value, serverTimestampBehavior);\n });\n return result;\n }\n\n /**\n * @internal\n */\n convertVectorValue(mapValue: ProtoMapValue): VectorValue {\n const values = mapValue.fields?.[\n VECTOR_MAP_VECTORS_KEY\n ].arrayValue?.values?.map(value => {\n return normalizeNumber(value.doubleValue);\n });\n\n return new VectorValue(values);\n }\n\n private convertGeoPoint(value: ProtoLatLng): GeoPoint {\n return new GeoPoint(\n normalizeNumber(value.latitude),\n normalizeNumber(value.longitude)\n );\n }\n\n private convertArray(\n arrayValue: ProtoArrayValue,\n serverTimestampBehavior: ServerTimestampBehavior\n ): unknown[] {\n return (arrayValue.values || []).map(value =>\n this.convertValue(value, serverTimestampBehavior)\n );\n }\n\n private convertServerTimestamp(\n value: ProtoValue,\n serverTimestampBehavior: ServerTimestampBehavior\n ): unknown {\n switch (serverTimestampBehavior) {\n case 'previous':\n const previousValue = getPreviousValue(value);\n if (previousValue == null) {\n return null;\n }\n return this.convertValue(previousValue, serverTimestampBehavior);\n case 'estimate':\n return this.convertTimestamp(getLocalWriteTime(value));\n default:\n return null;\n }\n }\n\n private convertTimestamp(value: ProtoTimestamp): Timestamp {\n const normalizedValue = normalizeTimestamp(value);\n return new Timestamp(normalizedValue.seconds, normalizedValue.nanos);\n }\n\n protected convertDocumentKey(\n name: string,\n expectedDatabaseId: DatabaseId\n ): DocumentKey {\n const resourcePath = ResourcePath.fromString(name);\n hardAssert(\n isValidResourceName(resourcePath),\n 0x25d8,\n 'ReferenceValue is not valid',\n { name }\n );\n const databaseId = new DatabaseId(resourcePath.get(1), resourcePath.get(3));\n const key = new DocumentKey(resourcePath.popFirst(5));\n\n if (!databaseId.isEqual(expectedDatabaseId)) {\n // TODO(b/64130202): Somehow support foreign references.\n logError(\n `Document ${key} contains a document ` +\n `reference within a different database (` +\n `${databaseId.projectId}/${databaseId.database}) which is not ` +\n `supported. It will be treated as a reference in the current ` +\n `database (${expectedDatabaseId.projectId}/${expectedDatabaseId.database}) ` +\n `instead.`\n );\n }\n return key;\n }\n\n protected abstract convertReference(name: string): unknown;\n\n protected abstract convertBytes(bytes: ByteString): unknown;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n DocumentData as PublicDocumentData,\n SetOptions as PublicSetOptions\n} from '@firebase/firestore-types';\nimport { getModularInstance } from '@firebase/util';\n\nimport { LimitType } from '../core/query';\nimport { DeleteMutation, Precondition } from '../model/mutation';\nimport {\n invokeBatchGetDocumentsRpc,\n invokeCommitRpc,\n invokeRunQueryRpc\n} from '../remote/datastore';\nimport { hardAssert } from '../util/assert';\nimport { ByteString } from '../util/byte_string';\nimport { cast } from '../util/input_validation';\n\nimport { Bytes } from './bytes';\nimport { getDatastore } from './components';\nimport { Firestore } from './database';\nimport { FieldPath } from './field_path';\nimport { validateHasExplicitOrderByForLimitToLast } from './query';\nimport {\n CollectionReference,\n doc,\n DocumentData,\n DocumentReference,\n PartialWithFieldValue,\n Query,\n SetOptions,\n UpdateData,\n WithFieldValue\n} from './reference';\nimport {\n DocumentSnapshot,\n QueryDocumentSnapshot,\n QuerySnapshot\n} from './snapshot';\nimport {\n newUserDataReader,\n ParsedUpdateData,\n parseSetData,\n parseUpdateData,\n parseUpdateVarargs,\n UntypedFirestoreDataConverter\n} from './user_data_reader';\nimport { AbstractUserDataWriter } from './user_data_writer';\n\n/**\n * Converts custom model object of type T into `DocumentData` by applying the\n * converter if it exists.\n *\n * This function is used when converting user objects to `DocumentData`\n * because we want to provide the user with a more specific error message if\n * their `set()` or fails due to invalid data originating from a `toFirestore()`\n * call.\n */\nexport function applyFirestoreDataConverter(\n converter: UntypedFirestoreDataConverter | null,\n value: WithFieldValue | PartialWithFieldValue,\n options?: PublicSetOptions\n): PublicDocumentData {\n let convertedValue;\n if (converter) {\n if (options && (options.merge || options.mergeFields)) {\n // Cast to `any` in order to satisfy the union type constraint on\n // toFirestore().\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n convertedValue = (converter as any).toFirestore(value, options);\n } else {\n convertedValue = converter.toFirestore(value as WithFieldValue);\n }\n } else {\n convertedValue = value as PublicDocumentData;\n }\n return convertedValue;\n}\n\nexport class LiteUserDataWriter extends AbstractUserDataWriter {\n constructor(protected firestore: Firestore) {\n super();\n }\n\n protected convertBytes(bytes: ByteString): Bytes {\n return new Bytes(bytes);\n }\n\n protected convertReference(name: string): DocumentReference {\n const key = this.convertDocumentKey(name, this.firestore._databaseId);\n return new DocumentReference(this.firestore, /* converter= */ null, key);\n }\n}\n\n/**\n * Reads the document referred to by the specified document reference.\n *\n * All documents are directly fetched from the server, even if the document was\n * previously read or modified. Recent modifications are only reflected in the\n * retrieved `DocumentSnapshot` if they have already been applied by the\n * backend. If the client is offline, the read fails. If you like to use\n * caching or see local modifications, please use the full Firestore SDK.\n *\n * @param reference - The reference of the document to fetch.\n * @returns A Promise resolved with a `DocumentSnapshot` containing the current\n * document contents.\n */\nexport function getDoc(\n reference: DocumentReference\n): Promise> {\n reference = cast>(\n reference,\n DocumentReference\n );\n const datastore = getDatastore(reference.firestore);\n const userDataWriter = new LiteUserDataWriter(reference.firestore);\n\n return invokeBatchGetDocumentsRpc(datastore, [reference._key]).then(\n result => {\n hardAssert(\n result.length === 1,\n 0x3d02,\n 'Expected a single document result'\n );\n const document = result[0];\n return new DocumentSnapshot(\n reference.firestore,\n userDataWriter,\n reference._key,\n document.isFoundDocument() ? document : null,\n reference.converter\n );\n }\n );\n}\n\n/**\n * Executes the query and returns the results as a {@link QuerySnapshot}.\n *\n * All queries are executed directly by the server, even if the query was\n * previously executed. Recent modifications are only reflected in the retrieved\n * results if they have already been applied by the backend. If the client is\n * offline, the operation fails. To see previously cached result and local\n * modifications, use the full Firestore SDK.\n *\n * @param query - The `Query` to execute.\n * @returns A Promise that will be resolved with the results of the query.\n */\nexport function getDocs(\n query: Query\n): Promise> {\n query = cast>(query, Query);\n validateHasExplicitOrderByForLimitToLast(query._query);\n\n const datastore = getDatastore(query.firestore);\n const userDataWriter = new LiteUserDataWriter(query.firestore);\n return invokeRunQueryRpc(datastore, query._query).then(result => {\n const docs = result.map(\n doc =>\n new QueryDocumentSnapshot(\n query.firestore,\n userDataWriter,\n doc.key,\n doc,\n query.converter\n )\n );\n\n if (query._query.limitType === LimitType.Last) {\n // Limit to last queries reverse the orderBy constraint that was\n // specified by the user. As such, we need to reverse the order of the\n // results to return the documents in the expected order.\n docs.reverse();\n }\n\n return new QuerySnapshot(query, docs);\n });\n}\n\n/**\n * Writes to the document referred to by the specified `DocumentReference`. If\n * the document does not yet exist, it will be created.\n *\n * The result of this write will only be reflected in document reads that occur\n * after the returned promise resolves. If the client is offline, the\n * write fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the document to write.\n * @param data - A map of the fields and values for the document.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns A `Promise` resolved once the data has been successfully written\n * to the backend.\n */\nexport function setDoc(\n reference: DocumentReference,\n data: WithFieldValue\n): Promise;\n/**\n * Writes to the document referred to by the specified `DocumentReference`. If\n * the document does not yet exist, it will be created. If you provide `merge`\n * or `mergeFields`, the provided data can be merged into an existing document.\n *\n * The result of this write will only be reflected in document reads that occur\n * after the returned promise resolves. If the client is offline, the\n * write fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the document to write.\n * @param data - A map of the fields and values for the document.\n * @param options - An object to configure the set behavior.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns A `Promise` resolved once the data has been successfully written\n * to the backend.\n */\nexport function setDoc(\n reference: DocumentReference,\n data: PartialWithFieldValue,\n options: SetOptions\n): Promise;\nexport function setDoc(\n reference: DocumentReference,\n data: PartialWithFieldValue,\n options?: SetOptions\n): Promise {\n reference = cast>(\n reference,\n DocumentReference\n );\n const convertedValue = applyFirestoreDataConverter(\n reference.converter,\n data,\n options\n );\n const dataReader = newUserDataReader(reference.firestore);\n const parsed = parseSetData(\n dataReader,\n 'setDoc',\n reference._key,\n convertedValue,\n reference.converter !== null,\n options\n );\n\n const datastore = getDatastore(reference.firestore);\n return invokeCommitRpc(datastore, [\n parsed.toMutation(reference._key, Precondition.none())\n ]);\n}\n\n/**\n * Updates fields in the document referred to by the specified\n * `DocumentReference`. The update will fail if applied to a document that does\n * not exist.\n *\n * The result of this update will only be reflected in document reads that occur\n * after the returned promise resolves. If the client is offline, the\n * update fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the document to update.\n * @param data - An object containing the fields and values with which to\n * update the document. Fields can contain dots to reference nested fields\n * within the document.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns A `Promise` resolved once the data has been successfully written\n * to the backend.\n */\nexport function updateDoc(\n reference: DocumentReference,\n data: UpdateData\n): Promise;\n/**\n * Updates fields in the document referred to by the specified\n * `DocumentReference` The update will fail if applied to a document that does\n * not exist.\n *\n * Nested fields can be updated by providing dot-separated field path\n * strings or by providing `FieldPath` objects.\n *\n * The result of this update will only be reflected in document reads that occur\n * after the returned promise resolves. If the client is offline, the\n * update fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the document to update.\n * @param field - The first field to update.\n * @param value - The first value.\n * @param moreFieldsAndValues - Additional key value pairs.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns A `Promise` resolved once the data has been successfully written\n * to the backend.\n */\nexport function updateDoc(\n reference: DocumentReference,\n field: string | FieldPath,\n value: unknown,\n ...moreFieldsAndValues: unknown[]\n): Promise;\nexport function updateDoc(\n reference: DocumentReference,\n fieldOrUpdateData: string | FieldPath | UpdateData,\n value?: unknown,\n ...moreFieldsAndValues: unknown[]\n): Promise {\n reference = cast>(\n reference,\n DocumentReference\n );\n const dataReader = newUserDataReader(reference.firestore);\n\n // For Compat types, we have to \"extract\" the underlying types before\n // performing validation.\n fieldOrUpdateData = getModularInstance(fieldOrUpdateData);\n\n let parsed: ParsedUpdateData;\n if (\n typeof fieldOrUpdateData === 'string' ||\n fieldOrUpdateData instanceof FieldPath\n ) {\n parsed = parseUpdateVarargs(\n dataReader,\n 'updateDoc',\n reference._key,\n fieldOrUpdateData,\n value,\n moreFieldsAndValues\n );\n } else {\n parsed = parseUpdateData(\n dataReader,\n 'updateDoc',\n reference._key,\n fieldOrUpdateData\n );\n }\n\n const datastore = getDatastore(reference.firestore);\n return invokeCommitRpc(datastore, [\n parsed.toMutation(reference._key, Precondition.exists(true))\n ]);\n}\n\n/**\n * Deletes the document referred to by the specified `DocumentReference`.\n *\n * The deletion will only be reflected in document reads that occur after the\n * returned promise resolves. If the client is offline, the\n * delete fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the document to delete.\n * @returns A `Promise` resolved once the document has been successfully\n * deleted from the backend.\n */\nexport function deleteDoc(\n reference: DocumentReference\n): Promise {\n reference = cast>(\n reference,\n DocumentReference\n );\n const datastore = getDatastore(reference.firestore);\n return invokeCommitRpc(datastore, [\n new DeleteMutation(reference._key, Precondition.none())\n ]);\n}\n\n/**\n * Add a new document to specified `CollectionReference` with the given data,\n * assigning it a document ID automatically.\n *\n * The result of this write will only be reflected in document reads that occur\n * after the returned promise resolves. If the client is offline, the\n * write fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the collection to add this document to.\n * @param data - An Object containing the data for the new document.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns A `Promise` resolved with a `DocumentReference` pointing to the\n * newly created document after it has been written to the backend.\n */\nexport function addDoc(\n reference: CollectionReference,\n data: WithFieldValue\n): Promise> {\n reference = cast>(\n reference,\n CollectionReference\n );\n const docRef = doc(reference);\n\n const convertedValue = applyFirestoreDataConverter(\n reference.converter,\n data as PartialWithFieldValue\n );\n\n const dataReader = newUserDataReader(reference.firestore);\n const parsed = parseSetData(\n dataReader,\n 'addDoc',\n docRef._key,\n convertedValue,\n docRef.converter !== null,\n {}\n );\n\n const datastore = getDatastore(reference.firestore);\n return invokeCommitRpc(datastore, [\n parsed.toMutation(docRef._key, Precondition.exists(false))\n ]).then(() => docRef);\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { deepEqual } from '@firebase/util';\n\nimport { AggregateImpl } from '../core/aggregate';\nimport { ApiClientObjectMap, Value } from '../protos/firestore_proto_api';\nimport { invokeRunAggregationQueryRpc } from '../remote/datastore';\nimport { cast } from '../util/input_validation';\nimport { mapToArray } from '../util/obj';\n\nimport {\n AggregateField,\n AggregateQuerySnapshot,\n AggregateSpec\n} from './aggregate_types';\nimport { getDatastore } from './components';\nimport { Firestore } from './database';\nimport { FieldPath } from './field_path';\nimport { DocumentData, Query, queryEqual } from './reference';\nimport { LiteUserDataWriter } from './reference_impl';\nimport { fieldPathFromArgument } from './user_data_reader';\n\n/**\n * Calculates the number of documents in the result set of the given query\n * without actually downloading the documents.\n *\n * Using this function to count the documents is efficient because only the\n * final count, not the documents' data, is downloaded. This function can\n * count the documents in cases where the result set is prohibitively large to\n * download entirely (thousands of documents).\n *\n * @param query The query whose result set size is calculated.\n * @returns A Promise that will be resolved with the count; the count can be\n * retrieved from `snapshot.data().count`, where `snapshot` is the\n * `AggregateQuerySnapshot` to which the returned Promise resolves.\n */\nexport function getCount(\n query: Query\n): Promise<\n AggregateQuerySnapshot<\n { count: AggregateField },\n AppModelType,\n DbModelType\n >\n> {\n const countQuerySpec: { count: AggregateField } = {\n count: count()\n };\n\n return getAggregate(query, countQuerySpec);\n}\n\n/**\n * Calculates the specified aggregations over the documents in the result\n * set of the given query without actually downloading the documents.\n *\n * Using this function to perform aggregations is efficient because only the\n * final aggregation values, not the documents' data, are downloaded. This\n * function can perform aggregations of the documents in cases where the result\n * set is prohibitively large to download entirely (thousands of documents).\n *\n * @param query The query whose result set is aggregated over.\n * @param aggregateSpec An `AggregateSpec` object that specifies the aggregates\n * to perform over the result set. The AggregateSpec specifies aliases for each\n * aggregate, which can be used to retrieve the aggregate result.\n * @example\n * ```typescript\n * const aggregateSnapshot = await getAggregate(query, {\n * countOfDocs: count(),\n * totalHours: sum('hours'),\n * averageScore: average('score')\n * });\n *\n * const countOfDocs: number = aggregateSnapshot.data().countOfDocs;\n * const totalHours: number = aggregateSnapshot.data().totalHours;\n * const averageScore: number | null = aggregateSnapshot.data().averageScore;\n * ```\n */\nexport function getAggregate<\n AggregateSpecType extends AggregateSpec,\n AppModelType,\n DbModelType extends DocumentData\n>(\n query: Query,\n aggregateSpec: AggregateSpecType\n): Promise<\n AggregateQuerySnapshot\n> {\n const firestore = cast(query.firestore, Firestore);\n const datastore = getDatastore(firestore);\n\n const internalAggregates = mapToArray(aggregateSpec, (aggregate, alias) => {\n return new AggregateImpl(\n alias,\n aggregate.aggregateType,\n aggregate._internalFieldPath\n );\n });\n\n // Run the aggregation and convert the results\n return invokeRunAggregationQueryRpc(\n datastore,\n query._query,\n internalAggregates\n ).then(aggregateResult =>\n convertToAggregateQuerySnapshot(firestore, query, aggregateResult)\n );\n}\n\nfunction convertToAggregateQuerySnapshot<\n AggregateSpecType extends AggregateSpec,\n AppModelType,\n DbModelType extends DocumentData\n>(\n firestore: Firestore,\n query: Query,\n aggregateResult: ApiClientObjectMap\n): AggregateQuerySnapshot {\n const userDataWriter = new LiteUserDataWriter(firestore);\n const querySnapshot = new AggregateQuerySnapshot<\n AggregateSpecType,\n AppModelType,\n DbModelType\n >(query, userDataWriter, aggregateResult);\n return querySnapshot;\n}\n\n/**\n * Create an AggregateField object that can be used to compute the sum of\n * a specified field over a range of documents in the result set of a query.\n * @param field Specifies the field to sum across the result set.\n */\nexport function sum(field: string | FieldPath): AggregateField {\n return new AggregateField('sum', fieldPathFromArgument('sum', field));\n}\n\n/**\n * Create an AggregateField object that can be used to compute the average of\n * a specified field over a range of documents in the result set of a query.\n * @param field Specifies the field to average across the result set.\n */\nexport function average(\n field: string | FieldPath\n): AggregateField {\n return new AggregateField('avg', fieldPathFromArgument('average', field));\n}\n\n/**\n * Create an AggregateField object that can be used to compute the count of\n * documents in the result set of a query.\n */\nexport function count(): AggregateField {\n return new AggregateField('count');\n}\n\n/**\n * Compares two 'AggregateField` instances for equality.\n *\n * @param left Compare this AggregateField to the `right`.\n * @param right Compare this AggregateField to the `left`.\n */\nexport function aggregateFieldEqual(\n left: AggregateField,\n right: AggregateField\n): boolean {\n return (\n left instanceof AggregateField &&\n right instanceof AggregateField &&\n left.aggregateType === right.aggregateType &&\n left._internalFieldPath?.canonicalString() ===\n right._internalFieldPath?.canonicalString()\n );\n}\n\n/**\n * Compares two `AggregateQuerySnapshot` instances for equality.\n *\n * Two `AggregateQuerySnapshot` instances are considered \"equal\" if they have\n * underlying queries that compare equal, and the same data.\n *\n * @param left - The first `AggregateQuerySnapshot` to compare.\n * @param right - The second `AggregateQuerySnapshot` to compare.\n *\n * @returns `true` if the objects are \"equal\", as defined above, or `false`\n * otherwise.\n */\nexport function aggregateQuerySnapshotEqual<\n AggregateSpecType extends AggregateSpec,\n AppModelType,\n DbModelType extends DocumentData\n>(\n left: AggregateQuerySnapshot,\n right: AggregateQuerySnapshot\n): boolean {\n return (\n queryEqual(left.query, right.query) && deepEqual(left.data(), right.data())\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FieldValue } from './field_value';\nimport {\n ArrayRemoveFieldValueImpl,\n ArrayUnionFieldValueImpl,\n DeleteFieldValueImpl,\n NumericIncrementFieldValueImpl,\n ServerTimestampFieldValueImpl\n} from './user_data_reader';\nimport { VectorValue } from './vector_value';\n\n/**\n * Returns a sentinel for use with {@link @firebase/firestore/lite#(updateDoc:1)} or\n * {@link @firebase/firestore/lite#(setDoc:1)} with `{merge: true}` to mark a field for deletion.\n */\nexport function deleteField(): FieldValue {\n return new DeleteFieldValueImpl('deleteField');\n}\n\n/**\n * Returns a sentinel used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link @firebase/firestore/lite#(updateDoc:1)} to\n * include a server-generated timestamp in the written data.\n */\nexport function serverTimestamp(): FieldValue {\n return new ServerTimestampFieldValueImpl('serverTimestamp');\n}\n\n/**\n * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link\n * @firebase/firestore/lite#(updateDoc:1)} that tells the server to union the given elements with any array\n * value that already exists on the server. Each specified element that doesn't\n * already exist in the array will be added to the end. If the field being\n * modified is not already an array it will be overwritten with an array\n * containing exactly the specified elements.\n *\n * @param elements - The elements to union into the array.\n * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or\n * `updateDoc()`.\n */\nexport function arrayUnion(...elements: unknown[]): FieldValue {\n // NOTE: We don't actually parse the data until it's used in set() or\n // update() since we'd need the Firestore instance to do this.\n return new ArrayUnionFieldValueImpl('arrayUnion', elements);\n}\n\n/**\n * Returns a special value that can be used with {@link (setDoc:1)} or {@link\n * updateDoc:1} that tells the server to remove the given elements from any\n * array value that already exists on the server. All instances of each element\n * specified will be removed from the array. If the field being modified is not\n * already an array it will be overwritten with an empty array.\n *\n * @param elements - The elements to remove from the array.\n * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or\n * `updateDoc()`\n */\nexport function arrayRemove(...elements: unknown[]): FieldValue {\n // NOTE: We don't actually parse the data until it's used in set() or\n // update() since we'd need the Firestore instance to do this.\n return new ArrayRemoveFieldValueImpl('arrayRemove', elements);\n}\n\n/**\n * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link\n * @firebase/firestore/lite#(updateDoc:1)} that tells the server to increment the field's current value by\n * the given value.\n *\n * If either the operand or the current field value uses floating point\n * precision, all arithmetic follows IEEE 754 semantics. If both values are\n * integers, values outside of JavaScript's safe number range\n * (`Number.MIN_SAFE_INTEGER` to `Number.MAX_SAFE_INTEGER`) are also subject to\n * precision loss. Furthermore, once processed by the Firestore backend, all\n * integer operations are capped between -2^63 and 2^63-1.\n *\n * If the current field value is not of type `number`, or if the field does not\n * yet exist, the transformation sets the field to the given value.\n *\n * @param n - The value to increment by.\n * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or\n * `updateDoc()`\n */\nexport function increment(n: number): FieldValue {\n return new NumericIncrementFieldValueImpl('increment', n);\n}\n\n/**\n * Creates a new `VectorValue` constructed with a copy of the given array of numbers.\n *\n * @param values - Create a `VectorValue` instance with a copy of this array of numbers.\n *\n * @returns A new `VectorValue` constructed with a copy of the given array of numbers.\n */\nexport function vector(values?: number[]): VectorValue {\n return new VectorValue(values);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Compat, getModularInstance } from '@firebase/util';\n\nimport { DeleteMutation, Mutation, Precondition } from '../model/mutation';\nimport { invokeCommitRpc } from '../remote/datastore';\nimport { Code, FirestoreError } from '../util/error';\nimport { cast } from '../util/input_validation';\n\nimport { getDatastore } from './components';\nimport { Firestore } from './database';\nimport { FieldPath } from './field_path';\nimport {\n DocumentData,\n DocumentReference,\n PartialWithFieldValue,\n SetOptions,\n UpdateData,\n WithFieldValue\n} from './reference';\nimport { applyFirestoreDataConverter } from './reference_impl';\nimport {\n newUserDataReader,\n parseSetData,\n parseUpdateData,\n parseUpdateVarargs,\n UserDataReader\n} from './user_data_reader';\n\n/**\n * A write batch, used to perform multiple writes as a single atomic unit.\n *\n * A `WriteBatch` object can be acquired by calling {@link writeBatch}. It\n * provides methods for adding writes to the write batch. None of the writes\n * will be committed (or visible locally) until {@link WriteBatch.commit} is\n * called.\n */\nexport class WriteBatch {\n // This is the lite version of the WriteBatch API used in the legacy SDK. The\n // class is a close copy but takes different input types.\n\n private readonly _dataReader: UserDataReader;\n private _mutations = [] as Mutation[];\n private _committed = false;\n\n /** @hideconstructor */\n constructor(\n private readonly _firestore: Firestore,\n private readonly _commitHandler: (m: Mutation[]) => Promise\n ) {\n this._dataReader = newUserDataReader(_firestore);\n }\n\n /**\n * Writes to the document referred to by the provided {@link\n * DocumentReference}. If the document does not exist yet, it will be created.\n *\n * @param documentRef - A reference to the document to be set.\n * @param data - An object of the fields and values for the document.\n * @returns This `WriteBatch` instance. Used for chaining method calls.\n */\n set(\n documentRef: DocumentReference,\n data: WithFieldValue\n ): WriteBatch;\n /**\n * Writes to the document referred to by the provided {@link\n * DocumentReference}. If the document does not exist yet, it will be created.\n * If you provide `merge` or `mergeFields`, the provided data can be merged\n * into an existing document.\n *\n * @param documentRef - A reference to the document to be set.\n * @param data - An object of the fields and values for the document.\n * @param options - An object to configure the set behavior.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns This `WriteBatch` instance. Used for chaining method calls.\n */\n set(\n documentRef: DocumentReference,\n data: PartialWithFieldValue,\n options: SetOptions\n ): WriteBatch;\n set(\n documentRef: DocumentReference,\n data: WithFieldValue | PartialWithFieldValue,\n options?: SetOptions\n ): WriteBatch {\n this._verifyNotCommitted();\n const ref = validateReference(documentRef, this._firestore);\n\n const convertedValue = applyFirestoreDataConverter(\n ref.converter,\n data,\n options\n );\n const parsed = parseSetData(\n this._dataReader,\n 'WriteBatch.set',\n ref._key,\n convertedValue,\n ref.converter !== null,\n options\n );\n this._mutations.push(parsed.toMutation(ref._key, Precondition.none()));\n return this;\n }\n\n /**\n * Updates fields in the document referred to by the provided {@link\n * DocumentReference}. The update will fail if applied to a document that does\n * not exist.\n *\n * @param documentRef - A reference to the document to be updated.\n * @param data - An object containing the fields and values with which to\n * update the document. Fields can contain dots to reference nested fields\n * within the document.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns This `WriteBatch` instance. Used for chaining method calls.\n */\n update(\n documentRef: DocumentReference,\n data: UpdateData\n ): WriteBatch;\n /**\n * Updates fields in the document referred to by this {@link\n * DocumentReference}. The update will fail if applied to a document that does\n * not exist.\n *\n * Nested fields can be update by providing dot-separated field path strings\n * or by providing `FieldPath` objects.\n *\n * @param documentRef - A reference to the document to be updated.\n * @param field - The first field to update.\n * @param value - The first value.\n * @param moreFieldsAndValues - Additional key value pairs.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns This `WriteBatch` instance. Used for chaining method calls.\n */\n update(\n documentRef: DocumentReference,\n field: string | FieldPath,\n value: unknown,\n ...moreFieldsAndValues: unknown[]\n ): WriteBatch;\n update(\n documentRef: DocumentReference,\n fieldOrUpdateData: string | FieldPath | UpdateData,\n value?: unknown,\n ...moreFieldsAndValues: unknown[]\n ): WriteBatch {\n this._verifyNotCommitted();\n const ref = validateReference(documentRef, this._firestore);\n\n // For Compat types, we have to \"extract\" the underlying types before\n // performing validation.\n fieldOrUpdateData = getModularInstance(fieldOrUpdateData);\n\n let parsed;\n if (\n typeof fieldOrUpdateData === 'string' ||\n fieldOrUpdateData instanceof FieldPath\n ) {\n parsed = parseUpdateVarargs(\n this._dataReader,\n 'WriteBatch.update',\n ref._key,\n fieldOrUpdateData,\n value,\n moreFieldsAndValues\n );\n } else {\n parsed = parseUpdateData(\n this._dataReader,\n 'WriteBatch.update',\n ref._key,\n fieldOrUpdateData\n );\n }\n\n this._mutations.push(\n parsed.toMutation(ref._key, Precondition.exists(true))\n );\n return this;\n }\n\n /**\n * Deletes the document referred to by the provided {@link DocumentReference}.\n *\n * @param documentRef - A reference to the document to be deleted.\n * @returns This `WriteBatch` instance. Used for chaining method calls.\n */\n delete(\n documentRef: DocumentReference\n ): WriteBatch {\n this._verifyNotCommitted();\n const ref = validateReference(documentRef, this._firestore);\n this._mutations = this._mutations.concat(\n new DeleteMutation(ref._key, Precondition.none())\n );\n return this;\n }\n\n /**\n * Commits all of the writes in this write batch as a single atomic unit.\n *\n * The result of these writes will only be reflected in document reads that\n * occur after the returned promise resolves. If the client is offline, the\n * write fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @returns A `Promise` resolved once all of the writes in the batch have been\n * successfully written to the backend as an atomic unit (note that it won't\n * resolve while you're offline).\n */\n commit(): Promise {\n this._verifyNotCommitted();\n this._committed = true;\n if (this._mutations.length > 0) {\n return this._commitHandler(this._mutations);\n }\n\n return Promise.resolve();\n }\n\n private _verifyNotCommitted(): void {\n if (this._committed) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'A write batch can no longer be used after commit() ' +\n 'has been called.'\n );\n }\n }\n}\n\nexport function validateReference<\n AppModelType,\n DbModelType extends DocumentData\n>(\n documentRef:\n | DocumentReference\n | Compat>,\n firestore: Firestore\n): DocumentReference {\n documentRef = getModularInstance(documentRef);\n\n if (documentRef.firestore !== firestore) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Provided document reference is from a different Firestore instance.'\n );\n } else {\n return documentRef as DocumentReference;\n }\n}\n\n/**\n * Creates a write batch, used for performing multiple writes as a single\n * atomic operation. The maximum number of writes allowed in a single WriteBatch\n * is 500.\n *\n * The result of these writes will only be reflected in document reads that\n * occur after the returned promise resolves. If the client is offline, the\n * write fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @returns A `WriteBatch` that can be used to atomically execute multiple\n * writes.\n */\nexport function writeBatch(firestore: Firestore): WriteBatch {\n firestore = cast(firestore, Firestore);\n const datastore = getDatastore(firestore);\n return new WriteBatch(firestore, writes =>\n invokeCommitRpc(datastore, writes)\n );\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ParsedSetData, ParsedUpdateData } from '../lite-api/user_data_reader';\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport {\n DeleteMutation,\n Mutation,\n Precondition,\n VerifyMutation\n} from '../model/mutation';\nimport {\n Datastore,\n invokeBatchGetDocumentsRpc,\n invokeCommitRpc\n} from '../remote/datastore';\nimport { fail, debugAssert } from '../util/assert';\nimport { Code, FirestoreError } from '../util/error';\n\nimport { SnapshotVersion } from './snapshot_version';\n\n/**\n * Internal transaction object responsible for accumulating the mutations to\n * perform and the base versions for any documents read.\n */\nexport class Transaction {\n // The version of each document that was read during this transaction.\n private readVersions = new Map();\n private mutations: Mutation[] = [];\n private committed = false;\n\n /**\n * A deferred usage error that occurred previously in this transaction that\n * will cause the transaction to fail once it actually commits.\n */\n private lastTransactionError: FirestoreError | null = null;\n\n /**\n * Set of documents that have been written in the transaction.\n *\n * When there's more than one write to the same key in a transaction, any\n * writes after the first are handled differently.\n */\n private writtenDocs: Set = new Set();\n\n constructor(private datastore: Datastore) {}\n\n async lookup(keys: DocumentKey[]): Promise {\n this.ensureCommitNotCalled();\n\n if (this.mutations.length > 0) {\n this.lastTransactionError = new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Firestore transactions require all reads to be executed before all writes.'\n );\n throw this.lastTransactionError;\n }\n const docs = await invokeBatchGetDocumentsRpc(this.datastore, keys);\n docs.forEach(doc => this.recordVersion(doc));\n return docs;\n }\n\n set(key: DocumentKey, data: ParsedSetData): void {\n this.write(data.toMutation(key, this.precondition(key)));\n this.writtenDocs.add(key.toString());\n }\n\n update(key: DocumentKey, data: ParsedUpdateData): void {\n try {\n this.write(data.toMutation(key, this.preconditionForUpdate(key)));\n } catch (e) {\n this.lastTransactionError = e as FirestoreError | null;\n }\n this.writtenDocs.add(key.toString());\n }\n\n delete(key: DocumentKey): void {\n this.write(new DeleteMutation(key, this.precondition(key)));\n this.writtenDocs.add(key.toString());\n }\n\n async commit(): Promise {\n this.ensureCommitNotCalled();\n\n if (this.lastTransactionError) {\n throw this.lastTransactionError;\n }\n const unwritten = this.readVersions;\n // For each mutation, note that the doc was written.\n this.mutations.forEach(mutation => {\n unwritten.delete(mutation.key.toString());\n });\n // For each document that was read but not written to, we want to perform\n // a `verify` operation.\n unwritten.forEach((_, path) => {\n const key = DocumentKey.fromPath(path);\n this.mutations.push(new VerifyMutation(key, this.precondition(key)));\n });\n await invokeCommitRpc(this.datastore, this.mutations);\n this.committed = true;\n }\n\n private recordVersion(doc: Document): void {\n let docVersion: SnapshotVersion;\n\n if (doc.isFoundDocument()) {\n docVersion = doc.version;\n } else if (doc.isNoDocument()) {\n // Represent a deleted doc using SnapshotVersion.min().\n docVersion = SnapshotVersion.min();\n } else {\n throw fail(0xc542, 'Document in a transaction was a ', {\n documentName: doc.constructor.name\n });\n }\n\n const existingVersion = this.readVersions.get(doc.key.toString());\n if (existingVersion) {\n if (!docVersion.isEqual(existingVersion)) {\n // This transaction will fail no matter what.\n throw new FirestoreError(\n Code.ABORTED,\n 'Document version changed between two reads.'\n );\n }\n } else {\n this.readVersions.set(doc.key.toString(), docVersion);\n }\n }\n\n /**\n * Returns the version of this document when it was read in this transaction,\n * as a precondition, or no precondition if it was not read.\n */\n private precondition(key: DocumentKey): Precondition {\n const version = this.readVersions.get(key.toString());\n if (!this.writtenDocs.has(key.toString()) && version) {\n if (version.isEqual(SnapshotVersion.min())) {\n return Precondition.exists(false);\n } else {\n return Precondition.updateTime(version);\n }\n } else {\n return Precondition.none();\n }\n }\n\n /**\n * Returns the precondition for a document if the operation is an update.\n */\n private preconditionForUpdate(key: DocumentKey): Precondition {\n const version = this.readVersions.get(key.toString());\n // The first time a document is written, we want to take into account the\n // read time and existence\n if (!this.writtenDocs.has(key.toString()) && version) {\n if (version.isEqual(SnapshotVersion.min())) {\n // The document doesn't exist, so fail the transaction.\n\n // This has to be validated locally because you can't send a\n // precondition that a document does not exist without changing the\n // semantics of the backend write to be an insert. This is the reverse\n // of what we want, since we want to assert that the document doesn't\n // exist but then send the update and have it fail. Since we can't\n // express that to the backend, we have to validate locally.\n\n // Note: this can change once we can send separate verify writes in the\n // transaction.\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n \"Can't update a document that doesn't exist.\"\n );\n }\n // Document exists, base precondition on document update time.\n return Precondition.updateTime(version);\n } else {\n // Document was not read, so we just use the preconditions for a blind\n // update.\n return Precondition.exists(true);\n }\n }\n\n private write(mutation: Mutation): void {\n this.ensureCommitNotCalled();\n this.mutations.push(mutation);\n }\n\n private ensureCommitNotCalled(): void {\n debugAssert(\n !this.committed,\n 'A transaction object cannot be used after its update callback has been invoked.'\n );\n }\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Code, FirestoreError } from '../util/error';\n\nexport const DEFAULT_TRANSACTION_OPTIONS: TransactionOptions = {\n maxAttempts: 5\n};\n\n/**\n * Options to customize transaction behavior.\n */\nexport declare interface TransactionOptions {\n /** Maximum number of attempts to commit, after which transaction fails. Default is 5. */\n readonly maxAttempts: number;\n}\n\nexport function validateTransactionOptions(options: TransactionOptions): void {\n if (options.maxAttempts < 1) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Max attempts must be at least 1'\n );\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ExponentialBackoff } from '../remote/backoff';\nimport { Datastore } from '../remote/datastore';\nimport { isPermanentError } from '../remote/rpc_error';\nimport { AsyncQueue, TimerId } from '../util/async_queue';\nimport { FirestoreError } from '../util/error';\nimport { Deferred } from '../util/promise';\nimport { isNullOrUndefined } from '../util/types';\n\nimport { Transaction } from './transaction';\nimport { TransactionOptions } from './transaction_options';\n\n/**\n * TransactionRunner encapsulates the logic needed to run and retry transactions\n * with backoff.\n */\nexport class TransactionRunner {\n private attemptsRemaining: number;\n private backoff: ExponentialBackoff;\n\n constructor(\n private readonly asyncQueue: AsyncQueue,\n private readonly datastore: Datastore,\n private readonly options: TransactionOptions,\n private readonly updateFunction: (transaction: Transaction) => Promise,\n private readonly deferred: Deferred\n ) {\n this.attemptsRemaining = options.maxAttempts;\n this.backoff = new ExponentialBackoff(\n this.asyncQueue,\n TimerId.TransactionRetry\n );\n }\n\n /** Runs the transaction and sets the result on deferred. */\n run(): void {\n this.attemptsRemaining -= 1;\n this.runWithBackOff();\n }\n\n private runWithBackOff(): void {\n this.backoff.backoffAndRun(async () => {\n const transaction = new Transaction(this.datastore);\n const userPromise = this.tryRunUpdateFunction(transaction);\n if (userPromise) {\n userPromise\n .then(result => {\n this.asyncQueue.enqueueAndForget(() => {\n return transaction\n .commit()\n .then(() => {\n this.deferred.resolve(result);\n })\n .catch(commitError => {\n this.handleTransactionError(commitError);\n });\n });\n })\n .catch(userPromiseError => {\n this.handleTransactionError(userPromiseError);\n });\n }\n });\n }\n\n private tryRunUpdateFunction(transaction: Transaction): Promise | null {\n try {\n const userPromise = this.updateFunction(transaction);\n if (\n isNullOrUndefined(userPromise) ||\n !userPromise.catch ||\n !userPromise.then\n ) {\n this.deferred.reject(\n Error('Transaction callback must return a Promise')\n );\n return null;\n }\n return userPromise;\n } catch (error) {\n // Do not retry errors thrown by user provided updateFunction.\n this.deferred.reject(error as Error);\n return null;\n }\n }\n\n private handleTransactionError(error: Error): void {\n if (this.attemptsRemaining > 0 && this.isRetryableTransactionError(error)) {\n this.attemptsRemaining -= 1;\n this.asyncQueue.enqueueAndForget(() => {\n this.runWithBackOff();\n return Promise.resolve();\n });\n } else {\n this.deferred.reject(error);\n }\n }\n\n private isRetryableTransactionError(error: Error | undefined): boolean {\n if (error?.name === 'FirebaseError') {\n // In transactions, the backend will fail outdated reads with FAILED_PRECONDITION and\n // non-matching document versions with ABORTED. These errors should be retried.\n const code = (error as FirestoreError).code;\n return (\n code === 'aborted' ||\n code === 'failed-precondition' ||\n code === 'already-exists' ||\n !isPermanentError(code)\n );\n }\n return false;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** The Platform's 'window' implementation or null if not available. */\nexport function getWindow(): Window | null {\n // `window` is not always available, e.g. in ReactNative and WebWorkers.\n // eslint-disable-next-line no-restricted-globals\n return typeof window !== 'undefined' ? window : null;\n}\n\n/** The Platform's 'document' implementation or null if not available. */\nexport function getDocument(): Document | null {\n // `document` is not always available, e.g. in ReactNative and WebWorkers.\n // eslint-disable-next-line no-restricted-globals\n return typeof document !== 'undefined' ? document : null;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isIndexedDbTransactionError } from '../local/simple_db';\n\nimport { Code, FirestoreError } from './error';\nimport { logError } from './log';\nimport { Deferred } from './promise';\n\nconst LOG_TAG = 'AsyncQueue';\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype TimerHandle = any;\n\n/**\n * Wellknown \"timer\" IDs used when scheduling delayed operations on the\n * AsyncQueue. These IDs can then be used from tests to check for the presence\n * of operations or to run them early.\n *\n * The string values are used when encoding these timer IDs in JSON spec tests.\n */\nexport const enum TimerId {\n /** All can be used with runDelayedOperationsEarly() to run all timers. */\n All = 'all',\n\n /**\n * The following 5 timers are used in persistent_stream.ts for the listen and\n * write streams. The \"Idle\" timer is used to close the stream due to\n * inactivity. The \"ConnectionBackoff\" timer is used to restart a stream once\n * the appropriate backoff delay has elapsed. The health check is used to mark\n * a stream healthy if it has not received an error during its initial setup.\n */\n ListenStreamIdle = 'listen_stream_idle',\n ListenStreamConnectionBackoff = 'listen_stream_connection_backoff',\n WriteStreamIdle = 'write_stream_idle',\n WriteStreamConnectionBackoff = 'write_stream_connection_backoff',\n HealthCheckTimeout = 'health_check_timeout',\n\n /**\n * A timer used in online_state_tracker.ts to transition from\n * OnlineState.Unknown to Offline after a set timeout, rather than waiting\n * indefinitely for success or failure.\n */\n OnlineStateTimeout = 'online_state_timeout',\n\n /**\n * A timer used to update the client metadata in IndexedDb, which is used\n * to determine the primary leaseholder.\n */\n ClientMetadataRefresh = 'client_metadata_refresh',\n\n /** A timer used to periodically attempt LRU Garbage collection */\n LruGarbageCollection = 'lru_garbage_collection',\n\n /**\n * A timer used to retry transactions. Since there can be multiple concurrent\n * transactions, multiple of these may be in the queue at a given time.\n */\n TransactionRetry = 'transaction_retry',\n\n /**\n * A timer used to retry operations scheduled via retryable AsyncQueue\n * operations.\n */\n AsyncQueueRetry = 'async_queue_retry',\n\n /**\n * A timer used to periodically attempt index backfill.\n */\n IndexBackfill = 'index_backfill'\n}\n\n/**\n * Represents an operation scheduled to be run in the future on an AsyncQueue.\n *\n * It is created via DelayedOperation.createAndSchedule().\n *\n * Supports cancellation (via cancel()) and early execution (via skipDelay()).\n *\n * Note: We implement `PromiseLike` instead of `Promise`, as the `Promise` type\n * in newer versions of TypeScript defines `finally`, which is not available in\n * IE.\n */\nexport class DelayedOperation implements PromiseLike {\n // handle for use with clearTimeout(), or null if the operation has been\n // executed or canceled already.\n private timerHandle: TimerHandle | null;\n\n private readonly deferred = new Deferred();\n\n private constructor(\n private readonly asyncQueue: AsyncQueue,\n readonly timerId: TimerId,\n readonly targetTimeMs: number,\n private readonly op: () => Promise,\n private readonly removalCallback: (op: DelayedOperation) => void\n ) {\n // It's normal for the deferred promise to be canceled (due to cancellation)\n // and so we attach a dummy catch callback to avoid\n // 'UnhandledPromiseRejectionWarning' log spam.\n this.deferred.promise.catch(err => {});\n }\n\n get promise(): Promise {\n return this.deferred.promise;\n }\n\n /**\n * Creates and returns a DelayedOperation that has been scheduled to be\n * executed on the provided asyncQueue after the provided delayMs.\n *\n * @param asyncQueue - The queue to schedule the operation on.\n * @param id - A Timer ID identifying the type of operation this is.\n * @param delayMs - The delay (ms) before the operation should be scheduled.\n * @param op - The operation to run.\n * @param removalCallback - A callback to be called synchronously once the\n * operation is executed or canceled, notifying the AsyncQueue to remove it\n * from its delayedOperations list.\n * PORTING NOTE: This exists to prevent making removeDelayedOperation() and\n * the DelayedOperation class public.\n */\n static createAndSchedule(\n asyncQueue: AsyncQueue,\n timerId: TimerId,\n delayMs: number,\n op: () => Promise,\n removalCallback: (op: DelayedOperation) => void\n ): DelayedOperation {\n const targetTime = Date.now() + delayMs;\n const delayedOp = new DelayedOperation(\n asyncQueue,\n timerId,\n targetTime,\n op,\n removalCallback\n );\n delayedOp.start(delayMs);\n return delayedOp;\n }\n\n /**\n * Starts the timer. This is called immediately after construction by\n * createAndSchedule().\n */\n private start(delayMs: number): void {\n this.timerHandle = setTimeout(() => this.handleDelayElapsed(), delayMs);\n }\n\n /**\n * Queues the operation to run immediately (if it hasn't already been run or\n * canceled).\n */\n skipDelay(): void {\n return this.handleDelayElapsed();\n }\n\n /**\n * Cancels the operation if it hasn't already been executed or canceled. The\n * promise will be rejected.\n *\n * As long as the operation has not yet been run, calling cancel() provides a\n * guarantee that the operation will not be run.\n */\n cancel(reason?: string): void {\n if (this.timerHandle !== null) {\n this.clearTimeout();\n this.deferred.reject(\n new FirestoreError(\n Code.CANCELLED,\n 'Operation cancelled' + (reason ? ': ' + reason : '')\n )\n );\n }\n }\n\n then = this.deferred.promise.then.bind(this.deferred.promise);\n\n private handleDelayElapsed(): void {\n this.asyncQueue.enqueueAndForget(() => {\n if (this.timerHandle !== null) {\n this.clearTimeout();\n return this.op().then(result => {\n return this.deferred.resolve(result);\n });\n } else {\n return Promise.resolve();\n }\n });\n }\n\n private clearTimeout(): void {\n if (this.timerHandle !== null) {\n this.removalCallback(this);\n clearTimeout(this.timerHandle);\n this.timerHandle = null;\n }\n }\n}\n\nexport interface AsyncQueue {\n // Is this AsyncQueue being shut down? If true, this instance will not enqueue\n // any new operations, Promises from enqueue requests will not resolve.\n readonly isShuttingDown: boolean;\n\n /**\n * Adds a new operation to the queue without waiting for it to complete (i.e.\n * we ignore the Promise result).\n */\n enqueueAndForget(op: () => Promise): void;\n\n /**\n * Regardless if the queue has initialized shutdown, adds a new operation to the\n * queue without waiting for it to complete (i.e. we ignore the Promise result).\n */\n enqueueAndForgetEvenWhileRestricted(\n op: () => Promise\n ): void;\n\n /**\n * Initialize the shutdown of this queue. Once this method is called, the\n * only possible way to request running an operation is through\n * `enqueueEvenWhileRestricted()`.\n *\n * @param purgeExistingTasks Whether already enqueued tasked should be\n * rejected (unless enqueued with `enqueueEvenWhileRestricted()`). Defaults\n * to false.\n */\n enterRestrictedMode(purgeExistingTasks?: boolean): void;\n\n /**\n * Adds a new operation to the queue. Returns a promise that will be resolved\n * when the promise returned by the new operation is (with its value).\n */\n enqueue(op: () => Promise): Promise;\n\n /**\n * Enqueue a retryable operation.\n *\n * A retryable operation is rescheduled with backoff if it fails with a\n * IndexedDbTransactionError (the error type used by SimpleDb). All\n * retryable operations are executed in order and only run if all prior\n * operations were retried successfully.\n */\n enqueueRetryable(op: () => Promise): void;\n\n /**\n * Schedules an operation to be queued on the AsyncQueue once the specified\n * `delayMs` has elapsed. The returned DelayedOperation can be used to cancel\n * or fast-forward the operation prior to its running.\n */\n enqueueAfterDelay(\n timerId: TimerId,\n delayMs: number,\n op: () => Promise\n ): DelayedOperation;\n\n /**\n * Verifies there's an operation currently in-progress on the AsyncQueue.\n * Unfortunately we can't verify that the running code is in the promise chain\n * of that operation, so this isn't a foolproof check, but it should be enough\n * to catch some bugs.\n */\n verifyOperationInProgress(): void;\n}\n\n/**\n * Returns a FirestoreError that can be surfaced to the user if the provided\n * error is an IndexedDbTransactionError. Re-throws the error otherwise.\n */\nexport function wrapInUserErrorIfRecoverable(\n e: Error,\n msg: string\n): FirestoreError {\n logError(LOG_TAG, `${msg}: ${e}`);\n if (isIndexedDbTransactionError(e)) {\n return new FirestoreError(Code.UNAVAILABLE, `${msg}: ${e}`);\n } else {\n throw e;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isIndexedDbTransactionError } from '../local/simple_db';\nimport { getDocument } from '../platform/dom';\nimport { ExponentialBackoff } from '../remote/backoff';\n\nimport { debugAssert, fail } from './assert';\nimport { AsyncQueue, DelayedOperation, TimerId } from './async_queue';\nimport { FirestoreError } from './error';\nimport { logDebug, logError } from './log';\nimport { Deferred } from './promise';\n\nconst LOG_TAG = 'AsyncQueue';\n\nexport class AsyncQueueImpl implements AsyncQueue {\n // The last promise in the queue.\n private tail: Promise;\n\n // A list of retryable operations. Retryable operations are run in order and\n // retried with backoff.\n private retryableOps: Array<() => Promise> = [];\n\n // Is this AsyncQueue being shut down? Once it is set to true, it will not\n // be changed again.\n private _isShuttingDown: boolean = false;\n\n // Operations scheduled to be queued in the future. Operations are\n // automatically removed after they are run or canceled.\n private delayedOperations: Array> = [];\n\n // visible for testing\n failure: FirestoreError | null = null;\n\n // Flag set while there's an outstanding AsyncQueue operation, used for\n // assertion sanity-checks.\n private operationInProgress = false;\n\n // Enabled during shutdown on Safari to prevent future access to IndexedDB.\n private skipNonRestrictedTasks = false;\n\n // List of TimerIds to fast-forward delays for.\n private timerIdsToSkip: TimerId[] = [];\n\n // Backoff timer used to schedule retries for retryable operations\n private backoff = new ExponentialBackoff(this, TimerId.AsyncQueueRetry);\n\n // Visibility handler that triggers an immediate retry of all retryable\n // operations. Meant to speed up recovery when we regain file system access\n // after page comes into foreground.\n private visibilityHandler: () => void = () => {\n const document = getDocument();\n if (document) {\n logDebug(\n LOG_TAG,\n 'Visibility state changed to ' + document.visibilityState\n );\n }\n this.backoff.skipBackoff();\n };\n\n constructor(tail: Promise = Promise.resolve()) {\n this.tail = tail;\n const document = getDocument();\n if (document && typeof document.addEventListener === 'function') {\n document.addEventListener('visibilitychange', this.visibilityHandler);\n }\n }\n\n get isShuttingDown(): boolean {\n return this._isShuttingDown;\n }\n\n /**\n * Adds a new operation to the queue without waiting for it to complete (i.e.\n * we ignore the Promise result).\n */\n enqueueAndForget(op: () => Promise): void {\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.enqueue(op);\n }\n\n enqueueAndForgetEvenWhileRestricted(\n op: () => Promise\n ): void {\n this.verifyNotFailed();\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.enqueueInternal(op);\n }\n\n enterRestrictedMode(purgeExistingTasks?: boolean): void {\n if (!this._isShuttingDown) {\n this._isShuttingDown = true;\n this.skipNonRestrictedTasks = purgeExistingTasks || false;\n const document = getDocument();\n if (document && typeof document.removeEventListener === 'function') {\n document.removeEventListener(\n 'visibilitychange',\n this.visibilityHandler\n );\n }\n }\n }\n\n enqueue(op: () => Promise): Promise {\n this.verifyNotFailed();\n if (this._isShuttingDown) {\n // Return a Promise which never resolves.\n return new Promise(() => {});\n }\n\n // Create a deferred Promise that we can return to the callee. This\n // allows us to return a \"hanging Promise\" only to the callee and still\n // advance the queue even when the operation is not run.\n const task = new Deferred();\n return this.enqueueInternal(() => {\n if (this._isShuttingDown && this.skipNonRestrictedTasks) {\n // We do not resolve 'task'\n return Promise.resolve();\n }\n\n op().then(task.resolve, task.reject);\n return task.promise;\n }).then(() => task.promise);\n }\n\n enqueueRetryable(op: () => Promise): void {\n this.enqueueAndForget(() => {\n this.retryableOps.push(op);\n return this.retryNextOp();\n });\n }\n\n /**\n * Runs the next operation from the retryable queue. If the operation fails,\n * reschedules with backoff.\n */\n private async retryNextOp(): Promise {\n if (this.retryableOps.length === 0) {\n return;\n }\n\n try {\n await this.retryableOps[0]();\n this.retryableOps.shift();\n this.backoff.reset();\n } catch (e) {\n if (isIndexedDbTransactionError(e as Error)) {\n logDebug(LOG_TAG, 'Operation failed with retryable error: ' + e);\n } else {\n throw e; // Failure will be handled by AsyncQueue\n }\n }\n\n if (this.retryableOps.length > 0) {\n // If there are additional operations, we re-schedule `retryNextOp()`.\n // This is necessary to run retryable operations that failed during\n // their initial attempt since we don't know whether they are already\n // enqueued. If, for example, `op1`, `op2`, `op3` are enqueued and `op1`\n // needs to be re-run, we will run `op1`, `op1`, `op2` using the\n // already enqueued calls to `retryNextOp()`. `op3()` will then run in the\n // call scheduled here.\n // Since `backoffAndRun()` cancels an existing backoff and schedules a\n // new backoff on every call, there is only ever a single additional\n // operation in the queue.\n this.backoff.backoffAndRun(() => this.retryNextOp());\n }\n }\n\n private enqueueInternal(op: () => Promise): Promise {\n const newTail = this.tail.then(() => {\n this.operationInProgress = true;\n return op()\n .catch((error: FirestoreError) => {\n this.failure = error;\n this.operationInProgress = false;\n const message = getMessageOrStack(error);\n logError('INTERNAL UNHANDLED ERROR: ', message);\n\n // Re-throw the error so that this.tail becomes a rejected Promise and\n // all further attempts to chain (via .then) will just short-circuit\n // and return the rejected Promise.\n throw error;\n })\n .then(result => {\n this.operationInProgress = false;\n return result;\n });\n });\n this.tail = newTail;\n return newTail;\n }\n\n enqueueAfterDelay(\n timerId: TimerId,\n delayMs: number,\n op: () => Promise\n ): DelayedOperation {\n this.verifyNotFailed();\n\n debugAssert(\n delayMs >= 0,\n `Attempted to schedule an operation with a negative delay of ${delayMs}`\n );\n\n // Fast-forward delays for timerIds that have been overridden.\n if (this.timerIdsToSkip.indexOf(timerId) > -1) {\n delayMs = 0;\n }\n\n const delayedOp = DelayedOperation.createAndSchedule(\n this,\n timerId,\n delayMs,\n op,\n removedOp =>\n this.removeDelayedOperation(removedOp as DelayedOperation)\n );\n this.delayedOperations.push(delayedOp as DelayedOperation);\n return delayedOp;\n }\n\n private verifyNotFailed(): void {\n if (this.failure) {\n fail(0xb815, 'AsyncQueue is already failed', {\n messageOrStack: getMessageOrStack(this.failure)\n });\n }\n }\n\n verifyOperationInProgress(): void {\n debugAssert(\n this.operationInProgress,\n 'verifyOpInProgress() called when no op in progress on this queue.'\n );\n }\n\n /**\n * Waits until all currently queued tasks are finished executing. Delayed\n * operations are not run.\n */\n async drain(): Promise {\n // Operations in the queue prior to draining may have enqueued additional\n // operations. Keep draining the queue until the tail is no longer advanced,\n // which indicates that no more new operations were enqueued and that all\n // operations were executed.\n let currentTail: Promise;\n do {\n currentTail = this.tail;\n await currentTail;\n } while (currentTail !== this.tail);\n }\n\n /**\n * For Tests: Determine if a delayed operation with a particular TimerId\n * exists.\n */\n containsDelayedOperation(timerId: TimerId): boolean {\n for (const op of this.delayedOperations) {\n if (op.timerId === timerId) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * For Tests: Runs some or all delayed operations early.\n *\n * @param lastTimerId - Delayed operations up to and including this TimerId\n * will be drained. Pass TimerId.All to run all delayed operations.\n * @returns a Promise that resolves once all operations have been run.\n */\n runAllDelayedOperationsUntil(lastTimerId: TimerId): Promise {\n // Note that draining may generate more delayed ops, so we do that first.\n return this.drain().then(() => {\n // Run ops in the same order they'd run if they ran naturally.\n /* eslint-disable-next-line @typescript-eslint/no-floating-promises */\n this.delayedOperations.sort((a, b) => a.targetTimeMs - b.targetTimeMs);\n\n for (const op of this.delayedOperations) {\n op.skipDelay();\n if (lastTimerId !== TimerId.All && op.timerId === lastTimerId) {\n break;\n }\n }\n\n return this.drain();\n });\n }\n\n /**\n * For Tests: Skip all subsequent delays for a timer id.\n */\n skipDelaysForTimerId(timerId: TimerId): void {\n this.timerIdsToSkip.push(timerId);\n }\n\n /** Called once a DelayedOperation is run or canceled. */\n private removeDelayedOperation(op: DelayedOperation): void {\n // NOTE: indexOf / slice are O(n), but delayedOperations is expected to be small.\n const index = this.delayedOperations.indexOf(op);\n debugAssert(index >= 0, 'Delayed operation not found.');\n /* eslint-disable-next-line @typescript-eslint/no-floating-promises */\n this.delayedOperations.splice(index, 1);\n }\n}\n\nexport function newAsyncQueue(): AsyncQueue {\n return new AsyncQueueImpl();\n}\n\n/**\n * Chrome includes Error.message in Error.stack. Other browsers do not.\n * This returns expected output of message + stack when available.\n * @param error - Error or FirestoreError\n */\nfunction getMessageOrStack(error: Error): string {\n let message = error.message || '';\n if (error.stack) {\n if (error.stack.includes(error.message)) {\n message = error.stack;\n } else {\n message = error.message + '\\n' + error.stack;\n }\n }\n return message;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getGlobal, getUA, isIndexedDBAvailable } from '@firebase/util';\n\nimport { debugAssert } from '../util/assert';\nimport { Code, FirestoreError } from '../util/error';\nimport { logDebug, logError } from '../util/log';\nimport { Deferred } from '../util/promise';\n\nimport { PersistencePromise } from './persistence_promise';\n\n// References to `indexedDB` are guarded by SimpleDb.isAvailable() and getGlobal()\n/* eslint-disable no-restricted-globals */\n\nconst LOG_TAG = 'SimpleDb';\n\n/**\n * The maximum number of retry attempts for an IndexedDb transaction that fails\n * with a DOMException.\n */\nconst TRANSACTION_RETRY_COUNT = 3;\n\n// The different modes supported by `SimpleDb.runTransaction()`\ntype SimpleDbTransactionMode = 'readonly' | 'readwrite';\n\nexport interface SimpleDbSchemaConverter {\n createOrUpgrade(\n db: IDBDatabase,\n txn: IDBTransaction,\n fromVersion: number,\n toVersion: number\n ): PersistencePromise;\n}\n\n/**\n * Wraps an IDBTransaction and exposes a store() method to get a handle to a\n * specific object store.\n */\nexport class SimpleDbTransaction {\n private aborted = false;\n\n /**\n * A `Promise` that resolves with the result of the IndexedDb transaction.\n */\n private readonly completionDeferred = new Deferred();\n\n static open(\n db: IDBDatabase,\n action: string,\n mode: IDBTransactionMode,\n objectStoreNames: string[]\n ): SimpleDbTransaction {\n try {\n return new SimpleDbTransaction(\n action,\n db.transaction(objectStoreNames, mode)\n );\n } catch (e) {\n throw new IndexedDbTransactionError(action, e as Error);\n }\n }\n\n constructor(\n private readonly action: string,\n private readonly transaction: IDBTransaction\n ) {\n this.transaction.oncomplete = () => {\n this.completionDeferred.resolve();\n };\n this.transaction.onabort = () => {\n if (transaction.error) {\n this.completionDeferred.reject(\n new IndexedDbTransactionError(action, transaction.error)\n );\n } else {\n this.completionDeferred.resolve();\n }\n };\n this.transaction.onerror = (event: Event) => {\n const error = checkForAndReportiOSError(\n (event.target as IDBRequest).error!\n );\n this.completionDeferred.reject(\n new IndexedDbTransactionError(action, error)\n );\n };\n }\n\n get completionPromise(): Promise {\n return this.completionDeferred.promise;\n }\n\n abort(error?: Error): void {\n if (error) {\n this.completionDeferred.reject(error);\n }\n\n if (!this.aborted) {\n logDebug(\n LOG_TAG,\n 'Aborting transaction:',\n error ? error.message : 'Client-initiated abort'\n );\n this.aborted = true;\n this.transaction.abort();\n }\n }\n\n maybeCommit(): void {\n // If the browser supports V3 IndexedDB, we invoke commit() explicitly to\n // speed up index DB processing if the event loop remains blocks.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const maybeV3IndexedDb = this.transaction as any;\n if (!this.aborted && typeof maybeV3IndexedDb.commit === 'function') {\n maybeV3IndexedDb.commit();\n }\n }\n\n /**\n * Returns a SimpleDbStore for the specified store. All\n * operations performed on the SimpleDbStore happen within the context of this\n * transaction and it cannot be used anymore once the transaction is\n * completed.\n *\n * Note that we can't actually enforce that the KeyType and ValueType are\n * correct, but they allow type safety through the rest of the consuming code.\n */\n store(\n storeName: string\n ): SimpleDbStore {\n const store = this.transaction.objectStore(storeName);\n debugAssert(!!store, 'Object store not part of transaction: ' + storeName);\n return new SimpleDbStore(store);\n }\n}\n\n/**\n * Provides a wrapper around IndexedDb with a simplified interface that uses\n * Promise-like return values to chain operations. Real promises cannot be used\n * since .then() continuations are executed asynchronously (e.g. via\n * .setImmediate), which would cause IndexedDB to end the transaction.\n * See PersistencePromise for more details.\n */\nexport class SimpleDb {\n private db?: IDBDatabase;\n private lastClosedDbVersion: number | null = null;\n private versionchangelistener?: (event: IDBVersionChangeEvent) => void;\n\n /** Deletes the specified database. */\n static delete(name: string): Promise {\n logDebug(LOG_TAG, 'Removing database:', name);\n const globals = getGlobal();\n return wrapRequest(\n globals.indexedDB.deleteDatabase(name)\n ).toPromise();\n }\n\n /** Returns true if IndexedDB is available in the current environment. */\n static isAvailable(): boolean {\n if (!isIndexedDBAvailable()) {\n return false;\n }\n\n if (SimpleDb.isMockPersistence()) {\n return true;\n }\n\n // We extensively use indexed array values and compound keys,\n // which IE and Edge do not support. However, they still have indexedDB\n // defined on the window, so we need to check for them here and make sure\n // to return that persistence is not enabled for those browsers.\n // For tracking support of this feature, see here:\n // https://developer.microsoft.com/en-us/microsoft-edge/platform/status/indexeddbarraysandmultientrysupport/\n\n // Check the UA string to find out the browser.\n const ua = getUA();\n\n // IE 10\n // ua = 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)';\n\n // IE 11\n // ua = 'Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko';\n\n // Edge\n // ua = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML,\n // like Gecko) Chrome/39.0.2171.71 Safari/537.36 Edge/12.0';\n\n // iOS Safari: Disable for users running iOS version < 10.\n const iOSVersion = SimpleDb.getIOSVersion(ua);\n const isUnsupportedIOS = 0 < iOSVersion && iOSVersion < 10;\n\n // Android browser: Disable for users running version < 4.5.\n const androidVersion = getAndroidVersion(ua);\n const isUnsupportedAndroid = 0 < androidVersion && androidVersion < 4.5;\n\n if (\n ua.indexOf('MSIE ') > 0 ||\n ua.indexOf('Trident/') > 0 ||\n ua.indexOf('Edge/') > 0 ||\n isUnsupportedIOS ||\n isUnsupportedAndroid\n ) {\n return false;\n } else {\n return true;\n }\n }\n\n /**\n * Returns true if the backing IndexedDB store is the Node IndexedDBShim\n * (see https://github.com/axemclion/IndexedDBShim).\n */\n static isMockPersistence(): boolean {\n return (\n typeof process !== 'undefined' &&\n process.env?.USE_MOCK_PERSISTENCE === 'YES'\n );\n }\n\n /** Helper to get a typed SimpleDbStore from a transaction. */\n static getStore(\n txn: SimpleDbTransaction,\n store: string\n ): SimpleDbStore {\n return txn.store(store);\n }\n\n // visible for testing\n /** Parse User Agent to determine iOS version. Returns -1 if not found. */\n static getIOSVersion(ua: string): number {\n const iOSVersionRegex = ua.match(/i(?:phone|pad|pod) os ([\\d_]+)/i);\n const version = iOSVersionRegex\n ? iOSVersionRegex[1].split('_').slice(0, 2).join('.')\n : '-1';\n return Number(version);\n }\n\n /*\n * Creates a new SimpleDb wrapper for IndexedDb database `name`.\n *\n * Note that `version` must not be a downgrade. IndexedDB does not support\n * downgrading the schema version. We currently do not support any way to do\n * versioning outside of IndexedDB's versioning mechanism, as only\n * version-upgrade transactions are allowed to do things like create\n * objectstores.\n */\n constructor(\n private readonly name: string,\n private readonly version: number,\n private readonly schemaConverter: SimpleDbSchemaConverter\n ) {\n debugAssert(\n SimpleDb.isAvailable(),\n 'IndexedDB not supported in current environment.'\n );\n\n const iOSVersion = SimpleDb.getIOSVersion(getUA());\n // NOTE: According to https://bugs.webkit.org/show_bug.cgi?id=197050, the\n // bug we're checking for should exist in iOS >= 12.2 and < 13, but for\n // whatever reason it's much harder to hit after 12.2 so we only proactively\n // log on 12.2.\n if (iOSVersion === 12.2) {\n logError(\n 'Firestore persistence suffers from a bug in iOS 12.2 ' +\n 'Safari that may cause your app to stop working. See ' +\n 'https://stackoverflow.com/q/56496296/110915 for details ' +\n 'and a potential workaround.'\n );\n }\n }\n\n /**\n * Opens the specified database, creating or upgrading it if necessary.\n */\n async ensureDb(action: string): Promise {\n if (!this.db) {\n logDebug(LOG_TAG, 'Opening database:', this.name);\n this.db = await new Promise((resolve, reject) => {\n // TODO(mikelehen): Investigate browser compatibility.\n // https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API/Using_IndexedDB\n // suggests IE9 and older WebKit browsers handle upgrade\n // differently. They expect setVersion, as described here:\n // https://developer.mozilla.org/en-US/docs/Web/API/IDBVersionChangeRequest/setVersion\n const request = indexedDB.open(this.name, this.version);\n\n request.onsuccess = (event: Event) => {\n const db = (event.target as IDBOpenDBRequest).result;\n resolve(db);\n };\n\n request.onblocked = () => {\n reject(\n new IndexedDbTransactionError(\n action,\n 'Cannot upgrade IndexedDB schema while another tab is open. ' +\n 'Close all tabs that access Firestore and reload this page to proceed.'\n )\n );\n };\n\n request.onerror = (event: Event) => {\n const error: DOMException = (event.target as IDBOpenDBRequest).error!;\n if (error.name === 'VersionError') {\n reject(\n new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'A newer version of the Firestore SDK was previously used and so the persisted ' +\n 'data is not compatible with the version of the SDK you are now using. The SDK ' +\n 'will operate with persistence disabled. If you need persistence, please ' +\n 're-upgrade to a newer version of the SDK or else clear the persisted IndexedDB ' +\n 'data for your app to start fresh.'\n )\n );\n } else if (error.name === 'InvalidStateError') {\n reject(\n new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'Unable to open an IndexedDB connection. This could be due to running in a ' +\n 'private browsing session on a browser whose private browsing sessions do not ' +\n 'support IndexedDB: ' +\n error\n )\n );\n } else {\n reject(new IndexedDbTransactionError(action, error));\n }\n };\n\n request.onupgradeneeded = (event: IDBVersionChangeEvent) => {\n logDebug(\n LOG_TAG,\n 'Database \"' + this.name + '\" requires upgrade from version:',\n event.oldVersion\n );\n const db = (event.target as IDBOpenDBRequest).result;\n this.schemaConverter\n .createOrUpgrade(\n db,\n request.transaction!,\n event.oldVersion,\n this.version\n )\n .next(() => {\n logDebug(\n LOG_TAG,\n 'Database upgrade to version ' + this.version + ' complete'\n );\n });\n };\n });\n }\n\n if (this.versionchangelistener) {\n this.db.onversionchange = event => this.versionchangelistener!(event);\n }\n\n return this.db;\n }\n\n setVersionChangeListener(\n versionChangeListener: (event: IDBVersionChangeEvent) => void\n ): void {\n this.versionchangelistener = versionChangeListener;\n if (this.db) {\n this.db.onversionchange = (event: IDBVersionChangeEvent) => {\n return versionChangeListener(event);\n };\n }\n }\n\n async runTransaction(\n action: string,\n mode: SimpleDbTransactionMode,\n objectStores: string[],\n transactionFn: (transaction: SimpleDbTransaction) => PersistencePromise\n ): Promise {\n const readonly = mode === 'readonly';\n let attemptNumber = 0;\n\n while (true) {\n ++attemptNumber;\n\n try {\n this.db = await this.ensureDb(action);\n\n const transaction = SimpleDbTransaction.open(\n this.db,\n action,\n readonly ? 'readonly' : 'readwrite',\n objectStores\n );\n const transactionFnResult = transactionFn(transaction)\n .next(result => {\n transaction.maybeCommit();\n return result;\n })\n .catch(error => {\n // Abort the transaction if there was an error.\n transaction.abort(error);\n // We cannot actually recover, and calling `abort()` will cause the transaction's\n // completion promise to be rejected. This in turn means that we won't use\n // `transactionFnResult` below. We return a rejection here so that we don't add the\n // possibility of returning `void` to the type of `transactionFnResult`.\n return PersistencePromise.reject(error);\n })\n .toPromise();\n\n // As noted above, errors are propagated by aborting the transaction. So\n // we swallow any error here to avoid the browser logging it as unhandled.\n transactionFnResult.catch(() => {});\n\n // Wait for the transaction to complete (i.e. IndexedDb's onsuccess event to\n // fire), but still return the original transactionFnResult back to the\n // caller.\n await transaction.completionPromise;\n return transactionFnResult;\n } catch (e) {\n const error = e as Error;\n // TODO(schmidt-sebastian): We could probably be smarter about this and\n // not retry exceptions that are likely unrecoverable (such as quota\n // exceeded errors).\n\n // Note: We cannot use an instanceof check for FirestoreException, since the\n // exception is wrapped in a generic error by our async/await handling.\n const retryable =\n error.name !== 'FirebaseError' &&\n attemptNumber < TRANSACTION_RETRY_COUNT;\n logDebug(\n LOG_TAG,\n 'Transaction failed with error:',\n error.message,\n 'Retrying:',\n retryable\n );\n\n this.close();\n\n if (!retryable) {\n return Promise.reject(error);\n }\n }\n }\n }\n\n close(): void {\n if (this.db) {\n this.db.close();\n }\n this.db = undefined;\n }\n}\n\n/** Parse User Agent to determine Android version. Returns -1 if not found. */\nexport function getAndroidVersion(ua: string): number {\n const androidVersionRegex = ua.match(/Android ([\\d.]+)/i);\n const version = androidVersionRegex\n ? androidVersionRegex[1].split('.').slice(0, 2).join('.')\n : '-1';\n return Number(version);\n}\n\n/**\n * A controller for iterating over a key range or index. It allows an iterate\n * callback to delete the currently-referenced object, or jump to a new key\n * within the key range or index.\n */\nexport class IterationController {\n private shouldStop = false;\n private nextKey: IDBValidKey | null = null;\n\n constructor(private dbCursor: IDBCursorWithValue) {}\n\n get isDone(): boolean {\n return this.shouldStop;\n }\n\n get skipToKey(): IDBValidKey | null {\n return this.nextKey;\n }\n\n set cursor(value: IDBCursorWithValue) {\n this.dbCursor = value;\n }\n\n /**\n * This function can be called to stop iteration at any point.\n */\n done(): void {\n this.shouldStop = true;\n }\n\n /**\n * This function can be called to skip to that next key, which could be\n * an index or a primary key.\n */\n skip(key: IDBValidKey): void {\n this.nextKey = key;\n }\n\n /**\n * Delete the current cursor value from the object store.\n *\n * NOTE: You CANNOT do this with a keysOnly query.\n */\n delete(): PersistencePromise {\n return wrapRequest(this.dbCursor.delete());\n }\n}\n\n/**\n * Callback used with iterate() method.\n */\nexport type IterateCallback = (\n key: KeyType,\n value: ValueType,\n control: IterationController\n) => void | PersistencePromise;\n\n/** Options available to the iterate() method. */\nexport interface IterateOptions {\n /** Index to iterate over (else primary keys will be iterated) */\n index?: string;\n\n /** IndexedDB Range to iterate over (else entire store will be iterated) */\n range?: IDBKeyRange;\n\n /** If true, values aren't read while iterating. */\n keysOnly?: boolean;\n\n /** If true, iterate over the store in reverse. */\n reverse?: boolean;\n}\n\n/** An error that wraps exceptions that thrown during IndexedDB execution. */\nexport class IndexedDbTransactionError extends FirestoreError {\n name = 'IndexedDbTransactionError';\n\n constructor(actionName: string, cause: Error | string) {\n super(\n Code.UNAVAILABLE,\n `IndexedDB transaction '${actionName}' failed: ${cause}`\n );\n }\n}\n\n/** Verifies whether `e` is an IndexedDbTransactionError. */\nexport function isIndexedDbTransactionError(e: Error): boolean {\n // Use name equality, as instanceof checks on errors don't work with errors\n // that wrap other errors.\n return e.name === 'IndexedDbTransactionError';\n}\n\n/**\n * A wrapper around an IDBObjectStore providing an API that:\n *\n * 1) Has generic KeyType / ValueType parameters to provide strongly-typed\n * methods for acting against the object store.\n * 2) Deals with IndexedDB's onsuccess / onerror event callbacks, making every\n * method return a PersistencePromise instead.\n * 3) Provides a higher-level API to avoid needing to do excessive wrapping of\n * intermediate IndexedDB types (IDBCursorWithValue, etc.)\n */\nexport class SimpleDbStore<\n KeyType extends IDBValidKey,\n ValueType extends unknown\n> {\n constructor(private store: IDBObjectStore) {}\n\n /**\n * Writes a value into the Object Store.\n *\n * @param key - Optional explicit key to use when writing the object, else the\n * key will be auto-assigned (e.g. via the defined keyPath for the store).\n * @param value - The object to write.\n */\n put(value: ValueType): PersistencePromise;\n put(key: KeyType, value: ValueType): PersistencePromise;\n put(\n keyOrValue: KeyType | ValueType,\n value?: ValueType\n ): PersistencePromise {\n let request;\n if (value !== undefined) {\n logDebug(LOG_TAG, 'PUT', this.store.name, keyOrValue, value);\n request = this.store.put(value, keyOrValue as KeyType);\n } else {\n logDebug(LOG_TAG, 'PUT', this.store.name, '', keyOrValue);\n request = this.store.put(keyOrValue as ValueType);\n }\n return wrapRequest(request);\n }\n\n /**\n * Adds a new value into an Object Store and returns the new key. Similar to\n * IndexedDb's `add()`, this method will fail on primary key collisions.\n *\n * @param value - The object to write.\n * @returns The key of the value to add.\n */\n add(value: ValueType): PersistencePromise {\n logDebug(LOG_TAG, 'ADD', this.store.name, value, value);\n const request = this.store.add(value as ValueType);\n return wrapRequest(request);\n }\n\n /**\n * Gets the object with the specified key from the specified store, or null\n * if no object exists with the specified key.\n *\n * @key The key of the object to get.\n * @returns The object with the specified key or null if no object exists.\n */\n get(key: KeyType): PersistencePromise {\n const request = this.store.get(key);\n // We're doing an unsafe cast to ValueType.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return wrapRequest(request).next(result => {\n // Normalize nonexistence to null.\n if (result === undefined) {\n result = null;\n }\n logDebug(LOG_TAG, 'GET', this.store.name, key, result);\n return result;\n });\n }\n\n delete(key: KeyType | IDBKeyRange): PersistencePromise {\n logDebug(LOG_TAG, 'DELETE', this.store.name, key);\n const request = this.store.delete(key);\n return wrapRequest(request);\n }\n\n /**\n * If we ever need more of the count variants, we can add overloads. For now,\n * all we need is to count everything in a store.\n *\n * Returns the number of rows in the store.\n */\n count(): PersistencePromise {\n logDebug(LOG_TAG, 'COUNT', this.store.name);\n const request = this.store.count();\n return wrapRequest(request);\n }\n\n /** Loads all elements from the object store. */\n loadAll(): PersistencePromise;\n /** Loads all elements for the index range from the object store. */\n loadAll(range: IDBKeyRange): PersistencePromise;\n /** Loads all elements ordered by the given index. */\n loadAll(index: string): PersistencePromise;\n /**\n * Loads all elements from the object store that fall into the provided in the\n * index range for the given index.\n */\n loadAll(index: string, range: IDBKeyRange): PersistencePromise;\n loadAll(\n indexOrRange?: string | IDBKeyRange,\n range?: IDBKeyRange\n ): PersistencePromise {\n const iterateOptions = this.options(indexOrRange, range);\n // Use `getAll()` if the browser supports IndexedDB v3, as it is roughly\n // 20% faster.\n const store = iterateOptions.index\n ? this.store.index(iterateOptions.index)\n : this.store;\n if (typeof store.getAll === 'function') {\n const request = store.getAll(iterateOptions.range);\n return new PersistencePromise((resolve, reject) => {\n request.onerror = (event: Event) => {\n reject((event.target as IDBRequest).error!);\n };\n request.onsuccess = (event: Event) => {\n resolve((event.target as IDBRequest).result);\n };\n });\n } else {\n const cursor = this.cursor(iterateOptions);\n const results: ValueType[] = [];\n return this.iterateCursor(cursor, (key, value) => {\n results.push(value);\n }).next(() => {\n return results;\n });\n }\n }\n\n /**\n * Loads the first `count` elements from the provided index range. Loads all\n * elements if no limit is provided.\n */\n loadFirst(\n range: IDBKeyRange,\n count: number | null\n ): PersistencePromise {\n const request = this.store.getAll(\n range,\n count === null ? undefined : count\n );\n return new PersistencePromise((resolve, reject) => {\n request.onerror = (event: Event) => {\n reject((event.target as IDBRequest).error!);\n };\n request.onsuccess = (event: Event) => {\n resolve((event.target as IDBRequest).result);\n };\n });\n }\n\n deleteAll(): PersistencePromise;\n deleteAll(range: IDBKeyRange): PersistencePromise;\n deleteAll(index: string, range: IDBKeyRange): PersistencePromise;\n deleteAll(\n indexOrRange?: string | IDBKeyRange,\n range?: IDBKeyRange\n ): PersistencePromise {\n logDebug(LOG_TAG, 'DELETE ALL', this.store.name);\n const options = this.options(indexOrRange, range);\n options.keysOnly = false;\n const cursor = this.cursor(options);\n return this.iterateCursor(cursor, (key, value, control) => {\n // NOTE: Calling delete() on a cursor is documented as more efficient than\n // calling delete() on an object store with a single key\n // (https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/delete),\n // however, this requires us *not* to use a keysOnly cursor\n // (https://developer.mozilla.org/en-US/docs/Web/API/IDBCursor/delete). We\n // may want to compare the performance of each method.\n return control.delete();\n });\n }\n\n /**\n * Iterates over keys and values in an object store.\n *\n * @param options - Options specifying how to iterate the objects in the\n * store.\n * @param callback - will be called for each iterated object. Iteration can be\n * canceled at any point by calling the doneFn passed to the callback.\n * The callback can return a PersistencePromise if it performs async\n * operations but note that iteration will continue without waiting for them\n * to complete.\n * @returns A PersistencePromise that resolves once all PersistencePromises\n * returned by callbacks resolve.\n */\n iterate(\n callback: IterateCallback\n ): PersistencePromise;\n iterate(\n options: IterateOptions,\n callback: IterateCallback\n ): PersistencePromise;\n iterate(\n optionsOrCallback: IterateOptions | IterateCallback,\n callback?: IterateCallback\n ): PersistencePromise {\n let options;\n if (!callback) {\n options = {};\n callback = optionsOrCallback as IterateCallback;\n } else {\n options = optionsOrCallback as IterateOptions;\n }\n const cursor = this.cursor(options);\n return this.iterateCursor(cursor, callback);\n }\n\n /**\n * Iterates over a store, but waits for the given callback to complete for\n * each entry before iterating the next entry. This allows the callback to do\n * asynchronous work to determine if this iteration should continue.\n *\n * The provided callback should return `true` to continue iteration, and\n * `false` otherwise.\n */\n iterateSerial(\n callback: (k: KeyType, v: ValueType) => PersistencePromise\n ): PersistencePromise {\n const cursorRequest = this.cursor({});\n return new PersistencePromise((resolve, reject) => {\n cursorRequest.onerror = (event: Event) => {\n const error = checkForAndReportiOSError(\n (event.target as IDBRequest).error!\n );\n reject(error);\n };\n cursorRequest.onsuccess = (event: Event) => {\n const cursor: IDBCursorWithValue = (event.target as IDBRequest).result;\n if (!cursor) {\n resolve();\n return;\n }\n\n callback(cursor.primaryKey as KeyType, cursor.value).next(\n shouldContinue => {\n if (shouldContinue) {\n cursor.continue();\n } else {\n resolve();\n }\n }\n );\n };\n });\n }\n\n private iterateCursor(\n cursorRequest: IDBRequest,\n fn: IterateCallback\n ): PersistencePromise {\n const results: Array> = [];\n return new PersistencePromise((resolve, reject) => {\n cursorRequest.onerror = (event: Event) => {\n reject((event.target as IDBRequest).error!);\n };\n cursorRequest.onsuccess = (event: Event) => {\n const cursor: IDBCursorWithValue = (event.target as IDBRequest).result;\n if (!cursor) {\n resolve();\n return;\n }\n const controller = new IterationController(cursor);\n const userResult = fn(\n cursor.primaryKey as KeyType,\n cursor.value,\n controller\n );\n if (userResult instanceof PersistencePromise) {\n const userPromise: PersistencePromise = userResult.catch(\n err => {\n controller.done();\n return PersistencePromise.reject(err);\n }\n );\n results.push(userPromise);\n }\n if (controller.isDone) {\n resolve();\n } else if (controller.skipToKey === null) {\n cursor.continue();\n } else {\n cursor.continue(controller.skipToKey);\n }\n };\n }).next(() => PersistencePromise.waitFor(results));\n }\n\n private options(\n indexOrRange?: string | IDBKeyRange,\n range?: IDBKeyRange\n ): IterateOptions {\n let indexName: string | undefined = undefined;\n if (indexOrRange !== undefined) {\n if (typeof indexOrRange === 'string') {\n indexName = indexOrRange;\n } else {\n debugAssert(\n range === undefined,\n '3rd argument must not be defined if 2nd is a range.'\n );\n range = indexOrRange;\n }\n }\n return { index: indexName, range };\n }\n\n private cursor(options: IterateOptions): IDBRequest {\n let direction: IDBCursorDirection = 'next';\n if (options.reverse) {\n direction = 'prev';\n }\n if (options.index) {\n const index = this.store.index(options.index);\n if (options.keysOnly) {\n return index.openKeyCursor(options.range, direction);\n } else {\n return index.openCursor(options.range, direction);\n }\n } else {\n return this.store.openCursor(options.range, direction);\n }\n }\n}\n\n/**\n * Wraps an IDBRequest in a PersistencePromise, using the onsuccess / onerror\n * handlers to resolve / reject the PersistencePromise as appropriate.\n */\nfunction wrapRequest(request: IDBRequest): PersistencePromise {\n return new PersistencePromise((resolve, reject) => {\n request.onsuccess = (event: Event) => {\n const result = (event.target as IDBRequest).result;\n resolve(result);\n };\n\n request.onerror = (event: Event) => {\n const error = checkForAndReportiOSError(\n (event.target as IDBRequest).error!\n );\n reject(error);\n };\n });\n}\n\n// Guard so we only report the error once.\nlet reportedIOSError = false;\nfunction checkForAndReportiOSError(error: DOMException): Error {\n const iOSVersion = SimpleDb.getIOSVersion(getUA());\n if (iOSVersion >= 12.2 && iOSVersion < 13) {\n const IOS_ERROR =\n 'An internal error was encountered in the Indexed Database server';\n if (error.message.indexOf(IOS_ERROR) >= 0) {\n // Wrap error in a more descriptive one.\n const newError = new FirestoreError(\n 'internal',\n `IOS_INDEXEDDB_BUG1: IndexedDb has thrown '${IOS_ERROR}'. This is likely ` +\n `due to an unavoidable bug in iOS. See https://stackoverflow.com/q/56496296/110915 ` +\n `for details and a potential workaround.`\n );\n if (!reportedIOSError) {\n reportedIOSError = true;\n // Throw a global exception outside of this promise chain, for the user to\n // potentially catch.\n setTimeout(() => {\n throw newError;\n }, 0);\n }\n return newError;\n }\n }\n return error;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getModularInstance } from '@firebase/util';\n\nimport { Transaction as InternalTransaction } from '../core/transaction';\nimport {\n DEFAULT_TRANSACTION_OPTIONS,\n TransactionOptions as TransactionOptionsInternal,\n validateTransactionOptions\n} from '../core/transaction_options';\nimport { TransactionRunner } from '../core/transaction_runner';\nimport { fail } from '../util/assert';\nimport { newAsyncQueue } from '../util/async_queue_impl';\nimport { cast } from '../util/input_validation';\nimport { Deferred } from '../util/promise';\n\nimport { getDatastore } from './components';\nimport { Firestore } from './database';\nimport { FieldPath } from './field_path';\nimport {\n DocumentData,\n DocumentReference,\n PartialWithFieldValue,\n SetOptions,\n UpdateData,\n WithFieldValue\n} from './reference';\nimport {\n applyFirestoreDataConverter,\n LiteUserDataWriter\n} from './reference_impl';\nimport { DocumentSnapshot } from './snapshot';\nimport { TransactionOptions } from './transaction_options';\nimport {\n newUserDataReader,\n parseSetData,\n parseUpdateData,\n parseUpdateVarargs,\n UserDataReader\n} from './user_data_reader';\nimport { validateReference } from './write_batch';\n\n// TODO(mrschmidt) Consider using `BaseTransaction` as the base class in the\n// legacy SDK.\n\n/**\n * A reference to a transaction.\n *\n * The `Transaction` object passed to a transaction's `updateFunction` provides\n * the methods to read and write data within the transaction context. See\n * {@link runTransaction}.\n */\nexport class Transaction {\n // This is the tree-shakeable version of the Transaction class used in the\n // legacy SDK. The class is a close copy but takes different input and output\n // types. The firestore-exp SDK further extends this class to return its API\n // type.\n\n private readonly _dataReader: UserDataReader;\n\n /** @hideconstructor */\n constructor(\n protected readonly _firestore: Firestore,\n private readonly _transaction: InternalTransaction\n ) {\n this._dataReader = newUserDataReader(_firestore);\n }\n\n /**\n * Reads the document referenced by the provided {@link DocumentReference}.\n *\n * @param documentRef - A reference to the document to be read.\n * @returns A `DocumentSnapshot` with the read data.\n */\n get(\n documentRef: DocumentReference\n ): Promise> {\n const ref = validateReference(documentRef, this._firestore);\n const userDataWriter = new LiteUserDataWriter(this._firestore);\n return this._transaction.lookup([ref._key]).then(docs => {\n if (!docs || docs.length !== 1) {\n return fail(0x5de9, 'Mismatch in docs returned from document lookup.');\n }\n const doc = docs[0];\n if (doc.isFoundDocument()) {\n return new DocumentSnapshot(\n this._firestore,\n userDataWriter,\n doc.key,\n doc,\n ref.converter\n );\n } else if (doc.isNoDocument()) {\n return new DocumentSnapshot(\n this._firestore,\n userDataWriter,\n ref._key,\n null,\n ref.converter\n );\n } else {\n throw fail(\n 0x4801,\n 'BatchGetDocumentsRequest returned unexpected document',\n {\n doc\n }\n );\n }\n });\n }\n\n /**\n * Writes to the document referred to by the provided {@link\n * DocumentReference}. If the document does not exist yet, it will be created.\n *\n * @param documentRef - A reference to the document to be set.\n * @param data - An object of the fields and values for the document.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns This `Transaction` instance. Used for chaining method calls.\n */\n set(\n documentRef: DocumentReference,\n data: WithFieldValue\n ): this;\n /**\n * Writes to the document referred to by the provided {@link\n * DocumentReference}. If the document does not exist yet, it will be created.\n * If you provide `merge` or `mergeFields`, the provided data can be merged\n * into an existing document.\n *\n * @param documentRef - A reference to the document to be set.\n * @param data - An object of the fields and values for the document.\n * @param options - An object to configure the set behavior.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns This `Transaction` instance. Used for chaining method calls.\n */\n set(\n documentRef: DocumentReference,\n data: PartialWithFieldValue,\n options: SetOptions\n ): this;\n set(\n documentRef: DocumentReference,\n value: PartialWithFieldValue,\n options?: SetOptions\n ): this {\n const ref = validateReference(documentRef, this._firestore);\n const convertedValue = applyFirestoreDataConverter(\n ref.converter,\n value,\n options\n );\n const parsed = parseSetData(\n this._dataReader,\n 'Transaction.set',\n ref._key,\n convertedValue,\n ref.converter !== null,\n options\n );\n this._transaction.set(ref._key, parsed);\n return this;\n }\n\n /**\n * Updates fields in the document referred to by the provided {@link\n * DocumentReference}. The update will fail if applied to a document that does\n * not exist.\n *\n * @param documentRef - A reference to the document to be updated.\n * @param data - An object containing the fields and values with which to\n * update the document. Fields can contain dots to reference nested fields\n * within the document.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns This `Transaction` instance. Used for chaining method calls.\n */\n update(\n documentRef: DocumentReference,\n data: UpdateData\n ): this;\n /**\n * Updates fields in the document referred to by the provided {@link\n * DocumentReference}. The update will fail if applied to a document that does\n * not exist.\n *\n * Nested fields can be updated by providing dot-separated field path\n * strings or by providing `FieldPath` objects.\n *\n * @param documentRef - A reference to the document to be updated.\n * @param field - The first field to update.\n * @param value - The first value.\n * @param moreFieldsAndValues - Additional key/value pairs.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns This `Transaction` instance. Used for chaining method calls.\n */\n update(\n documentRef: DocumentReference,\n field: string | FieldPath,\n value: unknown,\n ...moreFieldsAndValues: unknown[]\n ): this;\n update(\n documentRef: DocumentReference,\n fieldOrUpdateData: string | FieldPath | UpdateData,\n value?: unknown,\n ...moreFieldsAndValues: unknown[]\n ): this {\n const ref = validateReference(documentRef, this._firestore);\n\n // For Compat types, we have to \"extract\" the underlying types before\n // performing validation.\n fieldOrUpdateData = getModularInstance(fieldOrUpdateData);\n\n let parsed;\n if (\n typeof fieldOrUpdateData === 'string' ||\n fieldOrUpdateData instanceof FieldPath\n ) {\n parsed = parseUpdateVarargs(\n this._dataReader,\n 'Transaction.update',\n ref._key,\n fieldOrUpdateData,\n value,\n moreFieldsAndValues\n );\n } else {\n parsed = parseUpdateData(\n this._dataReader,\n 'Transaction.update',\n ref._key,\n fieldOrUpdateData\n );\n }\n\n this._transaction.update(ref._key, parsed);\n return this;\n }\n\n /**\n * Deletes the document referred to by the provided {@link DocumentReference}.\n *\n * @param documentRef - A reference to the document to be deleted.\n * @returns This `Transaction` instance. Used for chaining method calls.\n */\n delete(\n documentRef: DocumentReference\n ): this {\n const ref = validateReference(documentRef, this._firestore);\n this._transaction.delete(ref._key);\n return this;\n }\n}\n\n/**\n * Executes the given `updateFunction` and then attempts to commit the changes\n * applied within the transaction. If any document read within the transaction\n * has changed, Cloud Firestore retries the `updateFunction`. If it fails to\n * commit after 5 attempts, the transaction fails.\n *\n * The maximum number of writes allowed in a single transaction is 500.\n *\n * @param firestore - A reference to the Firestore database to run this\n * transaction against.\n * @param updateFunction - The function to execute within the transaction\n * context.\n * @param options - An options object to configure maximum number of attempts to\n * commit.\n * @returns If the transaction completed successfully or was explicitly aborted\n * (the `updateFunction` returned a failed promise), the promise returned by the\n * `updateFunction `is returned here. Otherwise, if the transaction failed, a\n * rejected promise with the corresponding failure error is returned.\n */\nexport function runTransaction(\n firestore: Firestore,\n updateFunction: (transaction: Transaction) => Promise,\n options?: TransactionOptions\n): Promise {\n firestore = cast(firestore, Firestore);\n const datastore = getDatastore(firestore);\n const optionsWithDefaults: TransactionOptionsInternal = {\n ...DEFAULT_TRANSACTION_OPTIONS,\n ...options\n };\n validateTransactionOptions(optionsWithDefaults);\n const deferred = new Deferred();\n new TransactionRunner(\n newAsyncQueue(),\n datastore,\n optionsWithDefaults,\n internalTransaction =>\n updateFunction(new Transaction(firestore, internalTransaction)),\n deferred\n ).run();\n return deferred.promise;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n _registerComponent,\n registerVersion,\n SDK_VERSION\n} from '@firebase/app';\nimport { Component, ComponentType } from '@firebase/component';\n\nimport { version } from '../package.json';\nimport {\n LiteAppCheckTokenProvider,\n LiteAuthCredentialsProvider\n} from '../src/api/credentials';\nimport { databaseIdFromApp } from '../src/core/database_info';\nimport { setSDKVersion } from '../src/core/version';\nimport { Firestore } from '../src/lite-api/database';\n\ndeclare module '@firebase/component' {\n interface NameServiceMapping {\n 'firestore/lite': Firestore;\n }\n}\n\nexport function registerFirestore(): void {\n setSDKVersion(`${SDK_VERSION}_lite`);\n _registerComponent(\n new Component(\n 'firestore/lite',\n (container, { instanceIdentifier: databaseId, options: settings }) => {\n const app = container.getProvider('app').getImmediate()!;\n const firestoreInstance = new Firestore(\n new LiteAuthCredentialsProvider(\n container.getProvider('auth-internal')\n ),\n new LiteAppCheckTokenProvider(\n app,\n container.getProvider('app-check-internal')\n ),\n databaseIdFromApp(app, databaseId),\n app\n );\n if (settings) {\n firestoreInstance._setSettings(settings);\n }\n return firestoreInstance;\n },\n 'PUBLIC' as ComponentType.PUBLIC\n ).setMultipleInstances(true)\n );\n // RUNTIME_ENV and BUILD_TARGET are replaced by real values during the compilation\n registerVersion('firestore-lite', version, '__RUNTIME_ENV__');\n registerVersion('firestore-lite', version, '__BUILD_TARGET__');\n}\n","/**\n * Firestore Lite\n *\n * @remarks Firestore Lite is a small online-only SDK that allows read\n * and write access to your Firestore database. All operations connect\n * directly to the backend, and `onSnapshot()` APIs are not supported.\n * @packageDocumentation\n */\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { registerFirestore } from './register';\nregisterFirestore();\n\nexport {\n aggregateQuerySnapshotEqual,\n getCount,\n getAggregate,\n count,\n sum,\n average,\n aggregateFieldEqual\n} from '../src/lite-api/aggregate';\n\nexport {\n AggregateField,\n AggregateFieldType,\n AggregateSpec,\n AggregateSpecData,\n AggregateQuerySnapshot,\n AggregateType\n} from '../src/lite-api/aggregate_types';\n\nexport { FirestoreSettings as Settings } from '../src/lite-api/settings';\n\nexport {\n Firestore as Firestore,\n EmulatorMockTokenOptions,\n initializeFirestore,\n getFirestore,\n terminate,\n connectFirestoreEmulator\n} from '../src/lite-api/database';\n\nexport {\n DocumentData,\n UpdateData,\n WithFieldValue,\n PartialWithFieldValue,\n SetOptions,\n DocumentReference,\n Query,\n CollectionReference,\n collection,\n collectionGroup,\n doc,\n refEqual,\n queryEqual\n} from '../src/lite-api/reference';\n\nexport {\n and,\n endAt,\n endBefore,\n startAt,\n startAfter,\n limit,\n limitToLast,\n where,\n or,\n orderBy,\n query,\n QueryConstraint,\n QueryConstraintType,\n QueryCompositeFilterConstraint,\n QueryFilterConstraint,\n QueryFieldFilterConstraint,\n QueryOrderByConstraint,\n QueryLimitConstraint,\n QueryNonFilterConstraint,\n QueryStartAtConstraint,\n QueryEndAtConstraint,\n OrderByDirection,\n WhereFilterOp\n} from '../src/lite-api/query';\n\nexport {\n addDoc,\n deleteDoc,\n updateDoc,\n setDoc,\n getDoc,\n getDocs\n} from '../src/lite-api/reference_impl';\n\nexport {\n Primitive,\n NestedUpdateFields,\n ChildUpdateFields,\n AddPrefixToKeys,\n UnionToIntersection\n} from '../src/lite-api/types';\n\n// TODO(firestorelite): Add tests when Queries are usable\nexport { FieldPath, documentId } from '../src/lite-api/field_path';\n\n// TODO(firestorelite): Add tests when setDoc() is available\nexport { FieldValue } from '../src/lite-api/field_value';\n\nexport {\n increment,\n arrayRemove,\n arrayUnion,\n serverTimestamp,\n deleteField,\n vector\n} from '../src/lite-api/field_value_impl';\n\nexport {\n FirestoreDataConverter,\n DocumentSnapshot,\n QueryDocumentSnapshot,\n QuerySnapshot,\n snapshotEqual\n} from '../src/lite-api/snapshot';\n\nexport { VectorValue } from '../src/lite-api/vector_value';\n\nexport { WriteBatch, writeBatch } from '../src/lite-api/write_batch';\n\nexport { TransactionOptions } from '../src/lite-api/transaction_options';\n\nexport { Transaction, runTransaction } from '../src/lite-api/transaction';\n\nexport { setLogLevel, LogLevelString as LogLevel } from '../src/util/log';\n\nexport { Bytes } from '../src/lite-api/bytes';\n\nexport { GeoPoint } from '../src/lite-api/geo_point';\n\nexport { Timestamp } from '../src/lite-api/timestamp';\n\nexport { FirestoreErrorCode, FirestoreError } from '../src/util/error';\n"],"names":["User","constructor","uid","this","isAuthenticated","toKey","isEqual","otherUser","UNAUTHENTICATED","GOOGLE_CREDENTIALS","FIRST_PARTY","MOCK_USER","SDK_VERSION","__PRIVATE_logClient","Logger","setLogLevel","logLevel","__PRIVATE_logDebug","msg","obj","LogLevel","DEBUG","args","map","__PRIVATE_argToString","debug","__PRIVATE_logError","ERROR","error","__PRIVATE_logWarn","WARN","warn","__PRIVATE_formatJSON","value","JSON","stringify","e","fail","id","__PRIVATE_messageOrContext","context","message","__PRIVATE__fail","__PRIVATE_failure","toString","undefined","Error","__PRIVATE_hardAssert","assertion","__PRIVATE_debugCast","Code","FirestoreError","FirebaseError","code","super","name","__PRIVATE_Deferred","promise","Promise","resolve","reject","__PRIVATE_OAuthToken","user","type","headers","Map","set","__PRIVATE_EmptyAuthCredentialsProvider","getToken","invalidateToken","start","asyncQueue","changeListener","enqueueRetryable","shutdown","__PRIVATE_EmulatorAuthCredentialsProvider","token","__PRIVATE_LiteAuthCredentialsProvider","__PRIVATE_authProvider","auth","onInit","then","__PRIVATE_tokenData","accessToken","getUid","__PRIVATE_FirstPartyToken","__PRIVATE_sessionIndex","__PRIVATE_iamToken","__PRIVATE_authTokenFactory","__PRIVATE_getAuthToken","__PRIVATE__headers","__PRIVATE_authHeaderTokenValue","__PRIVATE_FirstPartyAuthCredentialsProvider","AppCheckToken","length","__PRIVATE_LiteAppCheckTokenProvider","app","__PRIVATE_appCheckProvider","appCheck","__PRIVATE_serverAppAppCheckToken","_isFirebaseServerApp","settings","appCheckToken","tokenResult","DatabaseInfo","databaseId","appId","persistenceKey","host","ssl","forceLongPolling","autoDetectLongPolling","longPollingOptions","useFetchStreams","isUsingEmulator","__PRIVATE_DEFAULT_DATABASE_NAME","DatabaseId","projectId","database","empty","isDefaultDatabase","other","__PRIVATE_randomBytes","__PRIVATE_nBytes","crypto","self","bytes","Uint8Array","getRandomValues","__PRIVATE_i","Math","floor","random","__PRIVATE_AutoId","newId","__PRIVATE_chars","__PRIVATE_maxMultiple","__PRIVATE_autoId","charAt","__PRIVATE_primitiveComparator","left","right","__PRIVATE_compareUtf8Strings","min","__PRIVATE_leftChar","__PRIVATE_rightChar","__PRIVATE_isSurrogate","__PRIVATE_MIN_SURROGATE","__PRIVATE_MAX_SURROGATE","s","c","charCodeAt","__PRIVATE_arrayEquals","comparator","every","index","__PRIVATE_DOCUMENT_KEY_NAME","BasePath","segments","offset","range","len","child","nameOrPath","slice","limit","forEach","segment","push","construct","popFirst","size","popLast","firstSegment","lastSegment","get","isEmpty","isPrefixOf","isImmediateParentOf","potentialChild","fn","end","toArray","p1","p2","comparison","compareSegments","__PRIVATE_lhs","__PRIVATE_rhs","__PRIVATE_isLhsNumeric","isNumericId","__PRIVATE_isRhsNumeric","extractNumericId","compare","startsWith","endsWith","Integer","fromString","substring","ResourcePath","canonicalString","join","toUriEncodedString","encodeURIComponent","pathComponents","path","indexOf","split","filter","emptyPath","__PRIVATE_identifierRegExp","FieldPath","isValidIdentifier","test","str","replace","isKeyField","keyField","fromServerFormat","current","__PRIVATE_addCurrentSegment","__PRIVATE_inBackticks","next","DocumentKey","fromPath","fromName","collectionGroup","hasCollectionId","collectionId","getCollectionGroup","getCollectionPath","k1","k2","isDocumentKey","fromSegments","__PRIVATE_validateNonEmptyArgument","__PRIVATE_functionName","__PRIVATE_argumentName","__PRIVATE_argument","__PRIVATE_validateDocumentPath","__PRIVATE_validateCollectionPath","__PRIVATE_isPlainObject","input","Object","getPrototypeOf","prototype","__PRIVATE_valueDescription","Array","__PRIVATE_customObjectName","__PRIVATE_tryGetCustomObjectType","__PRIVATE_cast","_delegate","description","__PRIVATE_validatePositiveNumber","n","__PRIVATE_cloneLongPollingOptions","options","clone","timeoutSeconds","__PRIVATE_lastUniqueDebugId","__PRIVATE_generateUniqueDebugId","__PRIVATE_generateInitialUniqueDebugId","round","__PRIVATE_maxResult","__PRIVATE_isNullOrUndefined","__PRIVATE_isNegativeZero","__PRIVATE_LOG_TAG","__PRIVATE_RPC_NAME_URL_MAPPING","__PRIVATE_RestConnection","__PRIVATE_shouldResourcePathBeIncludedInRequest","databaseInfo","proto","__PRIVATE_baseUrl","__PRIVATE_databasePath","__PRIVATE_requestParams","__PRIVATE_invokeRPC","__PRIVATE_rpcName","__PRIVATE_req","__PRIVATE_authToken","streamId","url","__PRIVATE_makeUrl","__PRIVATE_modifyHeadersForRequest","URL","__PRIVATE_forwardCredentials","isCloudWorkstation","__PRIVATE_performRPCRequest","response","err","__PRIVATE_invokeStreamingRPC","request","__PRIVATE_expectedResponseCount","__PRIVATE_getGoogApiClientValue","key","__PRIVATE_urlRpcName","terminate","__PRIVATE_RpcCode","RpcCode","__PRIVATE_mapCodeFromHttpStatus","status","__PRIVATE_FetchConnection","__PRIVATE_openStream","body","__PRIVATE_requestJson","__PRIVATE_fetchArgs","method","credentials","fetch","statusText","ok","__PRIVATE_errorResponse","json","isArray","__PRIVATE_errorMessage","__PRIVATE_AggregateImpl","alias","aggregateType","fieldPath","__PRIVATE_objectSize","count","hasOwnProperty","call","__PRIVATE_Base64DecodeError","__PRIVATE_WEB_SAFE","__PRIVATE_decodeBase64","__PRIVATE_encoded","String","fromCharCode","apply","base64","decodeStringToByteArray","DecodeBase64StringError","ByteString","binaryString","fromBase64String","fromUint8Array","array","__PRIVATE_binaryStringFromUint8Array","Symbol","iterator","done","toBase64","__PRIVATE_encodeBase64","raw","encodeByteArray","toUint8Array","__PRIVATE_uint8ArrayFromBinaryString","buffer","approximateByteSize","compareTo","EMPTY_BYTE_STRING","__PRIVATE_ISO_TIMESTAMP_REG_EXP","RegExp","__PRIVATE_normalizeTimestamp","date","nanos","__PRIVATE_fraction","exec","timestamp","__PRIVATE_nanoStr","substr","Number","__PRIVATE_parsedDate","Date","seconds","getTime","__PRIVATE_normalizeNumber","__PRIVATE_normalizeByteString","blob","property","typeString","__PRIVATE_optionalValue","result","__PRIVATE_validateJSON","__PRIVATE_schema","__PRIVATE_fieldValue","__PRIVATE_MIN_SECONDS","__PRIVATE_MS_TO_NANOS","Timestamp","now","fromMillis","fromDate","milliseconds","nanoseconds","toDate","toMillis","_compareTo","toJSON","_jsonSchemaVersion","fromJSON","_jsonSchema","valueOf","__PRIVATE_adjustedSeconds","padStart","__PRIVATE_isServerTimestamp","mapValue","fields","stringValue","__PRIVATE_getPreviousValue","previousValue","__PRIVATE_getLocalWriteTime","localWriteTime","timestampValue","__PRIVATE_TYPE_KEY","__PRIVATE_MAX_VALUE_TYPE","MAX_VALUE","__type__","__PRIVATE_VECTOR_VALUE_SENTINEL","__PRIVATE_VECTOR_MAP_VECTORS_KEY","__PRIVATE_typeOrder","__PRIVATE_isMaxValue","__PRIVATE_isVectorValue","__PRIVATE_valueEquals","__PRIVATE_leftType","booleanValue","__PRIVATE_timestampEquals","__PRIVATE_leftTimestamp","__PRIVATE_rightTimestamp","__PRIVATE_blobEquals","bytesValue","referenceValue","__PRIVATE_geoPointEquals","geoPointValue","latitude","longitude","__PRIVATE_numberEquals","integerValue","__PRIVATE_n1","doubleValue","__PRIVATE_n2","isNaN","arrayValue","values","__PRIVATE_objectEquals","__PRIVATE_leftMap","__PRIVATE_rightMap","__PRIVATE_arrayValueContains","__PRIVATE_haystack","__PRIVATE_needle","find","v","__PRIVATE_valueCompare","__PRIVATE_rightType","__PRIVATE_compareNumbers","__PRIVATE_leftNumber","__PRIVATE_rightNumber","__PRIVATE_compareTimestamps","__PRIVATE_compareBlobs","__PRIVATE_leftBytes","__PRIVATE_rightBytes","__PRIVATE_compareReferences","__PRIVATE_leftPath","__PRIVATE_rightPath","__PRIVATE_leftSegments","__PRIVATE_rightSegments","__PRIVATE_compareGeoPoints","__PRIVATE_compareArrays","__PRIVATE_compareVectors","__PRIVATE_leftArrayValue","__PRIVATE_rightArrayValue","__PRIVATE_lengthCompare","__PRIVATE_compareMaps","__PRIVATE_leftKeys","keys","__PRIVATE_rightKeys","sort","__PRIVATE_keyCompare","__PRIVATE_leftArray","__PRIVATE_rightArray","__PRIVATE_refValue","__PRIVATE_isNullValue","__PRIVATE_isNanValue","__PRIVATE_isMapValue","__PRIVATE_deepClone","source","target","val","Bound","position","inclusive","__PRIVATE_boundEquals","Filter","FieldFilter","field","op","create","createKeyFieldInFilter","__PRIVATE_KeyFieldFilter","__PRIVATE_ArrayContainsFilter","__PRIVATE_InFilter","__PRIVATE_NotInFilter","__PRIVATE_ArrayContainsAnyFilter","__PRIVATE_KeyFieldInFilter","__PRIVATE_KeyFieldNotInFilter","matches","doc","data","nullValue","matchesComparison","operator","isInequality","getFlattenedFilters","getFilters","CompositeFilter","filters","__PRIVATE_memoizedFlattenedFilters","__PRIVATE_compositeFilterIsConjunction","compositeFilter","reduce","__PRIVATE_subfilter","concat","assign","__PRIVATE_filterEquals","__PRIVATE_f1","__PRIVATE_f2","__PRIVATE_fieldFilterEquals","__PRIVATE_compositeFilterEquals","__PRIVATE_f1Filter","__PRIVATE_extractDocumentKeysFromArrayValue","some","OrderBy","dir","__PRIVATE_orderByEquals","SnapshotVersion","fromTimestamp","max","toMicroseconds","toTimestamp","SortedMap","root","LLRBNode","EMPTY","insert","copy","BLACK","remove","node","cmp","__PRIVATE_prunedNodes","minKey","maxKey","inorderTraversal","action","k","__PRIVATE_descriptions","reverseTraversal","getIterator","SortedMapIterator","getIteratorFrom","getReverseIterator","getReverseIteratorFrom","startKey","isReverse","nodeStack","getNext","pop","hasNext","peek","color","RED","fixUp","removeMin","isRed","moveRedLeft","__PRIVATE_smallest","rotateRight","moveRedRight","rotateLeft","colorFlip","__PRIVATE_nl","__PRIVATE_nr","checkMaxDepth","__PRIVATE_blackDepth","check","pow","LLRBEmptyNode","SortedSet","has","elem","first","last","cb","forEachInRange","iter","forEachWhile","firstAfterOrEqual","SortedSetIterator","add","unionWith","__PRIVATE_thisIt","__PRIVATE_otherIt","__PRIVATE_thisElem","__PRIVATE_otherElem","__PRIVATE_res","targetId","FieldMask","extraFields","__PRIVATE_mergedMaskSet","covers","__PRIVATE_fieldMaskPath","l","r","ObjectValue","__PRIVATE_currentLevel","getFieldsMap","setAll","parent","__PRIVATE_upserts","__PRIVATE_deletes","__PRIVATE_fieldsMap","applyChanges","__PRIVATE_nestedValue","__PRIVATE_inserts","MutableDocument","documentType","version","readTime","createTime","documentState","newInvalidDocument","documentKey","newFoundDocument","newNoDocument","newUnknownDocument","convertToFoundDocument","convertToNoDocument","convertToUnknownDocument","setHasCommittedMutations","setHasLocalMutations","setReadTime","hasLocalMutations","hasCommittedMutations","hasPendingWrites","isValidDocument","isFoundDocument","isNoDocument","isUnknownDocument","mutableCopy","__PRIVATE_TargetImpl","orderBy","startAt","endAt","__PRIVATE_memoizedCanonicalId","__PRIVATE_newTarget","__PRIVATE_QueryImpl","explicitOrderBy","limitType","__PRIVATE_memoizedNormalizedOrderBy","__PRIVATE_memoizedTarget","__PRIVATE_memoizedAggregateTarget","__PRIVATE_isCollectionGroupQuery","query","__PRIVATE_queryNormalizedOrderBy","__PRIVATE_queryImpl","__PRIVATE_fieldsNormalized","Set","__PRIVATE_lastDirection","__PRIVATE_inequalityFields","__PRIVATE_getInequalityFilterFields","__PRIVATE_queryToTarget","__PRIVATE__queryToTarget","__PRIVATE_orderBys","__PRIVATE_queryWithAddedFilter","__PRIVATE_newFilters","__PRIVATE_queryEquals","__PRIVATE_targetEquals","__PRIVATE_toDouble","serializer","useProto3Json","Infinity","toNumber","isSafeInteger","isInteger","MAX_SAFE_INTEGER","MIN_SAFE_INTEGER","__PRIVATE_toInteger","TransformOperation","_","__PRIVATE_ServerTimestampTransform","__PRIVATE_ArrayUnionTransformOperation","elements","__PRIVATE_ArrayRemoveTransformOperation","__PRIVATE_NumericIncrementTransformOperation","__PRIVATE_operand","FieldTransform","transform","Precondition","updateTime","exists","none","isNone","Mutation","__PRIVATE_SetMutation","precondition","fieldTransforms","getFieldMask","__PRIVATE_PatchMutation","fieldMask","__PRIVATE_DeleteMutation","__PRIVATE_VerifyMutation","__PRIVATE_DIRECTIONS","__PRIVATE_dirs","__PRIVATE_OPERATORS","__PRIVATE_ops","__PRIVATE_COMPOSITE_OPERATORS","JsonProtoSerializer","toISOString","__PRIVATE_toBytes","__PRIVATE_toVersion","__PRIVATE_fromVersion","__PRIVATE_toResourceName","__PRIVATE_toResourcePath","__PRIVATE_resourcePath","__PRIVATE_fullyQualifiedPrefixPath","__PRIVATE_toName","__PRIVATE_resource","__PRIVATE_fromResourceName","__PRIVATE_isValidResourceName","__PRIVATE_extractLocalPathFromResourceName","__PRIVATE_resourceName","__PRIVATE_toMutationDocument","__PRIVATE_fromBatchGetDocumentsResponse","__PRIVATE_fromFound","found","__PRIVATE_fromMissing","missing","toMutation","mutation","update","delete","updateMask","__PRIVATE_toDocumentMask","__PRIVATE_mutationType","verify","updateTransforms","__PRIVATE_toFieldTransform","__PRIVATE_fieldTransform","setToServerValue","appendMissingElements","removeAllFromArray","increment","currentDocument","__PRIVATE_toPrecondition","__PRIVATE_toQueryTarget","__PRIVATE_queryTarget","structuredQuery","from","allDescendants","__PRIVATE_toQueryPath","where","__PRIVATE_toFilters","__PRIVATE_toFilter","__PRIVATE_toOrder","order","__PRIVATE_toPropertyOrder","__PRIVATE_toFieldPathReference","direction","__PRIVATE_toDirection","__PRIVATE_toInt32Proto","__PRIVATE_toStartAtCursor","cursor","before","__PRIVATE_toEndAtCursor","__PRIVATE_toOperatorName","__PRIVATE_toCompositeOperatorName","__PRIVATE_toUnaryOrFieldFilter","unaryFilter","fieldFilter","__PRIVATE_toCompositeFilter","__PRIVATE_protos","__PRIVATE_canonicalFields","fieldPaths","__PRIVATE_newSerializer","__PRIVATE_ExponentialBackoff","__PRIVATE_queue","timerId","__PRIVATE_initialDelayMs","__PRIVATE_backoffFactor","__PRIVATE_maxDelayMs","__PRIVATE_currentBaseMs","__PRIVATE_timerPromise","reset","__PRIVATE_resetToMax","__PRIVATE_backoffAndRun","cancel","__PRIVATE_desiredDelayWithJitterMs","__PRIVATE_jitterDelayMs","__PRIVATE_delaySoFarMs","__PRIVATE_lastAttemptTime","__PRIVATE_remainingDelayMs","enqueueAfterDelay","__PRIVATE_skipBackoff","skipDelay","Datastore","__PRIVATE_DatastoreImpl","authCredentials","appCheckCredentials","connection","__PRIVATE_terminated","__PRIVATE_verifyInitialized","all","catch","async","__PRIVATE_invokeCommitRpc","datastore","mutations","__PRIVATE_datastoreImpl","writes","m","__PRIVATE_invokeBatchGetDocumentsRpc","documents","docs","__PRIVATE_invokeRunQueryRpc","M","document","__PRIVATE_fromDocument","__PRIVATE_invokeRunAggregationQueryRpc","__PRIVATE_aggregates","nt","__PRIVATE_aliasMap","__PRIVATE_toRunAggregationQueryRequest","__PRIVATE_skipAliasing","aggregations","__PRIVATE_aggregationNum","__PRIVATE_aggregate","__PRIVATE_serverAlias","avg","sum","structuredAggregationQuery","__PRIVATE_queryToAggregateTarget","__PRIVATE_filteredResult","__PRIVATE_unmappedAggregateFields","aggregateFields","__PRIVATE_accumulator","__PRIVATE_datastoreInstances","__PRIVATE_getDatastore","firestore","_terminated","__PRIVATE_newConnection","__PRIVATE_makeDatabaseInfo","experimentalForceLongPolling","experimentalAutoDetectLongPolling","experimentalLongPollingOptions","_databaseId","_persistenceKey","_freezeSettings","__PRIVATE_newDatastore","_authCredentials","_appCheckCredentials","__PRIVATE_LRU_MINIMUM_CACHE_SIZE_BYTES","__PRIVATE_DEFAULT_HOST","__PRIVATE_DEFAULT_SSL","FirestoreSettingsImpl","emulatorOptions","ignoreUndefinedProperties","localCache","cacheSizeBytes","__PRIVATE_validateIsNotUsedTogether","optionName1","argument1","optionName2","argument2","__PRIVATE_validateLongPollingOptions","__PRIVATE_longPollingOptionsEqual","__PRIVATE_options1","__PRIVATE_options2","Firestore","_app","_settings","_settingsFrozen","_emulatorOptions","_terminateTask","_initialized","_setSettings","__PRIVATE_makeAuthCredentialsProvider","_getSettings","_getEmulatorOptions","_delete","_terminate","_restart","__PRIVATE_removeComponents","initializeFirestore","provider","_getProvider","isInitialized","initialize","instanceIdentifier","getFirestore","__PRIVATE_appOrDatabaseId","__PRIVATE_optionalDatabaseId","getApp","db","getImmediate","identifier","__PRIVATE_emulator","getDefaultEmulatorHostnameAndPort","connectFirestoreEmulator","port","__PRIVATE_useSsl","__PRIVATE_existingConfig","__PRIVATE_newHostSetting","pingServer","updateEmulatorBanner","__PRIVATE_newConfig","deepEqual","mockUserToken","createMockUserToken","sub","user_id","_removeServiceInstance","AggregateField","_internalFieldPath","AggregateQuerySnapshot","_userDataWriter","_data","convertObjectMap","Query","converter","_query","withConverter","DocumentReference","_key","_path","CollectionReference","referencePath","__PRIVATE_newQueryForPath","parentPath","collection","pathSegments","getModularInstance","__PRIVATE_absolutePath","__PRIVATE_newQueryForCollectionGroup","arguments","refEqual","queryEqual","Bytes","byteString","_byteString","fieldNames","_internalPath","__PRIVATE_InternalFieldPath","documentId","FieldValue","_methodName","GeoPoint","isFinite","_lat","_long","VectorValue","_values","__PRIVATE_isPrimitiveArrayEqual","vectorValues","element","__PRIVATE_RESERVED_FIELD_REGEX","ParsedSetData","ParsedUpdateData","__PRIVATE_isWrite","__PRIVATE_dataSource","__PRIVATE_ParseContextImpl","__PRIVATE_validatePath","__PRIVATE_contextWith","configuration","__PRIVATE_childContextForField","__PRIVATE_childPath","__PRIVATE_arrayElement","__PRIVATE_validatePathSegment","__PRIVATE_childContextForFieldPath","__PRIVATE_childContextForArray","__PRIVATE_createError","reason","methodName","__PRIVATE_hasConverter","__PRIVATE_targetDoc","contains","__PRIVATE_UserDataReader","__PRIVATE_createContext","__PRIVATE_newUserDataReader","__PRIVATE_parseSetData","__PRIVATE_userDataReader","merge","mergeFields","__PRIVATE_validatePlainObject","__PRIVATE_updateData","__PRIVATE_parseObject","__PRIVATE_validatedFieldPaths","__PRIVATE_stringOrFieldPath","__PRIVATE_fieldPathFromArgument","__PRIVATE_fieldMaskContains","__PRIVATE_DeleteFieldValueImpl","_toFieldTransform","__PRIVATE_createSentinelChildContext","__PRIVATE_ServerTimestampFieldValueImpl","__PRIVATE_ArrayUnionFieldValueImpl","__PRIVATE__elements","__PRIVATE_parseContext","__PRIVATE_parsedElements","__PRIVATE_parseData","arrayUnion","__PRIVATE_ArrayRemoveFieldValueImpl","__PRIVATE_NumericIncrementFieldValueImpl","__PRIVATE__operand","__PRIVATE_numericIncrement","__PRIVATE_parseUpdateData","__PRIVATE_fieldMaskPaths","__PRIVATE_fieldPathFromDotSeparatedString","__PRIVATE_childContext","__PRIVATE_parsedValue","mask","__PRIVATE_parseUpdateVarargs","moreFieldsAndValues","__PRIVATE_parseQueryValue","__PRIVATE_allowArrays","__PRIVATE_looksLikeJsonObject","__PRIVATE_parseSentinelFieldValue","__PRIVATE_parseArray","__PRIVATE_entryIndex","entry","__PRIVATE_parsedEntry","__PRIVATE_parseScalarValue","__PRIVATE_thisDb","__PRIVATE_otherDb","__PRIVATE_parseVectorValue","__PRIVATE_FIELD_PATH_RESERVED","search","__PRIVATE_hasPath","__PRIVATE_hasDocument","DocumentSnapshot","_firestore","_document","_converter","ref","snapshot","QueryDocumentSnapshot","fromFirestore","convertValue","QuerySnapshot","_docs","callback","thisArg","snapshotEqual","arg","AppliableConstraint","QueryConstraint","__PRIVATE_queryConstraint","__PRIVATE_additionalQueryConstraints","queryConstraints","__PRIVATE_validateQueryConstraintArray","__PRIVATE_compositeFilterCount","QueryCompositeFilterConstraint","__PRIVATE_fieldFilterCount","QueryFieldFilterConstraint","constraint","_apply","_field","_op","_value","_create","_parse","__PRIVATE_validateNewFieldFilter","__PRIVATE_reader","__PRIVATE_newQueryFilter","__PRIVATE_dataReader","__PRIVATE_validateDisjunctiveFilterElements","__PRIVATE_referenceList","__PRIVATE_parseDocumentIdValue","opStr","_queryConstraints","__PRIVATE_parsedFilters","__PRIVATE_parsedFilter","_getOperator","__PRIVATE_validateNewFilter","__PRIVATE_testQuery","__PRIVATE_subFilters","__PRIVATE_subFilter","_getQueryConstraints","or","__PRIVATE_validateQueryFilterConstraint","and","QueryOrderByConstraint","_direction","__PRIVATE_newQueryOrderBy","__PRIVATE_queryWithAddedOrderBy","__PRIVATE_newOrderBy","directionStr","QueryLimitConstraint","_limit","_limitType","__PRIVATE_queryWithLimit","limitToLast","QueryStartAtConstraint","_docOrFields","_inclusive","bound","__PRIVATE_newQueryBoundFromDocOrFields","__PRIVATE_queryWithStartAt","__PRIVATE_docOrFields","startAfter","QueryEndAtConstraint","__PRIVATE_queryWithEndAt","endBefore","__PRIVATE_newQueryBoundFromDocument","components","__PRIVATE_newQueryBoundFromFields","__PRIVATE_rawValue","__PRIVATE_wrapped","__PRIVATE_documentIdValue","__PRIVATE_conflictingOp","__PRIVATE_findOpInsideFilters","__PRIVATE_operators","__PRIVATE_conflictingOps","AbstractUserDataWriter","serverTimestampBehavior","convertTimestamp","convertServerTimestamp","convertBytes","convertReference","convertGeoPoint","convertArray","convertObject","convertVectorValue","__PRIVATE_normalizedValue","convertDocumentKey","expectedDatabaseId","__PRIVATE_applyFirestoreDataConverter","__PRIVATE_convertedValue","toFirestore","__PRIVATE_LiteUserDataWriter","getDoc","reference","userDataWriter","getDocs","__PRIVATE_validateHasExplicitOrderByForLimitToLast","reverse","setDoc","__PRIVATE_parsed","updateDoc","__PRIVATE_fieldOrUpdateData","deleteDoc","addDoc","__PRIVATE_docRef","getCount","getAggregate","aggregateSpec","__PRIVATE_internalAggregates","__PRIVATE_mapToArray","__PRIVATE_aggregateResult","__PRIVATE_convertToAggregateQuerySnapshot","__PRIVATE_querySnapshot","average","aggregateFieldEqual","aggregateQuerySnapshotEqual","deleteField","serverTimestamp","arrayRemove","vector","WriteBatch","_commitHandler","_mutations","_committed","_dataReader","documentRef","_verifyNotCommitted","__PRIVATE_validateReference","commit","writeBatch","Transaction","readVersions","committed","lastTransactionError","writtenDocs","lookup","ensureCommitNotCalled","recordVersion","write","preconditionForUpdate","__PRIVATE_unwritten","__PRIVATE_docVersion","__PRIVATE_documentName","__PRIVATE_existingVersion","__PRIVATE_DEFAULT_TRANSACTION_OPTIONS","maxAttempts","__PRIVATE_TransactionRunner","updateFunction","deferred","__PRIVATE_attemptsRemaining","__PRIVATE_backoff","__PRIVATE_run","__PRIVATE_runWithBackOff","transaction","__PRIVATE_userPromise","__PRIVATE_tryRunUpdateFunction","enqueueAndForget","__PRIVATE_commitError","__PRIVATE_handleTransactionError","__PRIVATE_userPromiseError","__PRIVATE_isRetryableTransactionError","__PRIVATE_isPermanentError","getDocument","DelayedOperation","targetTimeMs","removalCallback","bind","createAndSchedule","delayMs","__PRIVATE_targetTime","__PRIVATE_delayedOp","timerHandle","setTimeout","handleDelayElapsed","clearTimeout","__PRIVATE_AsyncQueueImpl","__PRIVATE_tail","__PRIVATE_retryableOps","__PRIVATE__isShuttingDown","__PRIVATE_delayedOperations","__PRIVATE_operationInProgress","__PRIVATE_skipNonRestrictedTasks","__PRIVATE_timerIdsToSkip","__PRIVATE_visibilityHandler","visibilityState","addEventListener","isShuttingDown","enqueue","enqueueAndForgetEvenWhileRestricted","__PRIVATE_verifyNotFailed","__PRIVATE_enqueueInternal","enterRestrictedMode","purgeExistingTasks","removeEventListener","task","__PRIVATE_retryNextOp","shift","__PRIVATE_isIndexedDbTransactionError","__PRIVATE_newTail","__PRIVATE_getMessageOrStack","__PRIVATE_removedOp","__PRIVATE_removeDelayedOperation","__PRIVATE_messageOrStack","verifyOperationInProgress","__PRIVATE_drain","__PRIVATE_currentTail","__PRIVATE_containsDelayedOperation","__PRIVATE_runAllDelayedOperationsUntil","__PRIVATE_lastTimerId","a","b","__PRIVATE_skipDelaysForTimerId","splice","stack","includes","_transaction","runTransaction","__PRIVATE_optionsWithDefaults","__PRIVATE_validateTransactionOptions","__PRIVATE_newAsyncQueue","__PRIVATE_internalTransaction","__PRIVATE_registerFirestore","__PRIVATE_setSDKVersion","_registerComponent","Component","container","getProvider","__PRIVATE_firestoreInstance","__PRIVATE_databaseIdFromApp","setMultipleInstances","registerVersion"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;UAqBaA;IAUX,WAAAC,CAAqBC;QAAAC,KAAGD,MAAHA;AAAsB;IAE3C,eAAAE;QACE,OAAmB,QAAZD,KAAKD;AACb;;;;WAMD,KAAAG;QACE,OAAIF,KAAKC,oBACA,SAASD,KAAKD,MAEd;AAEV;IAED,OAAAI,CAAQC;QACN,OAAOA,EAAUL,QAAQC,KAAKD;AAC/B;;;8BA5BeF,MAAAQ,kBAAkB,IAAIR,KAAK;;;AAI3BA,KAAAS,qBAAqB,IAAIT,KAAK,2BAC9BA,KAAAU,cAAc,IAAIV,KAAK;AACvBA,KAAAW,YAAY,IAAIX,KAAK;;;;;;;;;;;;;;;;;;ACVhC,IAAIY;;;;;;;;;;;;;;;;;;ACKX,MAAMC,IAAY,IAAIC,EAAO;;;;;;;;;;;;;;GAoBvB,UAAUC,YAAYC;IAC1BH,EAAUE,YAAYC;AACxB;;SAEgBC,mBAASC,MAAgBC;IACvC,IAAIN,EAAUG,YAAYI,EAASC,OAAO;QACxC,MAAMC,IAAOH,EAAII,IAAIC;QACrBX,EAAUY,MAAM,cAAcb,OAAiBM,QAAUI;AAC1D;AACH;;SAEgBI,mBAASR,MAAgBC;IACvC,IAAIN,EAAUG,YAAYI,EAASO,OAAO;QACxC,MAAML,IAAOH,EAAII,IAAIC;QACrBX,EAAUe,MAAM,cAAchB,OAAiBM,QAAUI;AAC1D;AACH;;;;aAKgBO,kBAAQX,MAAgBC;IACtC,IAAIN,EAAUG,YAAYI,EAASU,MAAM;QACvC,MAAMR,IAAOH,EAAII,IAAIC;QACrBX,EAAUkB,KAAK,cAAcnB,OAAiBM,QAAUI;AACzD;AACH;;;;GAKA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IAAIC,EACF,mBACA,CAACC,IAAatX,oBAAoB7wB,GAAYuJ,SAAS3J;QACrD,MAAML,IAAM4oC,EAAUC,YAAY,OAAOjX,gBACnCkX,IAAoB,IAAI5Y,UAC5B,IAAIrxB,sCACF+pC,EAAUC,YAAY,mBAExB,IAAI9oC,oCACFC,GACA4oC,EAAUC,YAAY,wBtEiClB,SAAAE,4BACd/oC,GACAsB;YAEA,KAAK6H,OAAOE,UAAU2E,eAAeQ,MAAMxO,EAAIgK,SAAS,EAAC,gBACvD,MAAM,IAAI7M,eACRD,GACA;YAIJ,OAAO,IAAIkE,WAAWpB,EAAIgK,QAAQ3I,WAAYC;AAChD,SsE3CUynC,CAAkB/oC,GAAKS,IACvBT;QAKF,OAHIK,KACFyoC,EAAkBrY,aAAapwB,IAE1ByoC;AAAiB,QAE1B,UACAE,sBAAqB;;IAGzBC,EAAgB,kBAAkB1oB,GAAS,OAC3C0oB,EAAgB,kBAAkB1oB,GAAS;AAC7C,CCzCAioB;;"} \ No newline at end of file diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/internal.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/internal.d.ts new file mode 100644 index 0000000..4e493ac --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/internal.d.ts @@ -0,0 +1,6201 @@ +/** + * Firestore Lite + * + * @remarks Firestore Lite is a small online-only SDK that allows read + * and write access to your Firestore database. All operations connect + * directly to the backend, and `onSnapshot()` APIs are not supported. + * @packageDocumentation + */ + +import { DocumentData as DocumentData_2 } from '@firebase/firestore-types'; +import { EmulatorMockTokenOptions } from '@firebase/util'; +import { FirebaseApp } from '@firebase/app'; +import { FirebaseError } from '@firebase/util'; +import { _FirebaseService } from '@firebase/app'; +import { LogLevelString as LogLevel } from '@firebase/logger'; +import { SetOptions as SetOptions_2 } from '@firebase/firestore-types'; + +/** + * Converts Firestore's internal types to the JavaScript types that we expose + * to the user. + * + * @internal + */ +declare abstract class AbstractUserDataWriter { + convertValue(value: Value, serverTimestampBehavior?: ServerTimestampBehavior): unknown; + private convertObject; + /** + * @internal + */ + convertObjectMap(fields: ApiClientObjectMap | undefined, serverTimestampBehavior?: ServerTimestampBehavior): DocumentData_2; + /** + * @internal + */ + convertVectorValue(mapValue: MapValue): VectorValue; + private convertGeoPoint; + private convertArray; + private convertServerTimestamp; + private convertTimestamp; + protected convertDocumentKey(name: string, expectedDatabaseId: DatabaseId): DocumentKey; + protected abstract convertReference(name: string): unknown; + protected abstract convertBytes(bytes: ByteString): unknown; +} + +/** + * Describes a map whose keys are active target ids. We do not care about the type of the + * values. + */ +declare type ActiveTargets = SortedMap; + +/** + * Add a new document to specified `CollectionReference` with the given data, + * assigning it a document ID automatically. + * + * The result of this write will only be reflected in document reads that occur + * after the returned promise resolves. If the client is offline, the + * write fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @param reference - A reference to the collection to add this document to. + * @param data - An Object containing the data for the new document. + * @throws Error - If the provided input is not a valid Firestore document. + * @returns A `Promise` resolved with a `DocumentReference` pointing to the + * newly created document after it has been written to the backend. + */ +export declare function addDoc(reference: CollectionReference, data: WithFieldValue): Promise>; + +/** + * Returns a new map where every key is prefixed with the outer key appended + * to a dot. + */ +export declare type AddPrefixToKeys> = { + [K in keyof T & string as `${Prefix}.${K}`]+?: string extends K ? any : T[K]; +}; + +/** + * Represents an aggregation that can be performed by Firestore. + */ +export declare class AggregateField { + readonly _internalFieldPath?: FieldPath_2 | undefined; + /** A type string to uniquely identify instances of this class. */ + readonly type = "AggregateField"; + /** Indicates the aggregation operation of this AggregateField. */ + readonly aggregateType: AggregateType; + /** + * Create a new AggregateField + * @param aggregateType Specifies the type of aggregation operation to perform. + * @param _internalFieldPath Optionally specifies the field that is aggregated. + * @internal + */ + constructor(aggregateType?: AggregateType, _internalFieldPath?: FieldPath_2 | undefined); +} + +/** + * Compares two 'AggregateField` instances for equality. + * + * @param left Compare this AggregateField to the `right`. + * @param right Compare this AggregateField to the `left`. + */ +export declare function aggregateFieldEqual(left: AggregateField, right: AggregateField): boolean; + +/** + * The union of all `AggregateField` types that are supported by Firestore. + */ +export declare type AggregateFieldType = ReturnType | ReturnType | ReturnType; + +/** + * The results of executing an aggregation query. + */ +export declare class AggregateQuerySnapshot { + private readonly _userDataWriter; + private readonly _data; + /** A type string to uniquely identify instances of this class. */ + readonly type = "AggregateQuerySnapshot"; + /** + * The underlying query over which the aggregations recorded in this + * `AggregateQuerySnapshot` were performed. + */ + readonly query: Query; + /** @hideconstructor */ + constructor(query: Query, _userDataWriter: AbstractUserDataWriter, _data: ApiClientObjectMap); + /** + * Returns the results of the aggregations performed over the underlying + * query. + * + * The keys of the returned object will be the same as those of the + * `AggregateSpec` object specified to the aggregation method, and the values + * will be the corresponding aggregation result. + * + * @returns The results of the aggregations performed over the underlying + * query. + */ + data(): AggregateSpecData; +} + +/** + * Compares two `AggregateQuerySnapshot` instances for equality. + * + * Two `AggregateQuerySnapshot` instances are considered "equal" if they have + * underlying queries that compare equal, and the same data. + * + * @param left - The first `AggregateQuerySnapshot` to compare. + * @param right - The second `AggregateQuerySnapshot` to compare. + * + * @returns `true` if the objects are "equal", as defined above, or `false` + * otherwise. + */ +export declare function aggregateQuerySnapshotEqual(left: AggregateQuerySnapshot, right: AggregateQuerySnapshot): boolean; + +/** + * Specifies a set of aggregations and their aliases. + */ +export declare interface AggregateSpec { + [field: string]: AggregateFieldType; +} + +/** + * A type whose keys are taken from an `AggregateSpec`, and whose values are the + * result of the aggregation performed by the corresponding `AggregateField` + * from the input `AggregateSpec`. + */ +export declare type AggregateSpecData = { + [P in keyof T]: T[P] extends AggregateField ? U : never; +}; + +/** + * Union type representing the aggregate type to be performed. + */ +export declare type AggregateType = 'count' | 'avg' | 'sum'; + +/** + * Creates a new {@link QueryCompositeFilterConstraint} that is a conjunction of + * the given filter constraints. A conjunction filter includes a document if it + * satisfies all of the given filters. + * + * @param queryConstraints - Optional. The list of + * {@link QueryFilterConstraint}s to perform a conjunction for. These must be + * created with calls to {@link where}, {@link or}, or {@link and}. + * @returns The newly created {@link QueryCompositeFilterConstraint}. + */ +export declare function and(...queryConstraints: QueryFilterConstraint[]): QueryCompositeFilterConstraint; + +declare interface ApiClientObjectMap { + [k: string]: T; +} + +/** + * An `AppliableConstraint` is an abstraction of a constraint that can be applied + * to a Firestore query. + */ +declare abstract class AppliableConstraint { + /** + * Takes the provided {@link Query} and returns a copy of the {@link Query} with this + * {@link AppliableConstraint} applied. + */ + abstract _apply(query: Query): Query; +} + +/** + * Returns a special value that can be used with {@link (setDoc:1)} or {@link + * updateDoc:1} that tells the server to remove the given elements from any + * array value that already exists on the server. All instances of each element + * specified will be removed from the array. If the field being modified is not + * already an array it will be overwritten with an empty array. + * + * @param elements - The elements to remove from the array. + * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or + * `updateDoc()` + */ +export declare function arrayRemove(...elements: unknown[]): FieldValue; + +/** + * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link + * @firebase/firestore/lite#(updateDoc:1)} that tells the server to union the given elements with any array + * value that already exists on the server. Each specified element that doesn't + * already exist in the array will be added to the end. If the field being + * modified is not already an array it will be overwritten with an array + * containing exactly the specified elements. + * + * @param elements - The elements to union into the array. + * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or + * `updateDoc()`. + */ +export declare function arrayUnion(...elements: unknown[]): FieldValue; + +declare interface AsyncQueue { + readonly isShuttingDown: boolean; + /** + * Adds a new operation to the queue without waiting for it to complete (i.e. + * we ignore the Promise result). + */ + enqueueAndForget(op: () => Promise): void; + /** + * Regardless if the queue has initialized shutdown, adds a new operation to the + * queue without waiting for it to complete (i.e. we ignore the Promise result). + */ + enqueueAndForgetEvenWhileRestricted(op: () => Promise): void; + /** + * Initialize the shutdown of this queue. Once this method is called, the + * only possible way to request running an operation is through + * `enqueueEvenWhileRestricted()`. + * + * @param purgeExistingTasks Whether already enqueued tasked should be + * rejected (unless enqueued with `enqueueEvenWhileRestricted()`). Defaults + * to false. + */ + enterRestrictedMode(purgeExistingTasks?: boolean): void; + /** + * Adds a new operation to the queue. Returns a promise that will be resolved + * when the promise returned by the new operation is (with its value). + */ + enqueue(op: () => Promise): Promise; + /** + * Enqueue a retryable operation. + * + * A retryable operation is rescheduled with backoff if it fails with a + * IndexedDbTransactionError (the error type used by SimpleDb). All + * retryable operations are executed in order and only run if all prior + * operations were retried successfully. + */ + enqueueRetryable(op: () => Promise): void; + /** + * Schedules an operation to be queued on the AsyncQueue once the specified + * `delayMs` has elapsed. The returned DelayedOperation can be used to cancel + * or fast-forward the operation prior to its running. + */ + enqueueAfterDelay(timerId: TimerId, delayMs: number, op: () => Promise): DelayedOperation; + /** + * Verifies there's an operation currently in-progress on the AsyncQueue. + * Unfortunately we can't verify that the running code is in the promise chain + * of that operation, so this isn't a foolproof check, but it should be enough + * to catch some bugs. + */ + verifyOperationInProgress(): void; +} + +/** + * @internal + */ +declare type AuthTokenFactory = () => string; + +/** + * Create an AggregateField object that can be used to compute the average of + * a specified field over a range of documents in the result set of a query. + * @param field Specifies the field to average across the result set. + */ +export declare function average(field: string | FieldPath): AggregateField; + +/** + * Path represents an ordered sequence of string segments. + */ +declare abstract class BasePath> { + private segments; + private offset; + private len; + constructor(segments: string[], offset?: number, length?: number); + /** + * Abstract constructor method to construct an instance of B with the given + * parameters. + */ + protected abstract construct(segments: string[], offset?: number, length?: number): B; + /** + * Returns a String representation. + * + * Implementing classes are required to provide deterministic implementations as + * the String representation is used to obtain canonical Query IDs. + */ + abstract toString(): string; + get length(): number; + isEqual(other: B): boolean; + child(nameOrPath: string | B): B; + /** The index of one past the last segment of the path. */ + private limit; + popFirst(size?: number): B; + popLast(): B; + firstSegment(): string; + lastSegment(): string; + get(index: number): string; + isEmpty(): boolean; + isPrefixOf(other: this): boolean; + isImmediateParentOf(potentialChild: this): boolean; + forEach(fn: (segment: string) => void): void; + toArray(): string[]; + /** + * Compare 2 paths segment by segment, prioritizing numeric IDs + * (e.g., "__id123__") in numeric ascending order, followed by string + * segments in lexicographical order. + */ + static comparator>(p1: BasePath, p2: BasePath): number; + private static compareSegments; + private static isNumericId; + private static extractNumericId; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * BatchID is a locally assigned ID for a batch of mutations that have been + * applied. + */ +declare type BatchId = number; + +/** + * Represents a bound of a query. + * + * The bound is specified with the given components representing a position and + * whether it's just before or just after the position (relative to whatever the + * query order is). + * + * The position represents a logical index position for a query. It's a prefix + * of values for the (potentially implicit) order by clauses of a query. + * + * Bound provides a function to determine whether a document comes before or + * after a bound. This is influenced by whether the position is just before or + * just after the provided values. + */ +declare class Bound { + readonly position: Value[]; + readonly inclusive: boolean; + constructor(position: Value[], inclusive: boolean); +} + +/** + * Provides interfaces to save and read Firestore bundles. + */ +declare interface BundleCache { + /** + * Gets the saved `BundleMetadata` for a given `bundleId`, returns undefined + * if no bundle metadata is found under the given id. + */ + getBundleMetadata(transaction: PersistenceTransaction, bundleId: string): PersistencePromise; + /** + * Saves a `BundleMetadata` from a bundle into local storage, using its id as + * the persistent key. + */ + saveBundleMetadata(transaction: PersistenceTransaction, metadata: BundleMetadata_2): PersistencePromise; + /** + * Gets a saved `NamedQuery` for the given query name. Returns undefined if + * no queries are found under the given name. + */ + getNamedQuery(transaction: PersistenceTransaction, queryName: string): PersistencePromise; + /** + * Saves a `NamedQuery` from a bundle, using its name as the persistent key. + */ + saveNamedQuery(transaction: PersistenceTransaction, query: NamedQuery_2): PersistencePromise; +} + +/** Properties of a BundledQuery. */ +declare interface BundledQuery { + /** BundledQuery parent */ + parent?: string | null; + /** BundledQuery structuredQuery */ + structuredQuery?: StructuredQuery | null; + /** BundledQuery limitType */ + limitType?: LimitType_2 | null; +} + +/** + * Represents a Firestore bundle saved by the SDK in its local storage. + */ +declare interface BundleMetadata { + /** + * Id of the bundle. It is used together with `createTime` to determine if a + * bundle has been loaded by the SDK. + */ + readonly id: string; + /** Schema version of the bundle. */ + readonly version: number; + /** + * Set to the snapshot version of the bundle if created by the Server SDKs. + * Otherwise set to SnapshotVersion.MIN. + */ + readonly createTime: SnapshotVersion; +} + +/** Properties of a BundleMetadata. */ +declare interface BundleMetadata_2 { + /** BundleMetadata id */ + id?: string | null; + /** BundleMetadata createTime */ + createTime?: Timestamp_2 | null; + /** BundleMetadata version */ + version?: number | null; + /** BundleMetadata totalDocuments */ + totalDocuments?: number | null; + /** BundleMetadata totalBytes */ + totalBytes?: number | null; +} + +/** + * An immutable object representing an array of bytes. + */ +export declare class Bytes { + _byteString: ByteString; + /** @hideconstructor */ + constructor(byteString: ByteString); + /** + * Creates a new `Bytes` object from the given Base64 string, converting it to + * bytes. + * + * @param base64 - The Base64 string used to create the `Bytes` object. + */ + static fromBase64String(base64: string): Bytes; + /** + * Creates a new `Bytes` object from the given Uint8Array. + * + * @param array - The Uint8Array used to create the `Bytes` object. + */ + static fromUint8Array(array: Uint8Array): Bytes; + /** + * Returns the underlying bytes as a Base64-encoded string. + * + * @returns The Base64-encoded string created from the `Bytes` object. + */ + toBase64(): string; + /** + * Returns the underlying bytes in a new `Uint8Array`. + * + * @returns The Uint8Array created from the `Bytes` object. + */ + toUint8Array(): Uint8Array; + /** + * Returns a string representation of the `Bytes` object. + * + * @returns A string representation of the `Bytes` object. + */ + toString(): string; + /** + * Returns true if this `Bytes` object is equal to the provided one. + * + * @param other - The `Bytes` object to compare against. + * @returns true if this `Bytes` object is equal to the provided one. + */ + isEqual(other: Bytes): boolean; + static _jsonSchemaVersion: string; + static _jsonSchema: { + type: Property<"string">; + bytes: Property<"string">; + }; + /** + * Returns a JSON-serializable representation of this `Bytes` instance. + * + * @returns a JSON representation of this object. + */ + toJSON(): object; + /** + * Builds a `Bytes` instance from a JSON object created by {@link Bytes.toJSON}. + * + * @param json a JSON object represention of a `Bytes` instance + * @returns an instance of {@link Bytes} if the JSON object could be parsed. Throws a + * {@link FirestoreError} if an error occurs. + */ + static fromJSON(json: object): Bytes; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Immutable class that represents a "proto" byte string. + * + * Proto byte strings can either be Base64-encoded strings or Uint8Arrays when + * sent on the wire. This class abstracts away this differentiation by holding + * the proto byte string in a common class that must be converted into a string + * before being sent as a proto. + * @internal + */ +declare class ByteString { + private readonly binaryString; + static readonly EMPTY_BYTE_STRING: ByteString; + private constructor(); + static fromBase64String(base64: string): ByteString; + static fromUint8Array(array: Uint8Array): ByteString; + [Symbol.iterator](): Iterator; + toBase64(): string; + toUint8Array(): Uint8Array; + approximateByteSize(): number; + compareTo(other: ByteString): number; + isEqual(other: ByteString): boolean; +} + +declare const enum ChangeType { + Added = 0, + Removed = 1, + Modified = 2, + Metadata = 3 +} + +/** + * Helper for calculating the nested fields for a given type T1. This is needed + * to distribute union types such as `undefined | {...}` (happens for optional + * props) or `{a: A} | {b: B}`. + * + * In this use case, `V` is used to distribute the union types of `T[K]` on + * `Record`, since `T[K]` is evaluated as an expression and not distributed. + * + * See https://www.typescriptlang.org/docs/handbook/advanced-types.html#distributive-conditional-types + */ +export declare type ChildUpdateFields = V extends Record ? AddPrefixToKeys> : never; + +/** + * A randomly-generated key assigned to each Firestore instance at startup. + */ +declare type ClientId = string; + +/** + * Gets a `CollectionReference` instance that refers to the collection at + * the specified absolute path. + * + * @param firestore - A reference to the root `Firestore` instance. + * @param path - A slash-separated path to a collection. + * @param pathSegments - Additional path segments to apply relative to the first + * argument. + * @throws If the final path has an even number of segments and does not point + * to a collection. + * @returns The `CollectionReference` instance. + */ +export declare function collection(firestore: Firestore, path: string, ...pathSegments: string[]): CollectionReference; + +/** + * Gets a `CollectionReference` instance that refers to a subcollection of + * `reference` at the specified relative path. + * + * @param reference - A reference to a collection. + * @param path - A slash-separated path to a collection. + * @param pathSegments - Additional path segments to apply relative to the first + * argument. + * @throws If the final path has an even number of segments and does not point + * to a collection. + * @returns The `CollectionReference` instance. + */ +export declare function collection(reference: CollectionReference, path: string, ...pathSegments: string[]): CollectionReference; + +/** + * Gets a `CollectionReference` instance that refers to a subcollection of + * `reference` at the specified relative path. + * + * @param reference - A reference to a Firestore document. + * @param path - A slash-separated path to a collection. + * @param pathSegments - Additional path segments that will be applied relative + * to the first argument. + * @throws If the final path has an even number of segments and does not point + * to a collection. + * @returns The `CollectionReference` instance. + */ +export declare function collection(reference: DocumentReference, path: string, ...pathSegments: string[]): CollectionReference; + +/** + * Creates and returns a new `Query` instance that includes all documents in the + * database that are contained in a collection or subcollection with the + * given `collectionId`. + * + * @param firestore - A reference to the root `Firestore` instance. + * @param collectionId - Identifies the collections to query over. Every + * collection or subcollection with this ID as the last segment of its path + * will be included. Cannot contain a slash. + * @returns The created `Query`. + */ +export declare function collectionGroup(firestore: Firestore, collectionId: string): Query; + +/** + * A `CollectionReference` object can be used for adding documents, getting + * document references, and querying for documents (using {@link (query:1)}). + */ +export declare class CollectionReference extends Query { + readonly _path: ResourcePath; + /** The type of this Firestore reference. */ + readonly type = "collection"; + /** @hideconstructor */ + constructor(firestore: Firestore, converter: FirestoreDataConverter | null, _path: ResourcePath); + /** The collection's identifier. */ + get id(): string; + /** + * A string representing the path of the referenced collection (relative + * to the root of the database). + */ + get path(): string; + /** + * A reference to the containing `DocumentReference` if this is a + * subcollection. If this isn't a subcollection, the reference is null. + */ + get parent(): DocumentReference | null; + /** + * Applies a custom data converter to this `CollectionReference`, allowing you + * to use your own custom model objects with Firestore. When you call {@link + * addDoc} with the returned `CollectionReference` instance, the provided + * converter will convert between Firestore data of type `NewDbModelType` and + * your custom type `NewAppModelType`. + * + * @param converter - Converts objects to and from Firestore. + * @returns A `CollectionReference` that uses the provided converter. + */ + withConverter(converter: FirestoreDataConverter): CollectionReference; + /** + * Removes the current converter. + * + * @param converter - `null` removes the current converter. + * @returns A `CollectionReference` that does not + * use a converter. + */ + withConverter(converter: null): CollectionReference; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +declare type Comparator = (key1: K, key2: K) => number; + +declare interface ComponentConfiguration { + asyncQueue: AsyncQueue; + databaseInfo: DatabaseInfo; + authCredentials: CredentialsProvider; + appCheckCredentials: CredentialsProvider; + clientId: ClientId; + initialUser: User; + maxConcurrentLimboResolutions: number; +} + +declare type CompositeFilterOp = 'OPERATOR_UNSPECIFIED' | 'AND' | 'OR'; + +declare const enum CompositeOperator { + OR = "or", + AND = "and" +} + +/** + * Modify this instance to communicate with the Cloud Firestore emulator. + * + * Note: This must be called before this instance has been used to do any + * operations. + * + * @param firestore - The `Firestore` instance to configure to connect to the + * emulator. + * @param host - the emulator host (ex: localhost). + * @param port - the emulator port (ex: 9000). + * @param options.mockUserToken - the mock auth token to use for unit testing + * Security Rules. + */ +export declare function connectFirestoreEmulator(firestore: Firestore, host: string, port: number, options?: { + mockUserToken?: EmulatorMockTokenOptions | string; +}): void; + +/** + * Create an AggregateField object that can be used to compute the count of + * documents in the result set of a query. + */ +export declare function count(): AggregateField; + +/** + * A Listener for credential change events. The listener should fetch a new + * token and may need to invalidate other state if the current user has also + * changed. + */ +declare type CredentialChangeListener = (credential: T) => Promise; + +/** + * Provides methods for getting the uid and token for the current user and + * listening for changes. + */ +declare interface CredentialsProvider { + /** + * Starts the credentials provider and specifies a listener to be notified of + * credential changes (sign-in / sign-out, token changes). It is immediately + * called once with the initial user. + * + * The change listener is invoked on the provided AsyncQueue. + */ + start(asyncQueue: AsyncQueue, changeListener: CredentialChangeListener): void; + /** Requests a token for the current user. */ + getToken(): Promise; + /** + * Marks the last retrieved token as invalid, making the next GetToken request + * force-refresh the token. + */ + invalidateToken(): void; + shutdown(): void; +} + +/** Settings for private credentials */ +declare type CredentialsSettings = FirstPartyCredentialsSettings | ProviderCredentialsSettings; + +/** + * Represents the database ID a Firestore client is associated with. + * @internal + */ +declare class DatabaseId { + readonly projectId: string; + readonly database: string; + constructor(projectId: string, database?: string); + static empty(): DatabaseId; + get isDefaultDatabase(): boolean; + isEqual(other: {}): boolean; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +declare class DatabaseInfo { + readonly databaseId: DatabaseId; + readonly appId: string; + readonly persistenceKey: string; + readonly host: string; + readonly ssl: boolean; + readonly forceLongPolling: boolean; + readonly autoDetectLongPolling: boolean; + readonly longPollingOptions: ExperimentalLongPollingOptions; + readonly useFetchStreams: boolean; + readonly isUsingEmulator: boolean; + /** + * Constructs a DatabaseInfo using the provided host, databaseId and + * persistenceKey. + * + * @param databaseId - The database to use. + * @param appId - The Firebase App Id. + * @param persistenceKey - A unique identifier for this Firestore's local + * storage (used in conjunction with the databaseId). + * @param host - The Firestore backend host to connect to. + * @param ssl - Whether to use SSL when connecting. + * @param forceLongPolling - Whether to use the forceLongPolling option + * when using WebChannel as the network transport. + * @param autoDetectLongPolling - Whether to use the detectBufferingProxy + * option when using WebChannel as the network transport. + * @param longPollingOptions Options that configure long-polling. + * @param useFetchStreams Whether to use the Fetch API instead of + * XMLHTTPRequest + */ + constructor(databaseId: DatabaseId, appId: string, persistenceKey: string, host: string, ssl: boolean, forceLongPolling: boolean, autoDetectLongPolling: boolean, longPollingOptions: ExperimentalLongPollingOptions, useFetchStreams: boolean, isUsingEmulator: boolean); +} + +/** + * Datastore and its related methods are a wrapper around the external Google + * Cloud Datastore grpc API, which provides an interface that is more convenient + * for the rest of the client SDK architecture to consume. + */ +declare abstract class Datastore { + abstract terminate(): void; + abstract serializer: JsonProtoSerializer; +} + +/** + * Represents an operation scheduled to be run in the future on an AsyncQueue. + * + * It is created via DelayedOperation.createAndSchedule(). + * + * Supports cancellation (via cancel()) and early execution (via skipDelay()). + * + * Note: We implement `PromiseLike` instead of `Promise`, as the `Promise` type + * in newer versions of TypeScript defines `finally`, which is not available in + * IE. + */ +declare class DelayedOperation implements PromiseLike { + private readonly asyncQueue; + readonly timerId: TimerId; + readonly targetTimeMs: number; + private readonly op; + private readonly removalCallback; + private timerHandle; + private readonly deferred; + private constructor(); + get promise(): Promise; + /** + * Creates and returns a DelayedOperation that has been scheduled to be + * executed on the provided asyncQueue after the provided delayMs. + * + * @param asyncQueue - The queue to schedule the operation on. + * @param id - A Timer ID identifying the type of operation this is. + * @param delayMs - The delay (ms) before the operation should be scheduled. + * @param op - The operation to run. + * @param removalCallback - A callback to be called synchronously once the + * operation is executed or canceled, notifying the AsyncQueue to remove it + * from its delayedOperations list. + * PORTING NOTE: This exists to prevent making removeDelayedOperation() and + * the DelayedOperation class public. + */ + static createAndSchedule(asyncQueue: AsyncQueue, timerId: TimerId, delayMs: number, op: () => Promise, removalCallback: (op: DelayedOperation) => void): DelayedOperation; + /** + * Starts the timer. This is called immediately after construction by + * createAndSchedule(). + */ + private start; + /** + * Queues the operation to run immediately (if it hasn't already been run or + * canceled). + */ + skipDelay(): void; + /** + * Cancels the operation if it hasn't already been executed or canceled. The + * promise will be rejected. + * + * As long as the operation has not yet been run, calling cancel() provides a + * guarantee that the operation will not be run. + */ + cancel(reason?: string): void; + then: (onfulfilled?: ((value: T) => TResult1 | PromiseLike) | null | undefined, onrejected?: ((reason: any) => TResult2 | PromiseLike) | null | undefined) => Promise; + private handleDelayElapsed; + private clearTimeout; +} + +/** + * Deletes the document referred to by the specified `DocumentReference`. + * + * The deletion will only be reflected in document reads that occur after the + * returned promise resolves. If the client is offline, the + * delete fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @param reference - A reference to the document to delete. + * @returns A `Promise` resolved once the document has been successfully + * deleted from the backend. + */ +export declare function deleteDoc(reference: DocumentReference): Promise; + +/** + * Returns a sentinel for use with {@link @firebase/firestore/lite#(updateDoc:1)} or + * {@link @firebase/firestore/lite#(setDoc:1)} with `{merge: true}` to mark a field for deletion. + */ +export declare function deleteField(): FieldValue; + +/** + * The direction of sorting in an order by. + */ +declare const enum Direction { + ASCENDING = "asc", + DESCENDING = "desc" +} + +/** + * Gets a `DocumentReference` instance that refers to the document at the + * specified absolute path. + * + * @param firestore - A reference to the root `Firestore` instance. + * @param path - A slash-separated path to a document. + * @param pathSegments - Additional path segments that will be applied relative + * to the first argument. + * @throws If the final path has an odd number of segments and does not point to + * a document. + * @returns The `DocumentReference` instance. + */ +export declare function doc(firestore: Firestore, path: string, ...pathSegments: string[]): DocumentReference; + +/** + * Gets a `DocumentReference` instance that refers to a document within + * `reference` at the specified relative path. If no path is specified, an + * automatically-generated unique ID will be used for the returned + * `DocumentReference`. + * + * @param reference - A reference to a collection. + * @param path - A slash-separated path to a document. Has to be omitted to use + * auto-generated IDs. + * @param pathSegments - Additional path segments that will be applied relative + * to the first argument. + * @throws If the final path has an odd number of segments and does not point to + * a document. + * @returns The `DocumentReference` instance. + */ +export declare function doc(reference: CollectionReference, path?: string, ...pathSegments: string[]): DocumentReference; + +/** + * Gets a `DocumentReference` instance that refers to a document within + * `reference` at the specified relative path. + * + * @param reference - A reference to a Firestore document. + * @param path - A slash-separated path to a document. + * @param pathSegments - Additional path segments that will be applied relative + * to the first argument. + * @throws If the final path has an odd number of segments and does not point to + * a document. + * @returns The `DocumentReference` instance. + */ +export declare function doc(reference: DocumentReference, path: string, ...pathSegments: string[]): DocumentReference; + +/** + * Represents a document in Firestore with a key, version, data and whether the + * data has local mutations applied to it. + */ +declare interface Document_2 { + /** The key for this document */ + readonly key: DocumentKey; + /** + * The version of this document if it exists or a version at which this + * document was guaranteed to not exist. + */ + readonly version: SnapshotVersion; + /** + * The timestamp at which this document was read from the remote server. Uses + * `SnapshotVersion.min()` for documents created by the user. + */ + readonly readTime: SnapshotVersion; + /** + * The timestamp at which the document was created. This value increases + * monotonically when a document is deleted then recreated. It can also be + * compared to `createTime` of other documents and the `readTime` of a query. + */ + readonly createTime: SnapshotVersion; + /** The underlying data of this document or an empty value if no data exists. */ + readonly data: ObjectValue; + /** Returns whether local mutations were applied via the mutation queue. */ + readonly hasLocalMutations: boolean; + /** Returns whether mutations were applied based on a write acknowledgment. */ + readonly hasCommittedMutations: boolean; + /** + * Whether this document had a local mutation applied that has not yet been + * acknowledged by Watch. + */ + readonly hasPendingWrites: boolean; + /** + * Returns whether this document is valid (i.e. it is an entry in the + * RemoteDocumentCache, was created by a mutation or read from the backend). + */ + isValidDocument(): boolean; + /** + * Returns whether the document exists and its data is known at the current + * version. + */ + isFoundDocument(): boolean; + /** + * Returns whether the document is known to not exist at the current version. + */ + isNoDocument(): boolean; + /** + * Returns whether the document exists and its data is unknown at the current + * version. + */ + isUnknownDocument(): boolean; + isEqual(other: Document_2 | null | undefined): boolean; + /** Creates a mutable copy of this document. */ + mutableCopy(): MutableDocument; + toString(): string; +} + +declare type DocumentComparator = (doc1: Document_2, doc2: Document_2) => number; + +/** + * Document data (for use with {@link @firebase/firestore/lite#(setDoc:1)}) consists of fields mapped to + * values. + */ +export declare interface DocumentData { + /** A mapping between a field and its value. */ + [field: string]: any; +} + +/** + * Returns a special sentinel `FieldPath` to refer to the ID of a document. + * It can be used in queries to sort or filter by the document ID. + */ +export declare function documentId(): FieldPath; + +/** + * @internal + */ +declare class DocumentKey { + readonly path: ResourcePath; + constructor(path: ResourcePath); + static fromPath(path: string): DocumentKey; + static fromName(name: string): DocumentKey; + static empty(): DocumentKey; + get collectionGroup(): string; + /** Returns true if the document is in the specified collectionId. */ + hasCollectionId(collectionId: string): boolean; + /** Returns the collection group (i.e. the name of the parent collection) for this key. */ + getCollectionGroup(): string; + /** Returns the fully qualified path to the parent collection. */ + getCollectionPath(): ResourcePath; + isEqual(other: DocumentKey | null): boolean; + toString(): string; + static comparator(k1: DocumentKey, k2: DocumentKey): number; + static isDocumentKey(path: ResourcePath): boolean; + /** + * Creates and returns a new document key with the given segments. + * + * @param segments - The segments of the path to the document + * @returns A new instance of DocumentKey + */ + static fromSegments(segments: string[]): DocumentKey; +} + +declare type DocumentKeyMap = ObjectMap; + +declare type DocumentKeySet = SortedSet; + +declare type DocumentMap = SortedMap; + +/** + * Provides methods to read and write document overlays. + * + * An overlay is a saved mutation, that gives a local view of a document when + * applied to the remote version of the document. + * + * Each overlay stores the largest batch ID that is included in the overlay, + * which allows us to remove the overlay once all batches leading up to it have + * been acknowledged. + */ +declare interface DocumentOverlayCache { + /** + * Gets the saved overlay mutation for the given document key. + * Returns null if there is no overlay for that key. + */ + getOverlay(transaction: PersistenceTransaction, key: DocumentKey): PersistencePromise; + /** + * Gets the saved overlay mutation for the given document keys. Skips keys for + * which there are no overlays. + */ + getOverlays(transaction: PersistenceTransaction, keys: DocumentKey[]): PersistencePromise; + /** + * Saves the given document mutation map to persistence as overlays. + * All overlays will have their largest batch id set to `largestBatchId`. + */ + saveOverlays(transaction: PersistenceTransaction, largestBatchId: number, overlays: MutationMap): PersistencePromise; + /** Removes overlays for the given document keys and batch ID. */ + removeOverlaysForBatchId(transaction: PersistenceTransaction, documentKeys: DocumentKeySet, batchId: number): PersistencePromise; + /** + * Returns all saved overlays for the given collection. + * + * @param transaction - The persistence transaction to use for this operation. + * @param collection - The collection path to get the overlays for. + * @param sinceBatchId - The minimum batch ID to filter by (exclusive). + * Only overlays that contain a change past `sinceBatchId` are returned. + * @returns Mapping of each document key in the collection to its overlay. + */ + getOverlaysForCollection(transaction: PersistenceTransaction, collection: ResourcePath, sinceBatchId: number): PersistencePromise; + /** + * Returns `count` overlays with a batch ID higher than `sinceBatchId` for the + * provided collection group, processed by ascending batch ID. The method + * always returns all overlays for a batch even if the last batch contains + * more documents than the remaining limit. + * + * @param transaction - The persistence transaction used for this operation. + * @param collectionGroup - The collection group to get the overlays for. + * @param sinceBatchId - The minimum batch ID to filter by (exclusive). + * Only overlays that contain a change past `sinceBatchId` are returned. + * @param count - The number of overlays to return. Can be exceeded if the last + * batch contains more entries. + * @return Mapping of each document key in the collection group to its overlay. + */ + getOverlaysForCollectionGroup(transaction: PersistenceTransaction, collectionGroup: string, sinceBatchId: number, count: number): PersistencePromise; +} + +/** + * A `DocumentReference` refers to a document location in a Firestore database + * and can be used to write, read, or listen to the location. The document at + * the referenced location may or may not exist. + */ +export declare class DocumentReference { + /** + * If provided, the `FirestoreDataConverter` associated with this instance. + */ + readonly converter: FirestoreDataConverter | null; + readonly _key: DocumentKey; + /** The type of this Firestore reference. */ + readonly type = "document"; + /** + * The {@link Firestore} instance the document is in. + * This is useful for performing transactions, for example. + */ + readonly firestore: Firestore; + /** @hideconstructor */ + constructor(firestore: Firestore, + /** + * If provided, the `FirestoreDataConverter` associated with this instance. + */ + converter: FirestoreDataConverter | null, _key: DocumentKey); + get _path(): ResourcePath; + /** + * The document's identifier within its collection. + */ + get id(): string; + /** + * A string representing the path of the referenced document (relative + * to the root of the database). + */ + get path(): string; + /** + * The collection this `DocumentReference` belongs to. + */ + get parent(): CollectionReference; + /** + * Applies a custom data converter to this `DocumentReference`, allowing you + * to use your own custom model objects with Firestore. When you call {@link + * @firebase/firestore/lite#(setDoc:1)}, {@link @firebase/firestore/lite#getDoc}, etc. with the returned `DocumentReference` + * instance, the provided converter will convert between Firestore data of + * type `NewDbModelType` and your custom type `NewAppModelType`. + * + * @param converter - Converts objects to and from Firestore. + * @returns A `DocumentReference` that uses the provided converter. + */ + withConverter(converter: FirestoreDataConverter): DocumentReference; + /** + * Removes the current converter. + * + * @param converter - `null` removes the current converter. + * @returns A `DocumentReference` that does not + * use a converter. + */ + withConverter(converter: null): DocumentReference; + static _jsonSchemaVersion: string; + static _jsonSchema: { + type: Property<"string">; + referencePath: Property<"string">; + }; + /** + * Returns a JSON-serializable representation of this `DocumentReference` instance. + * + * @returns a JSON representation of this object. + */ + toJSON(): object; + /** + * Builds a `DocumentReference` instance from a JSON object created by + * {@link DocumentReference.toJSON}. + * + * @param firestore - The {@link Firestore} instance the snapshot should be loaded for. + * @param json a JSON object represention of a `DocumentReference` instance + * @returns an instance of {@link DocumentReference} if the JSON object could be parsed. Throws a + * {@link FirestoreError} if an error occurs. + */ + static fromJSON(firestore: Firestore, json: object): DocumentReference; + /** + * Builds a `DocumentReference` instance from a JSON object created by + * {@link DocumentReference.toJSON}. + * + * @param firestore - The {@link Firestore} instance the snapshot should be loaded for. + * @param json a JSON object represention of a `DocumentReference` instance + * @param converter - Converts objects to and from Firestore. + * @returns an instance of {@link DocumentReference} if the JSON object could be parsed. Throws a + * {@link FirestoreError} if an error occurs. + */ + static fromJSON(firestore: Firestore, json: object, converter: FirestoreDataConverter): DocumentReference; +} + +/** + * DocumentSet is an immutable (copy-on-write) collection that holds documents + * in order specified by the provided comparator. We always add a document key + * comparator on top of what is provided to guarantee document equality based on + * the key. + */ +declare class DocumentSet { + /** + * Returns an empty copy of the existing DocumentSet, using the same + * comparator. + */ + static emptySet(oldSet: DocumentSet): DocumentSet; + private comparator; + private keyedMap; + private sortedSet; + /** The default ordering is by key if the comparator is omitted */ + constructor(comp?: DocumentComparator); + has(key: DocumentKey): boolean; + get(key: DocumentKey): Document_2 | null; + first(): Document_2 | null; + last(): Document_2 | null; + isEmpty(): boolean; + /** + * Returns the index of the provided key in the document set, or -1 if the + * document key is not present in the set; + */ + indexOf(key: DocumentKey): number; + get size(): number; + /** Iterates documents in order defined by "comparator" */ + forEach(cb: (doc: Document_2) => void): void; + /** Inserts or updates a document with the same key */ + add(doc: Document_2): DocumentSet; + /** Deletes a document with a given key */ + delete(key: DocumentKey): DocumentSet; + isEqual(other: DocumentSet | null | undefined): boolean; + toString(): string; + private copy; +} + +/** + * A `DocumentSnapshot` contains data read from a document in your Firestore + * database. The data can be extracted with `.data()` or `.get()` to + * get a specific field. + * + * For a `DocumentSnapshot` that points to a non-existing document, any data + * access will return 'undefined'. You can use the `exists()` method to + * explicitly verify a document's existence. + */ +export declare class DocumentSnapshot { + _firestore: Firestore; + _userDataWriter: AbstractUserDataWriter; + _key: DocumentKey; + _document: Document_2 | null; + _converter: UntypedFirestoreDataConverter | null; + /** @hideconstructor protected */ + constructor(_firestore: Firestore, _userDataWriter: AbstractUserDataWriter, _key: DocumentKey, _document: Document_2 | null, _converter: UntypedFirestoreDataConverter | null); + /** Property of the `DocumentSnapshot` that provides the document's ID. */ + get id(): string; + /** + * The `DocumentReference` for the document included in the `DocumentSnapshot`. + */ + get ref(): DocumentReference; + /** + * Signals whether or not the document at the snapshot's location exists. + * + * @returns true if the document exists. + */ + exists(): this is QueryDocumentSnapshot; + /** + * Retrieves all fields in the document as an `Object`. Returns `undefined` if + * the document doesn't exist. + * + * @returns An `Object` containing all fields in the document or `undefined` + * if the document doesn't exist. + */ + data(): AppModelType | undefined; + /** + * Retrieves the field specified by `fieldPath`. Returns `undefined` if the + * document or field doesn't exist. + * + * @param fieldPath - The path (for example 'foo' or 'foo.bar') to a specific + * field. + * @returns The data at the specified field location or undefined if no such + * field exists in the document. + */ + get(fieldPath: string | FieldPath): any; +} + +declare type DocumentVersionMap = SortedMap; + +declare interface DocumentViewChange { + type: ChangeType; + doc: Document_2; +} +export { EmulatorMockTokenOptions } + +/** + * Creates a {@link QueryEndAtConstraint} that modifies the result set to end at + * the provided document (inclusive). The end position is relative to the order + * of the query. The document must contain all of the fields provided in the + * orderBy of the query. + * + * @param snapshot - The snapshot of the document to end at. + * @returns A {@link QueryEndAtConstraint} to pass to `query()` + */ +export declare function endAt(snapshot: DocumentSnapshot): QueryEndAtConstraint; + +/** + * Creates a {@link QueryEndAtConstraint} that modifies the result set to end at + * the provided fields relative to the order of the query. The order of the field + * values must match the order of the order by clauses of the query. + * + * @param fieldValues - The field values to end this query at, in order + * of the query's order by. + * @returns A {@link QueryEndAtConstraint} to pass to `query()` + */ +export declare function endAt(...fieldValues: unknown[]): QueryEndAtConstraint; + +/** + * Creates a {@link QueryEndAtConstraint} that modifies the result set to end + * before the provided document (exclusive). The end position is relative to the + * order of the query. The document must contain all of the fields provided in + * the orderBy of the query. + * + * @param snapshot - The snapshot of the document to end before. + * @returns A {@link QueryEndAtConstraint} to pass to `query()` + */ +export declare function endBefore(snapshot: DocumentSnapshot): QueryEndAtConstraint; + +/** + * Creates a {@link QueryEndAtConstraint} that modifies the result set to end + * before the provided fields relative to the order of the query. The order of + * the field values must match the order of the order by clauses of the query. + * + * @param fieldValues - The field values to end this query before, in order + * of the query's order by. + * @returns A {@link QueryEndAtConstraint} to pass to `query()` + */ +export declare function endBefore(...fieldValues: unknown[]): QueryEndAtConstraint; + +declare interface Entry { + key: K; + value: V; +} + +/** + * EventManager is responsible for mapping queries to query event emitters. + * It handles "fan-out". -- Identical queries will re-use the same watch on the + * backend. + * + * PORTING NOTE: On Web, EventManager `onListen` and `onUnlisten` need to be + * assigned to SyncEngine's `listen()` and `unlisten()` API before usage. This + * allows users to tree-shake the Watch logic. + */ +declare interface EventManager { + onListen?: (query: Query_2, enableRemoteListen: boolean) => Promise; + onUnlisten?: (query: Query_2, disableRemoteListen: boolean) => Promise; + onFirstRemoteStoreListen?: (query: Query_2) => Promise; + onLastRemoteStoreUnlisten?: (query: Query_2) => Promise; + terminate(): void; +} + +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Options that configure the SDK’s underlying network transport (WebChannel) + * when long-polling is used. + * + * Note: This interface is "experimental" and is subject to change. + * + * See `FirestoreSettings.experimentalAutoDetectLongPolling`, + * `FirestoreSettings.experimentalForceLongPolling`, and + * `FirestoreSettings.experimentalLongPollingOptions`. + */ +declare interface ExperimentalLongPollingOptions { + /** + * The desired maximum timeout interval, in seconds, to complete a + * long-polling GET response. Valid values are between 5 and 30, inclusive. + * Floating point values are allowed and will be rounded to the nearest + * millisecond. + * + * By default, when long-polling is used the "hanging GET" request sent by + * the client times out after 30 seconds. To request a different timeout + * from the server, set this setting with the desired timeout. + * + * Changing the default timeout may be useful, for example, if the buffering + * proxy that necessitated enabling long-polling in the first place has a + * shorter timeout for hanging GET requests, in which case setting the + * long-polling timeout to a shorter value, such as 25 seconds, may fix + * prematurely-closed hanging GET requests. + * For example, see https://github.com/firebase/firebase-js-sdk/issues/6987. + */ + timeoutSeconds?: number; +} + +declare class FieldFilter extends Filter { + readonly field: FieldPath_2; + readonly op: Operator; + readonly value: Value; + protected constructor(field: FieldPath_2, op: Operator, value: Value); + /** + * Creates a filter based on the provided arguments. + */ + static create(field: FieldPath_2, op: Operator, value: Value): FieldFilter; + private static createKeyFieldInFilter; + matches(doc: Document_2): boolean; + protected matchesComparison(comparison: number): boolean; + isInequality(): boolean; + getFlattenedFilters(): readonly FieldFilter[]; + getFilters(): Filter[]; +} + +declare type FieldFilterOp = 'OPERATOR_UNSPECIFIED' | 'LESS_THAN' | 'LESS_THAN_OR_EQUAL' | 'GREATER_THAN' | 'GREATER_THAN_OR_EQUAL' | 'EQUAL' | 'NOT_EQUAL' | 'ARRAY_CONTAINS' | 'IN' | 'ARRAY_CONTAINS_ANY' | 'NOT_IN'; + +/** + * An index definition for field indexes in Firestore. + * + * Every index is associated with a collection. The definition contains a list + * of fields and their index kind (which can be `ASCENDING`, `DESCENDING` or + * `CONTAINS` for ArrayContains/ArrayContainsAny queries). + * + * Unlike the backend, the SDK does not differentiate between collection or + * collection group-scoped indices. Every index can be used for both single + * collection and collection group queries. + */ +declare class FieldIndex { + /** + * The index ID. Returns -1 if the index ID is not available (e.g. the index + * has not yet been persisted). + */ + readonly indexId: number; + /** The collection ID this index applies to. */ + readonly collectionGroup: string; + /** The field segments for this index. */ + readonly fields: IndexSegment[]; + /** Shows how up-to-date the index is for the current user. */ + readonly indexState: IndexState; + /** An ID for an index that has not yet been added to persistence. */ + static UNKNOWN_ID: number; + constructor( + /** + * The index ID. Returns -1 if the index ID is not available (e.g. the index + * has not yet been persisted). + */ + indexId: number, + /** The collection ID this index applies to. */ + collectionGroup: string, + /** The field segments for this index. */ + fields: IndexSegment[], + /** Shows how up-to-date the index is for the current user. */ + indexState: IndexState); +} + +/** + * Provides a set of fields that can be used to partially patch a document. + * FieldMask is used in conjunction with ObjectValue. + * Examples: + * foo - Overwrites foo entirely with the provided value. If foo is not + * present in the companion ObjectValue, the field is deleted. + * foo.bar - Overwrites only the field bar of the object foo. + * If foo is not an object, foo is replaced with an object + * containing foo + */ +declare class FieldMask { + readonly fields: FieldPath_2[]; + constructor(fields: FieldPath_2[]); + static empty(): FieldMask; + /** + * Returns a new FieldMask object that is the result of adding all the given + * fields paths to this field mask. + */ + unionWith(extraFields: FieldPath_2[]): FieldMask; + /** + * Verifies that `fieldPath` is included by at least one field in this field + * mask. + * + * This is an O(n) operation, where `n` is the size of the field mask. + */ + covers(fieldPath: FieldPath_2): boolean; + isEqual(other: FieldMask): boolean; +} + +/** + * A `FieldPath` refers to a field in a document. The path may consist of a + * single field name (referring to a top-level field in the document), or a + * list of field names (referring to a nested field in the document). + * + * Create a `FieldPath` by providing field names. If more than one field + * name is provided, the path will point to a nested field in a document. + */ +export declare class FieldPath { + /** Internal representation of a Firestore field path. */ + readonly _internalPath: FieldPath_2; + /** + * Creates a `FieldPath` from the provided field names. If more than one field + * name is provided, the path will point to a nested field in a document. + * + * @param fieldNames - A list of field names. + */ + constructor(...fieldNames: string[]); + /** + * Returns true if this `FieldPath` is equal to the provided one. + * + * @param other - The `FieldPath` to compare against. + * @returns true if this `FieldPath` is equal to the provided one. + */ + isEqual(other: FieldPath): boolean; +} + +/** + * A dot-separated path for navigating sub-objects within a document. + * @internal + */ +declare class FieldPath_2 extends BasePath { + protected construct(segments: string[], offset?: number, length?: number): FieldPath_2; + /** + * Returns true if the string could be used as a segment in a field path + * without escaping. + */ + private static isValidIdentifier; + canonicalString(): string; + toString(): string; + /** + * Returns true if this field references the key of a document. + */ + isKeyField(): boolean; + /** + * The field designating the key of a document. + */ + static keyField(): FieldPath_2; + /** + * Parses a field string from the given server-formatted string. + * + * - Splitting the empty string is not allowed (for now at least). + * - Empty segments within the string (e.g. if there are two consecutive + * separators) are not allowed. + * + * TODO(b/37244157): we should make this more strict. Right now, it allows + * non-identifier path components, even if they aren't escaped. + */ + static fromServerFormat(path: string): FieldPath_2; + static emptyPath(): FieldPath_2; +} + +/** A field path and the TransformOperation to perform upon it. */ +declare class FieldTransform { + readonly field: FieldPath_2; + readonly transform: TransformOperation; + constructor(field: FieldPath_2, transform: TransformOperation); +} + +declare type FieldTransformSetToServerValue = 'SERVER_VALUE_UNSPECIFIED' | 'REQUEST_TIME'; + +/** + * Sentinel values that can be used when writing document fields with `set()` + * or `update()`. + */ +export declare abstract class FieldValue { + _methodName: string; + /** + * @param _methodName - The public API endpoint that returns this class. + * @hideconstructor + */ + constructor(_methodName: string); + /** Compares `FieldValue`s for equality. */ + abstract isEqual(other: FieldValue): boolean; + abstract _toFieldTransform(context: ParseContext): FieldTransform | null; +} + +declare abstract class Filter { + abstract matches(doc: Document_2): boolean; + abstract getFlattenedFilters(): readonly FieldFilter[]; + abstract getFilters(): Filter[]; +} + +/** + * The Cloud Firestore service interface. + * + * Do not call this constructor directly. Instead, use {@link (getFirestore:1)}. + */ +export declare class Firestore implements FirestoreService { + _authCredentials: CredentialsProvider; + _appCheckCredentials: CredentialsProvider; + readonly _databaseId: DatabaseId; + readonly _app?: FirebaseApp | undefined; + /** + * Whether it's a Firestore or Firestore Lite instance. + */ + type: 'firestore-lite' | 'firestore'; + readonly _persistenceKey: string; + private _settings; + private _settingsFrozen; + private _emulatorOptions; + private _terminateTask; + /** @hideconstructor */ + constructor(_authCredentials: CredentialsProvider, _appCheckCredentials: CredentialsProvider, _databaseId: DatabaseId, _app?: FirebaseApp | undefined); + /** + * The {@link @firebase/app#FirebaseApp} associated with this `Firestore` service + * instance. + */ + get app(): FirebaseApp; + get _initialized(): boolean; + get _terminated(): boolean; + _setSettings(settings: PrivateSettings): void; + _getSettings(): FirestoreSettingsImpl; + _getEmulatorOptions(): { + mockUserToken?: EmulatorMockTokenOptions | string; + }; + _freezeSettings(): FirestoreSettingsImpl; + _delete(): Promise; + _restart(): Promise; + /** Returns a JSON-serializable representation of this `Firestore` instance. */ + toJSON(): object; + /** + * Terminates all components used by this client. Subclasses can override + * this method to clean up their own dependencies, but must also call this + * method. + * + * Only ever called once. + */ + protected _terminate(): Promise; +} + +/** + * Converter used by `withConverter()` to transform user objects of type + * `AppModelType` into Firestore data of type `DbModelType`. + * + * Using the converter allows you to specify generic type arguments when + * storing and retrieving objects from Firestore. + * + * In this context, an "AppModel" is a class that is used in an application to + * package together related information and functionality. Such a class could, + * for example, have properties with complex, nested data types, properties used + * for memoization, properties of types not supported by Firestore (such as + * `symbol` and `bigint`), and helper functions that perform compound + * operations. Such classes are not suitable and/or possible to store into a + * Firestore database. Instead, instances of such classes need to be converted + * to "plain old JavaScript objects" (POJOs) with exclusively primitive + * properties, potentially nested inside other POJOs or arrays of POJOs. In this + * context, this type is referred to as the "DbModel" and would be an object + * suitable for persisting into Firestore. For convenience, applications can + * implement `FirestoreDataConverter` and register the converter with Firestore + * objects, such as `DocumentReference` or `Query`, to automatically convert + * `AppModel` to `DbModel` when storing into Firestore, and convert `DbModel` + * to `AppModel` when retrieving from Firestore. + * + * @example + * + * Simple Example + * + * ```typescript + * const numberConverter = { + * toFirestore(value: WithFieldValue) { + * return { value }; + * }, + * fromFirestore(snapshot: QueryDocumentSnapshot, options: SnapshotOptions) { + * return snapshot.data(options).value as number; + * } + * }; + * + * async function simpleDemo(db: Firestore): Promise { + * const documentRef = doc(db, 'values/value123').withConverter(numberConverter); + * + * // converters are used with `setDoc`, `addDoc`, and `getDoc` + * await setDoc(documentRef, 42); + * const snapshot1 = await getDoc(documentRef); + * assertEqual(snapshot1.data(), 42); + * + * // converters are not used when writing data with `updateDoc` + * await updateDoc(documentRef, { value: 999 }); + * const snapshot2 = await getDoc(documentRef); + * assertEqual(snapshot2.data(), 999); + * } + * ``` + * + * Advanced Example + * + * ```typescript + * // The Post class is a model that is used by our application. + * // This class may have properties and methods that are specific + * // to our application execution, which do not need to be persisted + * // to Firestore. + * class Post { + * constructor( + * readonly title: string, + * readonly author: string, + * readonly lastUpdatedMillis: number + * ) {} + * toString(): string { + * return `${this.title} by ${this.author}`; + * } + * } + * + * // The PostDbModel represents how we want our posts to be stored + * // in Firestore. This DbModel has different properties (`ttl`, + * // `aut`, and `lut`) from the Post class we use in our application. + * interface PostDbModel { + * ttl: string; + * aut: { firstName: string; lastName: string }; + * lut: Timestamp; + * } + * + * // The `PostConverter` implements `FirestoreDataConverter` and specifies + * // how the Firestore SDK can convert `Post` objects to `PostDbModel` + * // objects and vice versa. + * class PostConverter implements FirestoreDataConverter { + * toFirestore(post: WithFieldValue): WithFieldValue { + * return { + * ttl: post.title, + * aut: this._autFromAuthor(post.author), + * lut: this._lutFromLastUpdatedMillis(post.lastUpdatedMillis) + * }; + * } + * + * fromFirestore(snapshot: QueryDocumentSnapshot, options: SnapshotOptions): Post { + * const data = snapshot.data(options) as PostDbModel; + * const author = `${data.aut.firstName} ${data.aut.lastName}`; + * return new Post(data.ttl, author, data.lut.toMillis()); + * } + * + * _autFromAuthor( + * author: string | FieldValue + * ): { firstName: string; lastName: string } | FieldValue { + * if (typeof author !== 'string') { + * // `author` is a FieldValue, so just return it. + * return author; + * } + * const [firstName, lastName] = author.split(' '); + * return {firstName, lastName}; + * } + * + * _lutFromLastUpdatedMillis( + * lastUpdatedMillis: number | FieldValue + * ): Timestamp | FieldValue { + * if (typeof lastUpdatedMillis !== 'number') { + * // `lastUpdatedMillis` must be a FieldValue, so just return it. + * return lastUpdatedMillis; + * } + * return Timestamp.fromMillis(lastUpdatedMillis); + * } + * } + * + * async function advancedDemo(db: Firestore): Promise { + * // Create a `DocumentReference` with a `FirestoreDataConverter`. + * const documentRef = doc(db, 'posts/post123').withConverter(new PostConverter()); + * + * // The `data` argument specified to `setDoc()` is type checked by the + * // TypeScript compiler to be compatible with `Post`. Since the `data` + * // argument is typed as `WithFieldValue` rather than just `Post`, + * // this allows properties of the `data` argument to also be special + * // Firestore values that perform server-side mutations, such as + * // `arrayRemove()`, `deleteField()`, and `serverTimestamp()`. + * await setDoc(documentRef, { + * title: 'My Life', + * author: 'Foo Bar', + * lastUpdatedMillis: serverTimestamp() + * }); + * + * // The TypeScript compiler will fail to compile if the `data` argument to + * // `setDoc()` is _not_ compatible with `WithFieldValue`. This + * // type checking prevents the caller from specifying objects with incorrect + * // properties or property values. + * // @ts-expect-error "Argument of type { ttl: string; } is not assignable + * // to parameter of type WithFieldValue" + * await setDoc(documentRef, { ttl: 'The Title' }); + * + * // When retrieving a document with `getDoc()` the `DocumentSnapshot` + * // object's `data()` method returns a `Post`, rather than a generic object, + * // which would have been returned if the `DocumentReference` did _not_ have a + * // `FirestoreDataConverter` attached to it. + * const snapshot1: DocumentSnapshot = await getDoc(documentRef); + * const post1: Post = snapshot1.data()!; + * if (post1) { + * assertEqual(post1.title, 'My Life'); + * assertEqual(post1.author, 'Foo Bar'); + * } + * + * // The `data` argument specified to `updateDoc()` is type checked by the + * // TypeScript compiler to be compatible with `PostDbModel`. Note that + * // unlike `setDoc()`, whose `data` argument must be compatible with `Post`, + * // the `data` argument to `updateDoc()` must be compatible with + * // `PostDbModel`. Similar to `setDoc()`, since the `data` argument is typed + * // as `WithFieldValue` rather than just `PostDbModel`, this + * // allows properties of the `data` argument to also be those special + * // Firestore values, like `arrayRemove()`, `deleteField()`, and + * // `serverTimestamp()`. + * await updateDoc(documentRef, { + * 'aut.firstName': 'NewFirstName', + * lut: serverTimestamp() + * }); + * + * // The TypeScript compiler will fail to compile if the `data` argument to + * // `updateDoc()` is _not_ compatible with `WithFieldValue`. + * // This type checking prevents the caller from specifying objects with + * // incorrect properties or property values. + * // @ts-expect-error "Argument of type { title: string; } is not assignable + * // to parameter of type WithFieldValue" + * await updateDoc(documentRef, { title: 'New Title' }); + * const snapshot2: DocumentSnapshot = await getDoc(documentRef); + * const post2: Post = snapshot2.data()!; + * if (post2) { + * assertEqual(post2.title, 'My Life'); + * assertEqual(post2.author, 'NewFirstName Bar'); + * } + * } + * ``` + */ +export declare interface FirestoreDataConverter { + /** + * Called by the Firestore SDK to convert a custom model object of type + * `AppModelType` into a plain JavaScript object (suitable for writing + * directly to the Firestore database) of type `DbModelType`. Used with + * {@link @firebase/firestore/lite#(setDoc:1)}, + * {@link @firebase/firestore/lite#(WriteBatch.set:1)} and + * {@link @firebase/firestore/lite#(Transaction.set:1)}. + * + * The `WithFieldValue` type extends `T` to also allow FieldValues such as + * {@link (deleteField:1)} to be used as property values. + */ + toFirestore(modelObject: WithFieldValue): WithFieldValue; + /** + * Called by the Firestore SDK to convert a custom model object of type + * `AppModelType` into a plain JavaScript object (suitable for writing + * directly to the Firestore database) of type `DbModelType`. Used with + * {@link @firebase/firestore/lite#(setDoc:1)}, + * {@link @firebase/firestore/lite#(WriteBatch.set:1)} and + * {@link @firebase/firestore/lite#(Transaction.set:1)} with `merge:true` + * or `mergeFields`. + * + * The `PartialWithFieldValue` type extends `Partial` to allow + * FieldValues such as {@link (arrayUnion:1)} to be used as property values. + * It also supports nested `Partial` by allowing nested fields to be + * omitted. + */ + toFirestore(modelObject: PartialWithFieldValue, options: SetOptions): PartialWithFieldValue; + /** + * Called by the Firestore SDK to convert Firestore data into an object of + * type `AppModelType`. You can access your data by calling: + * `snapshot.data()`. + * + * + * Generally, the data returned from `snapshot.data()` can be cast to + * `DbModelType`; however, this is not guaranteed because Firestore does not + * enforce a schema on the database. For example, writes from a previous + * version of the application or writes from another client that did not use a + * type converter could have written data with different properties and/or + * property types. The implementation will need to choose whether to + * gracefully recover from non-conforming data or throw an error. + * + * @param snapshot - A `QueryDocumentSnapshot` containing your data and + * metadata. + */ + fromFirestore(snapshot: QueryDocumentSnapshot): AppModelType; +} + +/** An error returned by a Firestore operation. */ +export declare class FirestoreError extends FirebaseError { + /** + * The backend error code associated with this error. + */ + readonly code: FirestoreErrorCode; + /** + * A custom error description. + */ + readonly message: string; + /** The stack of the error. */ + readonly stack?: string; + /** @hideconstructor */ + constructor( + /** + * The backend error code associated with this error. + */ + code: FirestoreErrorCode, + /** + * A custom error description. + */ + message: string); +} + +/** + * The set of Firestore status codes. The codes are the same at the ones + * exposed by gRPC here: + * https://github.com/grpc/grpc/blob/master/doc/statuscodes.md + * + * Possible values: + * - 'cancelled': The operation was cancelled (typically by the caller). + * - 'unknown': Unknown error or an error from a different error domain. + * - 'invalid-argument': Client specified an invalid argument. Note that this + * differs from 'failed-precondition'. 'invalid-argument' indicates + * arguments that are problematic regardless of the state of the system + * (e.g. an invalid field name). + * - 'deadline-exceeded': Deadline expired before operation could complete. + * For operations that change the state of the system, this error may be + * returned even if the operation has completed successfully. For example, + * a successful response from a server could have been delayed long enough + * for the deadline to expire. + * - 'not-found': Some requested document was not found. + * - 'already-exists': Some document that we attempted to create already + * exists. + * - 'permission-denied': The caller does not have permission to execute the + * specified operation. + * - 'resource-exhausted': Some resource has been exhausted, perhaps a + * per-user quota, or perhaps the entire file system is out of space. + * - 'failed-precondition': Operation was rejected because the system is not + * in a state required for the operation's execution. + * - 'aborted': The operation was aborted, typically due to a concurrency + * issue like transaction aborts, etc. + * - 'out-of-range': Operation was attempted past the valid range. + * - 'unimplemented': Operation is not implemented or not supported/enabled. + * - 'internal': Internal errors. Means some invariants expected by + * underlying system has been broken. If you see one of these errors, + * something is very broken. + * - 'unavailable': The service is currently unavailable. This is most likely + * a transient condition and may be corrected by retrying with a backoff. + * - 'data-loss': Unrecoverable data loss or corruption. + * - 'unauthenticated': The request does not have valid authentication + * credentials for the operation. + */ +export declare type FirestoreErrorCode = 'cancelled' | 'unknown' | 'invalid-argument' | 'deadline-exceeded' | 'not-found' | 'already-exists' | 'permission-denied' | 'resource-exhausted' | 'failed-precondition' | 'aborted' | 'out-of-range' | 'unimplemented' | 'internal' | 'unavailable' | 'data-loss' | 'unauthenticated'; + +/** + * Union type from all supported SDK cache layer. + */ +declare type FirestoreLocalCache = MemoryLocalCache | PersistentLocalCache; + +/** + * An interface implemented by FirebaseFirestore that provides compatibility + * with the usage in this file. + * + * This interface mainly exists to remove a cyclic dependency. + */ +declare interface FirestoreService extends _FirebaseService { + _authCredentials: CredentialsProvider; + _appCheckCredentials: CredentialsProvider; + _persistenceKey: string; + _databaseId: DatabaseId; + _terminated: boolean; + _freezeSettings(): FirestoreSettingsImpl; +} + +/** + * A concrete type describing all the values that can be applied via a + * user-supplied `FirestoreSettings` object. This is a separate type so that + * defaults can be supplied and the value can be checked for equality. + */ +declare class FirestoreSettingsImpl { + /** The hostname to connect to. */ + readonly host: string; + /** Whether to use SSL when connecting. */ + readonly ssl: boolean; + readonly cacheSizeBytes: number; + readonly experimentalForceLongPolling: boolean; + readonly experimentalAutoDetectLongPolling: boolean; + readonly experimentalLongPollingOptions: ExperimentalLongPollingOptions; + readonly ignoreUndefinedProperties: boolean; + readonly useFetchStreams: boolean; + readonly localCache?: FirestoreLocalCache; + readonly isUsingEmulator: boolean; + credentials?: any; + constructor(settings: PrivateSettings); + isEqual(other: FirestoreSettingsImpl): boolean; +} + +declare namespace firestoreV1ApiClientInterfaces { + interface ArrayValue { + values?: Value[]; + } + interface BatchGetDocumentsRequest { + database?: string; + documents?: string[]; + mask?: DocumentMask; + transaction?: string; + newTransaction?: TransactionOptions; + readTime?: string; + } + interface BatchGetDocumentsResponse { + found?: Document; + missing?: string; + transaction?: string; + readTime?: string; + } + interface BeginTransactionRequest { + options?: TransactionOptions; + } + interface BeginTransactionResponse { + transaction?: string; + } + interface CollectionSelector { + collectionId?: string; + allDescendants?: boolean; + } + interface CommitRequest { + database?: string; + writes?: Write[]; + transaction?: string; + } + interface CommitResponse { + writeResults?: WriteResult[]; + commitTime?: string; + } + interface CompositeFilter { + op?: CompositeFilterOp; + filters?: Filter[]; + } + interface Cursor { + values?: Value[]; + before?: boolean; + } + interface Document { + name?: string; + fields?: ApiClientObjectMap; + createTime?: Timestamp_2; + updateTime?: Timestamp_2; + } + interface DocumentChange { + document?: Document; + targetIds?: number[]; + removedTargetIds?: number[]; + } + interface DocumentDelete { + document?: string; + removedTargetIds?: number[]; + readTime?: Timestamp_2; + } + interface DocumentMask { + fieldPaths?: string[]; + } + interface DocumentRemove { + document?: string; + removedTargetIds?: number[]; + readTime?: string; + } + interface DocumentTransform { + document?: string; + fieldTransforms?: FieldTransform[]; + } + interface DocumentsTarget { + documents?: string[]; + } + interface Empty { + } + interface ExistenceFilter { + targetId?: number; + count?: number; + unchangedNames?: BloomFilter; + } + interface BloomFilter { + bits?: BitSequence; + hashCount?: number; + } + interface BitSequence { + bitmap?: string | Uint8Array; + padding?: number; + } + interface FieldFilter { + field?: FieldReference; + op?: FieldFilterOp; + value?: Value; + } + interface FieldReference { + fieldPath?: string; + } + interface FieldTransform { + fieldPath?: string; + setToServerValue?: FieldTransformSetToServerValue; + appendMissingElements?: ArrayValue; + removeAllFromArray?: ArrayValue; + increment?: Value; + } + interface Filter { + compositeFilter?: CompositeFilter; + fieldFilter?: FieldFilter; + unaryFilter?: UnaryFilter; + } + interface Index { + name?: string; + collectionId?: string; + fields?: IndexField[]; + state?: IndexState_2; + } + interface IndexField { + fieldPath?: string; + mode?: IndexFieldMode; + } + interface LatLng { + latitude?: number; + longitude?: number; + } + interface ListCollectionIdsRequest { + pageSize?: number; + pageToken?: string; + } + interface ListCollectionIdsResponse { + collectionIds?: string[]; + nextPageToken?: string; + } + interface ListDocumentsResponse { + documents?: Document[]; + nextPageToken?: string; + } + interface ListIndexesResponse { + indexes?: Index[]; + nextPageToken?: string; + } + interface ListenRequest { + addTarget?: Target; + removeTarget?: number; + labels?: ApiClientObjectMap; + } + interface ListenResponse { + targetChange?: TargetChange; + documentChange?: DocumentChange; + documentDelete?: DocumentDelete; + documentRemove?: DocumentRemove; + filter?: ExistenceFilter; + } + interface MapValue { + fields?: ApiClientObjectMap; + } + interface Operation { + name?: string; + metadata?: ApiClientObjectMap; + done?: boolean; + error?: Status; + response?: ApiClientObjectMap; + } + interface Order { + field?: FieldReference; + direction?: OrderDirection; + } + interface Precondition { + exists?: boolean; + updateTime?: Timestamp_2; + } + interface Projection { + fields?: FieldReference[]; + } + interface QueryTarget { + parent?: string; + structuredQuery?: StructuredQuery; + } + interface ReadOnly { + readTime?: string; + } + interface ReadWrite { + retryTransaction?: string; + } + interface RollbackRequest { + transaction?: string; + } + interface RunQueryRequest { + parent?: string; + structuredQuery?: StructuredQuery; + transaction?: string; + newTransaction?: TransactionOptions; + readTime?: string; + } + interface RunQueryResponse { + transaction?: string; + document?: Document; + readTime?: string; + skippedResults?: number; + } + interface RunAggregationQueryRequest { + parent?: string; + structuredAggregationQuery?: StructuredAggregationQuery; + transaction?: string; + newTransaction?: TransactionOptions; + readTime?: string; + } + interface RunAggregationQueryResponse { + result?: AggregationResult; + transaction?: string; + readTime?: string; + } + interface AggregationResult { + aggregateFields?: ApiClientObjectMap; + } + interface StructuredAggregationQuery { + structuredQuery?: StructuredQuery; + aggregations?: Aggregation[]; + } + interface Aggregation { + count?: Count; + sum?: Sum; + avg?: Avg; + alias?: string; + } + interface Count { + upTo?: number; + } + interface Sum { + field?: FieldReference; + } + interface Avg { + field?: FieldReference; + } + interface Status { + code?: number; + message?: string; + details?: Array>; + } + interface StructuredQuery { + select?: Projection; + from?: CollectionSelector[]; + where?: Filter; + orderBy?: Order[]; + startAt?: Cursor; + endAt?: Cursor; + offset?: number; + limit?: number | { + value: number; + }; + } + interface Target { + query?: QueryTarget; + documents?: DocumentsTarget; + resumeToken?: string | Uint8Array; + readTime?: Timestamp_2; + targetId?: number; + once?: boolean; + expectedCount?: number | { + value: number; + }; + } + interface TargetChange { + targetChangeType?: TargetChangeTargetChangeType; + targetIds?: number[]; + cause?: Status; + resumeToken?: string | Uint8Array; + readTime?: Timestamp_2; + } + interface TransactionOptions { + readOnly?: ReadOnly; + readWrite?: ReadWrite; + } + interface UnaryFilter { + op?: UnaryFilterOp; + field?: FieldReference; + } + interface Value { + nullValue?: ValueNullValue; + booleanValue?: boolean; + integerValue?: string | number; + doubleValue?: string | number; + timestampValue?: Timestamp_2; + stringValue?: string; + bytesValue?: string | Uint8Array; + referenceValue?: string; + geoPointValue?: LatLng; + arrayValue?: ArrayValue; + mapValue?: MapValue; + } + interface Write { + update?: Document; + delete?: string; + verify?: string; + transform?: DocumentTransform; + updateMask?: DocumentMask; + updateTransforms?: FieldTransform[]; + currentDocument?: Precondition; + } + interface WriteRequest { + streamId?: string; + writes?: Write[]; + streamToken?: string | Uint8Array; + labels?: ApiClientObjectMap; + } + interface WriteResponse { + streamId?: string; + streamToken?: string | Uint8Array; + writeResults?: WriteResult[]; + commitTime?: Timestamp_2; + } + interface WriteResult { + updateTime?: Timestamp_2; + transformResults?: Value[]; + } +} + +/** + * @internal + */ +declare interface FirstPartyCredentialsSettings { + ['type']: 'firstParty'; + ['sessionIndex']: string; + ['iamToken']: string | null; + ['authTokenFactory']: AuthTokenFactory | null; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +declare type FulfilledHandler = ((result: T) => R | PersistencePromise) | null; + +/** + * An immutable object representing a geographic location in Firestore. The + * location is represented as latitude/longitude pair. + * + * Latitude values are in the range of [-90, 90]. + * Longitude values are in the range of [-180, 180]. + */ +export declare class GeoPoint { + private _lat; + private _long; + /** + * Creates a new immutable `GeoPoint` object with the provided latitude and + * longitude values. + * @param latitude - The latitude as number between -90 and 90. + * @param longitude - The longitude as number between -180 and 180. + */ + constructor(latitude: number, longitude: number); + /** + * The latitude of this `GeoPoint` instance. + */ + get latitude(): number; + /** + * The longitude of this `GeoPoint` instance. + */ + get longitude(): number; + /** + * Returns true if this `GeoPoint` is equal to the provided one. + * + * @param other - The `GeoPoint` to compare against. + * @returns true if this `GeoPoint` is equal to the provided one. + */ + isEqual(other: GeoPoint): boolean; + /** + * Actually private to JS consumers of our API, so this function is prefixed + * with an underscore. + */ + _compareTo(other: GeoPoint): number; + static _jsonSchemaVersion: string; + static _jsonSchema: { + type: Property<"string">; + latitude: Property<"number">; + longitude: Property<"number">; + }; + /** + * Returns a JSON-serializable representation of this `GeoPoint` instance. + * + * @returns a JSON representation of this object. + */ + toJSON(): { + latitude: number; + longitude: number; + type: string; + }; + /** + * Builds a `GeoPoint` instance from a JSON object created by {@link GeoPoint.toJSON}. + * + * @param json a JSON object represention of a `GeoPoint` instance + * @returns an instance of {@link GeoPoint} if the JSON object could be parsed. Throws a + * {@link FirestoreError} if an error occurs. + */ + static fromJSON(json: object): GeoPoint; +} + +/** + * Calculates the specified aggregations over the documents in the result + * set of the given query without actually downloading the documents. + * + * Using this function to perform aggregations is efficient because only the + * final aggregation values, not the documents' data, are downloaded. This + * function can perform aggregations of the documents in cases where the result + * set is prohibitively large to download entirely (thousands of documents). + * + * @param query The query whose result set is aggregated over. + * @param aggregateSpec An `AggregateSpec` object that specifies the aggregates + * to perform over the result set. The AggregateSpec specifies aliases for each + * aggregate, which can be used to retrieve the aggregate result. + * @example + * ```typescript + * const aggregateSnapshot = await getAggregate(query, { + * countOfDocs: count(), + * totalHours: sum('hours'), + * averageScore: average('score') + * }); + * + * const countOfDocs: number = aggregateSnapshot.data().countOfDocs; + * const totalHours: number = aggregateSnapshot.data().totalHours; + * const averageScore: number | null = aggregateSnapshot.data().averageScore; + * ``` + */ +export declare function getAggregate(query: Query, aggregateSpec: AggregateSpecType): Promise>; + +/** + * Calculates the number of documents in the result set of the given query + * without actually downloading the documents. + * + * Using this function to count the documents is efficient because only the + * final count, not the documents' data, is downloaded. This function can + * count the documents in cases where the result set is prohibitively large to + * download entirely (thousands of documents). + * + * @param query The query whose result set size is calculated. + * @returns A Promise that will be resolved with the count; the count can be + * retrieved from `snapshot.data().count`, where `snapshot` is the + * `AggregateQuerySnapshot` to which the returned Promise resolves. + */ +export declare function getCount(query: Query): Promise; +}, AppModelType, DbModelType>>; + +/** + * Reads the document referred to by the specified document reference. + * + * All documents are directly fetched from the server, even if the document was + * previously read or modified. Recent modifications are only reflected in the + * retrieved `DocumentSnapshot` if they have already been applied by the + * backend. If the client is offline, the read fails. If you like to use + * caching or see local modifications, please use the full Firestore SDK. + * + * @param reference - The reference of the document to fetch. + * @returns A Promise resolved with a `DocumentSnapshot` containing the current + * document contents. + */ +export declare function getDoc(reference: DocumentReference): Promise>; + +/** + * Executes the query and returns the results as a {@link QuerySnapshot}. + * + * All queries are executed directly by the server, even if the query was + * previously executed. Recent modifications are only reflected in the retrieved + * results if they have already been applied by the backend. If the client is + * offline, the operation fails. To see previously cached result and local + * modifications, use the full Firestore SDK. + * + * @param query - The `Query` to execute. + * @returns A Promise that will be resolved with the results of the query. + */ +export declare function getDocs(query: Query): Promise>; + +/** + * Returns the existing default {@link Firestore} instance that is associated with the + * default {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new + * instance with default settings. + * + * @returns The {@link Firestore} instance of the provided app. + */ +export declare function getFirestore(): Firestore; + +/** + * Returns the existing default {@link Firestore} instance that is associated with the + * provided {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new + * instance with default settings. + * + * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned {@link Firestore} + * instance is associated with. + * @returns The {@link Firestore} instance of the provided app. + */ +export declare function getFirestore(app: FirebaseApp): Firestore; + +/** + * Returns the existing {@link Firestore} instance that is associated with the + * default {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new + * instance with default settings. + * + * @param databaseId - The name of the database. + * @returns The {@link Firestore} instance of the provided app. + * @beta + */ +export declare function getFirestore(databaseId: string): Firestore; + +/** + * Returns the existing {@link Firestore} instance that is associated with the + * provided {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new + * instance with default settings. + * + * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned {@link Firestore} + * instance is associated with. + * @param databaseId - The name of the database. + * @returns The {@link Firestore} instance of the provided app. + * @beta + */ +export declare function getFirestore(app: FirebaseApp, databaseId: string): Firestore; + +/** + * General purpose cache for global values. + * + * Global state that cuts across components should be saved here. Following are contained herein: + * + * `sessionToken` tracks server interaction across Listen and Write streams. This facilitates cache + * synchronization and invalidation. + */ +declare interface GlobalsCache { + /** + * Gets session token. + */ + getSessionToken(transaction: PersistenceTransaction): PersistencePromise; + /** + * Sets session token. + * + * @param sessionToken - The new session token. + */ + setSessionToken(transaction: PersistenceTransaction, sessionToken: ByteString): PersistencePromise; +} + +/** + * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link + * @firebase/firestore/lite#(updateDoc:1)} that tells the server to increment the field's current value by + * the given value. + * + * If either the operand or the current field value uses floating point + * precision, all arithmetic follows IEEE 754 semantics. If both values are + * integers, values outside of JavaScript's safe number range + * (`Number.MIN_SAFE_INTEGER` to `Number.MAX_SAFE_INTEGER`) are also subject to + * precision loss. Furthermore, once processed by the Firestore backend, all + * integer operations are capped between -2^63 and 2^63-1. + * + * If the current field value is not of type `number`, or if the field does not + * yet exist, the transformation sets the field to the given value. + * + * @param n - The value to increment by. + * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or + * `updateDoc()` + */ +export declare function increment(n: number): FieldValue; + +declare type IndexFieldMode = 'MODE_UNSPECIFIED' | 'ASCENDING' | 'DESCENDING'; + +/** The type of the index, e.g. for which type of query it can be used. */ +declare const enum IndexKind { + /** + * Ordered index. Can be used for <, <=, ==, >=, >, !=, IN and NOT IN queries. + */ + ASCENDING = 0, + /** + * Ordered index. Can be used for <, <=, ==, >=, >, !=, IN and NOT IN queries. + */ + DESCENDING = 1, + /** Contains index. Can be used for ArrayContains and ArrayContainsAny. */ + CONTAINS = 2 +} + +/** + * Represents a set of indexes that are used to execute queries efficiently. + * + * Currently the only index is a [collection id] => [parent path] index, used + * to execute Collection Group queries. + */ +declare interface IndexManager { + /** + * Creates an index entry mapping the collectionId (last segment of the path) + * to the parent path (either the containing document location or the empty + * path for root-level collections). Index entries can be retrieved via + * getCollectionParents(). + * + * NOTE: Currently we don't remove index entries. If this ends up being an + * issue we can devise some sort of GC strategy. + */ + addToCollectionParentIndex(transaction: PersistenceTransaction, collectionPath: ResourcePath): PersistencePromise; + /** + * Retrieves all parent locations containing the given collectionId, as a + * list of paths (each path being either a document location or the empty + * path for a root-level collection). + */ + getCollectionParents(transaction: PersistenceTransaction, collectionId: string): PersistencePromise; + /** + * Adds a field path index. + * + * Values for this index are persisted via the index backfill, which runs + * asynchronously in the background. Once the first values are written, + * an index can be used to serve partial results for any matching queries. + * Any unindexed portion of the database will continue to be served via + * collection scons. + */ + addFieldIndex(transaction: PersistenceTransaction, index: FieldIndex): PersistencePromise; + /** Removes the given field index and deletes all index values. */ + deleteFieldIndex(transaction: PersistenceTransaction, index: FieldIndex): PersistencePromise; + /** Removes all field indexes and deletes all index values. */ + deleteAllFieldIndexes(transaction: PersistenceTransaction): PersistencePromise; + /** Creates a full matched field index which serves the given target. */ + createTargetIndexes(transaction: PersistenceTransaction, target: Target): PersistencePromise; + /** + * Returns a list of field indexes that correspond to the specified collection + * group. + * + * @param collectionGroup The collection group to get matching field indexes + * for. + * @return A collection of field indexes for the specified collection group. + */ + getFieldIndexes(transaction: PersistenceTransaction, collectionGroup: string): PersistencePromise; + /** Returns all configured field indexes. */ + getFieldIndexes(transaction: PersistenceTransaction): PersistencePromise; + /** + * Returns the type of index (if any) that can be used to serve the given + * target. + */ + getIndexType(transaction: PersistenceTransaction, target: Target): PersistencePromise; + /** + * Returns the documents that match the given target based on the provided + * index or `null` if the target does not have a matching index. + */ + getDocumentsMatchingTarget(transaction: PersistenceTransaction, target: Target): PersistencePromise; + /** + * Returns the next collection group to update. Returns `null` if no group + * exists. + */ + getNextCollectionGroupToUpdate(transaction: PersistenceTransaction): PersistencePromise; + /** + * Sets the collection group's latest read time. + * + * This method updates the index offset for all field indices for the + * collection group and increments their sequence number. Subsequent calls to + * `getNextCollectionGroupToUpdate()` will return a different collection group + * (unless only one collection group is configured). + */ + updateCollectionGroup(transaction: PersistenceTransaction, collectionGroup: string, offset: IndexOffset): PersistencePromise; + /** Updates the index entries for the provided documents. */ + updateIndexEntries(transaction: PersistenceTransaction, documents: DocumentMap): PersistencePromise; + /** + * Iterates over all field indexes that are used to serve the given target, + * and returns the minimum offset of them all. + */ + getMinOffset(transaction: PersistenceTransaction, target: Target): PersistencePromise; + /** Returns the minimum offset for the given collection group. */ + getMinOffsetFromCollectionGroup(transaction: PersistenceTransaction, collectionGroup: string): PersistencePromise; +} + +/** + * Stores the latest read time, document and batch ID that were processed for an + * index. + */ +declare class IndexOffset { + /** + * The latest read time version that has been indexed by Firestore for this + * field index. + */ + readonly readTime: SnapshotVersion; + /** + * The key of the last document that was indexed for this query. Use + * `DocumentKey.empty()` if no document has been indexed. + */ + readonly documentKey: DocumentKey; + readonly largestBatchId: number; + constructor( + /** + * The latest read time version that has been indexed by Firestore for this + * field index. + */ + readTime: SnapshotVersion, + /** + * The key of the last document that was indexed for this query. Use + * `DocumentKey.empty()` if no document has been indexed. + */ + documentKey: DocumentKey, largestBatchId: number); + /** Returns an offset that sorts before all regular offsets. */ + static min(): IndexOffset; + /** Returns an offset that sorts after all regular offsets. */ + static max(): IndexOffset; +} + +/** An index component consisting of field path and index type. */ +declare class IndexSegment { + /** The field path of the component. */ + readonly fieldPath: FieldPath_2; + /** The fields sorting order. */ + readonly kind: IndexKind; + constructor( + /** The field path of the component. */ + fieldPath: FieldPath_2, + /** The fields sorting order. */ + kind: IndexKind); +} + +/** + * Stores the "high water mark" that indicates how updated the Index is for the + * current user. + */ +declare class IndexState { + /** + * Indicates when the index was last updated (relative to other indexes). + */ + readonly sequenceNumber: number; + /** The the latest indexed read time, document and batch id. */ + readonly offset: IndexOffset; + constructor( + /** + * Indicates when the index was last updated (relative to other indexes). + */ + sequenceNumber: number, + /** The the latest indexed read time, document and batch id. */ + offset: IndexOffset); + /** The state of an index that has not yet been backfilled. */ + static empty(): IndexState; +} + +declare type IndexState_2 = 'STATE_UNSPECIFIED' | 'CREATING' | 'READY' | 'ERROR'; + +/** Represents the index state as it relates to a particular target. */ +declare const enum IndexType { + /** Indicates that no index could be found for serving the target. */ + NONE = 0, + /** + * Indicates that only a "partial index" could be found for serving the + * target. A partial index is one which does not have a segment for every + * filter/orderBy in the target. + */ + PARTIAL = 1, + /** + * Indicates that a "full index" could be found for serving the target. A full + * index is one which has a segment for every filter/orderBy in the target. + */ + FULL = 2 +} + +/** + * Initializes a new instance of Cloud Firestore with the provided settings. + * Can only be called before any other functions, including + * {@link (getFirestore:1)}. If the custom settings are empty, this function is + * equivalent to calling {@link (getFirestore:1)}. + * + * @param app - The {@link @firebase/app#FirebaseApp} with which the `Firestore` instance will + * be associated. + * @param settings - A settings object to configure the `Firestore` instance. + * @returns A newly initialized `Firestore` instance. + */ +export declare function initializeFirestore(app: FirebaseApp, settings: Settings): Firestore; + +/** + * Initializes a new instance of Cloud Firestore with the provided settings. + * Can only be called before any other functions, including + * {@link (getFirestore:1)}. If the custom settings are empty, this function is + * equivalent to calling {@link (getFirestore:1)}. + * + * @param app - The {@link @firebase/app#FirebaseApp} with which the `Firestore` instance will + * be associated. + * @param settings - A settings object to configure the `Firestore` instance. + * @param databaseId - The name of the database. + * @returns A newly initialized `Firestore` instance. + * @beta + */ +export declare function initializeFirestore(app: FirebaseApp, settings: Settings, databaseId?: string): Firestore; + +/** + * This class generates JsonObject values for the Datastore API suitable for + * sending to either GRPC stub methods or via the JSON/HTTP REST API. + * + * The serializer supports both Protobuf.js and Proto3 JSON formats. By + * setting `useProto3Json` to true, the serializer will use the Proto3 JSON + * format. + * + * For a description of the Proto3 JSON format check + * https://developers.google.com/protocol-buffers/docs/proto3#json + * + * TODO(klimt): We can remove the databaseId argument if we keep the full + * resource name in documents. + */ +declare class JsonProtoSerializer implements Serializer { + readonly databaseId: DatabaseId; + readonly useProto3Json: boolean; + constructor(databaseId: DatabaseId, useProto3Json: boolean); +} + +/** + * @license + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A list of data types Firestore objects may serialize in their toJSON implemenetations. + * @private + * @internal + */ +declare type JsonTypeDesc = 'object' | 'string' | 'number' | 'boolean' | 'null' | 'undefined'; + +declare type Kind = 'memory' | 'persistent'; + +/** + * Creates a {@link QueryLimitConstraint} that only returns the first matching + * documents. + * + * @param limit - The maximum number of items to return. + * @returns The created {@link QueryLimitConstraint}. + */ +export declare function limit(limit: number): QueryLimitConstraint; + +/** + * Creates a {@link QueryLimitConstraint} that only returns the last matching + * documents. + * + * You must specify at least one `orderBy` clause for `limitToLast` queries, + * otherwise an exception will be thrown during execution. + * + * @param limit - The maximum number of items to return. + * @returns The created {@link QueryLimitConstraint}. + */ +export declare function limitToLast(limit: number): QueryLimitConstraint; + +declare const enum LimitType { + First = "F", + Last = "L" +} + +/** LimitType enum. */ +declare type LimitType_2 = 'FIRST' | 'LAST'; + +declare type ListenSequenceNumber = number; + +declare class LLRBEmptyNode { + get key(): never; + get value(): never; + get color(): never; + get left(): never; + get right(): never; + size: number; + copy(key: K | null, value: V | null, color: boolean | null, left: LLRBNode | LLRBEmptyNode | null, right: LLRBNode | LLRBEmptyNode | null): LLRBEmptyNode; + insert(key: K, value: V, comparator: Comparator): LLRBNode; + remove(key: K, comparator: Comparator): LLRBEmptyNode; + isEmpty(): boolean; + inorderTraversal(action: (k: K, v: V) => boolean): boolean; + reverseTraversal(action: (k: K, v: V) => boolean): boolean; + minKey(): K | null; + maxKey(): K | null; + isRed(): boolean; + checkMaxDepth(): boolean; + protected check(): 0; +} + +declare class LLRBNode { + key: K; + value: V; + readonly color: boolean; + readonly left: LLRBNode | LLRBEmptyNode; + readonly right: LLRBNode | LLRBEmptyNode; + readonly size: number; + static EMPTY: LLRBEmptyNode; + static RED: boolean; + static BLACK: boolean; + constructor(key: K, value: V, color?: boolean, left?: LLRBNode | LLRBEmptyNode, right?: LLRBNode | LLRBEmptyNode); + copy(key: K | null, value: V | null, color: boolean | null, left: LLRBNode | LLRBEmptyNode | null, right: LLRBNode | LLRBEmptyNode | null): LLRBNode; + isEmpty(): boolean; + inorderTraversal(action: (k: K, v: V) => T): T; + reverseTraversal(action: (k: K, v: V) => T): T; + private min; + minKey(): K | null; + maxKey(): K | null; + insert(key: K, value: V, comparator: Comparator): LLRBNode; + private removeMin; + remove(key: K, comparator: Comparator): LLRBNode | LLRBEmptyNode; + isRed(): boolean; + private fixUp; + private moveRedLeft; + private moveRedRight; + private rotateLeft; + private rotateRight; + private colorFlip; + checkMaxDepth(): boolean; + protected check(): number; +} + +/** + * A readonly view of the local state of all documents we're tracking (i.e. we + * have a cached version in remoteDocumentCache or local mutations for the + * document). The view is computed by applying the mutations in the + * MutationQueue to the RemoteDocumentCache. + */ +declare class LocalDocumentsView { + readonly remoteDocumentCache: RemoteDocumentCache; + readonly mutationQueue: MutationQueue; + readonly documentOverlayCache: DocumentOverlayCache; + readonly indexManager: IndexManager; + constructor(remoteDocumentCache: RemoteDocumentCache, mutationQueue: MutationQueue, documentOverlayCache: DocumentOverlayCache, indexManager: IndexManager); + /** + * Get the local view of the document identified by `key`. + * + * @returns Local view of the document or null if we don't have any cached + * state for it. + */ + getDocument(transaction: PersistenceTransaction, key: DocumentKey): PersistencePromise; + /** + * Gets the local view of the documents identified by `keys`. + * + * If we don't have cached state for a document in `keys`, a NoDocument will + * be stored for that key in the resulting set. + */ + getDocuments(transaction: PersistenceTransaction, keys: DocumentKeySet): PersistencePromise; + /** + * Similar to `getDocuments`, but creates the local view from the given + * `baseDocs` without retrieving documents from the local store. + * + * @param transaction - The transaction this operation is scoped to. + * @param docs - The documents to apply local mutations to get the local views. + * @param existenceStateChanged - The set of document keys whose existence state + * is changed. This is useful to determine if some documents overlay needs + * to be recalculated. + */ + getLocalViewOfDocuments(transaction: PersistenceTransaction, docs: MutableDocumentMap, existenceStateChanged?: DocumentKeySet): PersistencePromise; + /** + * Gets the overlayed documents for the given document map, which will include + * the local view of those documents and a `FieldMask` indicating which fields + * are mutated locally, `null` if overlay is a Set or Delete mutation. + */ + getOverlayedDocuments(transaction: PersistenceTransaction, docs: MutableDocumentMap): PersistencePromise; + /** + * Fetches the overlays for {@code docs} and adds them to provided overlay map + * if the map does not already contain an entry for the given document key. + */ + private populateOverlays; + /** + * Computes the local view for the given documents. + * + * @param docs - The documents to compute views for. It also has the base + * version of the documents. + * @param overlays - The overlays that need to be applied to the given base + * version of the documents. + * @param existenceStateChanged - A set of documents whose existence states + * might have changed. This is used to determine if we need to re-calculate + * overlays from mutation queues. + * @return A map represents the local documents view. + */ + computeViews(transaction: PersistenceTransaction, docs: MutableDocumentMap, overlays: OverlayMap, existenceStateChanged: DocumentKeySet): PersistencePromise; + private recalculateAndSaveOverlays; + /** + * Recalculates overlays by reading the documents from remote document cache + * first, and saves them after they are calculated. + */ + recalculateAndSaveOverlaysForDocumentKeys(transaction: PersistenceTransaction, documentKeys: DocumentKeySet): PersistencePromise>; + /** + * Performs a query against the local view of all documents. + * + * @param transaction - The persistence transaction. + * @param query - The query to match documents against. + * @param offset - Read time and key to start scanning by (exclusive). + * @param context - A optional tracker to keep a record of important details + * during database local query execution. + */ + getDocumentsMatchingQuery(transaction: PersistenceTransaction, query: Query_2, offset: IndexOffset, context?: QueryContext): PersistencePromise; + /** + * Given a collection group, returns the next documents that follow the provided offset, along + * with an updated batch ID. + * + *

The documents returned by this method are ordered by remote version from the provided + * offset. If there are no more remote documents after the provided offset, documents with + * mutations in order of batch id from the offset are returned. Since all documents in a batch are + * returned together, the total number of documents returned can exceed {@code count}. + * + * @param transaction + * @param collectionGroup The collection group for the documents. + * @param offset The offset to index into. + * @param count The number of documents to return + * @return A LocalWriteResult with the documents that follow the provided offset and the last processed batch id. + */ + getNextDocuments(transaction: PersistenceTransaction, collectionGroup: string, offset: IndexOffset, count: number): PersistencePromise; + private getDocumentsMatchingDocumentQuery; + private getDocumentsMatchingCollectionGroupQuery; + private getDocumentsMatchingCollectionQuery; +} + +declare interface LocalStore { + collectGarbage(garbageCollector: LruGarbageCollector): Promise; + /** Manages the list of active field and collection indices. */ + indexManager: IndexManager; + /** + * The "local" view of all documents (layering mutationQueue on top of + * remoteDocumentCache). + */ + localDocuments: LocalDocumentsView; +} + +/** The result of a write to the local store. */ +declare interface LocalWriteResult { + batchId: BatchId; + changes: DocumentMap; +} +export { LogLevel } + +declare interface LruGarbageCollector { + readonly params: LruParams; + collect(txn: PersistenceTransaction, activeTargetIds: ActiveTargets): PersistencePromise; + /** Given a percentile of target to collect, returns the number of targets to collect. */ + calculateTargetCount(txn: PersistenceTransaction, percentile: number): PersistencePromise; + /** Returns the nth sequence number, counting in order from the smallest. */ + nthSequenceNumber(txn: PersistenceTransaction, n: number): PersistencePromise; + /** + * Removes documents that have a sequence number equal to or less than the + * upper bound and are not otherwise pinned. + */ + removeOrphanedDocuments(txn: PersistenceTransaction, upperBound: ListenSequenceNumber): PersistencePromise; + getCacheSize(txn: PersistenceTransaction): PersistencePromise; + /** + * Removes targets with a sequence number equal to or less than the given + * upper bound, and removes document associations with those targets. + */ + removeTargets(txn: PersistenceTransaction, upperBound: ListenSequenceNumber, activeTargetIds: ActiveTargets): PersistencePromise; +} + +declare class LruParams { + readonly cacheSizeCollectionThreshold: number; + readonly percentileToCollect: number; + readonly maximumSequenceNumbersToCollect: number; + private static readonly DEFAULT_COLLECTION_PERCENTILE; + private static readonly DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT; + static withCacheSize(cacheSize: number): LruParams; + static readonly DEFAULT: LruParams; + static readonly DISABLED: LruParams; + constructor(cacheSizeCollectionThreshold: number, percentileToCollect: number, maximumSequenceNumbersToCollect: number); +} + +/** + * Describes the results of a garbage collection run. `didRun` will be set to + * `false` if collection was skipped (either it is disabled or the cache size + * has not hit the threshold). If collection ran, the other fields will be + * filled in with the details of the results. + */ +declare interface LruResults { + readonly didRun: boolean; + readonly sequenceNumbersCollected: number; + readonly targetsRemoved: number; + readonly documentsRemoved: number; +} + +declare type MapValue = firestoreV1ApiClientInterfaces.MapValue; + +/** + * Provides an in-memory cache to the SDK. This is the default cache unless explicitly + * configured otherwise. + * + * To use, create an instance using the factory function {@link memoryLocalCache()}, then + * set the instance to `FirestoreSettings.cache` and call `initializeFirestore` using + * the settings object. + */ +declare type MemoryLocalCache = { + kind: 'memory'; + /** + * @internal + */ + _onlineComponentProvider: OnlineComponentProviderFactory; + /** + * @internal + */ + _offlineComponentProvider: OfflineComponentProviderFactory; +}; + +/** + * Represents a document in Firestore with a key, version, data and whether it + * has local mutations applied to it. + * + * Documents can transition between states via `convertToFoundDocument()`, + * `convertToNoDocument()` and `convertToUnknownDocument()`. If a document does + * not transition to one of these states even after all mutations have been + * applied, `isValidDocument()` returns false and the document should be removed + * from all views. + */ +declare class MutableDocument implements Document_2 { + readonly key: DocumentKey; + private documentType; + version: SnapshotVersion; + readTime: SnapshotVersion; + createTime: SnapshotVersion; + data: ObjectValue; + private documentState; + private constructor(); + /** + * Creates a document with no known version or data, but which can serve as + * base document for mutations. + */ + static newInvalidDocument(documentKey: DocumentKey): MutableDocument; + /** + * Creates a new document that is known to exist with the given data at the + * given version. + */ + static newFoundDocument(documentKey: DocumentKey, version: SnapshotVersion, createTime: SnapshotVersion, value: ObjectValue): MutableDocument; + /** Creates a new document that is known to not exist at the given version. */ + static newNoDocument(documentKey: DocumentKey, version: SnapshotVersion): MutableDocument; + /** + * Creates a new document that is known to exist at the given version but + * whose data is not known (e.g. a document that was updated without a known + * base document). + */ + static newUnknownDocument(documentKey: DocumentKey, version: SnapshotVersion): MutableDocument; + /** + * Changes the document type to indicate that it exists and that its version + * and data are known. + */ + convertToFoundDocument(version: SnapshotVersion, value: ObjectValue): MutableDocument; + /** + * Changes the document type to indicate that it doesn't exist at the given + * version. + */ + convertToNoDocument(version: SnapshotVersion): MutableDocument; + /** + * Changes the document type to indicate that it exists at a given version but + * that its data is not known (e.g. a document that was updated without a known + * base document). + */ + convertToUnknownDocument(version: SnapshotVersion): MutableDocument; + setHasCommittedMutations(): MutableDocument; + setHasLocalMutations(): MutableDocument; + setReadTime(readTime: SnapshotVersion): MutableDocument; + get hasLocalMutations(): boolean; + get hasCommittedMutations(): boolean; + get hasPendingWrites(): boolean; + isValidDocument(): boolean; + isFoundDocument(): boolean; + isNoDocument(): boolean; + isUnknownDocument(): boolean; + isEqual(other: Document_2 | null | undefined): boolean; + mutableCopy(): MutableDocument; + toString(): string; +} + +/** Miscellaneous collection types / constants. */ +declare type MutableDocumentMap = SortedMap; + +/** + * A mutation describes a self-contained change to a document. Mutations can + * create, replace, delete, and update subsets of documents. + * + * Mutations not only act on the value of the document but also its version. + * + * For local mutations (mutations that haven't been committed yet), we preserve + * the existing version for Set and Patch mutations. For Delete mutations, we + * reset the version to 0. + * + * Here's the expected transition table. + * + * MUTATION APPLIED TO RESULTS IN + * + * SetMutation Document(v3) Document(v3) + * SetMutation NoDocument(v3) Document(v0) + * SetMutation InvalidDocument(v0) Document(v0) + * PatchMutation Document(v3) Document(v3) + * PatchMutation NoDocument(v3) NoDocument(v3) + * PatchMutation InvalidDocument(v0) UnknownDocument(v3) + * DeleteMutation Document(v3) NoDocument(v0) + * DeleteMutation NoDocument(v3) NoDocument(v0) + * DeleteMutation InvalidDocument(v0) NoDocument(v0) + * + * For acknowledged mutations, we use the updateTime of the WriteResponse as + * the resulting version for Set and Patch mutations. As deletes have no + * explicit update time, we use the commitTime of the WriteResponse for + * Delete mutations. + * + * If a mutation is acknowledged by the backend but fails the precondition check + * locally, we transition to an `UnknownDocument` and rely on Watch to send us + * the updated version. + * + * Field transforms are used only with Patch and Set Mutations. We use the + * `updateTransforms` message to store transforms, rather than the `transforms`s + * messages. + * + * ## Subclassing Notes + * + * Every type of mutation needs to implement its own applyToRemoteDocument() and + * applyToLocalView() to implement the actual behavior of applying the mutation + * to some source document (see `setMutationApplyToRemoteDocument()` for an + * example). + */ +declare abstract class Mutation { + abstract readonly type: MutationType; + abstract readonly key: DocumentKey; + abstract readonly precondition: Precondition; + abstract readonly fieldTransforms: FieldTransform[]; + /** + * Returns a `FieldMask` representing the fields that will be changed by + * applying this mutation. Returns `null` if the mutation will overwrite the + * entire document. + */ + abstract getFieldMask(): FieldMask | null; +} + +/** + * A batch of mutations that will be sent as one unit to the backend. + */ +declare class MutationBatch { + batchId: BatchId; + localWriteTime: Timestamp; + baseMutations: Mutation[]; + mutations: Mutation[]; + /** + * @param batchId - The unique ID of this mutation batch. + * @param localWriteTime - The original write time of this mutation. + * @param baseMutations - Mutations that are used to populate the base + * values when this mutation is applied locally. This can be used to locally + * overwrite values that are persisted in the remote document cache. Base + * mutations are never sent to the backend. + * @param mutations - The user-provided mutations in this mutation batch. + * User-provided mutations are applied both locally and remotely on the + * backend. + */ + constructor(batchId: BatchId, localWriteTime: Timestamp, baseMutations: Mutation[], mutations: Mutation[]); + /** + * Applies all the mutations in this MutationBatch to the specified document + * to compute the state of the remote document + * + * @param document - The document to apply mutations to. + * @param batchResult - The result of applying the MutationBatch to the + * backend. + */ + applyToRemoteDocument(document: MutableDocument, batchResult: MutationBatchResult): void; + /** + * Computes the local view of a document given all the mutations in this + * batch. + * + * @param document - The document to apply mutations to. + * @param mutatedFields - Fields that have been updated before applying this mutation batch. + * @returns A `FieldMask` representing all the fields that are mutated. + */ + applyToLocalView(document: MutableDocument, mutatedFields: FieldMask | null): FieldMask | null; + /** + * Computes the local view for all provided documents given the mutations in + * this batch. Returns a `DocumentKey` to `Mutation` map which can be used to + * replace all the mutation applications. + */ + applyToLocalDocumentSet(documentMap: OverlayedDocumentMap, documentsWithoutRemoteVersion: DocumentKeySet): MutationMap; + keys(): DocumentKeySet; + isEqual(other: MutationBatch): boolean; +} + +/** The result of applying a mutation batch to the backend. */ +declare class MutationBatchResult { + readonly batch: MutationBatch; + readonly commitVersion: SnapshotVersion; + readonly mutationResults: MutationResult[]; + /** + * A pre-computed mapping from each mutated document to the resulting + * version. + */ + readonly docVersions: DocumentVersionMap; + private constructor(); + /** + * Creates a new MutationBatchResult for the given batch and results. There + * must be one result for each mutation in the batch. This static factory + * caches a document=>version mapping (docVersions). + */ + static from(batch: MutationBatch, commitVersion: SnapshotVersion, results: MutationResult[]): MutationBatchResult; +} + +declare type MutationMap = DocumentKeyMap; + +/** A queue of mutations to apply to the remote store. */ +declare interface MutationQueue { + /** Returns true if this queue contains no mutation batches. */ + checkEmpty(transaction: PersistenceTransaction): PersistencePromise; + /** + * Creates a new mutation batch and adds it to this mutation queue. + * + * @param transaction - The transaction this operation is scoped to. + * @param localWriteTime - The original write time of this mutation. + * @param baseMutations - Mutations that are used to populate the base values + * when this mutation is applied locally. These mutations are used to locally + * overwrite values that are persisted in the remote document cache. + * @param mutations - The user-provided mutations in this mutation batch. + */ + addMutationBatch(transaction: PersistenceTransaction, localWriteTime: Timestamp, baseMutations: Mutation[], mutations: Mutation[]): PersistencePromise; + /** + * Loads the mutation batch with the given batchId. + */ + lookupMutationBatch(transaction: PersistenceTransaction, batchId: BatchId): PersistencePromise; + /** + * Gets the first unacknowledged mutation batch after the passed in batchId + * in the mutation queue or null if empty. + * + * @param batchId - The batch to search after, or BATCHID_UNKNOWN for the + * first mutation in the queue. + * + * @returns the next mutation or null if there wasn't one. + */ + getNextMutationBatchAfterBatchId(transaction: PersistenceTransaction, batchId: BatchId): PersistencePromise; + /** + * Gets the largest (latest) batch id in mutation queue for the current user + * that is pending server response, returns `BATCHID_UNKNOWN` if the queue is + * empty. + * + * @returns the largest batch id in the mutation queue that is not + * acknowledged. + */ + getHighestUnacknowledgedBatchId(transaction: PersistenceTransaction): PersistencePromise; + /** Gets all mutation batches in the mutation queue. */ + getAllMutationBatches(transaction: PersistenceTransaction): PersistencePromise; + /** + * Finds all mutation batches that could possibly affect the given + * document key. Not all mutations in a batch will necessarily affect the + * document key, so when looping through the batch you'll need to check that + * the mutation itself matches the key. + * + * Batches are guaranteed to be in sorted order. + * + * Note that because of this requirement implementations are free to return + * mutation batches that don't contain the document key at all if it's + * convenient. + */ + getAllMutationBatchesAffectingDocumentKey(transaction: PersistenceTransaction, documentKey: DocumentKey): PersistencePromise; + /** + * Finds all mutation batches that could possibly affect the given set of + * document keys. Not all mutations in a batch will necessarily affect each + * key, so when looping through the batch you'll need to check that the + * mutation itself matches the key. + * + * Batches are guaranteed to be in sorted order. + * + * Note that because of this requirement implementations are free to return + * mutation batches that don't contain any of the document keys at all if it's + * convenient. + */ + getAllMutationBatchesAffectingDocumentKeys(transaction: PersistenceTransaction, documentKeys: SortedMap): PersistencePromise; + /** + * Finds all mutation batches that could affect the results for the given + * query. Not all mutations in a batch will necessarily affect the query, so + * when looping through the batch you'll need to check that the mutation + * itself matches the query. + * + * Batches are guaranteed to be in sorted order. + * + * Note that because of this requirement implementations are free to return + * mutation batches that don't match the query at all if it's convenient. + * + * NOTE: A PatchMutation does not need to include all fields in the query + * filter criteria in order to be a match (but any fields it does contain do + * need to match). + */ + getAllMutationBatchesAffectingQuery(transaction: PersistenceTransaction, query: Query_2): PersistencePromise; + /** + * Removes the given mutation batch from the queue. This is useful in two + * circumstances: + * + * + Removing an applied mutation from the head of the queue + * + Removing a rejected mutation from anywhere in the queue + * + * Multi-Tab Note: This operation should only be called by the primary client. + */ + removeMutationBatch(transaction: PersistenceTransaction, batch: MutationBatch): PersistencePromise; + /** + * Performs a consistency check, examining the mutation queue for any + * leaks, if possible. + */ + performConsistencyCheck(transaction: PersistenceTransaction): PersistencePromise; +} + +/** The result of successfully applying a mutation to the backend. */ +declare class MutationResult { + /** + * The version at which the mutation was committed: + * + * - For most operations, this is the updateTime in the WriteResult. + * - For deletes, the commitTime of the WriteResponse (because deletes are + * not stored and have no updateTime). + * + * Note that these versions can be different: No-op writes will not change + * the updateTime even though the commitTime advances. + */ + readonly version: SnapshotVersion; + /** + * The resulting fields returned from the backend after a mutation + * containing field transforms has been committed. Contains one FieldValue + * for each FieldTransform that was in the mutation. + * + * Will be empty if the mutation did not contain any field transforms. + */ + readonly transformResults: Array; + constructor( + /** + * The version at which the mutation was committed: + * + * - For most operations, this is the updateTime in the WriteResult. + * - For deletes, the commitTime of the WriteResponse (because deletes are + * not stored and have no updateTime). + * + * Note that these versions can be different: No-op writes will not change + * the updateTime even though the commitTime advances. + */ + version: SnapshotVersion, + /** + * The resulting fields returned from the backend after a mutation + * containing field transforms has been committed. Contains one FieldValue + * for each FieldTransform that was in the mutation. + * + * Will be empty if the mutation did not contain any field transforms. + */ + transformResults: Array); +} + +declare const enum MutationType { + Set = 0, + Patch = 1, + Delete = 2, + Verify = 3 +} + +/** + * Represents a Query saved by the SDK in its local storage. + */ +declare interface NamedQuery { + /** The name of the query. */ + readonly name: string; + /** The underlying query associated with `name`. */ + readonly query: Query_2; + /** The time at which the results for this query were read. */ + readonly readTime: SnapshotVersion; +} + +/** Properties of a NamedQuery. */ +declare interface NamedQuery_2 { + /** NamedQuery name */ + name?: string | null; + /** NamedQuery bundledQuery */ + bundledQuery?: BundledQuery | null; + /** NamedQuery readTime */ + readTime?: Timestamp_2 | null; +} + +/** + * For each field (e.g. 'bar'), find all nested keys (e.g. {'bar.baz': T1, + * 'bar.qux': T2}). Intersect them together to make a single map containing + * all possible keys that are all marked as optional + */ +export declare type NestedUpdateFields> = UnionToIntersection<{ + [K in keyof T & string]: ChildUpdateFields; +}[keyof T & string]>; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A map implementation that uses objects as keys. Objects must have an + * associated equals function and must be immutable. Entries in the map are + * stored together with the key being produced from the mapKeyFn. This map + * automatically handles collisions of keys. + */ +declare class ObjectMap { + private mapKeyFn; + private equalsFn; + /** + * The inner map for a key/value pair. Due to the possibility of collisions we + * keep a list of entries that we do a linear search through to find an actual + * match. Note that collisions should be rare, so we still expect near + * constant time lookups in practice. + */ + private inner; + /** The number of entries stored in the map */ + private innerSize; + constructor(mapKeyFn: (key: KeyType) => string, equalsFn: (l: KeyType, r: KeyType) => boolean); + /** Get a value for this key, or undefined if it does not exist. */ + get(key: KeyType): ValueType | undefined; + has(key: KeyType): boolean; + /** Put this key and value in the map. */ + set(key: KeyType, value: ValueType): void; + /** + * Remove this key from the map. Returns a boolean if anything was deleted. + */ + delete(key: KeyType): boolean; + forEach(fn: (key: KeyType, val: ValueType) => void): void; + isEmpty(): boolean; + size(): number; +} + +/** + * An ObjectValue represents a MapValue in the Firestore Proto and offers the + * ability to add and remove fields (via the ObjectValueBuilder). + */ +declare class ObjectValue { + readonly value: { + mapValue: MapValue; + }; + constructor(value: { + mapValue: MapValue; + }); + static empty(): ObjectValue; + /** + * Returns the value at the given path or null. + * + * @param path - the path to search + * @returns The value at the path or null if the path is not set. + */ + field(path: FieldPath_2): Value | null; + /** + * Sets the field to the provided value. + * + * @param path - The field path to set. + * @param value - The value to set. + */ + set(path: FieldPath_2, value: Value): void; + /** + * Sets the provided fields to the provided values. + * + * @param data - A map of fields to values (or null for deletes). + */ + setAll(data: Map): void; + /** + * Removes the field at the specified path. If there is no field at the + * specified path, nothing is changed. + * + * @param path - The field path to remove. + */ + delete(path: FieldPath_2): void; + isEqual(other: ObjectValue): boolean; + /** + * Returns the map that contains the leaf element of `path`. If the parent + * entry does not yet exist, or if it is not a map, a new map will be created. + */ + private getFieldsMap; + /** + * Modifies `fieldsMap` by adding, replacing or deleting the specified + * entries. + */ + private applyChanges; + clone(): ObjectValue; +} + +/** + * Initializes and wires components that are needed to interface with the local + * cache. Implementations override `initialize()` to provide all components. + */ +declare interface OfflineComponentProvider { + readonly kind: Kind; + persistence: Persistence; + sharedClientState: SharedClientState; + localStore: LocalStore; + gcScheduler: Scheduler | null; + indexBackfillerScheduler: Scheduler | null; + synchronizeTabs: boolean; + initialize(cfg: ComponentConfiguration): Promise; + terminate(): Promise; +} + +declare interface OfflineComponentProviderFactory { + build(onlineComponents: OnlineComponentProvider): OfflineComponentProvider; +} + +/** + * Initializes and wires the components that are needed to interface with the + * network. + */ +declare class OnlineComponentProvider { + static readonly provider: OnlineComponentProviderFactory; + protected localStore: LocalStore; + protected sharedClientState: SharedClientState; + datastore: Datastore; + eventManager: EventManager; + remoteStore: RemoteStore; + syncEngine: SyncEngine; + initialize(offlineComponentProvider: OfflineComponentProvider, cfg: ComponentConfiguration): Promise; + createEventManager(cfg: ComponentConfiguration): EventManager; + createDatastore(cfg: ComponentConfiguration): Datastore; + createRemoteStore(cfg: ComponentConfiguration): RemoteStore; + createSyncEngine(cfg: ComponentConfiguration, startAsPrimary: boolean): SyncEngine; + terminate(): Promise; +} + +declare interface OnlineComponentProviderFactory { + build(): OnlineComponentProvider; +} + +/** + * Describes the online state of the Firestore client. Note that this does not + * indicate whether or not the remote store is trying to connect or not. This is + * primarily used by the View / EventManager code to change their behavior while + * offline (e.g. get() calls shouldn't wait for data from the server and + * snapshot events should set metadata.isFromCache=true). + * + * The string values should not be changed since they are persisted in + * WebStorage. + */ +declare const enum OnlineState { + /** + * The Firestore client is in an unknown online state. This means the client + * is either not actively trying to establish a connection or it is currently + * trying to establish a connection, but it has not succeeded or failed yet. + * Higher-level components should not operate in offline mode. + */ + Unknown = "Unknown", + /** + * The client is connected and the connections are healthy. This state is + * reached after a successful connection and there has been at least one + * successful message received from the backends. + */ + Online = "Online", + /** + * The client is either trying to establish a connection but failing, or it + * has been explicitly marked offline via a call to disableNetwork(). + * Higher-level components should operate in offline mode. + */ + Offline = "Offline" +} + +declare const enum Operator { + LESS_THAN = "<", + LESS_THAN_OR_EQUAL = "<=", + EQUAL = "==", + NOT_EQUAL = "!=", + GREATER_THAN = ">", + GREATER_THAN_OR_EQUAL = ">=", + ARRAY_CONTAINS = "array-contains", + IN = "in", + NOT_IN = "not-in", + ARRAY_CONTAINS_ANY = "array-contains-any" +} + +/** + * Creates a new {@link QueryCompositeFilterConstraint} that is a disjunction of + * the given filter constraints. A disjunction filter includes a document if it + * satisfies any of the given filters. + * + * @param queryConstraints - Optional. The list of + * {@link QueryFilterConstraint}s to perform a disjunction for. These must be + * created with calls to {@link where}, {@link or}, or {@link and}. + * @returns The newly created {@link QueryCompositeFilterConstraint}. + */ +export declare function or(...queryConstraints: QueryFilterConstraint[]): QueryCompositeFilterConstraint; + +/** + * An ordering on a field, in some Direction. Direction defaults to ASCENDING. + */ +declare class OrderBy { + readonly field: FieldPath_2; + readonly dir: Direction; + constructor(field: FieldPath_2, dir?: Direction); +} + +/** + * Creates a {@link QueryOrderByConstraint} that sorts the query result by the + * specified field, optionally in descending order instead of ascending. + * + * Note: Documents that do not contain the specified field will not be present + * in the query result. + * + * @param fieldPath - The field to sort by. + * @param directionStr - Optional direction to sort by ('asc' or 'desc'). If + * not specified, order will be ascending. + * @returns The created {@link QueryOrderByConstraint}. + */ +export declare function orderBy(fieldPath: string | FieldPath, directionStr?: OrderByDirection): QueryOrderByConstraint; + +/** + * The direction of a {@link orderBy} clause is specified as 'desc' or 'asc' + * (descending or ascending). + */ +export declare type OrderByDirection = 'desc' | 'asc'; + +declare type OrderDirection = 'DIRECTION_UNSPECIFIED' | 'ASCENDING' | 'DESCENDING'; + +/** + * Representation of an overlay computed by Firestore. + * + * Holds information about a mutation and the largest batch id in Firestore when + * the mutation was created. + */ +declare class Overlay { + readonly largestBatchId: number; + readonly mutation: Mutation; + constructor(largestBatchId: number, mutation: Mutation); + getKey(): DocumentKey; + isEqual(other: Overlay | null): boolean; + toString(): string; +} + +/** + * Represents a local view (overlay) of a document, and the fields that are + * locally mutated. + */ +declare class OverlayedDocument { + readonly overlayedDocument: Document_2; + /** + * The fields that are locally mutated by patch mutations. + * + * If the overlayed document is from set or delete mutations, this is `null`. + * If there is no overlay (mutation) for the document, this is an empty `FieldMask`. + */ + readonly mutatedFields: FieldMask | null; + constructor(overlayedDocument: Document_2, + /** + * The fields that are locally mutated by patch mutations. + * + * If the overlayed document is from set or delete mutations, this is `null`. + * If there is no overlay (mutation) for the document, this is an empty `FieldMask`. + */ + mutatedFields: FieldMask | null); +} + +declare type OverlayedDocumentMap = DocumentKeyMap; + +declare type OverlayMap = DocumentKeyMap; + +declare interface ParseContext { + readonly databaseId: DatabaseId; + readonly ignoreUndefinedProperties: boolean; +} + +/** The result of parsing document data (e.g. for a setData call). */ +declare class ParsedSetData { + readonly data: ObjectValue; + readonly fieldMask: FieldMask | null; + readonly fieldTransforms: FieldTransform[]; + constructor(data: ObjectValue, fieldMask: FieldMask | null, fieldTransforms: FieldTransform[]); + toMutation(key: DocumentKey, precondition: Precondition): Mutation; +} + +/** The result of parsing "update" data (i.e. for an updateData call). */ +declare class ParsedUpdateData { + readonly data: ObjectValue; + readonly fieldMask: FieldMask; + readonly fieldTransforms: FieldTransform[]; + constructor(data: ObjectValue, fieldMask: FieldMask, fieldTransforms: FieldTransform[]); + toMutation(key: DocumentKey, precondition: Precondition): Mutation; +} + +/** + * Similar to TypeScript's `Partial`, but allows nested fields to be + * omitted and FieldValues to be passed in as property values. + */ +export declare type PartialWithFieldValue = Partial | (T extends Primitive ? T : T extends {} ? { + [K in keyof T]?: PartialWithFieldValue | FieldValue; +} : never); + +/** + * Persistence is the lowest-level shared interface to persistent storage in + * Firestore. + * + * Persistence is used to create MutationQueue and RemoteDocumentCache + * instances backed by persistence (which might be in-memory or LevelDB). + * + * Persistence also exposes an API to create and run PersistenceTransactions + * against persistence. All read / write operations must be wrapped in a + * transaction. Implementations of PersistenceTransaction / Persistence only + * need to guarantee that writes made against the transaction are not made to + * durable storage until the transaction resolves its PersistencePromise. + * Since memory-only storage components do not alter durable storage, they are + * free to ignore the transaction. + * + * This contract is enough to allow the LocalStore be be written + * independently of whether or not the stored state actually is durably + * persisted. If persistent storage is enabled, writes are grouped together to + * avoid inconsistent state that could cause crashes. + * + * Concretely, when persistent storage is enabled, the persistent versions of + * MutationQueue, RemoteDocumentCache, and others (the mutators) will + * defer their writes into a transaction. Once the local store has completed + * one logical operation, it commits the transaction. + * + * When persistent storage is disabled, the non-persistent versions of the + * mutators ignore the transaction. This short-cut is allowed because + * memory-only storage leaves no state so it cannot be inconsistent. + * + * This simplifies the implementations of the mutators and allows memory-only + * implementations to supplement the persistent ones without requiring any + * special dual-store implementation of Persistence. The cost is that the + * LocalStore needs to be slightly careful about the order of its reads and + * writes in order to avoid relying on being able to read back uncommitted + * writes. + */ +declare interface Persistence { + /** + * Whether or not this persistence instance has been started. + */ + readonly started: boolean; + readonly referenceDelegate: ReferenceDelegate; + /** Starts persistence. */ + start(): Promise; + /** + * Releases any resources held during eager shutdown. + */ + shutdown(): Promise; + /** + * Registers a listener that gets called when the database receives a + * version change event indicating that it has deleted. + * + * PORTING NOTE: This is only used for Web multi-tab. + */ + setDatabaseDeletedListener(databaseDeletedListener: () => Promise): void; + /** + * Adjusts the current network state in the client's metadata, potentially + * affecting the primary lease. + * + * PORTING NOTE: This is only used for Web multi-tab. + */ + setNetworkEnabled(networkEnabled: boolean): void; + /** + * Returns GlobalCache representing a general purpose cache for global values. + */ + getGlobalsCache(): GlobalsCache; + /** + * Returns a MutationQueue representing the persisted mutations for the + * given user. + * + * Note: The implementation is free to return the same instance every time + * this is called for a given user. In particular, the memory-backed + * implementation does this to emulate the persisted implementation to the + * extent possible (e.g. in the case of uid switching from + * sally=>jack=>sally, sally's mutation queue will be preserved). + */ + getMutationQueue(user: User, indexManager: IndexManager): MutationQueue; + /** + * Returns a TargetCache representing the persisted cache of targets. + * + * Note: The implementation is free to return the same instance every time + * this is called. In particular, the memory-backed implementation does this + * to emulate the persisted implementation to the extent possible. + */ + getTargetCache(): TargetCache; + /** + * Returns a RemoteDocumentCache representing the persisted cache of remote + * documents. + * + * Note: The implementation is free to return the same instance every time + * this is called. In particular, the memory-backed implementation does this + * to emulate the persisted implementation to the extent possible. + */ + getRemoteDocumentCache(): RemoteDocumentCache; + /** + * Returns a BundleCache representing the persisted cache of loaded bundles. + * + * Note: The implementation is free to return the same instance every time + * this is called. In particular, the memory-backed implementation does this + * to emulate the persisted implementation to the extent possible. + */ + getBundleCache(): BundleCache; + /** + * Returns an IndexManager instance that manages our persisted query indexes. + * + * Note: The implementation is free to return the same instance every time + * this is called. In particular, the memory-backed implementation does this + * to emulate the persisted implementation to the extent possible. + */ + getIndexManager(user: User): IndexManager; + /** + * Returns a DocumentOverlayCache representing the documents that are mutated + * locally. + */ + getDocumentOverlayCache(user: User): DocumentOverlayCache; + /** + * Performs an operation inside a persistence transaction. Any reads or writes + * against persistence must be performed within a transaction. Writes will be + * committed atomically once the transaction completes. + * + * Persistence operations are asynchronous and therefore the provided + * transactionOperation must return a PersistencePromise. When it is resolved, + * the transaction will be committed and the Promise returned by this method + * will resolve. + * + * @param action - A description of the action performed by this transaction, + * used for logging. + * @param mode - The underlying mode of the IndexedDb transaction. Can be + * 'readonly', 'readwrite' or 'readwrite-primary'. Transactions marked + * 'readwrite-primary' can only be executed by the primary client. In this + * mode, the transactionOperation will not be run if the primary lease cannot + * be acquired and the returned promise will be rejected with a + * FAILED_PRECONDITION error. + * @param transactionOperation - The operation to run inside a transaction. + * @returns A `Promise` that is resolved once the transaction completes. + */ + runTransaction(action: string, mode: PersistenceTransactionMode, transactionOperation: (transaction: PersistenceTransaction) => PersistencePromise): Promise; +} + +/** + * PersistencePromise is essentially a re-implementation of Promise except + * it has a .next() method instead of .then() and .next() and .catch() callbacks + * are executed synchronously when a PersistencePromise resolves rather than + * asynchronously (Promise implementations use setImmediate() or similar). + * + * This is necessary to interoperate with IndexedDB which will automatically + * commit transactions if control is returned to the event loop without + * synchronously initiating another operation on the transaction. + * + * NOTE: .then() and .catch() only allow a single consumer, unlike normal + * Promises. + */ +declare class PersistencePromise { + private nextCallback; + private catchCallback; + private result; + private error; + private isDone; + private callbackAttached; + constructor(callback: (resolve: Resolver, reject: Rejector) => void); + catch(fn: (error: Error) => R | PersistencePromise): PersistencePromise; + next(nextFn?: FulfilledHandler, catchFn?: RejectedHandler): PersistencePromise; + toPromise(): Promise; + private wrapUserFunction; + private wrapSuccess; + private wrapFailure; + static resolve(): PersistencePromise; + static resolve(result: R): PersistencePromise; + static reject(error: Error): PersistencePromise; + static waitFor(all: { + forEach: (cb: (el: PersistencePromise) => void) => void; + }): PersistencePromise; + /** + * Given an array of predicate functions that asynchronously evaluate to a + * boolean, implements a short-circuiting `or` between the results. Predicates + * will be evaluated until one of them returns `true`, then stop. The final + * result will be whether any of them returned `true`. + */ + static or(predicates: Array<() => PersistencePromise>): PersistencePromise; + /** + * Given an iterable, call the given function on each element in the + * collection and wait for all of the resulting concurrent PersistencePromises + * to resolve. + */ + static forEach(collection: { + forEach: (cb: (r: R, s: S) => void) => void; + }, f: ((r: R, s: S) => PersistencePromise) | ((r: R) => PersistencePromise)): PersistencePromise; + static forEach(collection: { + forEach: (cb: (r: R) => void) => void; + }, f: (r: R) => PersistencePromise): PersistencePromise; + /** + * Concurrently map all array elements through asynchronous function. + */ + static mapArray(array: T[], f: (t: T) => PersistencePromise): PersistencePromise; + /** + * An alternative to recursive PersistencePromise calls, that avoids + * potential memory problems from unbounded chains of promises. + * + * The `action` will be called repeatedly while `condition` is true. + */ + static doWhile(condition: () => boolean, action: () => PersistencePromise): PersistencePromise; +} + +/** + * A base class representing a persistence transaction, encapsulating both the + * transaction's sequence numbers as well as a list of onCommitted listeners. + * + * When you call Persistence.runTransaction(), it will create a transaction and + * pass it to your callback. You then pass it to any method that operates + * on persistence. + */ +declare abstract class PersistenceTransaction { + private readonly onCommittedListeners; + abstract readonly currentSequenceNumber: ListenSequenceNumber; + addOnCommittedListener(listener: () => void): void; + raiseOnCommittedEvent(): void; +} + +/** The different modes supported by `Persistence.runTransaction()`. */ +declare type PersistenceTransactionMode = 'readonly' | 'readwrite' | 'readwrite-primary'; + +/** + * Provides a persistent cache backed by IndexedDb to the SDK. + * + * To use, create an instance using the factory function {@link persistentLocalCache()}, then + * set the instance to `FirestoreSettings.cache` and call `initializeFirestore` using + * the settings object. + */ +declare type PersistentLocalCache = { + kind: 'persistent'; + /** + * @internal + */ + _onlineComponentProvider: OnlineComponentProviderFactory; + /** + * @internal + */ + _offlineComponentProvider: OfflineComponentProviderFactory; +}; + +/** + * Encodes a precondition for a mutation. This follows the model that the + * backend accepts with the special case of an explicit "empty" precondition + * (meaning no precondition). + */ +declare class Precondition { + readonly updateTime?: SnapshotVersion | undefined; + readonly exists?: boolean | undefined; + private constructor(); + /** Creates a new empty Precondition. */ + static none(): Precondition; + /** Creates a new Precondition with an exists flag. */ + static exists(exists: boolean): Precondition; + /** Creates a new Precondition based on a version a document exists at. */ + static updateTime(version: SnapshotVersion): Precondition; + /** Returns whether this Precondition is empty. */ + get isNone(): boolean; + isEqual(other: Precondition): boolean; +} + +/** + * These types primarily exist to support the `UpdateData`, + * `WithFieldValue`, and `PartialWithFieldValue` types and are not consumed + * directly by the end developer. + */ +/** Primitive types. */ +export declare type Primitive = string | number | boolean | undefined | null; + +/** + * @internal + * Undocumented, private additional settings not exposed in our public API. + */ +declare interface PrivateSettings extends Settings { + credentials?: CredentialsSettings; + cacheSizeBytes?: number; + experimentalForceLongPolling?: boolean; + experimentalAutoDetectLongPolling?: boolean; + experimentalLongPollingOptions?: ExperimentalLongPollingOptions; + useFetchStreams?: boolean; + emulatorOptions?: { + mockUserToken?: EmulatorMockTokenOptions | string; + }; + localCache?: FirestoreLocalCache; +} + +/** + * The representation of a JSON object property name and its type value. + * @private + * @internal + */ +declare interface Property { + value?: TSType; + typeString: JsonTypeDesc; +} + +declare interface ProviderCredentialsSettings { + ['type']: 'provider'; + ['client']: CredentialsProvider; +} + +/** + * A `Query` refers to a query which you can read or listen to. You can also + * construct refined `Query` objects by adding filters and ordering. + */ +export declare class Query { + /** + * If provided, the `FirestoreDataConverter` associated with this instance. + */ + readonly converter: FirestoreDataConverter | null; + readonly _query: Query_2; + /** The type of this Firestore reference. */ + readonly type: 'query' | 'collection'; + /** + * The `Firestore` instance for the Firestore database (useful for performing + * transactions, etc.). + */ + readonly firestore: Firestore; + /** @hideconstructor protected */ + constructor(firestore: Firestore, + /** + * If provided, the `FirestoreDataConverter` associated with this instance. + */ + converter: FirestoreDataConverter | null, _query: Query_2); + /** + * Removes the current converter. + * + * @param converter - `null` removes the current converter. + * @returns A `Query` that does not use a + * converter. + */ + withConverter(converter: null): Query; + /** + * Applies a custom data converter to this query, allowing you to use your own + * custom model objects with Firestore. When you call {@link getDocs} with + * the returned query, the provided converter will convert between Firestore + * data of type `NewDbModelType` and your custom type `NewAppModelType`. + * + * @param converter - Converts objects to and from Firestore. + * @returns A `Query` that uses the provided converter. + */ + withConverter(converter: FirestoreDataConverter): Query; +} + +/** + * Creates a new immutable instance of {@link Query} that is extended to also + * include additional query constraints. + * + * @param query - The {@link Query} instance to use as a base for the new + * constraints. + * @param compositeFilter - The {@link QueryCompositeFilterConstraint} to + * apply. Create {@link QueryCompositeFilterConstraint} using {@link and} or + * {@link or}. + * @param queryConstraints - Additional {@link QueryNonFilterConstraint}s to + * apply (e.g. {@link orderBy}, {@link limit}). + * @throws if any of the provided query constraints cannot be combined with the + * existing or new constraints. + */ +export declare function query(query: Query, compositeFilter: QueryCompositeFilterConstraint, ...queryConstraints: QueryNonFilterConstraint[]): Query; + +/** + * Creates a new immutable instance of {@link Query} that is extended to also + * include additional query constraints. + * + * @param query - The {@link Query} instance to use as a base for the new + * constraints. + * @param queryConstraints - The list of {@link QueryConstraint}s to apply. + * @throws if any of the provided query constraints cannot be combined with the + * existing or new constraints. + */ +export declare function query(query: Query, ...queryConstraints: QueryConstraint[]): Query; + +/** + * The Query interface defines all external properties of a query. + * + * QueryImpl implements this interface to provide memoization for `queryNormalizedOrderBy` + * and `queryToTarget`. + */ +declare interface Query_2 { + readonly path: ResourcePath; + readonly collectionGroup: string | null; + readonly explicitOrderBy: OrderBy[]; + readonly filters: Filter[]; + readonly limit: number | null; + readonly limitType: LimitType; + readonly startAt: Bound | null; + readonly endAt: Bound | null; +} + +/** + * A `QueryCompositeFilterConstraint` is used to narrow the set of documents + * returned by a Firestore query by performing the logical OR or AND of multiple + * {@link QueryFieldFilterConstraint}s or {@link QueryCompositeFilterConstraint}s. + * `QueryCompositeFilterConstraint`s are created by invoking {@link or} or + * {@link and} and can then be passed to {@link (query:1)} to create a new query + * instance that also contains the `QueryCompositeFilterConstraint`. + */ +export declare class QueryCompositeFilterConstraint extends AppliableConstraint { + /** The type of this query constraint */ + readonly type: 'or' | 'and'; + private readonly _queryConstraints; + /** + * @internal + */ + protected constructor( + /** The type of this query constraint */ + type: 'or' | 'and', _queryConstraints: QueryFilterConstraint[]); + static _create(type: 'or' | 'and', _queryConstraints: QueryFilterConstraint[]): QueryCompositeFilterConstraint; + _parse(query: Query): Filter; + _apply(query: Query): Query; + _getQueryConstraints(): readonly AppliableConstraint[]; + _getOperator(): CompositeOperator; +} + +/** + * A `QueryConstraint` is used to narrow the set of documents returned by a + * Firestore query. `QueryConstraint`s are created by invoking {@link where}, + * {@link orderBy}, {@link (startAt:1)}, {@link (startAfter:1)}, {@link + * (endBefore:1)}, {@link (endAt:1)}, {@link limit}, {@link limitToLast} and + * can then be passed to {@link (query:1)} to create a new query instance that + * also contains this `QueryConstraint`. + */ +export declare abstract class QueryConstraint extends AppliableConstraint { + /** The type of this query constraint */ + abstract readonly type: QueryConstraintType; + /** + * Takes the provided {@link Query} and returns a copy of the {@link Query} with this + * {@link AppliableConstraint} applied. + */ + abstract _apply(query: Query): Query; +} + +/** Describes the different query constraints available in this SDK. */ +export declare type QueryConstraintType = 'where' | 'orderBy' | 'limit' | 'limitToLast' | 'startAt' | 'startAfter' | 'endAt' | 'endBefore'; + +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A tracker to keep a record of important details during database local query + * execution. + */ +declare class QueryContext { + /** + * Counts the number of documents passed through during local query execution. + */ + private _documentReadCount; + get documentReadCount(): number; + incrementDocumentReadCount(amount: number): void; +} + +/** + * A `QueryDocumentSnapshot` contains data read from a document in your + * Firestore database as part of a query. The document is guaranteed to exist + * and its data can be extracted with `.data()` or `.get()` to get a + * specific field. + * + * A `QueryDocumentSnapshot` offers the same API surface as a + * `DocumentSnapshot`. Since query results contain only existing documents, the + * `exists` property will always be true and `data()` will never return + * 'undefined'. + */ +export declare class QueryDocumentSnapshot extends DocumentSnapshot { + /** + * Retrieves all fields in the document as an `Object`. + * + * @override + * @returns An `Object` containing all fields in the document. + */ + data(): AppModelType; +} + +/** + * A `QueryEndAtConstraint` is used to exclude documents from the end of a + * result set returned by a Firestore query. + * `QueryEndAtConstraint`s are created by invoking {@link (endAt:1)} or + * {@link (endBefore:1)} and can then be passed to {@link (query:1)} to create a new + * query instance that also contains this `QueryEndAtConstraint`. + */ +export declare class QueryEndAtConstraint extends QueryConstraint { + /** The type of this query constraint */ + readonly type: 'endBefore' | 'endAt'; + private readonly _docOrFields; + private readonly _inclusive; + /** + * @internal + */ + protected constructor( + /** The type of this query constraint */ + type: 'endBefore' | 'endAt', _docOrFields: Array>, _inclusive: boolean); + static _create(type: 'endBefore' | 'endAt', _docOrFields: Array>, _inclusive: boolean): QueryEndAtConstraint; + _apply(query: Query): Query; +} + +/** + * Returns true if the provided queries point to the same collection and apply + * the same constraints. + * + * @param left - A `Query` to compare. + * @param right - A `Query` to compare. + * @returns true if the references point to the same location in the same + * Firestore database. + */ +export declare function queryEqual(left: Query, right: Query): boolean; + +/** + * A `QueryFieldFilterConstraint` is used to narrow the set of documents returned by + * a Firestore query by filtering on one or more document fields. + * `QueryFieldFilterConstraint`s are created by invoking {@link where} and can then + * be passed to {@link (query:1)} to create a new query instance that also contains + * this `QueryFieldFilterConstraint`. + */ +export declare class QueryFieldFilterConstraint extends QueryConstraint { + private readonly _field; + private _op; + private _value; + /** The type of this query constraint */ + readonly type = "where"; + /** + * @internal + */ + protected constructor(_field: FieldPath_2, _op: Operator, _value: unknown); + static _create(_field: FieldPath_2, _op: Operator, _value: unknown): QueryFieldFilterConstraint; + _apply(query: Query): Query; + _parse(query: Query): FieldFilter; +} + +/** + * `QueryFilterConstraint` is a helper union type that represents + * {@link QueryFieldFilterConstraint} and {@link QueryCompositeFilterConstraint}. + */ +export declare type QueryFilterConstraint = QueryFieldFilterConstraint | QueryCompositeFilterConstraint; + +/** + * A `QueryLimitConstraint` is used to limit the number of documents returned by + * a Firestore query. + * `QueryLimitConstraint`s are created by invoking {@link limit} or + * {@link limitToLast} and can then be passed to {@link (query:1)} to create a new + * query instance that also contains this `QueryLimitConstraint`. + */ +export declare class QueryLimitConstraint extends QueryConstraint { + /** The type of this query constraint */ + readonly type: 'limit' | 'limitToLast'; + private readonly _limit; + private readonly _limitType; + /** + * @internal + */ + protected constructor( + /** The type of this query constraint */ + type: 'limit' | 'limitToLast', _limit: number, _limitType: LimitType); + static _create(type: 'limit' | 'limitToLast', _limit: number, _limitType: LimitType): QueryLimitConstraint; + _apply(query: Query): Query; +} + +/** + * `QueryNonFilterConstraint` is a helper union type that represents + * QueryConstraints which are used to narrow or order the set of documents, + * but that do not explicitly filter on a document field. + * `QueryNonFilterConstraint`s are created by invoking {@link orderBy}, + * {@link (startAt:1)}, {@link (startAfter:1)}, {@link (endBefore:1)}, {@link (endAt:1)}, + * {@link limit} or {@link limitToLast} and can then be passed to {@link (query:1)} + * to create a new query instance that also contains the `QueryConstraint`. + */ +export declare type QueryNonFilterConstraint = QueryOrderByConstraint | QueryLimitConstraint | QueryStartAtConstraint | QueryEndAtConstraint; + +/** + * A `QueryOrderByConstraint` is used to sort the set of documents returned by a + * Firestore query. `QueryOrderByConstraint`s are created by invoking + * {@link orderBy} and can then be passed to {@link (query:1)} to create a new query + * instance that also contains this `QueryOrderByConstraint`. + * + * Note: Documents that do not contain the orderBy field will not be present in + * the query result. + */ +export declare class QueryOrderByConstraint extends QueryConstraint { + private readonly _field; + private _direction; + /** The type of this query constraint */ + readonly type = "orderBy"; + /** + * @internal + */ + protected constructor(_field: FieldPath_2, _direction: Direction); + static _create(_field: FieldPath_2, _direction: Direction): QueryOrderByConstraint; + _apply(query: Query): Query; +} + +/** + * A `QuerySnapshot` contains zero or more `DocumentSnapshot` objects + * representing the results of a query. The documents can be accessed as an + * array via the `docs` property or enumerated using the `forEach` method. The + * number of documents can be determined via the `empty` and `size` + * properties. + */ +export declare class QuerySnapshot { + readonly _docs: Array>; + /** + * The query on which you called {@link getDocs} in order to get this + * `QuerySnapshot`. + */ + readonly query: Query; + /** @hideconstructor */ + constructor(_query: Query, _docs: Array>); + /** An array of all the documents in the `QuerySnapshot`. */ + get docs(): Array>; + /** The number of documents in the `QuerySnapshot`. */ + get size(): number; + /** True if there are no documents in the `QuerySnapshot`. */ + get empty(): boolean; + /** + * Enumerates all of the documents in the `QuerySnapshot`. + * + * @param callback - A callback to be called with a `QueryDocumentSnapshot` for + * each document in the snapshot. + * @param thisArg - The `this` binding for the callback. + */ + forEach(callback: (result: QueryDocumentSnapshot) => void, thisArg?: unknown): void; +} + +/** + * A `QueryStartAtConstraint` is used to exclude documents from the start of a + * result set returned by a Firestore query. + * `QueryStartAtConstraint`s are created by invoking {@link (startAt:1)} or + * {@link (startAfter:1)} and can then be passed to {@link (query:1)} to create a + * new query instance that also contains this `QueryStartAtConstraint`. + */ +export declare class QueryStartAtConstraint extends QueryConstraint { + /** The type of this query constraint */ + readonly type: 'startAt' | 'startAfter'; + private readonly _docOrFields; + private readonly _inclusive; + /** + * @internal + */ + protected constructor( + /** The type of this query constraint */ + type: 'startAt' | 'startAfter', _docOrFields: Array>, _inclusive: boolean); + static _create(type: 'startAt' | 'startAfter', _docOrFields: Array>, _inclusive: boolean): QueryStartAtConstraint; + _apply(query: Query): Query; +} + +/** The different states of a watch target. */ +declare type QueryTargetState = 'not-current' | 'current' | 'rejected'; + +/** + * Returns true if the provided references are equal. + * + * @param left - A reference to compare. + * @param right - A reference to compare. + * @returns true if the references point to the same location in the same + * Firestore database. + */ +export declare function refEqual(left: DocumentReference | CollectionReference, right: DocumentReference | CollectionReference): boolean; + +/** + * A ReferenceDelegate instance handles all of the hooks into the document-reference lifecycle. This + * includes being added to a target, being removed from a target, being subject to mutation, and + * being mutated by the user. + * + * Different implementations may do different things with each of these events. Not every + * implementation needs to do something with every lifecycle hook. + * + * PORTING NOTE: since sequence numbers are attached to transactions in this + * client, the ReferenceDelegate does not need to deal in transactional + * semantics (onTransactionStarted/Committed()), nor does it need to track and + * generate sequence numbers (getCurrentSequenceNumber()). + */ +declare interface ReferenceDelegate { + /** Notify the delegate that the given document was added to a target. */ + addReference(txn: PersistenceTransaction, targetId: TargetId, doc: DocumentKey): PersistencePromise; + /** Notify the delegate that the given document was removed from a target. */ + removeReference(txn: PersistenceTransaction, targetId: TargetId, doc: DocumentKey): PersistencePromise; + /** + * Notify the delegate that a target was removed. The delegate may, but is not obligated to, + * actually delete the target and associated data. + */ + removeTarget(txn: PersistenceTransaction, targetData: TargetData): PersistencePromise; + /** + * Notify the delegate that a document may no longer be part of any views or + * have any mutations associated. + */ + markPotentiallyOrphaned(txn: PersistenceTransaction, doc: DocumentKey): PersistencePromise; + /** Notify the delegate that a limbo document was updated. */ + updateLimboDocument(txn: PersistenceTransaction, doc: DocumentKey): PersistencePromise; +} + +declare type RejectedHandler = ((reason: Error) => R | PersistencePromise) | null; + +declare type Rejector = (error: Error) => void; + +/** + * Represents cached documents received from the remote backend. + * + * The cache is keyed by DocumentKey and entries in the cache are + * MutableDocuments, meaning we can cache both actual documents as well as + * documents that are known to not exist. + */ +declare interface RemoteDocumentCache { + /** Sets the index manager to use for managing the collectionGroup index. */ + setIndexManager(indexManager: IndexManager): void; + /** + * Looks up an entry in the cache. + * + * @param documentKey - The key of the entry to look up.* + * @returns The cached document entry. Returns an invalid document if the + * document is not cached. + */ + getEntry(transaction: PersistenceTransaction, documentKey: DocumentKey): PersistencePromise; + /** + * Looks up a set of entries in the cache. + * + * @param documentKeys - The keys of the entries to look up. + * @returns The cached document entries indexed by key. If an entry is not + * cached, the corresponding key will be mapped to an invalid document. + */ + getEntries(transaction: PersistenceTransaction, documentKeys: DocumentKeySet): PersistencePromise; + /** + * Returns the documents matching the given query + * + * @param query - The query to match documents against. + * @param offset - The offset to start the scan at (exclusive). + * @param context - A optional tracker to keep a record of important details + * during database local query execution. + * @returns The set of matching documents. + */ + getDocumentsMatchingQuery(transaction: PersistenceTransaction, query: Query_2, offset: IndexOffset, mutatedDocs: OverlayMap, context?: QueryContext): PersistencePromise; + /** + * Looks up the next `limit` documents for a collection group based on the + * provided offset. The ordering is based on the document's read time and key. + * + * @param collectionGroup - The collection group to scan. + * @param offset - The offset to start the scan at (exclusive). + * @param limit - The maximum number of results to return. + * @returns The set of matching documents. + */ + getAllFromCollectionGroup(transaction: PersistenceTransaction, collectionGroup: string, offset: IndexOffset, limit: number): PersistencePromise; + /** + * Provides access to add or update the contents of the cache. The buffer + * handles proper size accounting for the change. + * + * Multi-Tab Note: This should only be called by the primary client. + * + * @param options - Specify `trackRemovals` to create sentinel entries for + * removed documents, which allows removals to be tracked by + * `getNewDocumentChanges()`. + */ + newChangeBuffer(options?: { + trackRemovals: boolean; + }): RemoteDocumentChangeBuffer; + /** + * Get an estimate of the size of the document cache. Note that for eager + * garbage collection, we don't track sizes so this will return 0. + */ + getSize(transaction: PersistenceTransaction): PersistencePromise; +} + +/** + * An in-memory buffer of entries to be written to a RemoteDocumentCache. + * It can be used to batch up a set of changes to be written to the cache, but + * additionally supports reading entries back with the `getEntry()` method, + * falling back to the underlying RemoteDocumentCache if no entry is + * buffered. + * + * Entries added to the cache *must* be read first. This is to facilitate + * calculating the size delta of the pending changes. + * + * PORTING NOTE: This class was implemented then removed from other platforms. + * If byte-counting ends up being needed on the other platforms, consider + * porting this class as part of that implementation work. + */ +declare abstract class RemoteDocumentChangeBuffer { + protected changes: ObjectMap; + private changesApplied; + protected abstract getFromCache(transaction: PersistenceTransaction, documentKey: DocumentKey): PersistencePromise; + protected abstract getAllFromCache(transaction: PersistenceTransaction, documentKeys: DocumentKeySet): PersistencePromise; + protected abstract applyChanges(transaction: PersistenceTransaction): PersistencePromise; + /** + * Buffers a `RemoteDocumentCache.addEntry()` call. + * + * You can only modify documents that have already been retrieved via + * `getEntry()/getEntries()` (enforced via IndexedDbs `apply()`). + */ + addEntry(document: MutableDocument): void; + /** + * Buffers a `RemoteDocumentCache.removeEntry()` call. + * + * You can only remove documents that have already been retrieved via + * `getEntry()/getEntries()` (enforced via IndexedDbs `apply()`). + */ + removeEntry(key: DocumentKey, readTime: SnapshotVersion): void; + /** + * Looks up an entry in the cache. The buffered changes will first be checked, + * and if no buffered change applies, this will forward to + * `RemoteDocumentCache.getEntry()`. + * + * @param transaction - The transaction in which to perform any persistence + * operations. + * @param documentKey - The key of the entry to look up. + * @returns The cached document or an invalid document if we have nothing + * cached. + */ + getEntry(transaction: PersistenceTransaction, documentKey: DocumentKey): PersistencePromise; + /** + * Looks up several entries in the cache, forwarding to + * `RemoteDocumentCache.getEntry()`. + * + * @param transaction - The transaction in which to perform any persistence + * operations. + * @param documentKeys - The keys of the entries to look up. + * @returns A map of cached documents, indexed by key. If an entry cannot be + * found, the corresponding key will be mapped to an invalid document. + */ + getEntries(transaction: PersistenceTransaction, documentKeys: DocumentKeySet): PersistencePromise; + /** + * Applies buffered changes to the underlying RemoteDocumentCache, using + * the provided transaction. + */ + apply(transaction: PersistenceTransaction): PersistencePromise; + /** Helper to assert this.changes is not null */ + protected assertNotApplied(): void; +} + +/** + * An event from the RemoteStore. It is split into targetChanges (changes to the + * state or the set of documents in our watched targets) and documentUpdates + * (changes to the actual documents). + */ +declare class RemoteEvent { + /** + * The snapshot version this event brings us up to, or MIN if not set. + */ + readonly snapshotVersion: SnapshotVersion; + /** + * A map from target to changes to the target. See TargetChange. + */ + readonly targetChanges: Map; + /** + * A map of targets that is known to be inconsistent, and the purpose for + * re-listening. Listens for these targets should be re-established without + * resume tokens. + */ + readonly targetMismatches: SortedMap; + /** + * A set of which documents have changed or been deleted, along with the + * doc's new values (if not deleted). + */ + readonly documentUpdates: MutableDocumentMap; + /** + * A set of which document updates are due only to limbo resolution targets. + */ + readonly resolvedLimboDocuments: DocumentKeySet; + constructor( + /** + * The snapshot version this event brings us up to, or MIN if not set. + */ + snapshotVersion: SnapshotVersion, + /** + * A map from target to changes to the target. See TargetChange. + */ + targetChanges: Map, + /** + * A map of targets that is known to be inconsistent, and the purpose for + * re-listening. Listens for these targets should be re-established without + * resume tokens. + */ + targetMismatches: SortedMap, + /** + * A set of which documents have changed or been deleted, along with the + * doc's new values (if not deleted). + */ + documentUpdates: MutableDocumentMap, + /** + * A set of which document updates are due only to limbo resolution targets. + */ + resolvedLimboDocuments: DocumentKeySet); + /** + * HACK: Views require RemoteEvents in order to determine whether the view is + * CURRENT, but secondary tabs don't receive remote events. So this method is + * used to create a synthesized RemoteEvent that can be used to apply a + * CURRENT status change to a View, for queries executed in a different tab. + */ + static createSynthesizedRemoteEventForCurrentChange(targetId: TargetId, current: boolean, resumeToken: ByteString): RemoteEvent; +} + +/** + * RemoteStore - An interface to remotely stored data, basically providing a + * wrapper around the Datastore that is more reliable for the rest of the + * system. + * + * RemoteStore is responsible for maintaining the connection to the server. + * - maintaining a list of active listens. + * - reconnecting when the connection is dropped. + * - resuming all the active listens on reconnect. + * + * RemoteStore handles all incoming events from the Datastore. + * - listening to the watch stream and repackaging the events as RemoteEvents + * - notifying SyncEngine of any changes to the active listens. + * + * RemoteStore takes writes from other components and handles them reliably. + * - pulling pending mutations from LocalStore and sending them to Datastore. + * - retrying mutations that failed because of network problems. + * - acking mutations to the SyncEngine once they are accepted or rejected. + */ +declare interface RemoteStore { + /** + * SyncEngine to notify of watch and write events. This must be set + * immediately after construction. + */ + remoteSyncer: RemoteSyncer; +} + +/** + * An interface that describes the actions the RemoteStore needs to perform on + * a cooperating synchronization engine. + */ +declare interface RemoteSyncer { + /** + * Applies one remote event to the sync engine, notifying any views of the + * changes, and releasing any pending mutation batches that would become + * visible because of the snapshot version the remote event contains. + */ + applyRemoteEvent?(remoteEvent: RemoteEvent): Promise; + /** + * Rejects the listen for the given targetID. This can be triggered by the + * backend for any active target. + * + * @param targetId - The targetID corresponds to one previously initiated by + * the user as part of TargetData passed to listen() on RemoteStore. + * @param error - A description of the condition that has forced the rejection. + * Nearly always this will be an indication that the user is no longer + * authorized to see the data matching the target. + */ + rejectListen?(targetId: TargetId, error: FirestoreError): Promise; + /** + * Applies the result of a successful write of a mutation batch to the sync + * engine, emitting snapshots in any views that the mutation applies to, and + * removing the batch from the mutation queue. + */ + applySuccessfulWrite?(result: MutationBatchResult): Promise; + /** + * Rejects the batch, removing the batch from the mutation queue, recomputing + * the local view of any documents affected by the batch and then, emitting + * snapshots with the reverted value. + */ + rejectFailedWrite?(batchId: BatchId, error: FirestoreError): Promise; + /** + * Returns the set of remote document keys for the given target ID. This list + * includes the documents that were assigned to the target when we received + * the last snapshot. + */ + getRemoteKeysForTarget?(targetId: TargetId): DocumentKeySet; + /** + * Updates all local state to match the pending mutations for the given user. + * May be called repeatedly for the same user. + */ + handleCredentialChange?(user: User): Promise; +} + +declare type Resolver = (value?: T) => void; + +/** + * A slash-separated path for navigating resources (documents and collections) + * within Firestore. + * + * @internal + */ +declare class ResourcePath extends BasePath { + protected construct(segments: string[], offset?: number, length?: number): ResourcePath; + canonicalString(): string; + toString(): string; + /** + * Returns a string representation of this path + * where each path segment has been encoded with + * `encodeURIComponent`. + */ + toUriEncodedString(): string; + /** + * Creates a resource path from the given slash-delimited string. If multiple + * arguments are provided, all components are combined. Leading and trailing + * slashes from all components are ignored. + */ + static fromString(...pathComponents: string[]): ResourcePath; + static emptyPath(): ResourcePath; +} + +/** + * Executes the given `updateFunction` and then attempts to commit the changes + * applied within the transaction. If any document read within the transaction + * has changed, Cloud Firestore retries the `updateFunction`. If it fails to + * commit after 5 attempts, the transaction fails. + * + * The maximum number of writes allowed in a single transaction is 500. + * + * @param firestore - A reference to the Firestore database to run this + * transaction against. + * @param updateFunction - The function to execute within the transaction + * context. + * @param options - An options object to configure maximum number of attempts to + * commit. + * @returns If the transaction completed successfully or was explicitly aborted + * (the `updateFunction` returned a failed promise), the promise returned by the + * `updateFunction `is returned here. Otherwise, if the transaction failed, a + * rejected promise with the corresponding failure error is returned. + */ +export declare function runTransaction(firestore: Firestore, updateFunction: (transaction: Transaction) => Promise, options?: TransactionOptions): Promise; + +/** + * Interface to schedule periodic tasks within SDK. + */ +declare interface Scheduler { + readonly started: boolean; + start(): void; + stop(): void; +} + +/** Base interface for the Serializer implementation. */ +declare interface Serializer { + readonly useProto3Json: boolean; +} + +/** + * Returns a sentinel used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link @firebase/firestore/lite#(updateDoc:1)} to + * include a server-generated timestamp in the written data. + */ +export declare function serverTimestamp(): FieldValue; + +declare type ServerTimestampBehavior = 'estimate' | 'previous' | 'none'; + +/** + * Writes to the document referred to by the specified `DocumentReference`. If + * the document does not yet exist, it will be created. + * + * The result of this write will only be reflected in document reads that occur + * after the returned promise resolves. If the client is offline, the + * write fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @param reference - A reference to the document to write. + * @param data - A map of the fields and values for the document. + * @throws Error - If the provided input is not a valid Firestore document. + * @returns A `Promise` resolved once the data has been successfully written + * to the backend. + */ +export declare function setDoc(reference: DocumentReference, data: WithFieldValue): Promise; + +/** + * Writes to the document referred to by the specified `DocumentReference`. If + * the document does not yet exist, it will be created. If you provide `merge` + * or `mergeFields`, the provided data can be merged into an existing document. + * + * The result of this write will only be reflected in document reads that occur + * after the returned promise resolves. If the client is offline, the + * write fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @param reference - A reference to the document to write. + * @param data - A map of the fields and values for the document. + * @param options - An object to configure the set behavior. + * @throws Error - If the provided input is not a valid Firestore document. + * @returns A `Promise` resolved once the data has been successfully written + * to the backend. + */ +export declare function setDoc(reference: DocumentReference, data: PartialWithFieldValue, options: SetOptions): Promise; + +/** + * Sets the verbosity of Cloud Firestore logs (debug, error, or silent). + * + * @param logLevel - The verbosity you set for activity and error logging. Can + * be any of the following values: + * + *

    + *
  • `debug` for the most verbose logging level, primarily for + * debugging.
  • + *
  • `error` to log errors only.
  • + *
  • `silent` to turn off logging.
  • + *
+ */ +export declare function setLogLevel(logLevel: LogLevel): void; + +/** + * An options object that configures the behavior of {@link @firebase/firestore/lite#(setDoc:1)}, {@link + * @firebase/firestore/lite#(WriteBatch.set:1)} and {@link @firebase/firestore/lite#(Transaction.set:1)} calls. These calls can be + * configured to perform granular merges instead of overwriting the target + * documents in their entirety by providing a `SetOptions` with `merge: true`. + * + * @param merge - Changes the behavior of a `setDoc()` call to only replace the + * values specified in its data argument. Fields omitted from the `setDoc()` + * call remain untouched. If your input sets any field to an empty map, all + * nested fields are overwritten. + * @param mergeFields - Changes the behavior of `setDoc()` calls to only replace + * the specified field paths. Any field path that is not specified is ignored + * and remains untouched. If your input sets any field to an empty map, all + * nested fields are overwritten. + */ +export declare type SetOptions = { + readonly merge?: boolean; +} | { + readonly mergeFields?: Array; +}; + +/** + * Specifies custom configurations for your Cloud Firestore instance. + * You must set these before invoking any other methods. + */ +export declare interface Settings { + /** The hostname to connect to. */ + host?: string; + /** Whether to use SSL when connecting. */ + ssl?: boolean; + /** + * Whether to skip nested properties that are set to `undefined` during + * object serialization. If set to `true`, these properties are skipped + * and not written to Firestore. If set to `false` or omitted, the SDK + * throws an exception when it encounters properties of type `undefined`. + */ + ignoreUndefinedProperties?: boolean; +} + +/** + * A `SharedClientState` keeps track of the global state of the mutations + * and query targets for all active clients with the same persistence key (i.e. + * project ID and FirebaseApp name). It relays local changes to other clients + * and updates its local state as new state is observed. + * + * `SharedClientState` is primarily used for synchronization in Multi-Tab + * environments. Each tab is responsible for registering its active query + * targets and mutations. `SharedClientState` will then notify the listener + * assigned to `.syncEngine` for updates to mutations and queries that + * originated in other clients. + * + * To receive notifications, `.syncEngine` and `.onlineStateHandler` has to be + * assigned before calling `start()`. + */ +declare interface SharedClientState { + onlineStateHandler: ((onlineState: OnlineState) => void) | null; + sequenceNumberHandler: ((sequenceNumber: ListenSequenceNumber) => void) | null; + /** Registers the Mutation Batch ID of a newly pending mutation. */ + addPendingMutation(batchId: BatchId): void; + /** + * Records that a pending mutation has been acknowledged or rejected. + * Called by the primary client to notify secondary clients of mutation + * results as they come back from the backend. + */ + updateMutationState(batchId: BatchId, state: 'acknowledged' | 'rejected', error?: FirestoreError): void; + /** + * Associates a new Query Target ID with the local Firestore client. Returns + * the new query state for the query (which can be 'current' if the query is + * already associated with another tab). + * + * If the target id is already associated with local client, the method simply + * returns its `QueryTargetState`. + */ + addLocalQueryTarget(targetId: TargetId, addToActiveTargetIds?: boolean): QueryTargetState; + /** Removes the Query Target ID association from the local client. */ + removeLocalQueryTarget(targetId: TargetId): void; + /** Checks whether the target is associated with the local client. */ + isLocalQueryTarget(targetId: TargetId): boolean; + /** + * Processes an update to a query target. + * + * Called by the primary client to notify secondary clients of document + * changes or state transitions that affect the provided query target. + */ + updateQueryState(targetId: TargetId, state: QueryTargetState, error?: FirestoreError): void; + /** + * Removes the target's metadata entry. + * + * Called by the primary client when all clients stopped listening to a query + * target. + */ + clearQueryState(targetId: TargetId): void; + /** + * Gets the active Query Targets IDs for all active clients. + * + * The implementation for this may require O(n) runtime, where 'n' is the size + * of the result set. + */ + getAllActiveQueryTargets(): SortedSet; + /** + * Checks whether the provided target ID is currently being listened to by + * any of the active clients. + * + * The implementation may require O(n*log m) runtime, where 'n' is the number + * of clients and 'm' the number of targets. + */ + isActiveQueryTarget(targetId: TargetId): boolean; + /** + * Starts the SharedClientState, reads existing client data and registers + * listeners for updates to new and existing clients. + */ + start(): Promise; + /** Shuts down the `SharedClientState` and its listeners. */ + shutdown(): void; + /** + * Changes the active user and removes all existing user-specific data. The + * user change does not call back into SyncEngine (for example, no mutations + * will be marked as removed). + */ + handleUserChange(user: User, removedBatchIds: BatchId[], addedBatchIds: BatchId[]): void; + /** Changes the shared online state of all clients. */ + setOnlineState(onlineState: OnlineState): void; + writeSequenceNumber(sequenceNumber: ListenSequenceNumber): void; + /** + * Notifies other clients when remote documents have changed due to loading + * a bundle. + * + * @param collectionGroups The collection groups affected by this bundle. + */ + notifyBundleLoaded(collectionGroups: Set): void; +} + +/** + * Returns true if the provided snapshots are equal. + * + * @param left - A snapshot to compare. + * @param right - A snapshot to compare. + * @returns true if the snapshots are equal. + */ +export declare function snapshotEqual(left: DocumentSnapshot | QuerySnapshot, right: DocumentSnapshot | QuerySnapshot): boolean; + +/** + * A version of a document in Firestore. This corresponds to the version + * timestamp, such as update_time or read_time. + */ +declare class SnapshotVersion { + private timestamp; + static fromTimestamp(value: Timestamp): SnapshotVersion; + static min(): SnapshotVersion; + static max(): SnapshotVersion; + private constructor(); + compareTo(other: SnapshotVersion): number; + isEqual(other: SnapshotVersion): boolean; + /** Returns a number representation of the version for use in spec tests. */ + toMicroseconds(): number; + toString(): string; + toTimestamp(): Timestamp; +} + +declare class SortedMap { + comparator: Comparator; + root: LLRBNode | LLRBEmptyNode; + constructor(comparator: Comparator, root?: LLRBNode | LLRBEmptyNode); + insert(key: K, value: V): SortedMap; + remove(key: K): SortedMap; + get(key: K): V | null; + indexOf(key: K): number; + isEmpty(): boolean; + get size(): number; + minKey(): K | null; + maxKey(): K | null; + inorderTraversal(action: (k: K, v: V) => T): T; + forEach(fn: (k: K, v: V) => void): void; + toString(): string; + reverseTraversal(action: (k: K, v: V) => T): T; + getIterator(): SortedMapIterator; + getIteratorFrom(key: K): SortedMapIterator; + getReverseIterator(): SortedMapIterator; + getReverseIteratorFrom(key: K): SortedMapIterator; +} + +declare class SortedMapIterator { + private isReverse; + private nodeStack; + constructor(node: LLRBNode | LLRBEmptyNode, startKey: K | null, comparator: Comparator, isReverse: boolean); + getNext(): Entry; + hasNext(): boolean; + peek(): Entry | null; +} + +/** + * SortedSet is an immutable (copy-on-write) collection that holds elements + * in order specified by the provided comparator. + * + * NOTE: if provided comparator returns 0 for two elements, we consider them to + * be equal! + */ +declare class SortedSet { + private comparator; + private data; + constructor(comparator: (left: T, right: T) => number); + has(elem: T): boolean; + first(): T | null; + last(): T | null; + get size(): number; + indexOf(elem: T): number; + /** Iterates elements in order defined by "comparator" */ + forEach(cb: (elem: T) => void): void; + /** Iterates over `elem`s such that: range[0] <= elem < range[1]. */ + forEachInRange(range: [T, T], cb: (elem: T) => void): void; + /** + * Iterates over `elem`s such that: start <= elem until false is returned. + */ + forEachWhile(cb: (elem: T) => boolean, start?: T): void; + /** Finds the least element greater than or equal to `elem`. */ + firstAfterOrEqual(elem: T): T | null; + getIterator(): SortedSetIterator; + getIteratorFrom(key: T): SortedSetIterator; + /** Inserts or updates an element */ + add(elem: T): SortedSet; + /** Deletes an element */ + delete(elem: T): SortedSet; + isEmpty(): boolean; + unionWith(other: SortedSet): SortedSet; + isEqual(other: SortedSet): boolean; + toArray(): T[]; + toString(): string; + private copy; +} + +declare class SortedSetIterator { + private iter; + constructor(iter: SortedMapIterator); + getNext(): T; + hasNext(): boolean; +} + +/** + * Creates a {@link QueryStartAtConstraint} that modifies the result set to + * start after the provided document (exclusive). The starting position is + * relative to the order of the query. The document must contain all of the + * fields provided in the orderBy of the query. + * + * @param snapshot - The snapshot of the document to start after. + * @returns A {@link QueryStartAtConstraint} to pass to `query()` + */ +export declare function startAfter(snapshot: DocumentSnapshot): QueryStartAtConstraint; + +/** + * Creates a {@link QueryStartAtConstraint} that modifies the result set to + * start after the provided fields relative to the order of the query. The order + * of the field values must match the order of the order by clauses of the query. + * + * @param fieldValues - The field values to start this query after, in order + * of the query's order by. + * @returns A {@link QueryStartAtConstraint} to pass to `query()` + */ +export declare function startAfter(...fieldValues: unknown[]): QueryStartAtConstraint; + +/** + * Creates a {@link QueryStartAtConstraint} that modifies the result set to + * start at the provided document (inclusive). The starting position is relative + * to the order of the query. The document must contain all of the fields + * provided in the `orderBy` of this query. + * + * @param snapshot - The snapshot of the document to start at. + * @returns A {@link QueryStartAtConstraint} to pass to `query()`. + */ +export declare function startAt(snapshot: DocumentSnapshot): QueryStartAtConstraint; + +/** + * Creates a {@link QueryStartAtConstraint} that modifies the result set to + * start at the provided fields relative to the order of the query. The order of + * the field values must match the order of the order by clauses of the query. + * + * @param fieldValues - The field values to start this query at, in order + * of the query's order by. + * @returns A {@link QueryStartAtConstraint} to pass to `query()`. + */ +export declare function startAt(...fieldValues: unknown[]): QueryStartAtConstraint; + +declare type StructuredQuery = firestoreV1ApiClientInterfaces.StructuredQuery; + +/** + * Create an AggregateField object that can be used to compute the sum of + * a specified field over a range of documents in the result set of a query. + * @param field Specifies the field to sum across the result set. + */ +export declare function sum(field: string | FieldPath): AggregateField; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * SyncEngine is the central controller in the client SDK architecture. It is + * the glue code between the EventManager, LocalStore, and RemoteStore. Some of + * SyncEngine's responsibilities include: + * 1. Coordinating client requests and remote events between the EventManager + * and the local and remote data stores. + * 2. Managing a View object for each query, providing the unified view between + * the local and remote data stores. + * 3. Notifying the RemoteStore when the LocalStore has new mutations in its + * queue that need sending to the backend. + * + * The SyncEngine’s methods should only ever be called by methods running in the + * global async queue. + * + * PORTING NOTE: On Web, SyncEngine does not have an explicit subscribe() + * function. Instead, it directly depends on EventManager's tree-shakeable API + * (via `ensureWatchStream()`). + */ +declare interface SyncEngine { + isPrimaryClient: boolean; +} + +/** + * A Target represents the WatchTarget representation of a Query, which is used + * by the LocalStore and the RemoteStore to keep track of and to execute + * backend queries. While a Query can represent multiple Targets, each Targets + * maps to a single WatchTarget in RemoteStore and a single TargetData entry + * in persistence. + */ +declare interface Target { + readonly path: ResourcePath; + readonly collectionGroup: string | null; + readonly orderBy: OrderBy[]; + readonly filters: Filter[]; + readonly limit: number | null; + readonly startAt: Bound | null; + readonly endAt: Bound | null; +} + +/** + * Represents cached targets received from the remote backend. + * + * The cache is keyed by `Target` and entries in the cache are `TargetData` + * instances. + */ +declare interface TargetCache { + /** + * A global snapshot version representing the last consistent snapshot we + * received from the backend. This is monotonically increasing and any + * snapshots received from the backend prior to this version (e.g. for targets + * resumed with a resume_token) should be suppressed (buffered) until the + * backend has caught up to this snapshot version again. This prevents our + * cache from ever going backwards in time. + * + * This is updated whenever our we get a TargetChange with a read_time and + * empty target_ids. + */ + getLastRemoteSnapshotVersion(transaction: PersistenceTransaction): PersistencePromise; + /** + * @returns The highest sequence number observed, including any that might be + * persisted on-disk. + */ + getHighestSequenceNumber(transaction: PersistenceTransaction): PersistencePromise; + /** + * Call provided function with each `TargetData` that we have cached. + */ + forEachTarget(txn: PersistenceTransaction, f: (q: TargetData) => void): PersistencePromise; + /** + * Set the highest listen sequence number and optionally updates the + * snapshot version of the last consistent snapshot received from the backend + * (see getLastRemoteSnapshotVersion() for more details). + * + * @param highestListenSequenceNumber - The new maximum listen sequence number. + * @param lastRemoteSnapshotVersion - The new snapshot version. Optional. + */ + setTargetsMetadata(transaction: PersistenceTransaction, highestListenSequenceNumber: number, lastRemoteSnapshotVersion?: SnapshotVersion): PersistencePromise; + /** + * Adds an entry in the cache. + * + * The cache key is extracted from `targetData.target`. The key must not already + * exist in the cache. + * + * @param targetData - A TargetData instance to put in the cache. + */ + addTargetData(transaction: PersistenceTransaction, targetData: TargetData): PersistencePromise; + /** + * Updates an entry in the cache. + * + * The cache key is extracted from `targetData.target`. The entry must already + * exist in the cache, and it will be replaced. + * @param targetData - The TargetData to be replaced into the cache. + */ + updateTargetData(transaction: PersistenceTransaction, targetData: TargetData): PersistencePromise; + /** + * Removes the cached entry for the given target data. It is an error to remove + * a target data that does not exist. + * + * Multi-Tab Note: This operation should only be called by the primary client. + */ + removeTargetData(transaction: PersistenceTransaction, targetData: TargetData): PersistencePromise; + /** + * The number of targets currently in the cache. + */ + getTargetCount(transaction: PersistenceTransaction): PersistencePromise; + /** + * Looks up a TargetData entry by target. + * + * @param target - The query target corresponding to the entry to look up. + * @returns The cached TargetData entry, or null if the cache has no entry for + * the target. + */ + getTargetData(transaction: PersistenceTransaction, target: Target): PersistencePromise; + /** + * Adds the given document keys to cached query results of the given target + * ID. + * + * Multi-Tab Note: This operation should only be called by the primary client. + */ + addMatchingKeys(transaction: PersistenceTransaction, keys: DocumentKeySet, targetId: TargetId): PersistencePromise; + /** + * Removes the given document keys from the cached query results of the + * given target ID. + * + * Multi-Tab Note: This operation should only be called by the primary client. + */ + removeMatchingKeys(transaction: PersistenceTransaction, keys: DocumentKeySet, targetId: TargetId): PersistencePromise; + /** + * Removes all the keys in the query results of the given target ID. + * + * Multi-Tab Note: This operation should only be called by the primary client. + */ + removeMatchingKeysForTargetId(transaction: PersistenceTransaction, targetId: TargetId): PersistencePromise; + /** + * Returns the document keys that match the provided target ID. + */ + getMatchingKeysForTargetId(transaction: PersistenceTransaction, targetId: TargetId): PersistencePromise; + /** + * Returns a new target ID that is higher than any query in the cache. If + * there are no queries in the cache, returns the first valid target ID. + * Allocated target IDs are persisted and `allocateTargetId()` will never + * return the same ID twice. + */ + allocateTargetId(transaction: PersistenceTransaction): PersistencePromise; + containsKey(transaction: PersistenceTransaction, key: DocumentKey): PersistencePromise; +} + +/** + * A TargetChange specifies the set of changes for a specific target as part of + * a RemoteEvent. These changes track which documents are added, modified or + * removed, as well as the target's resume token and whether the target is + * marked CURRENT. + * The actual changes *to* documents are not part of the TargetChange since + * documents may be part of multiple targets. + */ +declare class TargetChange { + /** + * An opaque, server-assigned token that allows watching a query to be resumed + * after disconnecting without retransmitting all the data that matches the + * query. The resume token essentially identifies a point in time from which + * the server should resume sending results. + */ + readonly resumeToken: ByteString; + /** + * The "current" (synced) status of this target. Note that "current" + * has special meaning in the RPC protocol that implies that a target is + * both up-to-date and consistent with the rest of the watch stream. + */ + readonly current: boolean; + /** + * The set of documents that were newly assigned to this target as part of + * this remote event. + */ + readonly addedDocuments: DocumentKeySet; + /** + * The set of documents that were already assigned to this target but received + * an update during this remote event. + */ + readonly modifiedDocuments: DocumentKeySet; + /** + * The set of documents that were removed from this target as part of this + * remote event. + */ + readonly removedDocuments: DocumentKeySet; + constructor( + /** + * An opaque, server-assigned token that allows watching a query to be resumed + * after disconnecting without retransmitting all the data that matches the + * query. The resume token essentially identifies a point in time from which + * the server should resume sending results. + */ + resumeToken: ByteString, + /** + * The "current" (synced) status of this target. Note that "current" + * has special meaning in the RPC protocol that implies that a target is + * both up-to-date and consistent with the rest of the watch stream. + */ + current: boolean, + /** + * The set of documents that were newly assigned to this target as part of + * this remote event. + */ + addedDocuments: DocumentKeySet, + /** + * The set of documents that were already assigned to this target but received + * an update during this remote event. + */ + modifiedDocuments: DocumentKeySet, + /** + * The set of documents that were removed from this target as part of this + * remote event. + */ + removedDocuments: DocumentKeySet); + /** + * This method is used to create a synthesized TargetChanges that can be used to + * apply a CURRENT status change to a View (for queries executed in a different + * tab) or for new queries (to raise snapshots with correct CURRENT status). + */ + static createSynthesizedTargetChangeForCurrentChange(targetId: TargetId, current: boolean, resumeToken: ByteString): TargetChange; +} + +declare type TargetChangeTargetChangeType = 'NO_CHANGE' | 'ADD' | 'REMOVE' | 'CURRENT' | 'RESET'; + +/** + * An immutable set of metadata that the local store tracks for each target. + */ +declare class TargetData { + /** The target being listened to. */ + readonly target: Target; + /** + * The target ID to which the target corresponds; Assigned by the + * LocalStore for user listens and by the SyncEngine for limbo watches. + */ + readonly targetId: TargetId; + /** The purpose of the target. */ + readonly purpose: TargetPurpose; + /** + * The sequence number of the last transaction during which this target data + * was modified. + */ + readonly sequenceNumber: ListenSequenceNumber; + /** The latest snapshot version seen for this target. */ + readonly snapshotVersion: SnapshotVersion; + /** + * The maximum snapshot version at which the associated view + * contained no limbo documents. + */ + readonly lastLimboFreeSnapshotVersion: SnapshotVersion; + /** + * An opaque, server-assigned token that allows watching a target to be + * resumed after disconnecting without retransmitting all the data that + * matches the target. The resume token essentially identifies a point in + * time from which the server should resume sending results. + */ + readonly resumeToken: ByteString; + /** + * The number of documents that last matched the query at the resume token or + * read time. Documents are counted only when making a listen request with + * resume token or read time, otherwise, keep it null. + */ + readonly expectedCount: number | null; + constructor( + /** The target being listened to. */ + target: Target, + /** + * The target ID to which the target corresponds; Assigned by the + * LocalStore for user listens and by the SyncEngine for limbo watches. + */ + targetId: TargetId, + /** The purpose of the target. */ + purpose: TargetPurpose, + /** + * The sequence number of the last transaction during which this target data + * was modified. + */ + sequenceNumber: ListenSequenceNumber, + /** The latest snapshot version seen for this target. */ + snapshotVersion?: SnapshotVersion, + /** + * The maximum snapshot version at which the associated view + * contained no limbo documents. + */ + lastLimboFreeSnapshotVersion?: SnapshotVersion, + /** + * An opaque, server-assigned token that allows watching a target to be + * resumed after disconnecting without retransmitting all the data that + * matches the target. The resume token essentially identifies a point in + * time from which the server should resume sending results. + */ + resumeToken?: ByteString, + /** + * The number of documents that last matched the query at the resume token or + * read time. Documents are counted only when making a listen request with + * resume token or read time, otherwise, keep it null. + */ + expectedCount?: number | null); + /** Creates a new target data instance with an updated sequence number. */ + withSequenceNumber(sequenceNumber: number): TargetData; + /** + * Creates a new target data instance with an updated resume token and + * snapshot version. + */ + withResumeToken(resumeToken: ByteString, snapshotVersion: SnapshotVersion): TargetData; + /** + * Creates a new target data instance with an updated expected count. + */ + withExpectedCount(expectedCount: number): TargetData; + /** + * Creates a new target data instance with an updated last limbo free + * snapshot version number. + */ + withLastLimboFreeSnapshotVersion(lastLimboFreeSnapshotVersion: SnapshotVersion): TargetData; +} + +/** + * A locally-assigned ID used to refer to a target being watched via the + * Watch service. + */ +declare type TargetId = number; + +/** An enumeration of the different purposes we have for targets. */ +declare const enum TargetPurpose { + /** A regular, normal query target. */ + Listen = "TargetPurposeListen", + /** + * The query target was used to refill a query after an existence filter + * mismatch. + */ + ExistenceFilterMismatch = "TargetPurposeExistenceFilterMismatch", + /** + * The query target was used if the query is the result of a false positive in + * the bloom filter. + */ + ExistenceFilterMismatchBloom = "TargetPurposeExistenceFilterMismatchBloom", + /** The query target was used to resolve a limbo document. */ + LimboResolution = "TargetPurposeLimboResolution" +} + +/** + * Terminates the provided `Firestore` instance. + * + * After calling `terminate()` only the `clearIndexedDbPersistence()` functions + * may be used. Any other function will throw a `FirestoreError`. Termination + * does not cancel any pending writes, and any promises that are awaiting a + * response from the server will not be resolved. + * + * To restart after termination, create a new instance of `Firestore` with + * {@link (getFirestore:1)}. + * + * Note: Under normal circumstances, calling `terminate()` is not required. This + * function is useful only when you want to force this instance to release all of + * its resources or in combination with {@link clearIndexedDbPersistence} to + * ensure that all local state is destroyed between test runs. + * + * @param firestore - The `Firestore` instance to terminate. + * @returns A `Promise` that is resolved when the instance has been successfully + * terminated. + */ +export declare function terminate(firestore: Firestore): Promise; + +/** + * Wellknown "timer" IDs used when scheduling delayed operations on the + * AsyncQueue. These IDs can then be used from tests to check for the presence + * of operations or to run them early. + * + * The string values are used when encoding these timer IDs in JSON spec tests. + */ +declare const enum TimerId { + /** All can be used with runDelayedOperationsEarly() to run all timers. */ + All = "all", + /** + * The following 5 timers are used in persistent_stream.ts for the listen and + * write streams. The "Idle" timer is used to close the stream due to + * inactivity. The "ConnectionBackoff" timer is used to restart a stream once + * the appropriate backoff delay has elapsed. The health check is used to mark + * a stream healthy if it has not received an error during its initial setup. + */ + ListenStreamIdle = "listen_stream_idle", + ListenStreamConnectionBackoff = "listen_stream_connection_backoff", + WriteStreamIdle = "write_stream_idle", + WriteStreamConnectionBackoff = "write_stream_connection_backoff", + HealthCheckTimeout = "health_check_timeout", + /** + * A timer used in online_state_tracker.ts to transition from + * OnlineState.Unknown to Offline after a set timeout, rather than waiting + * indefinitely for success or failure. + */ + OnlineStateTimeout = "online_state_timeout", + /** + * A timer used to update the client metadata in IndexedDb, which is used + * to determine the primary leaseholder. + */ + ClientMetadataRefresh = "client_metadata_refresh", + /** A timer used to periodically attempt LRU Garbage collection */ + LruGarbageCollection = "lru_garbage_collection", + /** + * A timer used to retry transactions. Since there can be multiple concurrent + * transactions, multiple of these may be in the queue at a given time. + */ + TransactionRetry = "transaction_retry", + /** + * A timer used to retry operations scheduled via retryable AsyncQueue + * operations. + */ + AsyncQueueRetry = "async_queue_retry", + /** + * A timer used to periodically attempt index backfill. + */ + IndexBackfill = "index_backfill" +} + +/** + * A `Timestamp` represents a point in time independent of any time zone or + * calendar, represented as seconds and fractions of seconds at nanosecond + * resolution in UTC Epoch time. + * + * It is encoded using the Proleptic Gregorian Calendar which extends the + * Gregorian calendar backwards to year one. It is encoded assuming all minutes + * are 60 seconds long, i.e. leap seconds are "smeared" so that no leap second + * table is needed for interpretation. Range is from 0001-01-01T00:00:00Z to + * 9999-12-31T23:59:59.999999999Z. + * + * For examples and further specifications, refer to the + * {@link https://github.com/google/protobuf/blob/master/src/google/protobuf/timestamp.proto | Timestamp definition}. + */ +export declare class Timestamp { + /** + * The number of seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z. + */ + readonly seconds: number; + /** + * The fractions of a second at nanosecond resolution.* + */ + readonly nanoseconds: number; + /** + * Creates a new timestamp with the current date, with millisecond precision. + * + * @returns a new timestamp representing the current date. + */ + static now(): Timestamp; + /** + * Creates a new timestamp from the given date. + * + * @param date - The date to initialize the `Timestamp` from. + * @returns A new `Timestamp` representing the same point in time as the given + * date. + */ + static fromDate(date: Date): Timestamp; + /** + * Creates a new timestamp from the given number of milliseconds. + * + * @param milliseconds - Number of milliseconds since Unix epoch + * 1970-01-01T00:00:00Z. + * @returns A new `Timestamp` representing the same point in time as the given + * number of milliseconds. + */ + static fromMillis(milliseconds: number): Timestamp; + /** + * Creates a new timestamp. + * + * @param seconds - The number of seconds of UTC time since Unix epoch + * 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to + * 9999-12-31T23:59:59Z inclusive. + * @param nanoseconds - The non-negative fractions of a second at nanosecond + * resolution. Negative second values with fractions must still have + * non-negative nanoseconds values that count forward in time. Must be + * from 0 to 999,999,999 inclusive. + */ + constructor( + /** + * The number of seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z. + */ + seconds: number, + /** + * The fractions of a second at nanosecond resolution.* + */ + nanoseconds: number); + /** + * Converts a `Timestamp` to a JavaScript `Date` object. This conversion + * causes a loss of precision since `Date` objects only support millisecond + * precision. + * + * @returns JavaScript `Date` object representing the same point in time as + * this `Timestamp`, with millisecond precision. + */ + toDate(): Date; + /** + * Converts a `Timestamp` to a numeric timestamp (in milliseconds since + * epoch). This operation causes a loss of precision. + * + * @returns The point in time corresponding to this timestamp, represented as + * the number of milliseconds since Unix epoch 1970-01-01T00:00:00Z. + */ + toMillis(): number; + _compareTo(other: Timestamp): number; + /** + * Returns true if this `Timestamp` is equal to the provided one. + * + * @param other - The `Timestamp` to compare against. + * @returns true if this `Timestamp` is equal to the provided one. + */ + isEqual(other: Timestamp): boolean; + /** Returns a textual representation of this `Timestamp`. */ + toString(): string; + static _jsonSchemaVersion: string; + static _jsonSchema: { + type: Property<"string">; + seconds: Property<"number">; + nanoseconds: Property<"number">; + }; + /** + * Returns a JSON-serializable representation of this `Timestamp`. + */ + toJSON(): { + seconds: number; + nanoseconds: number; + type: string; + }; + /** + * Builds a `Timestamp` instance from a JSON object created by {@link Timestamp.toJSON}. + */ + static fromJSON(json: object): Timestamp; + /** + * Converts this object to a primitive string, which allows `Timestamp` objects + * to be compared using the `>`, `<=`, `>=` and `>` operators. + */ + valueOf(): string; +} + +declare type Timestamp_2 = string | { + seconds?: string | number; + nanos?: number; +}; + +declare interface Token { + /** Type of token. */ + type: TokenType; + /** + * The user with which the token is associated (used for persisting user + * state on disk, etc.). + * This will be null for Tokens of the type 'AppCheck'. + */ + user?: User; + /** Header values to set for this token */ + headers: Map; +} + +declare type TokenType = 'OAuth' | 'FirstParty' | 'AppCheck'; + +/** + * A reference to a transaction. + * + * The `Transaction` object passed to a transaction's `updateFunction` provides + * the methods to read and write data within the transaction context. See + * {@link runTransaction}. + */ +export declare class Transaction { + protected readonly _firestore: Firestore; + private readonly _transaction; + private readonly _dataReader; + /** @hideconstructor */ + constructor(_firestore: Firestore, _transaction: Transaction_2); + /** + * Reads the document referenced by the provided {@link DocumentReference}. + * + * @param documentRef - A reference to the document to be read. + * @returns A `DocumentSnapshot` with the read data. + */ + get(documentRef: DocumentReference): Promise>; + /** + * Writes to the document referred to by the provided {@link + * DocumentReference}. If the document does not exist yet, it will be created. + * + * @param documentRef - A reference to the document to be set. + * @param data - An object of the fields and values for the document. + * @throws Error - If the provided input is not a valid Firestore document. + * @returns This `Transaction` instance. Used for chaining method calls. + */ + set(documentRef: DocumentReference, data: WithFieldValue): this; + /** + * Writes to the document referred to by the provided {@link + * DocumentReference}. If the document does not exist yet, it will be created. + * If you provide `merge` or `mergeFields`, the provided data can be merged + * into an existing document. + * + * @param documentRef - A reference to the document to be set. + * @param data - An object of the fields and values for the document. + * @param options - An object to configure the set behavior. + * @throws Error - If the provided input is not a valid Firestore document. + * @returns This `Transaction` instance. Used for chaining method calls. + */ + set(documentRef: DocumentReference, data: PartialWithFieldValue, options: SetOptions): this; + /** + * Updates fields in the document referred to by the provided {@link + * DocumentReference}. The update will fail if applied to a document that does + * not exist. + * + * @param documentRef - A reference to the document to be updated. + * @param data - An object containing the fields and values with which to + * update the document. Fields can contain dots to reference nested fields + * within the document. + * @throws Error - If the provided input is not valid Firestore data. + * @returns This `Transaction` instance. Used for chaining method calls. + */ + update(documentRef: DocumentReference, data: UpdateData): this; + /** + * Updates fields in the document referred to by the provided {@link + * DocumentReference}. The update will fail if applied to a document that does + * not exist. + * + * Nested fields can be updated by providing dot-separated field path + * strings or by providing `FieldPath` objects. + * + * @param documentRef - A reference to the document to be updated. + * @param field - The first field to update. + * @param value - The first value. + * @param moreFieldsAndValues - Additional key/value pairs. + * @throws Error - If the provided input is not valid Firestore data. + * @returns This `Transaction` instance. Used for chaining method calls. + */ + update(documentRef: DocumentReference, field: string | FieldPath, value: unknown, ...moreFieldsAndValues: unknown[]): this; + /** + * Deletes the document referred to by the provided {@link DocumentReference}. + * + * @param documentRef - A reference to the document to be deleted. + * @returns This `Transaction` instance. Used for chaining method calls. + */ + delete(documentRef: DocumentReference): this; +} + +/** + * Internal transaction object responsible for accumulating the mutations to + * perform and the base versions for any documents read. + */ +declare class Transaction_2 { + private datastore; + private readVersions; + private mutations; + private committed; + /** + * A deferred usage error that occurred previously in this transaction that + * will cause the transaction to fail once it actually commits. + */ + private lastTransactionError; + /** + * Set of documents that have been written in the transaction. + * + * When there's more than one write to the same key in a transaction, any + * writes after the first are handled differently. + */ + private writtenDocs; + constructor(datastore: Datastore); + lookup(keys: DocumentKey[]): Promise; + set(key: DocumentKey, data: ParsedSetData): void; + update(key: DocumentKey, data: ParsedUpdateData): void; + delete(key: DocumentKey): void; + commit(): Promise; + private recordVersion; + /** + * Returns the version of this document when it was read in this transaction, + * as a precondition, or no precondition if it was not read. + */ + private precondition; + /** + * Returns the precondition for a document if the operation is an update. + */ + private preconditionForUpdate; + private write; + private ensureCommitNotCalled; +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Options to customize transaction behavior. + */ +export declare interface TransactionOptions { + /** Maximum number of attempts to commit, after which transaction fails. Default is 5. */ + readonly maxAttempts?: number; +} + +/** Used to represent a field transform on a mutation. */ +declare class TransformOperation { + private _; +} + +/** + * An association of JsonTypeDesc values to their native types. + * @private + * @internal + */ +declare type TSType = T extends 'object' ? object : T extends 'string' ? string : T extends 'number' ? number : T extends 'boolean' ? boolean : T extends 'null' ? null : T extends 'undefined' ? undefined : never; + +declare type UnaryFilterOp = 'OPERATOR_UNSPECIFIED' | 'IS_NAN' | 'IS_NULL' | 'IS_NOT_NAN' | 'IS_NOT_NULL'; + +/** + * Given a union type `U = T1 | T2 | ...`, returns an intersected type + * `(T1 & T2 & ...)`. + * + * Uses distributive conditional types and inference from conditional types. + * This works because multiple candidates for the same type variable in + * contra-variant positions causes an intersection type to be inferred. + * https://www.typescriptlang.org/docs/handbook/advanced-types.html#type-inference-in-conditional-types + * https://stackoverflow.com/questions/50374908/transform-union-type-to-intersection-type + */ +export declare type UnionToIntersection = (U extends unknown ? (k: U) => void : never) extends (k: infer I) => void ? I : never; + +/** + * An untyped Firestore Data Converter interface that is shared between the + * lite, firestore-exp and classic SDK. + */ +declare interface UntypedFirestoreDataConverter { + toFirestore(modelObject: WithFieldValue): WithFieldValue; + toFirestore(modelObject: PartialWithFieldValue, options: SetOptions_2): PartialWithFieldValue; + fromFirestore(snapshot: unknown, options?: unknown): AppModelType; +} + +/** + * Update data (for use with {@link (updateDoc:1)}) that consists of field paths + * (e.g. 'foo' or 'foo.baz') mapped to values. Fields that contain dots + * reference nested fields within the document. FieldValues can be passed in + * as property values. + */ +export declare type UpdateData = T extends Primitive ? T : T extends {} ? { + [K in keyof T]?: UpdateData | FieldValue; +} & NestedUpdateFields : Partial; + +/** + * Updates fields in the document referred to by the specified + * `DocumentReference`. The update will fail if applied to a document that does + * not exist. + * + * The result of this update will only be reflected in document reads that occur + * after the returned promise resolves. If the client is offline, the + * update fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @param reference - A reference to the document to update. + * @param data - An object containing the fields and values with which to + * update the document. Fields can contain dots to reference nested fields + * within the document. + * @throws Error - If the provided input is not valid Firestore data. + * @returns A `Promise` resolved once the data has been successfully written + * to the backend. + */ +export declare function updateDoc(reference: DocumentReference, data: UpdateData): Promise; + +/** + * Updates fields in the document referred to by the specified + * `DocumentReference` The update will fail if applied to a document that does + * not exist. + * + * Nested fields can be updated by providing dot-separated field path + * strings or by providing `FieldPath` objects. + * + * The result of this update will only be reflected in document reads that occur + * after the returned promise resolves. If the client is offline, the + * update fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @param reference - A reference to the document to update. + * @param field - The first field to update. + * @param value - The first value. + * @param moreFieldsAndValues - Additional key value pairs. + * @throws Error - If the provided input is not valid Firestore data. + * @returns A `Promise` resolved once the data has been successfully written + * to the backend. + */ +export declare function updateDoc(reference: DocumentReference, field: string | FieldPath, value: unknown, ...moreFieldsAndValues: unknown[]): Promise; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Simple wrapper around a nullable UID. Mostly exists to make code more + * readable. + */ +declare class User { + readonly uid: string | null; + /** A user with a null UID. */ + static readonly UNAUTHENTICATED: User; + static readonly GOOGLE_CREDENTIALS: User; + static readonly FIRST_PARTY: User; + static readonly MOCK_USER: User; + constructor(uid: string | null); + isAuthenticated(): boolean; + /** + * Returns a key representing this user, suitable for inclusion in a + * dictionary. + */ + toKey(): string; + isEqual(otherUser: User): boolean; +} + +declare type Value = firestoreV1ApiClientInterfaces.Value; + +declare type ValueNullValue = 'NULL_VALUE'; + +/** + * Creates a new `VectorValue` constructed with a copy of the given array of numbers. + * + * @param values - Create a `VectorValue` instance with a copy of this array of numbers. + * + * @returns A new `VectorValue` constructed with a copy of the given array of numbers. + */ +export declare function vector(values?: number[]): VectorValue; + +/** + * Represents a vector type in Firestore documents. + * Create an instance with {@link vector}. + * + * @class VectorValue + */ +export declare class VectorValue { + private readonly _values; + /** + * @private + * @internal + */ + constructor(values: number[] | undefined); + /** + * Returns a copy of the raw number array form of the vector. + */ + toArray(): number[]; + /** + * Returns `true` if the two `VectorValue` values have the same raw number arrays, returns `false` otherwise. + */ + isEqual(other: VectorValue): boolean; + static _jsonSchemaVersion: string; + static _jsonSchema: { + type: Property<"string">; + vectorValues: Property<"object">; + }; + /** + * Returns a JSON-serializable representation of this `VectorValue` instance. + * + * @returns a JSON representation of this object. + */ + toJSON(): object; + /** + * Builds a `VectorValue` instance from a JSON object created by {@link VectorValue.toJSON}. + * + * @param json a JSON object represention of a `VectorValue` instance. + * @returns an instance of {@link VectorValue} if the JSON object could be parsed. Throws a + * {@link FirestoreError} if an error occurs. + */ + static fromJSON(json: object): VectorValue; +} + +declare class ViewSnapshot { + readonly query: Query_2; + readonly docs: DocumentSet; + readonly oldDocs: DocumentSet; + readonly docChanges: DocumentViewChange[]; + readonly mutatedKeys: DocumentKeySet; + readonly fromCache: boolean; + readonly syncStateChanged: boolean; + readonly excludesMetadataChanges: boolean; + readonly hasCachedResults: boolean; + constructor(query: Query_2, docs: DocumentSet, oldDocs: DocumentSet, docChanges: DocumentViewChange[], mutatedKeys: DocumentKeySet, fromCache: boolean, syncStateChanged: boolean, excludesMetadataChanges: boolean, hasCachedResults: boolean); + /** Returns a view snapshot as if all documents in the snapshot were added. */ + static fromInitialDocuments(query: Query_2, documents: DocumentSet, mutatedKeys: DocumentKeySet, fromCache: boolean, hasCachedResults: boolean): ViewSnapshot; + get hasPendingWrites(): boolean; + isEqual(other: ViewSnapshot): boolean; +} + +/** + * Creates a {@link QueryFieldFilterConstraint} that enforces that documents + * must contain the specified field and that the value should satisfy the + * relation constraint provided. + * + * @param fieldPath - The path to compare + * @param opStr - The operation string (e.g "<", "<=", "==", "<", + * "<=", "!="). + * @param value - The value for comparison + * @returns The created {@link QueryFieldFilterConstraint}. + */ +export declare function where(fieldPath: string | FieldPath, opStr: WhereFilterOp, value: unknown): QueryFieldFilterConstraint; + +/** + * Filter conditions in a {@link where} clause are specified using the + * strings '<', '<=', '==', '!=', '>=', '>', 'array-contains', 'in', + * 'array-contains-any', and 'not-in'. + */ +export declare type WhereFilterOp = '<' | '<=' | '==' | '!=' | '>=' | '>' | 'array-contains' | 'in' | 'array-contains-any' | 'not-in'; + +/** + * Allows FieldValues to be passed in as a property value while maintaining + * type safety. + */ +export declare type WithFieldValue = T | (T extends Primitive ? T : T extends {} ? { + [K in keyof T]: WithFieldValue | FieldValue; +} : never); + +/** + * A write batch, used to perform multiple writes as a single atomic unit. + * + * A `WriteBatch` object can be acquired by calling {@link writeBatch}. It + * provides methods for adding writes to the write batch. None of the writes + * will be committed (or visible locally) until {@link WriteBatch.commit} is + * called. + */ +export declare class WriteBatch { + private readonly _firestore; + private readonly _commitHandler; + private readonly _dataReader; + private _mutations; + private _committed; + /** @hideconstructor */ + constructor(_firestore: Firestore, _commitHandler: (m: Mutation[]) => Promise); + /** + * Writes to the document referred to by the provided {@link + * DocumentReference}. If the document does not exist yet, it will be created. + * + * @param documentRef - A reference to the document to be set. + * @param data - An object of the fields and values for the document. + * @returns This `WriteBatch` instance. Used for chaining method calls. + */ + set(documentRef: DocumentReference, data: WithFieldValue): WriteBatch; + /** + * Writes to the document referred to by the provided {@link + * DocumentReference}. If the document does not exist yet, it will be created. + * If you provide `merge` or `mergeFields`, the provided data can be merged + * into an existing document. + * + * @param documentRef - A reference to the document to be set. + * @param data - An object of the fields and values for the document. + * @param options - An object to configure the set behavior. + * @throws Error - If the provided input is not a valid Firestore document. + * @returns This `WriteBatch` instance. Used for chaining method calls. + */ + set(documentRef: DocumentReference, data: PartialWithFieldValue, options: SetOptions): WriteBatch; + /** + * Updates fields in the document referred to by the provided {@link + * DocumentReference}. The update will fail if applied to a document that does + * not exist. + * + * @param documentRef - A reference to the document to be updated. + * @param data - An object containing the fields and values with which to + * update the document. Fields can contain dots to reference nested fields + * within the document. + * @throws Error - If the provided input is not valid Firestore data. + * @returns This `WriteBatch` instance. Used for chaining method calls. + */ + update(documentRef: DocumentReference, data: UpdateData): WriteBatch; + /** + * Updates fields in the document referred to by this {@link + * DocumentReference}. The update will fail if applied to a document that does + * not exist. + * + * Nested fields can be update by providing dot-separated field path strings + * or by providing `FieldPath` objects. + * + * @param documentRef - A reference to the document to be updated. + * @param field - The first field to update. + * @param value - The first value. + * @param moreFieldsAndValues - Additional key value pairs. + * @throws Error - If the provided input is not valid Firestore data. + * @returns This `WriteBatch` instance. Used for chaining method calls. + */ + update(documentRef: DocumentReference, field: string | FieldPath, value: unknown, ...moreFieldsAndValues: unknown[]): WriteBatch; + /** + * Deletes the document referred to by the provided {@link DocumentReference}. + * + * @param documentRef - A reference to the document to be deleted. + * @returns This `WriteBatch` instance. Used for chaining method calls. + */ + delete(documentRef: DocumentReference): WriteBatch; + /** + * Commits all of the writes in this write batch as a single atomic unit. + * + * The result of these writes will only be reflected in document reads that + * occur after the returned promise resolves. If the client is offline, the + * write fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @returns A `Promise` resolved once all of the writes in the batch have been + * successfully written to the backend as an atomic unit (note that it won't + * resolve while you're offline). + */ + commit(): Promise; + private _verifyNotCommitted; +} + +/** + * Creates a write batch, used for performing multiple writes as a single + * atomic operation. The maximum number of writes allowed in a single WriteBatch + * is 500. + * + * The result of these writes will only be reflected in document reads that + * occur after the returned promise resolves. If the client is offline, the + * write fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @returns A `WriteBatch` that can be used to atomically execute multiple + * writes. + */ +export declare function writeBatch(firestore: Firestore): WriteBatch; + +export { } diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/private.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/private.d.ts new file mode 100644 index 0000000..bae2be6 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/private.d.ts @@ -0,0 +1,5939 @@ +/** + * Firestore Lite + * + * @remarks Firestore Lite is a small online-only SDK that allows read + * and write access to your Firestore database. All operations connect + * directly to the backend, and `onSnapshot()` APIs are not supported. + * @packageDocumentation + */ + +import { DocumentData as DocumentData_2 } from '@firebase/firestore-types'; +import { EmulatorMockTokenOptions } from '@firebase/util'; +import { FirebaseApp } from '@firebase/app'; +import { FirebaseError } from '@firebase/util'; +import { LogLevelString as LogLevel } from '@firebase/logger'; +import { SetOptions as SetOptions_2 } from '@firebase/firestore-types'; + +/* Excluded from this release type: AbstractUserDataWriter */ + +/** + * Describes a map whose keys are active target ids. We do not care about the type of the + * values. + */ +declare type ActiveTargets = SortedMap; + +/** + * Add a new document to specified `CollectionReference` with the given data, + * assigning it a document ID automatically. + * + * The result of this write will only be reflected in document reads that occur + * after the returned promise resolves. If the client is offline, the + * write fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @param reference - A reference to the collection to add this document to. + * @param data - An Object containing the data for the new document. + * @throws Error - If the provided input is not a valid Firestore document. + * @returns A `Promise` resolved with a `DocumentReference` pointing to the + * newly created document after it has been written to the backend. + */ +export declare function addDoc(reference: CollectionReference, data: WithFieldValue): Promise>; + +/** + * Returns a new map where every key is prefixed with the outer key appended + * to a dot. + */ +export declare type AddPrefixToKeys> = { + [K in keyof T & string as `${Prefix}.${K}`]+?: string extends K ? any : T[K]; +}; + +/** + * Represents an aggregation that can be performed by Firestore. + */ +export declare class AggregateField { + readonly _internalFieldPath?: FieldPath_2 | undefined; + /** A type string to uniquely identify instances of this class. */ + readonly type = "AggregateField"; + /** Indicates the aggregation operation of this AggregateField. */ + readonly aggregateType: AggregateType; + /* Excluded from this release type: __constructor */ +} + +/** + * Compares two 'AggregateField` instances for equality. + * + * @param left Compare this AggregateField to the `right`. + * @param right Compare this AggregateField to the `left`. + */ +export declare function aggregateFieldEqual(left: AggregateField, right: AggregateField): boolean; + +/** + * The union of all `AggregateField` types that are supported by Firestore. + */ +export declare type AggregateFieldType = ReturnType | ReturnType | ReturnType; + +/** + * The results of executing an aggregation query. + */ +export declare class AggregateQuerySnapshot { + private readonly _userDataWriter; + private readonly _data; + /** A type string to uniquely identify instances of this class. */ + readonly type = "AggregateQuerySnapshot"; + /** + * The underlying query over which the aggregations recorded in this + * `AggregateQuerySnapshot` were performed. + */ + readonly query: Query; + /** @hideconstructor */ + constructor(query: Query, _userDataWriter: AbstractUserDataWriter, _data: ApiClientObjectMap); + /** + * Returns the results of the aggregations performed over the underlying + * query. + * + * The keys of the returned object will be the same as those of the + * `AggregateSpec` object specified to the aggregation method, and the values + * will be the corresponding aggregation result. + * + * @returns The results of the aggregations performed over the underlying + * query. + */ + data(): AggregateSpecData; +} + +/** + * Compares two `AggregateQuerySnapshot` instances for equality. + * + * Two `AggregateQuerySnapshot` instances are considered "equal" if they have + * underlying queries that compare equal, and the same data. + * + * @param left - The first `AggregateQuerySnapshot` to compare. + * @param right - The second `AggregateQuerySnapshot` to compare. + * + * @returns `true` if the objects are "equal", as defined above, or `false` + * otherwise. + */ +export declare function aggregateQuerySnapshotEqual(left: AggregateQuerySnapshot, right: AggregateQuerySnapshot): boolean; + +/** + * Specifies a set of aggregations and their aliases. + */ +export declare interface AggregateSpec { + [field: string]: AggregateFieldType; +} + +/** + * A type whose keys are taken from an `AggregateSpec`, and whose values are the + * result of the aggregation performed by the corresponding `AggregateField` + * from the input `AggregateSpec`. + */ +export declare type AggregateSpecData = { + [P in keyof T]: T[P] extends AggregateField ? U : never; +}; + +/** + * Union type representing the aggregate type to be performed. + */ +export declare type AggregateType = 'count' | 'avg' | 'sum'; + +/** + * Creates a new {@link QueryCompositeFilterConstraint} that is a conjunction of + * the given filter constraints. A conjunction filter includes a document if it + * satisfies all of the given filters. + * + * @param queryConstraints - Optional. The list of + * {@link QueryFilterConstraint}s to perform a conjunction for. These must be + * created with calls to {@link where}, {@link or}, or {@link and}. + * @returns The newly created {@link QueryCompositeFilterConstraint}. + */ +export declare function and(...queryConstraints: QueryFilterConstraint[]): QueryCompositeFilterConstraint; + +declare interface ApiClientObjectMap { + [k: string]: T; +} + +/** + * An `AppliableConstraint` is an abstraction of a constraint that can be applied + * to a Firestore query. + */ +declare abstract class AppliableConstraint { + /** + * Takes the provided {@link Query} and returns a copy of the {@link Query} with this + * {@link AppliableConstraint} applied. + */ + abstract _apply(query: Query): Query; +} + +/** + * Returns a special value that can be used with {@link (setDoc:1)} or {@link + * updateDoc:1} that tells the server to remove the given elements from any + * array value that already exists on the server. All instances of each element + * specified will be removed from the array. If the field being modified is not + * already an array it will be overwritten with an empty array. + * + * @param elements - The elements to remove from the array. + * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or + * `updateDoc()` + */ +export declare function arrayRemove(...elements: unknown[]): FieldValue; + +/** + * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link + * @firebase/firestore/lite#(updateDoc:1)} that tells the server to union the given elements with any array + * value that already exists on the server. Each specified element that doesn't + * already exist in the array will be added to the end. If the field being + * modified is not already an array it will be overwritten with an array + * containing exactly the specified elements. + * + * @param elements - The elements to union into the array. + * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or + * `updateDoc()`. + */ +export declare function arrayUnion(...elements: unknown[]): FieldValue; + +declare interface AsyncQueue { + readonly isShuttingDown: boolean; + /** + * Adds a new operation to the queue without waiting for it to complete (i.e. + * we ignore the Promise result). + */ + enqueueAndForget(op: () => Promise): void; + /** + * Regardless if the queue has initialized shutdown, adds a new operation to the + * queue without waiting for it to complete (i.e. we ignore the Promise result). + */ + enqueueAndForgetEvenWhileRestricted(op: () => Promise): void; + /** + * Initialize the shutdown of this queue. Once this method is called, the + * only possible way to request running an operation is through + * `enqueueEvenWhileRestricted()`. + * + * @param purgeExistingTasks Whether already enqueued tasked should be + * rejected (unless enqueued with `enqueueEvenWhileRestricted()`). Defaults + * to false. + */ + enterRestrictedMode(purgeExistingTasks?: boolean): void; + /** + * Adds a new operation to the queue. Returns a promise that will be resolved + * when the promise returned by the new operation is (with its value). + */ + enqueue(op: () => Promise): Promise; + /** + * Enqueue a retryable operation. + * + * A retryable operation is rescheduled with backoff if it fails with a + * IndexedDbTransactionError (the error type used by SimpleDb). All + * retryable operations are executed in order and only run if all prior + * operations were retried successfully. + */ + enqueueRetryable(op: () => Promise): void; + /** + * Schedules an operation to be queued on the AsyncQueue once the specified + * `delayMs` has elapsed. The returned DelayedOperation can be used to cancel + * or fast-forward the operation prior to its running. + */ + enqueueAfterDelay(timerId: TimerId, delayMs: number, op: () => Promise): DelayedOperation; + /** + * Verifies there's an operation currently in-progress on the AsyncQueue. + * Unfortunately we can't verify that the running code is in the promise chain + * of that operation, so this isn't a foolproof check, but it should be enough + * to catch some bugs. + */ + verifyOperationInProgress(): void; +} + +/* Excluded from this release type: AuthTokenFactory */ + +/** + * Create an AggregateField object that can be used to compute the average of + * a specified field over a range of documents in the result set of a query. + * @param field Specifies the field to average across the result set. + */ +export declare function average(field: string | FieldPath): AggregateField; + +/** + * Path represents an ordered sequence of string segments. + */ +declare abstract class BasePath> { + private segments; + private offset; + private len; + constructor(segments: string[], offset?: number, length?: number); + /** + * Abstract constructor method to construct an instance of B with the given + * parameters. + */ + protected abstract construct(segments: string[], offset?: number, length?: number): B; + /** + * Returns a String representation. + * + * Implementing classes are required to provide deterministic implementations as + * the String representation is used to obtain canonical Query IDs. + */ + abstract toString(): string; + get length(): number; + isEqual(other: B): boolean; + child(nameOrPath: string | B): B; + /** The index of one past the last segment of the path. */ + private limit; + popFirst(size?: number): B; + popLast(): B; + firstSegment(): string; + lastSegment(): string; + get(index: number): string; + isEmpty(): boolean; + isPrefixOf(other: this): boolean; + isImmediateParentOf(potentialChild: this): boolean; + forEach(fn: (segment: string) => void): void; + toArray(): string[]; + /** + * Compare 2 paths segment by segment, prioritizing numeric IDs + * (e.g., "__id123__") in numeric ascending order, followed by string + * segments in lexicographical order. + */ + static comparator>(p1: BasePath, p2: BasePath): number; + private static compareSegments; + private static isNumericId; + private static extractNumericId; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * BatchID is a locally assigned ID for a batch of mutations that have been + * applied. + */ +declare type BatchId = number; + +/** + * Represents a bound of a query. + * + * The bound is specified with the given components representing a position and + * whether it's just before or just after the position (relative to whatever the + * query order is). + * + * The position represents a logical index position for a query. It's a prefix + * of values for the (potentially implicit) order by clauses of a query. + * + * Bound provides a function to determine whether a document comes before or + * after a bound. This is influenced by whether the position is just before or + * just after the provided values. + */ +declare class Bound { + readonly position: Value[]; + readonly inclusive: boolean; + constructor(position: Value[], inclusive: boolean); +} + +/** + * Provides interfaces to save and read Firestore bundles. + */ +declare interface BundleCache { + /** + * Gets the saved `BundleMetadata` for a given `bundleId`, returns undefined + * if no bundle metadata is found under the given id. + */ + getBundleMetadata(transaction: PersistenceTransaction, bundleId: string): PersistencePromise; + /** + * Saves a `BundleMetadata` from a bundle into local storage, using its id as + * the persistent key. + */ + saveBundleMetadata(transaction: PersistenceTransaction, metadata: BundleMetadata_2): PersistencePromise; + /** + * Gets a saved `NamedQuery` for the given query name. Returns undefined if + * no queries are found under the given name. + */ + getNamedQuery(transaction: PersistenceTransaction, queryName: string): PersistencePromise; + /** + * Saves a `NamedQuery` from a bundle, using its name as the persistent key. + */ + saveNamedQuery(transaction: PersistenceTransaction, query: NamedQuery_2): PersistencePromise; +} + +/** Properties of a BundledQuery. */ +declare interface BundledQuery { + /** BundledQuery parent */ + parent?: string | null; + /** BundledQuery structuredQuery */ + structuredQuery?: StructuredQuery | null; + /** BundledQuery limitType */ + limitType?: LimitType_2 | null; +} + +/** + * Represents a Firestore bundle saved by the SDK in its local storage. + */ +declare interface BundleMetadata { + /** + * Id of the bundle. It is used together with `createTime` to determine if a + * bundle has been loaded by the SDK. + */ + readonly id: string; + /** Schema version of the bundle. */ + readonly version: number; + /** + * Set to the snapshot version of the bundle if created by the Server SDKs. + * Otherwise set to SnapshotVersion.MIN. + */ + readonly createTime: SnapshotVersion; +} + +/** Properties of a BundleMetadata. */ +declare interface BundleMetadata_2 { + /** BundleMetadata id */ + id?: string | null; + /** BundleMetadata createTime */ + createTime?: Timestamp_2 | null; + /** BundleMetadata version */ + version?: number | null; + /** BundleMetadata totalDocuments */ + totalDocuments?: number | null; + /** BundleMetadata totalBytes */ + totalBytes?: number | null; +} + +/** + * An immutable object representing an array of bytes. + */ +export declare class Bytes { + _byteString: ByteString; + /** @hideconstructor */ + constructor(byteString: ByteString); + /** + * Creates a new `Bytes` object from the given Base64 string, converting it to + * bytes. + * + * @param base64 - The Base64 string used to create the `Bytes` object. + */ + static fromBase64String(base64: string): Bytes; + /** + * Creates a new `Bytes` object from the given Uint8Array. + * + * @param array - The Uint8Array used to create the `Bytes` object. + */ + static fromUint8Array(array: Uint8Array): Bytes; + /** + * Returns the underlying bytes as a Base64-encoded string. + * + * @returns The Base64-encoded string created from the `Bytes` object. + */ + toBase64(): string; + /** + * Returns the underlying bytes in a new `Uint8Array`. + * + * @returns The Uint8Array created from the `Bytes` object. + */ + toUint8Array(): Uint8Array; + /** + * Returns a string representation of the `Bytes` object. + * + * @returns A string representation of the `Bytes` object. + */ + toString(): string; + /** + * Returns true if this `Bytes` object is equal to the provided one. + * + * @param other - The `Bytes` object to compare against. + * @returns true if this `Bytes` object is equal to the provided one. + */ + isEqual(other: Bytes): boolean; + static _jsonSchemaVersion: string; + static _jsonSchema: { + type: Property<"string">; + bytes: Property<"string">; + }; + /** + * Returns a JSON-serializable representation of this `Bytes` instance. + * + * @returns a JSON representation of this object. + */ + toJSON(): object; + /** + * Builds a `Bytes` instance from a JSON object created by {@link Bytes.toJSON}. + * + * @param json a JSON object represention of a `Bytes` instance + * @returns an instance of {@link Bytes} if the JSON object could be parsed. Throws a + * {@link FirestoreError} if an error occurs. + */ + static fromJSON(json: object): Bytes; +} + +/* Excluded from this release type: ByteString */ + +declare const enum ChangeType { + Added = 0, + Removed = 1, + Modified = 2, + Metadata = 3 +} + +/** + * Helper for calculating the nested fields for a given type T1. This is needed + * to distribute union types such as `undefined | {...}` (happens for optional + * props) or `{a: A} | {b: B}`. + * + * In this use case, `V` is used to distribute the union types of `T[K]` on + * `Record`, since `T[K]` is evaluated as an expression and not distributed. + * + * See https://www.typescriptlang.org/docs/handbook/advanced-types.html#distributive-conditional-types + */ +export declare type ChildUpdateFields = V extends Record ? AddPrefixToKeys> : never; + +/** + * A randomly-generated key assigned to each Firestore instance at startup. + */ +declare type ClientId = string; + +/** + * Gets a `CollectionReference` instance that refers to the collection at + * the specified absolute path. + * + * @param firestore - A reference to the root `Firestore` instance. + * @param path - A slash-separated path to a collection. + * @param pathSegments - Additional path segments to apply relative to the first + * argument. + * @throws If the final path has an even number of segments and does not point + * to a collection. + * @returns The `CollectionReference` instance. + */ +export declare function collection(firestore: Firestore, path: string, ...pathSegments: string[]): CollectionReference; + +/** + * Gets a `CollectionReference` instance that refers to a subcollection of + * `reference` at the specified relative path. + * + * @param reference - A reference to a collection. + * @param path - A slash-separated path to a collection. + * @param pathSegments - Additional path segments to apply relative to the first + * argument. + * @throws If the final path has an even number of segments and does not point + * to a collection. + * @returns The `CollectionReference` instance. + */ +export declare function collection(reference: CollectionReference, path: string, ...pathSegments: string[]): CollectionReference; + +/** + * Gets a `CollectionReference` instance that refers to a subcollection of + * `reference` at the specified relative path. + * + * @param reference - A reference to a Firestore document. + * @param path - A slash-separated path to a collection. + * @param pathSegments - Additional path segments that will be applied relative + * to the first argument. + * @throws If the final path has an even number of segments and does not point + * to a collection. + * @returns The `CollectionReference` instance. + */ +export declare function collection(reference: DocumentReference, path: string, ...pathSegments: string[]): CollectionReference; + +/** + * Creates and returns a new `Query` instance that includes all documents in the + * database that are contained in a collection or subcollection with the + * given `collectionId`. + * + * @param firestore - A reference to the root `Firestore` instance. + * @param collectionId - Identifies the collections to query over. Every + * collection or subcollection with this ID as the last segment of its path + * will be included. Cannot contain a slash. + * @returns The created `Query`. + */ +export declare function collectionGroup(firestore: Firestore, collectionId: string): Query; + +/** + * A `CollectionReference` object can be used for adding documents, getting + * document references, and querying for documents (using {@link (query:1)}). + */ +export declare class CollectionReference extends Query { + readonly _path: ResourcePath; + /** The type of this Firestore reference. */ + readonly type = "collection"; + /** @hideconstructor */ + constructor(firestore: Firestore, converter: FirestoreDataConverter | null, _path: ResourcePath); + /** The collection's identifier. */ + get id(): string; + /** + * A string representing the path of the referenced collection (relative + * to the root of the database). + */ + get path(): string; + /** + * A reference to the containing `DocumentReference` if this is a + * subcollection. If this isn't a subcollection, the reference is null. + */ + get parent(): DocumentReference | null; + /** + * Applies a custom data converter to this `CollectionReference`, allowing you + * to use your own custom model objects with Firestore. When you call {@link + * addDoc} with the returned `CollectionReference` instance, the provided + * converter will convert between Firestore data of type `NewDbModelType` and + * your custom type `NewAppModelType`. + * + * @param converter - Converts objects to and from Firestore. + * @returns A `CollectionReference` that uses the provided converter. + */ + withConverter(converter: FirestoreDataConverter): CollectionReference; + /** + * Removes the current converter. + * + * @param converter - `null` removes the current converter. + * @returns A `CollectionReference` that does not + * use a converter. + */ + withConverter(converter: null): CollectionReference; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +declare type Comparator = (key1: K, key2: K) => number; + +declare interface ComponentConfiguration { + asyncQueue: AsyncQueue; + databaseInfo: DatabaseInfo; + authCredentials: CredentialsProvider; + appCheckCredentials: CredentialsProvider; + clientId: ClientId; + initialUser: User; + maxConcurrentLimboResolutions: number; +} + +declare type CompositeFilterOp = 'OPERATOR_UNSPECIFIED' | 'AND' | 'OR'; + +declare const enum CompositeOperator { + OR = "or", + AND = "and" +} + +/** + * Modify this instance to communicate with the Cloud Firestore emulator. + * + * Note: This must be called before this instance has been used to do any + * operations. + * + * @param firestore - The `Firestore` instance to configure to connect to the + * emulator. + * @param host - the emulator host (ex: localhost). + * @param port - the emulator port (ex: 9000). + * @param options.mockUserToken - the mock auth token to use for unit testing + * Security Rules. + */ +export declare function connectFirestoreEmulator(firestore: Firestore, host: string, port: number, options?: { + mockUserToken?: EmulatorMockTokenOptions | string; +}): void; + +/** + * Create an AggregateField object that can be used to compute the count of + * documents in the result set of a query. + */ +export declare function count(): AggregateField; + +/** + * A Listener for credential change events. The listener should fetch a new + * token and may need to invalidate other state if the current user has also + * changed. + */ +declare type CredentialChangeListener = (credential: T) => Promise; + +/** + * Provides methods for getting the uid and token for the current user and + * listening for changes. + */ +declare interface CredentialsProvider { + /** + * Starts the credentials provider and specifies a listener to be notified of + * credential changes (sign-in / sign-out, token changes). It is immediately + * called once with the initial user. + * + * The change listener is invoked on the provided AsyncQueue. + */ + start(asyncQueue: AsyncQueue, changeListener: CredentialChangeListener): void; + /** Requests a token for the current user. */ + getToken(): Promise; + /** + * Marks the last retrieved token as invalid, making the next GetToken request + * force-refresh the token. + */ + invalidateToken(): void; + shutdown(): void; +} + +/** Settings for private credentials */ +declare type CredentialsSettings = FirstPartyCredentialsSettings | ProviderCredentialsSettings; + +/* Excluded from this release type: DatabaseId */ + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +declare class DatabaseInfo { + readonly databaseId: DatabaseId; + readonly appId: string; + readonly persistenceKey: string; + readonly host: string; + readonly ssl: boolean; + readonly forceLongPolling: boolean; + readonly autoDetectLongPolling: boolean; + readonly longPollingOptions: ExperimentalLongPollingOptions; + readonly useFetchStreams: boolean; + readonly isUsingEmulator: boolean; + /** + * Constructs a DatabaseInfo using the provided host, databaseId and + * persistenceKey. + * + * @param databaseId - The database to use. + * @param appId - The Firebase App Id. + * @param persistenceKey - A unique identifier for this Firestore's local + * storage (used in conjunction with the databaseId). + * @param host - The Firestore backend host to connect to. + * @param ssl - Whether to use SSL when connecting. + * @param forceLongPolling - Whether to use the forceLongPolling option + * when using WebChannel as the network transport. + * @param autoDetectLongPolling - Whether to use the detectBufferingProxy + * option when using WebChannel as the network transport. + * @param longPollingOptions Options that configure long-polling. + * @param useFetchStreams Whether to use the Fetch API instead of + * XMLHTTPRequest + */ + constructor(databaseId: DatabaseId, appId: string, persistenceKey: string, host: string, ssl: boolean, forceLongPolling: boolean, autoDetectLongPolling: boolean, longPollingOptions: ExperimentalLongPollingOptions, useFetchStreams: boolean, isUsingEmulator: boolean); +} + +/** + * Datastore and its related methods are a wrapper around the external Google + * Cloud Datastore grpc API, which provides an interface that is more convenient + * for the rest of the client SDK architecture to consume. + */ +declare abstract class Datastore { + abstract terminate(): void; + abstract serializer: JsonProtoSerializer; +} + +/** + * Represents an operation scheduled to be run in the future on an AsyncQueue. + * + * It is created via DelayedOperation.createAndSchedule(). + * + * Supports cancellation (via cancel()) and early execution (via skipDelay()). + * + * Note: We implement `PromiseLike` instead of `Promise`, as the `Promise` type + * in newer versions of TypeScript defines `finally`, which is not available in + * IE. + */ +declare class DelayedOperation implements PromiseLike { + private readonly asyncQueue; + readonly timerId: TimerId; + readonly targetTimeMs: number; + private readonly op; + private readonly removalCallback; + private timerHandle; + private readonly deferred; + private constructor(); + get promise(): Promise; + /** + * Creates and returns a DelayedOperation that has been scheduled to be + * executed on the provided asyncQueue after the provided delayMs. + * + * @param asyncQueue - The queue to schedule the operation on. + * @param id - A Timer ID identifying the type of operation this is. + * @param delayMs - The delay (ms) before the operation should be scheduled. + * @param op - The operation to run. + * @param removalCallback - A callback to be called synchronously once the + * operation is executed or canceled, notifying the AsyncQueue to remove it + * from its delayedOperations list. + * PORTING NOTE: This exists to prevent making removeDelayedOperation() and + * the DelayedOperation class public. + */ + static createAndSchedule(asyncQueue: AsyncQueue, timerId: TimerId, delayMs: number, op: () => Promise, removalCallback: (op: DelayedOperation) => void): DelayedOperation; + /** + * Starts the timer. This is called immediately after construction by + * createAndSchedule(). + */ + private start; + /** + * Queues the operation to run immediately (if it hasn't already been run or + * canceled). + */ + skipDelay(): void; + /** + * Cancels the operation if it hasn't already been executed or canceled. The + * promise will be rejected. + * + * As long as the operation has not yet been run, calling cancel() provides a + * guarantee that the operation will not be run. + */ + cancel(reason?: string): void; + then: (onfulfilled?: ((value: T) => TResult1 | PromiseLike) | null | undefined, onrejected?: ((reason: any) => TResult2 | PromiseLike) | null | undefined) => Promise; + private handleDelayElapsed; + private clearTimeout; +} + +/** + * Deletes the document referred to by the specified `DocumentReference`. + * + * The deletion will only be reflected in document reads that occur after the + * returned promise resolves. If the client is offline, the + * delete fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @param reference - A reference to the document to delete. + * @returns A `Promise` resolved once the document has been successfully + * deleted from the backend. + */ +export declare function deleteDoc(reference: DocumentReference): Promise; + +/** + * Returns a sentinel for use with {@link @firebase/firestore/lite#(updateDoc:1)} or + * {@link @firebase/firestore/lite#(setDoc:1)} with `{merge: true}` to mark a field for deletion. + */ +export declare function deleteField(): FieldValue; + +/** + * The direction of sorting in an order by. + */ +declare const enum Direction { + ASCENDING = "asc", + DESCENDING = "desc" +} + +/** + * Gets a `DocumentReference` instance that refers to the document at the + * specified absolute path. + * + * @param firestore - A reference to the root `Firestore` instance. + * @param path - A slash-separated path to a document. + * @param pathSegments - Additional path segments that will be applied relative + * to the first argument. + * @throws If the final path has an odd number of segments and does not point to + * a document. + * @returns The `DocumentReference` instance. + */ +export declare function doc(firestore: Firestore, path: string, ...pathSegments: string[]): DocumentReference; + +/** + * Gets a `DocumentReference` instance that refers to a document within + * `reference` at the specified relative path. If no path is specified, an + * automatically-generated unique ID will be used for the returned + * `DocumentReference`. + * + * @param reference - A reference to a collection. + * @param path - A slash-separated path to a document. Has to be omitted to use + * auto-generated IDs. + * @param pathSegments - Additional path segments that will be applied relative + * to the first argument. + * @throws If the final path has an odd number of segments and does not point to + * a document. + * @returns The `DocumentReference` instance. + */ +export declare function doc(reference: CollectionReference, path?: string, ...pathSegments: string[]): DocumentReference; + +/** + * Gets a `DocumentReference` instance that refers to a document within + * `reference` at the specified relative path. + * + * @param reference - A reference to a Firestore document. + * @param path - A slash-separated path to a document. + * @param pathSegments - Additional path segments that will be applied relative + * to the first argument. + * @throws If the final path has an odd number of segments and does not point to + * a document. + * @returns The `DocumentReference` instance. + */ +export declare function doc(reference: DocumentReference, path: string, ...pathSegments: string[]): DocumentReference; + +/** + * Represents a document in Firestore with a key, version, data and whether the + * data has local mutations applied to it. + */ +declare interface Document_2 { + /** The key for this document */ + readonly key: DocumentKey; + /** + * The version of this document if it exists or a version at which this + * document was guaranteed to not exist. + */ + readonly version: SnapshotVersion; + /** + * The timestamp at which this document was read from the remote server. Uses + * `SnapshotVersion.min()` for documents created by the user. + */ + readonly readTime: SnapshotVersion; + /** + * The timestamp at which the document was created. This value increases + * monotonically when a document is deleted then recreated. It can also be + * compared to `createTime` of other documents and the `readTime` of a query. + */ + readonly createTime: SnapshotVersion; + /** The underlying data of this document or an empty value if no data exists. */ + readonly data: ObjectValue; + /** Returns whether local mutations were applied via the mutation queue. */ + readonly hasLocalMutations: boolean; + /** Returns whether mutations were applied based on a write acknowledgment. */ + readonly hasCommittedMutations: boolean; + /** + * Whether this document had a local mutation applied that has not yet been + * acknowledged by Watch. + */ + readonly hasPendingWrites: boolean; + /** + * Returns whether this document is valid (i.e. it is an entry in the + * RemoteDocumentCache, was created by a mutation or read from the backend). + */ + isValidDocument(): boolean; + /** + * Returns whether the document exists and its data is known at the current + * version. + */ + isFoundDocument(): boolean; + /** + * Returns whether the document is known to not exist at the current version. + */ + isNoDocument(): boolean; + /** + * Returns whether the document exists and its data is unknown at the current + * version. + */ + isUnknownDocument(): boolean; + isEqual(other: Document_2 | null | undefined): boolean; + /** Creates a mutable copy of this document. */ + mutableCopy(): MutableDocument; + toString(): string; +} + +declare type DocumentComparator = (doc1: Document_2, doc2: Document_2) => number; + +/** + * Document data (for use with {@link @firebase/firestore/lite#(setDoc:1)}) consists of fields mapped to + * values. + */ +export declare interface DocumentData { + /** A mapping between a field and its value. */ + [field: string]: any; +} + +/** + * Returns a special sentinel `FieldPath` to refer to the ID of a document. + * It can be used in queries to sort or filter by the document ID. + */ +export declare function documentId(): FieldPath; + +/* Excluded from this release type: DocumentKey */ + +declare type DocumentKeyMap = ObjectMap; + +declare type DocumentKeySet = SortedSet; + +declare type DocumentMap = SortedMap; + +/** + * Provides methods to read and write document overlays. + * + * An overlay is a saved mutation, that gives a local view of a document when + * applied to the remote version of the document. + * + * Each overlay stores the largest batch ID that is included in the overlay, + * which allows us to remove the overlay once all batches leading up to it have + * been acknowledged. + */ +declare interface DocumentOverlayCache { + /** + * Gets the saved overlay mutation for the given document key. + * Returns null if there is no overlay for that key. + */ + getOverlay(transaction: PersistenceTransaction, key: DocumentKey): PersistencePromise; + /** + * Gets the saved overlay mutation for the given document keys. Skips keys for + * which there are no overlays. + */ + getOverlays(transaction: PersistenceTransaction, keys: DocumentKey[]): PersistencePromise; + /** + * Saves the given document mutation map to persistence as overlays. + * All overlays will have their largest batch id set to `largestBatchId`. + */ + saveOverlays(transaction: PersistenceTransaction, largestBatchId: number, overlays: MutationMap): PersistencePromise; + /** Removes overlays for the given document keys and batch ID. */ + removeOverlaysForBatchId(transaction: PersistenceTransaction, documentKeys: DocumentKeySet, batchId: number): PersistencePromise; + /** + * Returns all saved overlays for the given collection. + * + * @param transaction - The persistence transaction to use for this operation. + * @param collection - The collection path to get the overlays for. + * @param sinceBatchId - The minimum batch ID to filter by (exclusive). + * Only overlays that contain a change past `sinceBatchId` are returned. + * @returns Mapping of each document key in the collection to its overlay. + */ + getOverlaysForCollection(transaction: PersistenceTransaction, collection: ResourcePath, sinceBatchId: number): PersistencePromise; + /** + * Returns `count` overlays with a batch ID higher than `sinceBatchId` for the + * provided collection group, processed by ascending batch ID. The method + * always returns all overlays for a batch even if the last batch contains + * more documents than the remaining limit. + * + * @param transaction - The persistence transaction used for this operation. + * @param collectionGroup - The collection group to get the overlays for. + * @param sinceBatchId - The minimum batch ID to filter by (exclusive). + * Only overlays that contain a change past `sinceBatchId` are returned. + * @param count - The number of overlays to return. Can be exceeded if the last + * batch contains more entries. + * @return Mapping of each document key in the collection group to its overlay. + */ + getOverlaysForCollectionGroup(transaction: PersistenceTransaction, collectionGroup: string, sinceBatchId: number, count: number): PersistencePromise; +} + +/** + * A `DocumentReference` refers to a document location in a Firestore database + * and can be used to write, read, or listen to the location. The document at + * the referenced location may or may not exist. + */ +export declare class DocumentReference { + /** + * If provided, the `FirestoreDataConverter` associated with this instance. + */ + readonly converter: FirestoreDataConverter | null; + readonly _key: DocumentKey; + /** The type of this Firestore reference. */ + readonly type = "document"; + /** + * The {@link Firestore} instance the document is in. + * This is useful for performing transactions, for example. + */ + readonly firestore: Firestore; + /** @hideconstructor */ + constructor(firestore: Firestore, + /** + * If provided, the `FirestoreDataConverter` associated with this instance. + */ + converter: FirestoreDataConverter | null, _key: DocumentKey); + get _path(): ResourcePath; + /** + * The document's identifier within its collection. + */ + get id(): string; + /** + * A string representing the path of the referenced document (relative + * to the root of the database). + */ + get path(): string; + /** + * The collection this `DocumentReference` belongs to. + */ + get parent(): CollectionReference; + /** + * Applies a custom data converter to this `DocumentReference`, allowing you + * to use your own custom model objects with Firestore. When you call {@link + * @firebase/firestore/lite#(setDoc:1)}, {@link @firebase/firestore/lite#getDoc}, etc. with the returned `DocumentReference` + * instance, the provided converter will convert between Firestore data of + * type `NewDbModelType` and your custom type `NewAppModelType`. + * + * @param converter - Converts objects to and from Firestore. + * @returns A `DocumentReference` that uses the provided converter. + */ + withConverter(converter: FirestoreDataConverter): DocumentReference; + /** + * Removes the current converter. + * + * @param converter - `null` removes the current converter. + * @returns A `DocumentReference` that does not + * use a converter. + */ + withConverter(converter: null): DocumentReference; + static _jsonSchemaVersion: string; + static _jsonSchema: { + type: Property<"string">; + referencePath: Property<"string">; + }; + /** + * Returns a JSON-serializable representation of this `DocumentReference` instance. + * + * @returns a JSON representation of this object. + */ + toJSON(): object; + /** + * Builds a `DocumentReference` instance from a JSON object created by + * {@link DocumentReference.toJSON}. + * + * @param firestore - The {@link Firestore} instance the snapshot should be loaded for. + * @param json a JSON object represention of a `DocumentReference` instance + * @returns an instance of {@link DocumentReference} if the JSON object could be parsed. Throws a + * {@link FirestoreError} if an error occurs. + */ + static fromJSON(firestore: Firestore, json: object): DocumentReference; + /** + * Builds a `DocumentReference` instance from a JSON object created by + * {@link DocumentReference.toJSON}. + * + * @param firestore - The {@link Firestore} instance the snapshot should be loaded for. + * @param json a JSON object represention of a `DocumentReference` instance + * @param converter - Converts objects to and from Firestore. + * @returns an instance of {@link DocumentReference} if the JSON object could be parsed. Throws a + * {@link FirestoreError} if an error occurs. + */ + static fromJSON(firestore: Firestore, json: object, converter: FirestoreDataConverter): DocumentReference; +} + +/** + * DocumentSet is an immutable (copy-on-write) collection that holds documents + * in order specified by the provided comparator. We always add a document key + * comparator on top of what is provided to guarantee document equality based on + * the key. + */ +declare class DocumentSet { + /** + * Returns an empty copy of the existing DocumentSet, using the same + * comparator. + */ + static emptySet(oldSet: DocumentSet): DocumentSet; + private comparator; + private keyedMap; + private sortedSet; + /** The default ordering is by key if the comparator is omitted */ + constructor(comp?: DocumentComparator); + has(key: DocumentKey): boolean; + get(key: DocumentKey): Document_2 | null; + first(): Document_2 | null; + last(): Document_2 | null; + isEmpty(): boolean; + /** + * Returns the index of the provided key in the document set, or -1 if the + * document key is not present in the set; + */ + indexOf(key: DocumentKey): number; + get size(): number; + /** Iterates documents in order defined by "comparator" */ + forEach(cb: (doc: Document_2) => void): void; + /** Inserts or updates a document with the same key */ + add(doc: Document_2): DocumentSet; + /** Deletes a document with a given key */ + delete(key: DocumentKey): DocumentSet; + isEqual(other: DocumentSet | null | undefined): boolean; + toString(): string; + private copy; +} + +/** + * A `DocumentSnapshot` contains data read from a document in your Firestore + * database. The data can be extracted with `.data()` or `.get()` to + * get a specific field. + * + * For a `DocumentSnapshot` that points to a non-existing document, any data + * access will return 'undefined'. You can use the `exists()` method to + * explicitly verify a document's existence. + */ +export declare class DocumentSnapshot { + _firestore: Firestore; + _userDataWriter: AbstractUserDataWriter; + _key: DocumentKey; + _document: Document_2 | null; + _converter: UntypedFirestoreDataConverter | null; + /** @hideconstructor protected */ + constructor(_firestore: Firestore, _userDataWriter: AbstractUserDataWriter, _key: DocumentKey, _document: Document_2 | null, _converter: UntypedFirestoreDataConverter | null); + /** Property of the `DocumentSnapshot` that provides the document's ID. */ + get id(): string; + /** + * The `DocumentReference` for the document included in the `DocumentSnapshot`. + */ + get ref(): DocumentReference; + /** + * Signals whether or not the document at the snapshot's location exists. + * + * @returns true if the document exists. + */ + exists(): this is QueryDocumentSnapshot; + /** + * Retrieves all fields in the document as an `Object`. Returns `undefined` if + * the document doesn't exist. + * + * @returns An `Object` containing all fields in the document or `undefined` + * if the document doesn't exist. + */ + data(): AppModelType | undefined; + /** + * Retrieves the field specified by `fieldPath`. Returns `undefined` if the + * document or field doesn't exist. + * + * @param fieldPath - The path (for example 'foo' or 'foo.bar') to a specific + * field. + * @returns The data at the specified field location or undefined if no such + * field exists in the document. + */ + get(fieldPath: string | FieldPath): any; +} + +declare type DocumentVersionMap = SortedMap; + +declare interface DocumentViewChange { + type: ChangeType; + doc: Document_2; +} +export { EmulatorMockTokenOptions } + +/** + * Creates a {@link QueryEndAtConstraint} that modifies the result set to end at + * the provided document (inclusive). The end position is relative to the order + * of the query. The document must contain all of the fields provided in the + * orderBy of the query. + * + * @param snapshot - The snapshot of the document to end at. + * @returns A {@link QueryEndAtConstraint} to pass to `query()` + */ +export declare function endAt(snapshot: DocumentSnapshot): QueryEndAtConstraint; + +/** + * Creates a {@link QueryEndAtConstraint} that modifies the result set to end at + * the provided fields relative to the order of the query. The order of the field + * values must match the order of the order by clauses of the query. + * + * @param fieldValues - The field values to end this query at, in order + * of the query's order by. + * @returns A {@link QueryEndAtConstraint} to pass to `query()` + */ +export declare function endAt(...fieldValues: unknown[]): QueryEndAtConstraint; + +/** + * Creates a {@link QueryEndAtConstraint} that modifies the result set to end + * before the provided document (exclusive). The end position is relative to the + * order of the query. The document must contain all of the fields provided in + * the orderBy of the query. + * + * @param snapshot - The snapshot of the document to end before. + * @returns A {@link QueryEndAtConstraint} to pass to `query()` + */ +export declare function endBefore(snapshot: DocumentSnapshot): QueryEndAtConstraint; + +/** + * Creates a {@link QueryEndAtConstraint} that modifies the result set to end + * before the provided fields relative to the order of the query. The order of + * the field values must match the order of the order by clauses of the query. + * + * @param fieldValues - The field values to end this query before, in order + * of the query's order by. + * @returns A {@link QueryEndAtConstraint} to pass to `query()` + */ +export declare function endBefore(...fieldValues: unknown[]): QueryEndAtConstraint; + +declare interface Entry { + key: K; + value: V; +} + +/** + * EventManager is responsible for mapping queries to query event emitters. + * It handles "fan-out". -- Identical queries will re-use the same watch on the + * backend. + * + * PORTING NOTE: On Web, EventManager `onListen` and `onUnlisten` need to be + * assigned to SyncEngine's `listen()` and `unlisten()` API before usage. This + * allows users to tree-shake the Watch logic. + */ +declare interface EventManager { + onListen?: (query: Query_2, enableRemoteListen: boolean) => Promise; + onUnlisten?: (query: Query_2, disableRemoteListen: boolean) => Promise; + onFirstRemoteStoreListen?: (query: Query_2) => Promise; + onLastRemoteStoreUnlisten?: (query: Query_2) => Promise; + terminate(): void; +} + +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Options that configure the SDK’s underlying network transport (WebChannel) + * when long-polling is used. + * + * Note: This interface is "experimental" and is subject to change. + * + * See `FirestoreSettings.experimentalAutoDetectLongPolling`, + * `FirestoreSettings.experimentalForceLongPolling`, and + * `FirestoreSettings.experimentalLongPollingOptions`. + */ +declare interface ExperimentalLongPollingOptions { + /** + * The desired maximum timeout interval, in seconds, to complete a + * long-polling GET response. Valid values are between 5 and 30, inclusive. + * Floating point values are allowed and will be rounded to the nearest + * millisecond. + * + * By default, when long-polling is used the "hanging GET" request sent by + * the client times out after 30 seconds. To request a different timeout + * from the server, set this setting with the desired timeout. + * + * Changing the default timeout may be useful, for example, if the buffering + * proxy that necessitated enabling long-polling in the first place has a + * shorter timeout for hanging GET requests, in which case setting the + * long-polling timeout to a shorter value, such as 25 seconds, may fix + * prematurely-closed hanging GET requests. + * For example, see https://github.com/firebase/firebase-js-sdk/issues/6987. + */ + timeoutSeconds?: number; +} + +declare class FieldFilter extends Filter { + readonly field: FieldPath_2; + readonly op: Operator; + readonly value: Value; + protected constructor(field: FieldPath_2, op: Operator, value: Value); + /** + * Creates a filter based on the provided arguments. + */ + static create(field: FieldPath_2, op: Operator, value: Value): FieldFilter; + private static createKeyFieldInFilter; + matches(doc: Document_2): boolean; + protected matchesComparison(comparison: number): boolean; + isInequality(): boolean; + getFlattenedFilters(): readonly FieldFilter[]; + getFilters(): Filter[]; +} + +declare type FieldFilterOp = 'OPERATOR_UNSPECIFIED' | 'LESS_THAN' | 'LESS_THAN_OR_EQUAL' | 'GREATER_THAN' | 'GREATER_THAN_OR_EQUAL' | 'EQUAL' | 'NOT_EQUAL' | 'ARRAY_CONTAINS' | 'IN' | 'ARRAY_CONTAINS_ANY' | 'NOT_IN'; + +/** + * An index definition for field indexes in Firestore. + * + * Every index is associated with a collection. The definition contains a list + * of fields and their index kind (which can be `ASCENDING`, `DESCENDING` or + * `CONTAINS` for ArrayContains/ArrayContainsAny queries). + * + * Unlike the backend, the SDK does not differentiate between collection or + * collection group-scoped indices. Every index can be used for both single + * collection and collection group queries. + */ +declare class FieldIndex { + /** + * The index ID. Returns -1 if the index ID is not available (e.g. the index + * has not yet been persisted). + */ + readonly indexId: number; + /** The collection ID this index applies to. */ + readonly collectionGroup: string; + /** The field segments for this index. */ + readonly fields: IndexSegment[]; + /** Shows how up-to-date the index is for the current user. */ + readonly indexState: IndexState; + /** An ID for an index that has not yet been added to persistence. */ + static UNKNOWN_ID: number; + constructor( + /** + * The index ID. Returns -1 if the index ID is not available (e.g. the index + * has not yet been persisted). + */ + indexId: number, + /** The collection ID this index applies to. */ + collectionGroup: string, + /** The field segments for this index. */ + fields: IndexSegment[], + /** Shows how up-to-date the index is for the current user. */ + indexState: IndexState); +} + +/** + * Provides a set of fields that can be used to partially patch a document. + * FieldMask is used in conjunction with ObjectValue. + * Examples: + * foo - Overwrites foo entirely with the provided value. If foo is not + * present in the companion ObjectValue, the field is deleted. + * foo.bar - Overwrites only the field bar of the object foo. + * If foo is not an object, foo is replaced with an object + * containing foo + */ +declare class FieldMask { + readonly fields: FieldPath_2[]; + constructor(fields: FieldPath_2[]); + static empty(): FieldMask; + /** + * Returns a new FieldMask object that is the result of adding all the given + * fields paths to this field mask. + */ + unionWith(extraFields: FieldPath_2[]): FieldMask; + /** + * Verifies that `fieldPath` is included by at least one field in this field + * mask. + * + * This is an O(n) operation, where `n` is the size of the field mask. + */ + covers(fieldPath: FieldPath_2): boolean; + isEqual(other: FieldMask): boolean; +} + +/** + * A `FieldPath` refers to a field in a document. The path may consist of a + * single field name (referring to a top-level field in the document), or a + * list of field names (referring to a nested field in the document). + * + * Create a `FieldPath` by providing field names. If more than one field + * name is provided, the path will point to a nested field in a document. + */ +export declare class FieldPath { + /** Internal representation of a Firestore field path. */ + readonly _internalPath: FieldPath_2; + /** + * Creates a `FieldPath` from the provided field names. If more than one field + * name is provided, the path will point to a nested field in a document. + * + * @param fieldNames - A list of field names. + */ + constructor(...fieldNames: string[]); + /** + * Returns true if this `FieldPath` is equal to the provided one. + * + * @param other - The `FieldPath` to compare against. + * @returns true if this `FieldPath` is equal to the provided one. + */ + isEqual(other: FieldPath): boolean; +} + +/* Excluded from this release type: FieldPath_2 */ + +/** A field path and the TransformOperation to perform upon it. */ +declare class FieldTransform { + readonly field: FieldPath_2; + readonly transform: TransformOperation; + constructor(field: FieldPath_2, transform: TransformOperation); +} + +declare type FieldTransformSetToServerValue = 'SERVER_VALUE_UNSPECIFIED' | 'REQUEST_TIME'; + +/** + * Sentinel values that can be used when writing document fields with `set()` + * or `update()`. + */ +export declare abstract class FieldValue { + _methodName: string; + /** + * @param _methodName - The public API endpoint that returns this class. + * @hideconstructor + */ + constructor(_methodName: string); + /** Compares `FieldValue`s for equality. */ + abstract isEqual(other: FieldValue): boolean; + abstract _toFieldTransform(context: ParseContext): FieldTransform | null; +} + +declare abstract class Filter { + abstract matches(doc: Document_2): boolean; + abstract getFlattenedFilters(): readonly FieldFilter[]; + abstract getFilters(): Filter[]; +} + +/* Excluded from this release type: _FirebaseService */ + +/** + * The Cloud Firestore service interface. + * + * Do not call this constructor directly. Instead, use {@link (getFirestore:1)}. + */ +export declare class Firestore implements FirestoreService { + _authCredentials: CredentialsProvider; + _appCheckCredentials: CredentialsProvider; + readonly _databaseId: DatabaseId; + readonly _app?: FirebaseApp | undefined; + /** + * Whether it's a Firestore or Firestore Lite instance. + */ + type: 'firestore-lite' | 'firestore'; + readonly _persistenceKey: string; + private _settings; + private _settingsFrozen; + private _emulatorOptions; + private _terminateTask; + /** @hideconstructor */ + constructor(_authCredentials: CredentialsProvider, _appCheckCredentials: CredentialsProvider, _databaseId: DatabaseId, _app?: FirebaseApp | undefined); + /** + * The {@link @firebase/app#FirebaseApp} associated with this `Firestore` service + * instance. + */ + get app(): FirebaseApp; + get _initialized(): boolean; + get _terminated(): boolean; + _setSettings(settings: PrivateSettings): void; + _getSettings(): FirestoreSettingsImpl; + _getEmulatorOptions(): { + mockUserToken?: EmulatorMockTokenOptions | string; + }; + _freezeSettings(): FirestoreSettingsImpl; + _delete(): Promise; + _restart(): Promise; + /** Returns a JSON-serializable representation of this `Firestore` instance. */ + toJSON(): object; + /** + * Terminates all components used by this client. Subclasses can override + * this method to clean up their own dependencies, but must also call this + * method. + * + * Only ever called once. + */ + protected _terminate(): Promise; +} + +/** + * Converter used by `withConverter()` to transform user objects of type + * `AppModelType` into Firestore data of type `DbModelType`. + * + * Using the converter allows you to specify generic type arguments when + * storing and retrieving objects from Firestore. + * + * In this context, an "AppModel" is a class that is used in an application to + * package together related information and functionality. Such a class could, + * for example, have properties with complex, nested data types, properties used + * for memoization, properties of types not supported by Firestore (such as + * `symbol` and `bigint`), and helper functions that perform compound + * operations. Such classes are not suitable and/or possible to store into a + * Firestore database. Instead, instances of such classes need to be converted + * to "plain old JavaScript objects" (POJOs) with exclusively primitive + * properties, potentially nested inside other POJOs or arrays of POJOs. In this + * context, this type is referred to as the "DbModel" and would be an object + * suitable for persisting into Firestore. For convenience, applications can + * implement `FirestoreDataConverter` and register the converter with Firestore + * objects, such as `DocumentReference` or `Query`, to automatically convert + * `AppModel` to `DbModel` when storing into Firestore, and convert `DbModel` + * to `AppModel` when retrieving from Firestore. + * + * @example + * + * Simple Example + * + * ```typescript + * const numberConverter = { + * toFirestore(value: WithFieldValue) { + * return { value }; + * }, + * fromFirestore(snapshot: QueryDocumentSnapshot, options: SnapshotOptions) { + * return snapshot.data(options).value as number; + * } + * }; + * + * async function simpleDemo(db: Firestore): Promise { + * const documentRef = doc(db, 'values/value123').withConverter(numberConverter); + * + * // converters are used with `setDoc`, `addDoc`, and `getDoc` + * await setDoc(documentRef, 42); + * const snapshot1 = await getDoc(documentRef); + * assertEqual(snapshot1.data(), 42); + * + * // converters are not used when writing data with `updateDoc` + * await updateDoc(documentRef, { value: 999 }); + * const snapshot2 = await getDoc(documentRef); + * assertEqual(snapshot2.data(), 999); + * } + * ``` + * + * Advanced Example + * + * ```typescript + * // The Post class is a model that is used by our application. + * // This class may have properties and methods that are specific + * // to our application execution, which do not need to be persisted + * // to Firestore. + * class Post { + * constructor( + * readonly title: string, + * readonly author: string, + * readonly lastUpdatedMillis: number + * ) {} + * toString(): string { + * return `${this.title} by ${this.author}`; + * } + * } + * + * // The PostDbModel represents how we want our posts to be stored + * // in Firestore. This DbModel has different properties (`ttl`, + * // `aut`, and `lut`) from the Post class we use in our application. + * interface PostDbModel { + * ttl: string; + * aut: { firstName: string; lastName: string }; + * lut: Timestamp; + * } + * + * // The `PostConverter` implements `FirestoreDataConverter` and specifies + * // how the Firestore SDK can convert `Post` objects to `PostDbModel` + * // objects and vice versa. + * class PostConverter implements FirestoreDataConverter { + * toFirestore(post: WithFieldValue): WithFieldValue { + * return { + * ttl: post.title, + * aut: this._autFromAuthor(post.author), + * lut: this._lutFromLastUpdatedMillis(post.lastUpdatedMillis) + * }; + * } + * + * fromFirestore(snapshot: QueryDocumentSnapshot, options: SnapshotOptions): Post { + * const data = snapshot.data(options) as PostDbModel; + * const author = `${data.aut.firstName} ${data.aut.lastName}`; + * return new Post(data.ttl, author, data.lut.toMillis()); + * } + * + * _autFromAuthor( + * author: string | FieldValue + * ): { firstName: string; lastName: string } | FieldValue { + * if (typeof author !== 'string') { + * // `author` is a FieldValue, so just return it. + * return author; + * } + * const [firstName, lastName] = author.split(' '); + * return {firstName, lastName}; + * } + * + * _lutFromLastUpdatedMillis( + * lastUpdatedMillis: number | FieldValue + * ): Timestamp | FieldValue { + * if (typeof lastUpdatedMillis !== 'number') { + * // `lastUpdatedMillis` must be a FieldValue, so just return it. + * return lastUpdatedMillis; + * } + * return Timestamp.fromMillis(lastUpdatedMillis); + * } + * } + * + * async function advancedDemo(db: Firestore): Promise { + * // Create a `DocumentReference` with a `FirestoreDataConverter`. + * const documentRef = doc(db, 'posts/post123').withConverter(new PostConverter()); + * + * // The `data` argument specified to `setDoc()` is type checked by the + * // TypeScript compiler to be compatible with `Post`. Since the `data` + * // argument is typed as `WithFieldValue` rather than just `Post`, + * // this allows properties of the `data` argument to also be special + * // Firestore values that perform server-side mutations, such as + * // `arrayRemove()`, `deleteField()`, and `serverTimestamp()`. + * await setDoc(documentRef, { + * title: 'My Life', + * author: 'Foo Bar', + * lastUpdatedMillis: serverTimestamp() + * }); + * + * // The TypeScript compiler will fail to compile if the `data` argument to + * // `setDoc()` is _not_ compatible with `WithFieldValue`. This + * // type checking prevents the caller from specifying objects with incorrect + * // properties or property values. + * // @ts-expect-error "Argument of type { ttl: string; } is not assignable + * // to parameter of type WithFieldValue" + * await setDoc(documentRef, { ttl: 'The Title' }); + * + * // When retrieving a document with `getDoc()` the `DocumentSnapshot` + * // object's `data()` method returns a `Post`, rather than a generic object, + * // which would have been returned if the `DocumentReference` did _not_ have a + * // `FirestoreDataConverter` attached to it. + * const snapshot1: DocumentSnapshot = await getDoc(documentRef); + * const post1: Post = snapshot1.data()!; + * if (post1) { + * assertEqual(post1.title, 'My Life'); + * assertEqual(post1.author, 'Foo Bar'); + * } + * + * // The `data` argument specified to `updateDoc()` is type checked by the + * // TypeScript compiler to be compatible with `PostDbModel`. Note that + * // unlike `setDoc()`, whose `data` argument must be compatible with `Post`, + * // the `data` argument to `updateDoc()` must be compatible with + * // `PostDbModel`. Similar to `setDoc()`, since the `data` argument is typed + * // as `WithFieldValue` rather than just `PostDbModel`, this + * // allows properties of the `data` argument to also be those special + * // Firestore values, like `arrayRemove()`, `deleteField()`, and + * // `serverTimestamp()`. + * await updateDoc(documentRef, { + * 'aut.firstName': 'NewFirstName', + * lut: serverTimestamp() + * }); + * + * // The TypeScript compiler will fail to compile if the `data` argument to + * // `updateDoc()` is _not_ compatible with `WithFieldValue`. + * // This type checking prevents the caller from specifying objects with + * // incorrect properties or property values. + * // @ts-expect-error "Argument of type { title: string; } is not assignable + * // to parameter of type WithFieldValue" + * await updateDoc(documentRef, { title: 'New Title' }); + * const snapshot2: DocumentSnapshot = await getDoc(documentRef); + * const post2: Post = snapshot2.data()!; + * if (post2) { + * assertEqual(post2.title, 'My Life'); + * assertEqual(post2.author, 'NewFirstName Bar'); + * } + * } + * ``` + */ +export declare interface FirestoreDataConverter { + /** + * Called by the Firestore SDK to convert a custom model object of type + * `AppModelType` into a plain JavaScript object (suitable for writing + * directly to the Firestore database) of type `DbModelType`. Used with + * {@link @firebase/firestore/lite#(setDoc:1)}, + * {@link @firebase/firestore/lite#(WriteBatch.set:1)} and + * {@link @firebase/firestore/lite#(Transaction.set:1)}. + * + * The `WithFieldValue` type extends `T` to also allow FieldValues such as + * {@link (deleteField:1)} to be used as property values. + */ + toFirestore(modelObject: WithFieldValue): WithFieldValue; + /** + * Called by the Firestore SDK to convert a custom model object of type + * `AppModelType` into a plain JavaScript object (suitable for writing + * directly to the Firestore database) of type `DbModelType`. Used with + * {@link @firebase/firestore/lite#(setDoc:1)}, + * {@link @firebase/firestore/lite#(WriteBatch.set:1)} and + * {@link @firebase/firestore/lite#(Transaction.set:1)} with `merge:true` + * or `mergeFields`. + * + * The `PartialWithFieldValue` type extends `Partial` to allow + * FieldValues such as {@link (arrayUnion:1)} to be used as property values. + * It also supports nested `Partial` by allowing nested fields to be + * omitted. + */ + toFirestore(modelObject: PartialWithFieldValue, options: SetOptions): PartialWithFieldValue; + /** + * Called by the Firestore SDK to convert Firestore data into an object of + * type `AppModelType`. You can access your data by calling: + * `snapshot.data()`. + * + * + * Generally, the data returned from `snapshot.data()` can be cast to + * `DbModelType`; however, this is not guaranteed because Firestore does not + * enforce a schema on the database. For example, writes from a previous + * version of the application or writes from another client that did not use a + * type converter could have written data with different properties and/or + * property types. The implementation will need to choose whether to + * gracefully recover from non-conforming data or throw an error. + * + * @param snapshot - A `QueryDocumentSnapshot` containing your data and + * metadata. + */ + fromFirestore(snapshot: QueryDocumentSnapshot): AppModelType; +} + +/** An error returned by a Firestore operation. */ +export declare class FirestoreError extends FirebaseError { + /** + * The backend error code associated with this error. + */ + readonly code: FirestoreErrorCode; + /** + * A custom error description. + */ + readonly message: string; + /** The stack of the error. */ + readonly stack?: string; + /** @hideconstructor */ + constructor( + /** + * The backend error code associated with this error. + */ + code: FirestoreErrorCode, + /** + * A custom error description. + */ + message: string); +} + +/** + * The set of Firestore status codes. The codes are the same at the ones + * exposed by gRPC here: + * https://github.com/grpc/grpc/blob/master/doc/statuscodes.md + * + * Possible values: + * - 'cancelled': The operation was cancelled (typically by the caller). + * - 'unknown': Unknown error or an error from a different error domain. + * - 'invalid-argument': Client specified an invalid argument. Note that this + * differs from 'failed-precondition'. 'invalid-argument' indicates + * arguments that are problematic regardless of the state of the system + * (e.g. an invalid field name). + * - 'deadline-exceeded': Deadline expired before operation could complete. + * For operations that change the state of the system, this error may be + * returned even if the operation has completed successfully. For example, + * a successful response from a server could have been delayed long enough + * for the deadline to expire. + * - 'not-found': Some requested document was not found. + * - 'already-exists': Some document that we attempted to create already + * exists. + * - 'permission-denied': The caller does not have permission to execute the + * specified operation. + * - 'resource-exhausted': Some resource has been exhausted, perhaps a + * per-user quota, or perhaps the entire file system is out of space. + * - 'failed-precondition': Operation was rejected because the system is not + * in a state required for the operation's execution. + * - 'aborted': The operation was aborted, typically due to a concurrency + * issue like transaction aborts, etc. + * - 'out-of-range': Operation was attempted past the valid range. + * - 'unimplemented': Operation is not implemented or not supported/enabled. + * - 'internal': Internal errors. Means some invariants expected by + * underlying system has been broken. If you see one of these errors, + * something is very broken. + * - 'unavailable': The service is currently unavailable. This is most likely + * a transient condition and may be corrected by retrying with a backoff. + * - 'data-loss': Unrecoverable data loss or corruption. + * - 'unauthenticated': The request does not have valid authentication + * credentials for the operation. + */ +export declare type FirestoreErrorCode = 'cancelled' | 'unknown' | 'invalid-argument' | 'deadline-exceeded' | 'not-found' | 'already-exists' | 'permission-denied' | 'resource-exhausted' | 'failed-precondition' | 'aborted' | 'out-of-range' | 'unimplemented' | 'internal' | 'unavailable' | 'data-loss' | 'unauthenticated'; + +/** + * Union type from all supported SDK cache layer. + */ +declare type FirestoreLocalCache = MemoryLocalCache | PersistentLocalCache; + +/** + * An interface implemented by FirebaseFirestore that provides compatibility + * with the usage in this file. + * + * This interface mainly exists to remove a cyclic dependency. + */ +declare interface FirestoreService extends _FirebaseService { + _authCredentials: CredentialsProvider; + _appCheckCredentials: CredentialsProvider; + _persistenceKey: string; + _databaseId: DatabaseId; + _terminated: boolean; + _freezeSettings(): FirestoreSettingsImpl; +} + +/** + * A concrete type describing all the values that can be applied via a + * user-supplied `FirestoreSettings` object. This is a separate type so that + * defaults can be supplied and the value can be checked for equality. + */ +declare class FirestoreSettingsImpl { + /** The hostname to connect to. */ + readonly host: string; + /** Whether to use SSL when connecting. */ + readonly ssl: boolean; + readonly cacheSizeBytes: number; + readonly experimentalForceLongPolling: boolean; + readonly experimentalAutoDetectLongPolling: boolean; + readonly experimentalLongPollingOptions: ExperimentalLongPollingOptions; + readonly ignoreUndefinedProperties: boolean; + readonly useFetchStreams: boolean; + readonly localCache?: FirestoreLocalCache; + readonly isUsingEmulator: boolean; + credentials?: any; + constructor(settings: PrivateSettings); + isEqual(other: FirestoreSettingsImpl): boolean; +} + +declare namespace firestoreV1ApiClientInterfaces { + interface ArrayValue { + values?: Value[]; + } + interface BatchGetDocumentsRequest { + database?: string; + documents?: string[]; + mask?: DocumentMask; + transaction?: string; + newTransaction?: TransactionOptions; + readTime?: string; + } + interface BatchGetDocumentsResponse { + found?: Document; + missing?: string; + transaction?: string; + readTime?: string; + } + interface BeginTransactionRequest { + options?: TransactionOptions; + } + interface BeginTransactionResponse { + transaction?: string; + } + interface CollectionSelector { + collectionId?: string; + allDescendants?: boolean; + } + interface CommitRequest { + database?: string; + writes?: Write[]; + transaction?: string; + } + interface CommitResponse { + writeResults?: WriteResult[]; + commitTime?: string; + } + interface CompositeFilter { + op?: CompositeFilterOp; + filters?: Filter[]; + } + interface Cursor { + values?: Value[]; + before?: boolean; + } + interface Document { + name?: string; + fields?: ApiClientObjectMap; + createTime?: Timestamp_2; + updateTime?: Timestamp_2; + } + interface DocumentChange { + document?: Document; + targetIds?: number[]; + removedTargetIds?: number[]; + } + interface DocumentDelete { + document?: string; + removedTargetIds?: number[]; + readTime?: Timestamp_2; + } + interface DocumentMask { + fieldPaths?: string[]; + } + interface DocumentRemove { + document?: string; + removedTargetIds?: number[]; + readTime?: string; + } + interface DocumentTransform { + document?: string; + fieldTransforms?: FieldTransform[]; + } + interface DocumentsTarget { + documents?: string[]; + } + interface Empty { + } + interface ExistenceFilter { + targetId?: number; + count?: number; + unchangedNames?: BloomFilter; + } + interface BloomFilter { + bits?: BitSequence; + hashCount?: number; + } + interface BitSequence { + bitmap?: string | Uint8Array; + padding?: number; + } + interface FieldFilter { + field?: FieldReference; + op?: FieldFilterOp; + value?: Value; + } + interface FieldReference { + fieldPath?: string; + } + interface FieldTransform { + fieldPath?: string; + setToServerValue?: FieldTransformSetToServerValue; + appendMissingElements?: ArrayValue; + removeAllFromArray?: ArrayValue; + increment?: Value; + } + interface Filter { + compositeFilter?: CompositeFilter; + fieldFilter?: FieldFilter; + unaryFilter?: UnaryFilter; + } + interface Index { + name?: string; + collectionId?: string; + fields?: IndexField[]; + state?: IndexState_2; + } + interface IndexField { + fieldPath?: string; + mode?: IndexFieldMode; + } + interface LatLng { + latitude?: number; + longitude?: number; + } + interface ListCollectionIdsRequest { + pageSize?: number; + pageToken?: string; + } + interface ListCollectionIdsResponse { + collectionIds?: string[]; + nextPageToken?: string; + } + interface ListDocumentsResponse { + documents?: Document[]; + nextPageToken?: string; + } + interface ListIndexesResponse { + indexes?: Index[]; + nextPageToken?: string; + } + interface ListenRequest { + addTarget?: Target; + removeTarget?: number; + labels?: ApiClientObjectMap; + } + interface ListenResponse { + targetChange?: TargetChange; + documentChange?: DocumentChange; + documentDelete?: DocumentDelete; + documentRemove?: DocumentRemove; + filter?: ExistenceFilter; + } + interface MapValue { + fields?: ApiClientObjectMap; + } + interface Operation { + name?: string; + metadata?: ApiClientObjectMap; + done?: boolean; + error?: Status; + response?: ApiClientObjectMap; + } + interface Order { + field?: FieldReference; + direction?: OrderDirection; + } + interface Precondition { + exists?: boolean; + updateTime?: Timestamp_2; + } + interface Projection { + fields?: FieldReference[]; + } + interface QueryTarget { + parent?: string; + structuredQuery?: StructuredQuery; + } + interface ReadOnly { + readTime?: string; + } + interface ReadWrite { + retryTransaction?: string; + } + interface RollbackRequest { + transaction?: string; + } + interface RunQueryRequest { + parent?: string; + structuredQuery?: StructuredQuery; + transaction?: string; + newTransaction?: TransactionOptions; + readTime?: string; + } + interface RunQueryResponse { + transaction?: string; + document?: Document; + readTime?: string; + skippedResults?: number; + } + interface RunAggregationQueryRequest { + parent?: string; + structuredAggregationQuery?: StructuredAggregationQuery; + transaction?: string; + newTransaction?: TransactionOptions; + readTime?: string; + } + interface RunAggregationQueryResponse { + result?: AggregationResult; + transaction?: string; + readTime?: string; + } + interface AggregationResult { + aggregateFields?: ApiClientObjectMap; + } + interface StructuredAggregationQuery { + structuredQuery?: StructuredQuery; + aggregations?: Aggregation[]; + } + interface Aggregation { + count?: Count; + sum?: Sum; + avg?: Avg; + alias?: string; + } + interface Count { + upTo?: number; + } + interface Sum { + field?: FieldReference; + } + interface Avg { + field?: FieldReference; + } + interface Status { + code?: number; + message?: string; + details?: Array>; + } + interface StructuredQuery { + select?: Projection; + from?: CollectionSelector[]; + where?: Filter; + orderBy?: Order[]; + startAt?: Cursor; + endAt?: Cursor; + offset?: number; + limit?: number | { + value: number; + }; + } + interface Target { + query?: QueryTarget; + documents?: DocumentsTarget; + resumeToken?: string | Uint8Array; + readTime?: Timestamp_2; + targetId?: number; + once?: boolean; + expectedCount?: number | { + value: number; + }; + } + interface TargetChange { + targetChangeType?: TargetChangeTargetChangeType; + targetIds?: number[]; + cause?: Status; + resumeToken?: string | Uint8Array; + readTime?: Timestamp_2; + } + interface TransactionOptions { + readOnly?: ReadOnly; + readWrite?: ReadWrite; + } + interface UnaryFilter { + op?: UnaryFilterOp; + field?: FieldReference; + } + interface Value { + nullValue?: ValueNullValue; + booleanValue?: boolean; + integerValue?: string | number; + doubleValue?: string | number; + timestampValue?: Timestamp_2; + stringValue?: string; + bytesValue?: string | Uint8Array; + referenceValue?: string; + geoPointValue?: LatLng; + arrayValue?: ArrayValue; + mapValue?: MapValue; + } + interface Write { + update?: Document; + delete?: string; + verify?: string; + transform?: DocumentTransform; + updateMask?: DocumentMask; + updateTransforms?: FieldTransform[]; + currentDocument?: Precondition; + } + interface WriteRequest { + streamId?: string; + writes?: Write[]; + streamToken?: string | Uint8Array; + labels?: ApiClientObjectMap; + } + interface WriteResponse { + streamId?: string; + streamToken?: string | Uint8Array; + writeResults?: WriteResult[]; + commitTime?: Timestamp_2; + } + interface WriteResult { + updateTime?: Timestamp_2; + transformResults?: Value[]; + } +} + +/* Excluded from this release type: FirstPartyCredentialsSettings */ + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +declare type FulfilledHandler = ((result: T) => R | PersistencePromise) | null; + +/** + * An immutable object representing a geographic location in Firestore. The + * location is represented as latitude/longitude pair. + * + * Latitude values are in the range of [-90, 90]. + * Longitude values are in the range of [-180, 180]. + */ +export declare class GeoPoint { + private _lat; + private _long; + /** + * Creates a new immutable `GeoPoint` object with the provided latitude and + * longitude values. + * @param latitude - The latitude as number between -90 and 90. + * @param longitude - The longitude as number between -180 and 180. + */ + constructor(latitude: number, longitude: number); + /** + * The latitude of this `GeoPoint` instance. + */ + get latitude(): number; + /** + * The longitude of this `GeoPoint` instance. + */ + get longitude(): number; + /** + * Returns true if this `GeoPoint` is equal to the provided one. + * + * @param other - The `GeoPoint` to compare against. + * @returns true if this `GeoPoint` is equal to the provided one. + */ + isEqual(other: GeoPoint): boolean; + /** + * Actually private to JS consumers of our API, so this function is prefixed + * with an underscore. + */ + _compareTo(other: GeoPoint): number; + static _jsonSchemaVersion: string; + static _jsonSchema: { + type: Property<"string">; + latitude: Property<"number">; + longitude: Property<"number">; + }; + /** + * Returns a JSON-serializable representation of this `GeoPoint` instance. + * + * @returns a JSON representation of this object. + */ + toJSON(): { + latitude: number; + longitude: number; + type: string; + }; + /** + * Builds a `GeoPoint` instance from a JSON object created by {@link GeoPoint.toJSON}. + * + * @param json a JSON object represention of a `GeoPoint` instance + * @returns an instance of {@link GeoPoint} if the JSON object could be parsed. Throws a + * {@link FirestoreError} if an error occurs. + */ + static fromJSON(json: object): GeoPoint; +} + +/** + * Calculates the specified aggregations over the documents in the result + * set of the given query without actually downloading the documents. + * + * Using this function to perform aggregations is efficient because only the + * final aggregation values, not the documents' data, are downloaded. This + * function can perform aggregations of the documents in cases where the result + * set is prohibitively large to download entirely (thousands of documents). + * + * @param query The query whose result set is aggregated over. + * @param aggregateSpec An `AggregateSpec` object that specifies the aggregates + * to perform over the result set. The AggregateSpec specifies aliases for each + * aggregate, which can be used to retrieve the aggregate result. + * @example + * ```typescript + * const aggregateSnapshot = await getAggregate(query, { + * countOfDocs: count(), + * totalHours: sum('hours'), + * averageScore: average('score') + * }); + * + * const countOfDocs: number = aggregateSnapshot.data().countOfDocs; + * const totalHours: number = aggregateSnapshot.data().totalHours; + * const averageScore: number | null = aggregateSnapshot.data().averageScore; + * ``` + */ +export declare function getAggregate(query: Query, aggregateSpec: AggregateSpecType): Promise>; + +/** + * Calculates the number of documents in the result set of the given query + * without actually downloading the documents. + * + * Using this function to count the documents is efficient because only the + * final count, not the documents' data, is downloaded. This function can + * count the documents in cases where the result set is prohibitively large to + * download entirely (thousands of documents). + * + * @param query The query whose result set size is calculated. + * @returns A Promise that will be resolved with the count; the count can be + * retrieved from `snapshot.data().count`, where `snapshot` is the + * `AggregateQuerySnapshot` to which the returned Promise resolves. + */ +export declare function getCount(query: Query): Promise; +}, AppModelType, DbModelType>>; + +/** + * Reads the document referred to by the specified document reference. + * + * All documents are directly fetched from the server, even if the document was + * previously read or modified. Recent modifications are only reflected in the + * retrieved `DocumentSnapshot` if they have already been applied by the + * backend. If the client is offline, the read fails. If you like to use + * caching or see local modifications, please use the full Firestore SDK. + * + * @param reference - The reference of the document to fetch. + * @returns A Promise resolved with a `DocumentSnapshot` containing the current + * document contents. + */ +export declare function getDoc(reference: DocumentReference): Promise>; + +/** + * Executes the query and returns the results as a {@link QuerySnapshot}. + * + * All queries are executed directly by the server, even if the query was + * previously executed. Recent modifications are only reflected in the retrieved + * results if they have already been applied by the backend. If the client is + * offline, the operation fails. To see previously cached result and local + * modifications, use the full Firestore SDK. + * + * @param query - The `Query` to execute. + * @returns A Promise that will be resolved with the results of the query. + */ +export declare function getDocs(query: Query): Promise>; + +/** + * Returns the existing default {@link Firestore} instance that is associated with the + * default {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new + * instance with default settings. + * + * @returns The {@link Firestore} instance of the provided app. + */ +export declare function getFirestore(): Firestore; + +/** + * Returns the existing default {@link Firestore} instance that is associated with the + * provided {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new + * instance with default settings. + * + * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned {@link Firestore} + * instance is associated with. + * @returns The {@link Firestore} instance of the provided app. + */ +export declare function getFirestore(app: FirebaseApp): Firestore; + +/** + * Returns the existing {@link Firestore} instance that is associated with the + * default {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new + * instance with default settings. + * + * @param databaseId - The name of the database. + * @returns The {@link Firestore} instance of the provided app. + * @beta + */ +export declare function getFirestore(databaseId: string): Firestore; + +/** + * Returns the existing {@link Firestore} instance that is associated with the + * provided {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new + * instance with default settings. + * + * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned {@link Firestore} + * instance is associated with. + * @param databaseId - The name of the database. + * @returns The {@link Firestore} instance of the provided app. + * @beta + */ +export declare function getFirestore(app: FirebaseApp, databaseId: string): Firestore; + +/** + * General purpose cache for global values. + * + * Global state that cuts across components should be saved here. Following are contained herein: + * + * `sessionToken` tracks server interaction across Listen and Write streams. This facilitates cache + * synchronization and invalidation. + */ +declare interface GlobalsCache { + /** + * Gets session token. + */ + getSessionToken(transaction: PersistenceTransaction): PersistencePromise; + /** + * Sets session token. + * + * @param sessionToken - The new session token. + */ + setSessionToken(transaction: PersistenceTransaction, sessionToken: ByteString): PersistencePromise; +} + +/** + * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link + * @firebase/firestore/lite#(updateDoc:1)} that tells the server to increment the field's current value by + * the given value. + * + * If either the operand or the current field value uses floating point + * precision, all arithmetic follows IEEE 754 semantics. If both values are + * integers, values outside of JavaScript's safe number range + * (`Number.MIN_SAFE_INTEGER` to `Number.MAX_SAFE_INTEGER`) are also subject to + * precision loss. Furthermore, once processed by the Firestore backend, all + * integer operations are capped between -2^63 and 2^63-1. + * + * If the current field value is not of type `number`, or if the field does not + * yet exist, the transformation sets the field to the given value. + * + * @param n - The value to increment by. + * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or + * `updateDoc()` + */ +export declare function increment(n: number): FieldValue; + +declare type IndexFieldMode = 'MODE_UNSPECIFIED' | 'ASCENDING' | 'DESCENDING'; + +/** The type of the index, e.g. for which type of query it can be used. */ +declare const enum IndexKind { + /** + * Ordered index. Can be used for <, <=, ==, >=, >, !=, IN and NOT IN queries. + */ + ASCENDING = 0, + /** + * Ordered index. Can be used for <, <=, ==, >=, >, !=, IN and NOT IN queries. + */ + DESCENDING = 1, + /** Contains index. Can be used for ArrayContains and ArrayContainsAny. */ + CONTAINS = 2 +} + +/** + * Represents a set of indexes that are used to execute queries efficiently. + * + * Currently the only index is a [collection id] => [parent path] index, used + * to execute Collection Group queries. + */ +declare interface IndexManager { + /** + * Creates an index entry mapping the collectionId (last segment of the path) + * to the parent path (either the containing document location or the empty + * path for root-level collections). Index entries can be retrieved via + * getCollectionParents(). + * + * NOTE: Currently we don't remove index entries. If this ends up being an + * issue we can devise some sort of GC strategy. + */ + addToCollectionParentIndex(transaction: PersistenceTransaction, collectionPath: ResourcePath): PersistencePromise; + /** + * Retrieves all parent locations containing the given collectionId, as a + * list of paths (each path being either a document location or the empty + * path for a root-level collection). + */ + getCollectionParents(transaction: PersistenceTransaction, collectionId: string): PersistencePromise; + /** + * Adds a field path index. + * + * Values for this index are persisted via the index backfill, which runs + * asynchronously in the background. Once the first values are written, + * an index can be used to serve partial results for any matching queries. + * Any unindexed portion of the database will continue to be served via + * collection scons. + */ + addFieldIndex(transaction: PersistenceTransaction, index: FieldIndex): PersistencePromise; + /** Removes the given field index and deletes all index values. */ + deleteFieldIndex(transaction: PersistenceTransaction, index: FieldIndex): PersistencePromise; + /** Removes all field indexes and deletes all index values. */ + deleteAllFieldIndexes(transaction: PersistenceTransaction): PersistencePromise; + /** Creates a full matched field index which serves the given target. */ + createTargetIndexes(transaction: PersistenceTransaction, target: Target): PersistencePromise; + /** + * Returns a list of field indexes that correspond to the specified collection + * group. + * + * @param collectionGroup The collection group to get matching field indexes + * for. + * @return A collection of field indexes for the specified collection group. + */ + getFieldIndexes(transaction: PersistenceTransaction, collectionGroup: string): PersistencePromise; + /** Returns all configured field indexes. */ + getFieldIndexes(transaction: PersistenceTransaction): PersistencePromise; + /** + * Returns the type of index (if any) that can be used to serve the given + * target. + */ + getIndexType(transaction: PersistenceTransaction, target: Target): PersistencePromise; + /** + * Returns the documents that match the given target based on the provided + * index or `null` if the target does not have a matching index. + */ + getDocumentsMatchingTarget(transaction: PersistenceTransaction, target: Target): PersistencePromise; + /** + * Returns the next collection group to update. Returns `null` if no group + * exists. + */ + getNextCollectionGroupToUpdate(transaction: PersistenceTransaction): PersistencePromise; + /** + * Sets the collection group's latest read time. + * + * This method updates the index offset for all field indices for the + * collection group and increments their sequence number. Subsequent calls to + * `getNextCollectionGroupToUpdate()` will return a different collection group + * (unless only one collection group is configured). + */ + updateCollectionGroup(transaction: PersistenceTransaction, collectionGroup: string, offset: IndexOffset): PersistencePromise; + /** Updates the index entries for the provided documents. */ + updateIndexEntries(transaction: PersistenceTransaction, documents: DocumentMap): PersistencePromise; + /** + * Iterates over all field indexes that are used to serve the given target, + * and returns the minimum offset of them all. + */ + getMinOffset(transaction: PersistenceTransaction, target: Target): PersistencePromise; + /** Returns the minimum offset for the given collection group. */ + getMinOffsetFromCollectionGroup(transaction: PersistenceTransaction, collectionGroup: string): PersistencePromise; +} + +/** + * Stores the latest read time, document and batch ID that were processed for an + * index. + */ +declare class IndexOffset { + /** + * The latest read time version that has been indexed by Firestore for this + * field index. + */ + readonly readTime: SnapshotVersion; + /** + * The key of the last document that was indexed for this query. Use + * `DocumentKey.empty()` if no document has been indexed. + */ + readonly documentKey: DocumentKey; + readonly largestBatchId: number; + constructor( + /** + * The latest read time version that has been indexed by Firestore for this + * field index. + */ + readTime: SnapshotVersion, + /** + * The key of the last document that was indexed for this query. Use + * `DocumentKey.empty()` if no document has been indexed. + */ + documentKey: DocumentKey, largestBatchId: number); + /** Returns an offset that sorts before all regular offsets. */ + static min(): IndexOffset; + /** Returns an offset that sorts after all regular offsets. */ + static max(): IndexOffset; +} + +/** An index component consisting of field path and index type. */ +declare class IndexSegment { + /** The field path of the component. */ + readonly fieldPath: FieldPath_2; + /** The fields sorting order. */ + readonly kind: IndexKind; + constructor( + /** The field path of the component. */ + fieldPath: FieldPath_2, + /** The fields sorting order. */ + kind: IndexKind); +} + +/** + * Stores the "high water mark" that indicates how updated the Index is for the + * current user. + */ +declare class IndexState { + /** + * Indicates when the index was last updated (relative to other indexes). + */ + readonly sequenceNumber: number; + /** The the latest indexed read time, document and batch id. */ + readonly offset: IndexOffset; + constructor( + /** + * Indicates when the index was last updated (relative to other indexes). + */ + sequenceNumber: number, + /** The the latest indexed read time, document and batch id. */ + offset: IndexOffset); + /** The state of an index that has not yet been backfilled. */ + static empty(): IndexState; +} + +declare type IndexState_2 = 'STATE_UNSPECIFIED' | 'CREATING' | 'READY' | 'ERROR'; + +/** Represents the index state as it relates to a particular target. */ +declare const enum IndexType { + /** Indicates that no index could be found for serving the target. */ + NONE = 0, + /** + * Indicates that only a "partial index" could be found for serving the + * target. A partial index is one which does not have a segment for every + * filter/orderBy in the target. + */ + PARTIAL = 1, + /** + * Indicates that a "full index" could be found for serving the target. A full + * index is one which has a segment for every filter/orderBy in the target. + */ + FULL = 2 +} + +/** + * Initializes a new instance of Cloud Firestore with the provided settings. + * Can only be called before any other functions, including + * {@link (getFirestore:1)}. If the custom settings are empty, this function is + * equivalent to calling {@link (getFirestore:1)}. + * + * @param app - The {@link @firebase/app#FirebaseApp} with which the `Firestore` instance will + * be associated. + * @param settings - A settings object to configure the `Firestore` instance. + * @returns A newly initialized `Firestore` instance. + */ +export declare function initializeFirestore(app: FirebaseApp, settings: Settings): Firestore; + +/** + * Initializes a new instance of Cloud Firestore with the provided settings. + * Can only be called before any other functions, including + * {@link (getFirestore:1)}. If the custom settings are empty, this function is + * equivalent to calling {@link (getFirestore:1)}. + * + * @param app - The {@link @firebase/app#FirebaseApp} with which the `Firestore` instance will + * be associated. + * @param settings - A settings object to configure the `Firestore` instance. + * @param databaseId - The name of the database. + * @returns A newly initialized `Firestore` instance. + * @beta + */ +export declare function initializeFirestore(app: FirebaseApp, settings: Settings, databaseId?: string): Firestore; + +/** + * This class generates JsonObject values for the Datastore API suitable for + * sending to either GRPC stub methods or via the JSON/HTTP REST API. + * + * The serializer supports both Protobuf.js and Proto3 JSON formats. By + * setting `useProto3Json` to true, the serializer will use the Proto3 JSON + * format. + * + * For a description of the Proto3 JSON format check + * https://developers.google.com/protocol-buffers/docs/proto3#json + * + * TODO(klimt): We can remove the databaseId argument if we keep the full + * resource name in documents. + */ +declare class JsonProtoSerializer implements Serializer { + readonly databaseId: DatabaseId; + readonly useProto3Json: boolean; + constructor(databaseId: DatabaseId, useProto3Json: boolean); +} + +/* Excluded from this release type: JsonTypeDesc */ + +declare type Kind = 'memory' | 'persistent'; + +/** + * Creates a {@link QueryLimitConstraint} that only returns the first matching + * documents. + * + * @param limit - The maximum number of items to return. + * @returns The created {@link QueryLimitConstraint}. + */ +export declare function limit(limit: number): QueryLimitConstraint; + +/** + * Creates a {@link QueryLimitConstraint} that only returns the last matching + * documents. + * + * You must specify at least one `orderBy` clause for `limitToLast` queries, + * otherwise an exception will be thrown during execution. + * + * @param limit - The maximum number of items to return. + * @returns The created {@link QueryLimitConstraint}. + */ +export declare function limitToLast(limit: number): QueryLimitConstraint; + +declare const enum LimitType { + First = "F", + Last = "L" +} + +/** LimitType enum. */ +declare type LimitType_2 = 'FIRST' | 'LAST'; + +declare type ListenSequenceNumber = number; + +declare class LLRBEmptyNode { + get key(): never; + get value(): never; + get color(): never; + get left(): never; + get right(): never; + size: number; + copy(key: K | null, value: V | null, color: boolean | null, left: LLRBNode | LLRBEmptyNode | null, right: LLRBNode | LLRBEmptyNode | null): LLRBEmptyNode; + insert(key: K, value: V, comparator: Comparator): LLRBNode; + remove(key: K, comparator: Comparator): LLRBEmptyNode; + isEmpty(): boolean; + inorderTraversal(action: (k: K, v: V) => boolean): boolean; + reverseTraversal(action: (k: K, v: V) => boolean): boolean; + minKey(): K | null; + maxKey(): K | null; + isRed(): boolean; + checkMaxDepth(): boolean; + protected check(): 0; +} + +declare class LLRBNode { + key: K; + value: V; + readonly color: boolean; + readonly left: LLRBNode | LLRBEmptyNode; + readonly right: LLRBNode | LLRBEmptyNode; + readonly size: number; + static EMPTY: LLRBEmptyNode; + static RED: boolean; + static BLACK: boolean; + constructor(key: K, value: V, color?: boolean, left?: LLRBNode | LLRBEmptyNode, right?: LLRBNode | LLRBEmptyNode); + copy(key: K | null, value: V | null, color: boolean | null, left: LLRBNode | LLRBEmptyNode | null, right: LLRBNode | LLRBEmptyNode | null): LLRBNode; + isEmpty(): boolean; + inorderTraversal(action: (k: K, v: V) => T): T; + reverseTraversal(action: (k: K, v: V) => T): T; + private min; + minKey(): K | null; + maxKey(): K | null; + insert(key: K, value: V, comparator: Comparator): LLRBNode; + private removeMin; + remove(key: K, comparator: Comparator): LLRBNode | LLRBEmptyNode; + isRed(): boolean; + private fixUp; + private moveRedLeft; + private moveRedRight; + private rotateLeft; + private rotateRight; + private colorFlip; + checkMaxDepth(): boolean; + protected check(): number; +} + +/** + * A readonly view of the local state of all documents we're tracking (i.e. we + * have a cached version in remoteDocumentCache or local mutations for the + * document). The view is computed by applying the mutations in the + * MutationQueue to the RemoteDocumentCache. + */ +declare class LocalDocumentsView { + readonly remoteDocumentCache: RemoteDocumentCache; + readonly mutationQueue: MutationQueue; + readonly documentOverlayCache: DocumentOverlayCache; + readonly indexManager: IndexManager; + constructor(remoteDocumentCache: RemoteDocumentCache, mutationQueue: MutationQueue, documentOverlayCache: DocumentOverlayCache, indexManager: IndexManager); + /** + * Get the local view of the document identified by `key`. + * + * @returns Local view of the document or null if we don't have any cached + * state for it. + */ + getDocument(transaction: PersistenceTransaction, key: DocumentKey): PersistencePromise; + /** + * Gets the local view of the documents identified by `keys`. + * + * If we don't have cached state for a document in `keys`, a NoDocument will + * be stored for that key in the resulting set. + */ + getDocuments(transaction: PersistenceTransaction, keys: DocumentKeySet): PersistencePromise; + /** + * Similar to `getDocuments`, but creates the local view from the given + * `baseDocs` without retrieving documents from the local store. + * + * @param transaction - The transaction this operation is scoped to. + * @param docs - The documents to apply local mutations to get the local views. + * @param existenceStateChanged - The set of document keys whose existence state + * is changed. This is useful to determine if some documents overlay needs + * to be recalculated. + */ + getLocalViewOfDocuments(transaction: PersistenceTransaction, docs: MutableDocumentMap, existenceStateChanged?: DocumentKeySet): PersistencePromise; + /** + * Gets the overlayed documents for the given document map, which will include + * the local view of those documents and a `FieldMask` indicating which fields + * are mutated locally, `null` if overlay is a Set or Delete mutation. + */ + getOverlayedDocuments(transaction: PersistenceTransaction, docs: MutableDocumentMap): PersistencePromise; + /** + * Fetches the overlays for {@code docs} and adds them to provided overlay map + * if the map does not already contain an entry for the given document key. + */ + private populateOverlays; + /** + * Computes the local view for the given documents. + * + * @param docs - The documents to compute views for. It also has the base + * version of the documents. + * @param overlays - The overlays that need to be applied to the given base + * version of the documents. + * @param existenceStateChanged - A set of documents whose existence states + * might have changed. This is used to determine if we need to re-calculate + * overlays from mutation queues. + * @return A map represents the local documents view. + */ + computeViews(transaction: PersistenceTransaction, docs: MutableDocumentMap, overlays: OverlayMap, existenceStateChanged: DocumentKeySet): PersistencePromise; + private recalculateAndSaveOverlays; + /** + * Recalculates overlays by reading the documents from remote document cache + * first, and saves them after they are calculated. + */ + recalculateAndSaveOverlaysForDocumentKeys(transaction: PersistenceTransaction, documentKeys: DocumentKeySet): PersistencePromise>; + /** + * Performs a query against the local view of all documents. + * + * @param transaction - The persistence transaction. + * @param query - The query to match documents against. + * @param offset - Read time and key to start scanning by (exclusive). + * @param context - A optional tracker to keep a record of important details + * during database local query execution. + */ + getDocumentsMatchingQuery(transaction: PersistenceTransaction, query: Query_2, offset: IndexOffset, context?: QueryContext): PersistencePromise; + /** + * Given a collection group, returns the next documents that follow the provided offset, along + * with an updated batch ID. + * + *

The documents returned by this method are ordered by remote version from the provided + * offset. If there are no more remote documents after the provided offset, documents with + * mutations in order of batch id from the offset are returned. Since all documents in a batch are + * returned together, the total number of documents returned can exceed {@code count}. + * + * @param transaction + * @param collectionGroup The collection group for the documents. + * @param offset The offset to index into. + * @param count The number of documents to return + * @return A LocalWriteResult with the documents that follow the provided offset and the last processed batch id. + */ + getNextDocuments(transaction: PersistenceTransaction, collectionGroup: string, offset: IndexOffset, count: number): PersistencePromise; + private getDocumentsMatchingDocumentQuery; + private getDocumentsMatchingCollectionGroupQuery; + private getDocumentsMatchingCollectionQuery; +} + +declare interface LocalStore { + collectGarbage(garbageCollector: LruGarbageCollector): Promise; + /** Manages the list of active field and collection indices. */ + indexManager: IndexManager; + /** + * The "local" view of all documents (layering mutationQueue on top of + * remoteDocumentCache). + */ + localDocuments: LocalDocumentsView; +} + +/** The result of a write to the local store. */ +declare interface LocalWriteResult { + batchId: BatchId; + changes: DocumentMap; +} +export { LogLevel } + +declare interface LruGarbageCollector { + readonly params: LruParams; + collect(txn: PersistenceTransaction, activeTargetIds: ActiveTargets): PersistencePromise; + /** Given a percentile of target to collect, returns the number of targets to collect. */ + calculateTargetCount(txn: PersistenceTransaction, percentile: number): PersistencePromise; + /** Returns the nth sequence number, counting in order from the smallest. */ + nthSequenceNumber(txn: PersistenceTransaction, n: number): PersistencePromise; + /** + * Removes documents that have a sequence number equal to or less than the + * upper bound and are not otherwise pinned. + */ + removeOrphanedDocuments(txn: PersistenceTransaction, upperBound: ListenSequenceNumber): PersistencePromise; + getCacheSize(txn: PersistenceTransaction): PersistencePromise; + /** + * Removes targets with a sequence number equal to or less than the given + * upper bound, and removes document associations with those targets. + */ + removeTargets(txn: PersistenceTransaction, upperBound: ListenSequenceNumber, activeTargetIds: ActiveTargets): PersistencePromise; +} + +declare class LruParams { + readonly cacheSizeCollectionThreshold: number; + readonly percentileToCollect: number; + readonly maximumSequenceNumbersToCollect: number; + private static readonly DEFAULT_COLLECTION_PERCENTILE; + private static readonly DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT; + static withCacheSize(cacheSize: number): LruParams; + static readonly DEFAULT: LruParams; + static readonly DISABLED: LruParams; + constructor(cacheSizeCollectionThreshold: number, percentileToCollect: number, maximumSequenceNumbersToCollect: number); +} + +/** + * Describes the results of a garbage collection run. `didRun` will be set to + * `false` if collection was skipped (either it is disabled or the cache size + * has not hit the threshold). If collection ran, the other fields will be + * filled in with the details of the results. + */ +declare interface LruResults { + readonly didRun: boolean; + readonly sequenceNumbersCollected: number; + readonly targetsRemoved: number; + readonly documentsRemoved: number; +} + +declare type MapValue = firestoreV1ApiClientInterfaces.MapValue; + +/** + * Provides an in-memory cache to the SDK. This is the default cache unless explicitly + * configured otherwise. + * + * To use, create an instance using the factory function {@link memoryLocalCache()}, then + * set the instance to `FirestoreSettings.cache` and call `initializeFirestore` using + * the settings object. + */ +declare type MemoryLocalCache = { + kind: 'memory'; + /* Excluded from this release type: _onlineComponentProvider */ + /* Excluded from this release type: _offlineComponentProvider */ +}; + +/** + * Represents a document in Firestore with a key, version, data and whether it + * has local mutations applied to it. + * + * Documents can transition between states via `convertToFoundDocument()`, + * `convertToNoDocument()` and `convertToUnknownDocument()`. If a document does + * not transition to one of these states even after all mutations have been + * applied, `isValidDocument()` returns false and the document should be removed + * from all views. + */ +declare class MutableDocument implements Document_2 { + readonly key: DocumentKey; + private documentType; + version: SnapshotVersion; + readTime: SnapshotVersion; + createTime: SnapshotVersion; + data: ObjectValue; + private documentState; + private constructor(); + /** + * Creates a document with no known version or data, but which can serve as + * base document for mutations. + */ + static newInvalidDocument(documentKey: DocumentKey): MutableDocument; + /** + * Creates a new document that is known to exist with the given data at the + * given version. + */ + static newFoundDocument(documentKey: DocumentKey, version: SnapshotVersion, createTime: SnapshotVersion, value: ObjectValue): MutableDocument; + /** Creates a new document that is known to not exist at the given version. */ + static newNoDocument(documentKey: DocumentKey, version: SnapshotVersion): MutableDocument; + /** + * Creates a new document that is known to exist at the given version but + * whose data is not known (e.g. a document that was updated without a known + * base document). + */ + static newUnknownDocument(documentKey: DocumentKey, version: SnapshotVersion): MutableDocument; + /** + * Changes the document type to indicate that it exists and that its version + * and data are known. + */ + convertToFoundDocument(version: SnapshotVersion, value: ObjectValue): MutableDocument; + /** + * Changes the document type to indicate that it doesn't exist at the given + * version. + */ + convertToNoDocument(version: SnapshotVersion): MutableDocument; + /** + * Changes the document type to indicate that it exists at a given version but + * that its data is not known (e.g. a document that was updated without a known + * base document). + */ + convertToUnknownDocument(version: SnapshotVersion): MutableDocument; + setHasCommittedMutations(): MutableDocument; + setHasLocalMutations(): MutableDocument; + setReadTime(readTime: SnapshotVersion): MutableDocument; + get hasLocalMutations(): boolean; + get hasCommittedMutations(): boolean; + get hasPendingWrites(): boolean; + isValidDocument(): boolean; + isFoundDocument(): boolean; + isNoDocument(): boolean; + isUnknownDocument(): boolean; + isEqual(other: Document_2 | null | undefined): boolean; + mutableCopy(): MutableDocument; + toString(): string; +} + +/** Miscellaneous collection types / constants. */ +declare type MutableDocumentMap = SortedMap; + +/** + * A mutation describes a self-contained change to a document. Mutations can + * create, replace, delete, and update subsets of documents. + * + * Mutations not only act on the value of the document but also its version. + * + * For local mutations (mutations that haven't been committed yet), we preserve + * the existing version for Set and Patch mutations. For Delete mutations, we + * reset the version to 0. + * + * Here's the expected transition table. + * + * MUTATION APPLIED TO RESULTS IN + * + * SetMutation Document(v3) Document(v3) + * SetMutation NoDocument(v3) Document(v0) + * SetMutation InvalidDocument(v0) Document(v0) + * PatchMutation Document(v3) Document(v3) + * PatchMutation NoDocument(v3) NoDocument(v3) + * PatchMutation InvalidDocument(v0) UnknownDocument(v3) + * DeleteMutation Document(v3) NoDocument(v0) + * DeleteMutation NoDocument(v3) NoDocument(v0) + * DeleteMutation InvalidDocument(v0) NoDocument(v0) + * + * For acknowledged mutations, we use the updateTime of the WriteResponse as + * the resulting version for Set and Patch mutations. As deletes have no + * explicit update time, we use the commitTime of the WriteResponse for + * Delete mutations. + * + * If a mutation is acknowledged by the backend but fails the precondition check + * locally, we transition to an `UnknownDocument` and rely on Watch to send us + * the updated version. + * + * Field transforms are used only with Patch and Set Mutations. We use the + * `updateTransforms` message to store transforms, rather than the `transforms`s + * messages. + * + * ## Subclassing Notes + * + * Every type of mutation needs to implement its own applyToRemoteDocument() and + * applyToLocalView() to implement the actual behavior of applying the mutation + * to some source document (see `setMutationApplyToRemoteDocument()` for an + * example). + */ +declare abstract class Mutation { + abstract readonly type: MutationType; + abstract readonly key: DocumentKey; + abstract readonly precondition: Precondition; + abstract readonly fieldTransforms: FieldTransform[]; + /** + * Returns a `FieldMask` representing the fields that will be changed by + * applying this mutation. Returns `null` if the mutation will overwrite the + * entire document. + */ + abstract getFieldMask(): FieldMask | null; +} + +/** + * A batch of mutations that will be sent as one unit to the backend. + */ +declare class MutationBatch { + batchId: BatchId; + localWriteTime: Timestamp; + baseMutations: Mutation[]; + mutations: Mutation[]; + /** + * @param batchId - The unique ID of this mutation batch. + * @param localWriteTime - The original write time of this mutation. + * @param baseMutations - Mutations that are used to populate the base + * values when this mutation is applied locally. This can be used to locally + * overwrite values that are persisted in the remote document cache. Base + * mutations are never sent to the backend. + * @param mutations - The user-provided mutations in this mutation batch. + * User-provided mutations are applied both locally and remotely on the + * backend. + */ + constructor(batchId: BatchId, localWriteTime: Timestamp, baseMutations: Mutation[], mutations: Mutation[]); + /** + * Applies all the mutations in this MutationBatch to the specified document + * to compute the state of the remote document + * + * @param document - The document to apply mutations to. + * @param batchResult - The result of applying the MutationBatch to the + * backend. + */ + applyToRemoteDocument(document: MutableDocument, batchResult: MutationBatchResult): void; + /** + * Computes the local view of a document given all the mutations in this + * batch. + * + * @param document - The document to apply mutations to. + * @param mutatedFields - Fields that have been updated before applying this mutation batch. + * @returns A `FieldMask` representing all the fields that are mutated. + */ + applyToLocalView(document: MutableDocument, mutatedFields: FieldMask | null): FieldMask | null; + /** + * Computes the local view for all provided documents given the mutations in + * this batch. Returns a `DocumentKey` to `Mutation` map which can be used to + * replace all the mutation applications. + */ + applyToLocalDocumentSet(documentMap: OverlayedDocumentMap, documentsWithoutRemoteVersion: DocumentKeySet): MutationMap; + keys(): DocumentKeySet; + isEqual(other: MutationBatch): boolean; +} + +/** The result of applying a mutation batch to the backend. */ +declare class MutationBatchResult { + readonly batch: MutationBatch; + readonly commitVersion: SnapshotVersion; + readonly mutationResults: MutationResult[]; + /** + * A pre-computed mapping from each mutated document to the resulting + * version. + */ + readonly docVersions: DocumentVersionMap; + private constructor(); + /** + * Creates a new MutationBatchResult for the given batch and results. There + * must be one result for each mutation in the batch. This static factory + * caches a document=>version mapping (docVersions). + */ + static from(batch: MutationBatch, commitVersion: SnapshotVersion, results: MutationResult[]): MutationBatchResult; +} + +declare type MutationMap = DocumentKeyMap; + +/** A queue of mutations to apply to the remote store. */ +declare interface MutationQueue { + /** Returns true if this queue contains no mutation batches. */ + checkEmpty(transaction: PersistenceTransaction): PersistencePromise; + /** + * Creates a new mutation batch and adds it to this mutation queue. + * + * @param transaction - The transaction this operation is scoped to. + * @param localWriteTime - The original write time of this mutation. + * @param baseMutations - Mutations that are used to populate the base values + * when this mutation is applied locally. These mutations are used to locally + * overwrite values that are persisted in the remote document cache. + * @param mutations - The user-provided mutations in this mutation batch. + */ + addMutationBatch(transaction: PersistenceTransaction, localWriteTime: Timestamp, baseMutations: Mutation[], mutations: Mutation[]): PersistencePromise; + /** + * Loads the mutation batch with the given batchId. + */ + lookupMutationBatch(transaction: PersistenceTransaction, batchId: BatchId): PersistencePromise; + /** + * Gets the first unacknowledged mutation batch after the passed in batchId + * in the mutation queue or null if empty. + * + * @param batchId - The batch to search after, or BATCHID_UNKNOWN for the + * first mutation in the queue. + * + * @returns the next mutation or null if there wasn't one. + */ + getNextMutationBatchAfterBatchId(transaction: PersistenceTransaction, batchId: BatchId): PersistencePromise; + /** + * Gets the largest (latest) batch id in mutation queue for the current user + * that is pending server response, returns `BATCHID_UNKNOWN` if the queue is + * empty. + * + * @returns the largest batch id in the mutation queue that is not + * acknowledged. + */ + getHighestUnacknowledgedBatchId(transaction: PersistenceTransaction): PersistencePromise; + /** Gets all mutation batches in the mutation queue. */ + getAllMutationBatches(transaction: PersistenceTransaction): PersistencePromise; + /** + * Finds all mutation batches that could possibly affect the given + * document key. Not all mutations in a batch will necessarily affect the + * document key, so when looping through the batch you'll need to check that + * the mutation itself matches the key. + * + * Batches are guaranteed to be in sorted order. + * + * Note that because of this requirement implementations are free to return + * mutation batches that don't contain the document key at all if it's + * convenient. + */ + getAllMutationBatchesAffectingDocumentKey(transaction: PersistenceTransaction, documentKey: DocumentKey): PersistencePromise; + /** + * Finds all mutation batches that could possibly affect the given set of + * document keys. Not all mutations in a batch will necessarily affect each + * key, so when looping through the batch you'll need to check that the + * mutation itself matches the key. + * + * Batches are guaranteed to be in sorted order. + * + * Note that because of this requirement implementations are free to return + * mutation batches that don't contain any of the document keys at all if it's + * convenient. + */ + getAllMutationBatchesAffectingDocumentKeys(transaction: PersistenceTransaction, documentKeys: SortedMap): PersistencePromise; + /** + * Finds all mutation batches that could affect the results for the given + * query. Not all mutations in a batch will necessarily affect the query, so + * when looping through the batch you'll need to check that the mutation + * itself matches the query. + * + * Batches are guaranteed to be in sorted order. + * + * Note that because of this requirement implementations are free to return + * mutation batches that don't match the query at all if it's convenient. + * + * NOTE: A PatchMutation does not need to include all fields in the query + * filter criteria in order to be a match (but any fields it does contain do + * need to match). + */ + getAllMutationBatchesAffectingQuery(transaction: PersistenceTransaction, query: Query_2): PersistencePromise; + /** + * Removes the given mutation batch from the queue. This is useful in two + * circumstances: + * + * + Removing an applied mutation from the head of the queue + * + Removing a rejected mutation from anywhere in the queue + * + * Multi-Tab Note: This operation should only be called by the primary client. + */ + removeMutationBatch(transaction: PersistenceTransaction, batch: MutationBatch): PersistencePromise; + /** + * Performs a consistency check, examining the mutation queue for any + * leaks, if possible. + */ + performConsistencyCheck(transaction: PersistenceTransaction): PersistencePromise; +} + +/** The result of successfully applying a mutation to the backend. */ +declare class MutationResult { + /** + * The version at which the mutation was committed: + * + * - For most operations, this is the updateTime in the WriteResult. + * - For deletes, the commitTime of the WriteResponse (because deletes are + * not stored and have no updateTime). + * + * Note that these versions can be different: No-op writes will not change + * the updateTime even though the commitTime advances. + */ + readonly version: SnapshotVersion; + /** + * The resulting fields returned from the backend after a mutation + * containing field transforms has been committed. Contains one FieldValue + * for each FieldTransform that was in the mutation. + * + * Will be empty if the mutation did not contain any field transforms. + */ + readonly transformResults: Array; + constructor( + /** + * The version at which the mutation was committed: + * + * - For most operations, this is the updateTime in the WriteResult. + * - For deletes, the commitTime of the WriteResponse (because deletes are + * not stored and have no updateTime). + * + * Note that these versions can be different: No-op writes will not change + * the updateTime even though the commitTime advances. + */ + version: SnapshotVersion, + /** + * The resulting fields returned from the backend after a mutation + * containing field transforms has been committed. Contains one FieldValue + * for each FieldTransform that was in the mutation. + * + * Will be empty if the mutation did not contain any field transforms. + */ + transformResults: Array); +} + +declare const enum MutationType { + Set = 0, + Patch = 1, + Delete = 2, + Verify = 3 +} + +/** + * Represents a Query saved by the SDK in its local storage. + */ +declare interface NamedQuery { + /** The name of the query. */ + readonly name: string; + /** The underlying query associated with `name`. */ + readonly query: Query_2; + /** The time at which the results for this query were read. */ + readonly readTime: SnapshotVersion; +} + +/** Properties of a NamedQuery. */ +declare interface NamedQuery_2 { + /** NamedQuery name */ + name?: string | null; + /** NamedQuery bundledQuery */ + bundledQuery?: BundledQuery | null; + /** NamedQuery readTime */ + readTime?: Timestamp_2 | null; +} + +/** + * For each field (e.g. 'bar'), find all nested keys (e.g. {'bar.baz': T1, + * 'bar.qux': T2}). Intersect them together to make a single map containing + * all possible keys that are all marked as optional + */ +export declare type NestedUpdateFields> = UnionToIntersection<{ + [K in keyof T & string]: ChildUpdateFields; +}[keyof T & string]>; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A map implementation that uses objects as keys. Objects must have an + * associated equals function and must be immutable. Entries in the map are + * stored together with the key being produced from the mapKeyFn. This map + * automatically handles collisions of keys. + */ +declare class ObjectMap { + private mapKeyFn; + private equalsFn; + /** + * The inner map for a key/value pair. Due to the possibility of collisions we + * keep a list of entries that we do a linear search through to find an actual + * match. Note that collisions should be rare, so we still expect near + * constant time lookups in practice. + */ + private inner; + /** The number of entries stored in the map */ + private innerSize; + constructor(mapKeyFn: (key: KeyType) => string, equalsFn: (l: KeyType, r: KeyType) => boolean); + /** Get a value for this key, or undefined if it does not exist. */ + get(key: KeyType): ValueType | undefined; + has(key: KeyType): boolean; + /** Put this key and value in the map. */ + set(key: KeyType, value: ValueType): void; + /** + * Remove this key from the map. Returns a boolean if anything was deleted. + */ + delete(key: KeyType): boolean; + forEach(fn: (key: KeyType, val: ValueType) => void): void; + isEmpty(): boolean; + size(): number; +} + +/** + * An ObjectValue represents a MapValue in the Firestore Proto and offers the + * ability to add and remove fields (via the ObjectValueBuilder). + */ +declare class ObjectValue { + readonly value: { + mapValue: MapValue; + }; + constructor(value: { + mapValue: MapValue; + }); + static empty(): ObjectValue; + /** + * Returns the value at the given path or null. + * + * @param path - the path to search + * @returns The value at the path or null if the path is not set. + */ + field(path: FieldPath_2): Value | null; + /** + * Sets the field to the provided value. + * + * @param path - The field path to set. + * @param value - The value to set. + */ + set(path: FieldPath_2, value: Value): void; + /** + * Sets the provided fields to the provided values. + * + * @param data - A map of fields to values (or null for deletes). + */ + setAll(data: Map): void; + /** + * Removes the field at the specified path. If there is no field at the + * specified path, nothing is changed. + * + * @param path - The field path to remove. + */ + delete(path: FieldPath_2): void; + isEqual(other: ObjectValue): boolean; + /** + * Returns the map that contains the leaf element of `path`. If the parent + * entry does not yet exist, or if it is not a map, a new map will be created. + */ + private getFieldsMap; + /** + * Modifies `fieldsMap` by adding, replacing or deleting the specified + * entries. + */ + private applyChanges; + clone(): ObjectValue; +} + +/** + * Initializes and wires components that are needed to interface with the local + * cache. Implementations override `initialize()` to provide all components. + */ +declare interface OfflineComponentProvider { + readonly kind: Kind; + persistence: Persistence; + sharedClientState: SharedClientState; + localStore: LocalStore; + gcScheduler: Scheduler | null; + indexBackfillerScheduler: Scheduler | null; + synchronizeTabs: boolean; + initialize(cfg: ComponentConfiguration): Promise; + terminate(): Promise; +} + +declare interface OfflineComponentProviderFactory { + build(onlineComponents: OnlineComponentProvider): OfflineComponentProvider; +} + +/** + * Initializes and wires the components that are needed to interface with the + * network. + */ +declare class OnlineComponentProvider { + static readonly provider: OnlineComponentProviderFactory; + protected localStore: LocalStore; + protected sharedClientState: SharedClientState; + datastore: Datastore; + eventManager: EventManager; + remoteStore: RemoteStore; + syncEngine: SyncEngine; + initialize(offlineComponentProvider: OfflineComponentProvider, cfg: ComponentConfiguration): Promise; + createEventManager(cfg: ComponentConfiguration): EventManager; + createDatastore(cfg: ComponentConfiguration): Datastore; + createRemoteStore(cfg: ComponentConfiguration): RemoteStore; + createSyncEngine(cfg: ComponentConfiguration, startAsPrimary: boolean): SyncEngine; + terminate(): Promise; +} + +declare interface OnlineComponentProviderFactory { + build(): OnlineComponentProvider; +} + +/** + * Describes the online state of the Firestore client. Note that this does not + * indicate whether or not the remote store is trying to connect or not. This is + * primarily used by the View / EventManager code to change their behavior while + * offline (e.g. get() calls shouldn't wait for data from the server and + * snapshot events should set metadata.isFromCache=true). + * + * The string values should not be changed since they are persisted in + * WebStorage. + */ +declare const enum OnlineState { + /** + * The Firestore client is in an unknown online state. This means the client + * is either not actively trying to establish a connection or it is currently + * trying to establish a connection, but it has not succeeded or failed yet. + * Higher-level components should not operate in offline mode. + */ + Unknown = "Unknown", + /** + * The client is connected and the connections are healthy. This state is + * reached after a successful connection and there has been at least one + * successful message received from the backends. + */ + Online = "Online", + /** + * The client is either trying to establish a connection but failing, or it + * has been explicitly marked offline via a call to disableNetwork(). + * Higher-level components should operate in offline mode. + */ + Offline = "Offline" +} + +declare const enum Operator { + LESS_THAN = "<", + LESS_THAN_OR_EQUAL = "<=", + EQUAL = "==", + NOT_EQUAL = "!=", + GREATER_THAN = ">", + GREATER_THAN_OR_EQUAL = ">=", + ARRAY_CONTAINS = "array-contains", + IN = "in", + NOT_IN = "not-in", + ARRAY_CONTAINS_ANY = "array-contains-any" +} + +/** + * Creates a new {@link QueryCompositeFilterConstraint} that is a disjunction of + * the given filter constraints. A disjunction filter includes a document if it + * satisfies any of the given filters. + * + * @param queryConstraints - Optional. The list of + * {@link QueryFilterConstraint}s to perform a disjunction for. These must be + * created with calls to {@link where}, {@link or}, or {@link and}. + * @returns The newly created {@link QueryCompositeFilterConstraint}. + */ +export declare function or(...queryConstraints: QueryFilterConstraint[]): QueryCompositeFilterConstraint; + +/** + * An ordering on a field, in some Direction. Direction defaults to ASCENDING. + */ +declare class OrderBy { + readonly field: FieldPath_2; + readonly dir: Direction; + constructor(field: FieldPath_2, dir?: Direction); +} + +/** + * Creates a {@link QueryOrderByConstraint} that sorts the query result by the + * specified field, optionally in descending order instead of ascending. + * + * Note: Documents that do not contain the specified field will not be present + * in the query result. + * + * @param fieldPath - The field to sort by. + * @param directionStr - Optional direction to sort by ('asc' or 'desc'). If + * not specified, order will be ascending. + * @returns The created {@link QueryOrderByConstraint}. + */ +export declare function orderBy(fieldPath: string | FieldPath, directionStr?: OrderByDirection): QueryOrderByConstraint; + +/** + * The direction of a {@link orderBy} clause is specified as 'desc' or 'asc' + * (descending or ascending). + */ +export declare type OrderByDirection = 'desc' | 'asc'; + +declare type OrderDirection = 'DIRECTION_UNSPECIFIED' | 'ASCENDING' | 'DESCENDING'; + +/** + * Representation of an overlay computed by Firestore. + * + * Holds information about a mutation and the largest batch id in Firestore when + * the mutation was created. + */ +declare class Overlay { + readonly largestBatchId: number; + readonly mutation: Mutation; + constructor(largestBatchId: number, mutation: Mutation); + getKey(): DocumentKey; + isEqual(other: Overlay | null): boolean; + toString(): string; +} + +/** + * Represents a local view (overlay) of a document, and the fields that are + * locally mutated. + */ +declare class OverlayedDocument { + readonly overlayedDocument: Document_2; + /** + * The fields that are locally mutated by patch mutations. + * + * If the overlayed document is from set or delete mutations, this is `null`. + * If there is no overlay (mutation) for the document, this is an empty `FieldMask`. + */ + readonly mutatedFields: FieldMask | null; + constructor(overlayedDocument: Document_2, + /** + * The fields that are locally mutated by patch mutations. + * + * If the overlayed document is from set or delete mutations, this is `null`. + * If there is no overlay (mutation) for the document, this is an empty `FieldMask`. + */ + mutatedFields: FieldMask | null); +} + +declare type OverlayedDocumentMap = DocumentKeyMap; + +declare type OverlayMap = DocumentKeyMap; + +declare interface ParseContext { + readonly databaseId: DatabaseId; + readonly ignoreUndefinedProperties: boolean; +} + +/** The result of parsing document data (e.g. for a setData call). */ +declare class ParsedSetData { + readonly data: ObjectValue; + readonly fieldMask: FieldMask | null; + readonly fieldTransforms: FieldTransform[]; + constructor(data: ObjectValue, fieldMask: FieldMask | null, fieldTransforms: FieldTransform[]); + toMutation(key: DocumentKey, precondition: Precondition): Mutation; +} + +/** The result of parsing "update" data (i.e. for an updateData call). */ +declare class ParsedUpdateData { + readonly data: ObjectValue; + readonly fieldMask: FieldMask; + readonly fieldTransforms: FieldTransform[]; + constructor(data: ObjectValue, fieldMask: FieldMask, fieldTransforms: FieldTransform[]); + toMutation(key: DocumentKey, precondition: Precondition): Mutation; +} + +/** + * Similar to TypeScript's `Partial`, but allows nested fields to be + * omitted and FieldValues to be passed in as property values. + */ +export declare type PartialWithFieldValue = Partial | (T extends Primitive ? T : T extends {} ? { + [K in keyof T]?: PartialWithFieldValue | FieldValue; +} : never); + +/** + * Persistence is the lowest-level shared interface to persistent storage in + * Firestore. + * + * Persistence is used to create MutationQueue and RemoteDocumentCache + * instances backed by persistence (which might be in-memory or LevelDB). + * + * Persistence also exposes an API to create and run PersistenceTransactions + * against persistence. All read / write operations must be wrapped in a + * transaction. Implementations of PersistenceTransaction / Persistence only + * need to guarantee that writes made against the transaction are not made to + * durable storage until the transaction resolves its PersistencePromise. + * Since memory-only storage components do not alter durable storage, they are + * free to ignore the transaction. + * + * This contract is enough to allow the LocalStore be be written + * independently of whether or not the stored state actually is durably + * persisted. If persistent storage is enabled, writes are grouped together to + * avoid inconsistent state that could cause crashes. + * + * Concretely, when persistent storage is enabled, the persistent versions of + * MutationQueue, RemoteDocumentCache, and others (the mutators) will + * defer their writes into a transaction. Once the local store has completed + * one logical operation, it commits the transaction. + * + * When persistent storage is disabled, the non-persistent versions of the + * mutators ignore the transaction. This short-cut is allowed because + * memory-only storage leaves no state so it cannot be inconsistent. + * + * This simplifies the implementations of the mutators and allows memory-only + * implementations to supplement the persistent ones without requiring any + * special dual-store implementation of Persistence. The cost is that the + * LocalStore needs to be slightly careful about the order of its reads and + * writes in order to avoid relying on being able to read back uncommitted + * writes. + */ +declare interface Persistence { + /** + * Whether or not this persistence instance has been started. + */ + readonly started: boolean; + readonly referenceDelegate: ReferenceDelegate; + /** Starts persistence. */ + start(): Promise; + /** + * Releases any resources held during eager shutdown. + */ + shutdown(): Promise; + /** + * Registers a listener that gets called when the database receives a + * version change event indicating that it has deleted. + * + * PORTING NOTE: This is only used for Web multi-tab. + */ + setDatabaseDeletedListener(databaseDeletedListener: () => Promise): void; + /** + * Adjusts the current network state in the client's metadata, potentially + * affecting the primary lease. + * + * PORTING NOTE: This is only used for Web multi-tab. + */ + setNetworkEnabled(networkEnabled: boolean): void; + /** + * Returns GlobalCache representing a general purpose cache for global values. + */ + getGlobalsCache(): GlobalsCache; + /** + * Returns a MutationQueue representing the persisted mutations for the + * given user. + * + * Note: The implementation is free to return the same instance every time + * this is called for a given user. In particular, the memory-backed + * implementation does this to emulate the persisted implementation to the + * extent possible (e.g. in the case of uid switching from + * sally=>jack=>sally, sally's mutation queue will be preserved). + */ + getMutationQueue(user: User, indexManager: IndexManager): MutationQueue; + /** + * Returns a TargetCache representing the persisted cache of targets. + * + * Note: The implementation is free to return the same instance every time + * this is called. In particular, the memory-backed implementation does this + * to emulate the persisted implementation to the extent possible. + */ + getTargetCache(): TargetCache; + /** + * Returns a RemoteDocumentCache representing the persisted cache of remote + * documents. + * + * Note: The implementation is free to return the same instance every time + * this is called. In particular, the memory-backed implementation does this + * to emulate the persisted implementation to the extent possible. + */ + getRemoteDocumentCache(): RemoteDocumentCache; + /** + * Returns a BundleCache representing the persisted cache of loaded bundles. + * + * Note: The implementation is free to return the same instance every time + * this is called. In particular, the memory-backed implementation does this + * to emulate the persisted implementation to the extent possible. + */ + getBundleCache(): BundleCache; + /** + * Returns an IndexManager instance that manages our persisted query indexes. + * + * Note: The implementation is free to return the same instance every time + * this is called. In particular, the memory-backed implementation does this + * to emulate the persisted implementation to the extent possible. + */ + getIndexManager(user: User): IndexManager; + /** + * Returns a DocumentOverlayCache representing the documents that are mutated + * locally. + */ + getDocumentOverlayCache(user: User): DocumentOverlayCache; + /** + * Performs an operation inside a persistence transaction. Any reads or writes + * against persistence must be performed within a transaction. Writes will be + * committed atomically once the transaction completes. + * + * Persistence operations are asynchronous and therefore the provided + * transactionOperation must return a PersistencePromise. When it is resolved, + * the transaction will be committed and the Promise returned by this method + * will resolve. + * + * @param action - A description of the action performed by this transaction, + * used for logging. + * @param mode - The underlying mode of the IndexedDb transaction. Can be + * 'readonly', 'readwrite' or 'readwrite-primary'. Transactions marked + * 'readwrite-primary' can only be executed by the primary client. In this + * mode, the transactionOperation will not be run if the primary lease cannot + * be acquired and the returned promise will be rejected with a + * FAILED_PRECONDITION error. + * @param transactionOperation - The operation to run inside a transaction. + * @returns A `Promise` that is resolved once the transaction completes. + */ + runTransaction(action: string, mode: PersistenceTransactionMode, transactionOperation: (transaction: PersistenceTransaction) => PersistencePromise): Promise; +} + +/** + * PersistencePromise is essentially a re-implementation of Promise except + * it has a .next() method instead of .then() and .next() and .catch() callbacks + * are executed synchronously when a PersistencePromise resolves rather than + * asynchronously (Promise implementations use setImmediate() or similar). + * + * This is necessary to interoperate with IndexedDB which will automatically + * commit transactions if control is returned to the event loop without + * synchronously initiating another operation on the transaction. + * + * NOTE: .then() and .catch() only allow a single consumer, unlike normal + * Promises. + */ +declare class PersistencePromise { + private nextCallback; + private catchCallback; + private result; + private error; + private isDone; + private callbackAttached; + constructor(callback: (resolve: Resolver, reject: Rejector) => void); + catch(fn: (error: Error) => R | PersistencePromise): PersistencePromise; + next(nextFn?: FulfilledHandler, catchFn?: RejectedHandler): PersistencePromise; + toPromise(): Promise; + private wrapUserFunction; + private wrapSuccess; + private wrapFailure; + static resolve(): PersistencePromise; + static resolve(result: R): PersistencePromise; + static reject(error: Error): PersistencePromise; + static waitFor(all: { + forEach: (cb: (el: PersistencePromise) => void) => void; + }): PersistencePromise; + /** + * Given an array of predicate functions that asynchronously evaluate to a + * boolean, implements a short-circuiting `or` between the results. Predicates + * will be evaluated until one of them returns `true`, then stop. The final + * result will be whether any of them returned `true`. + */ + static or(predicates: Array<() => PersistencePromise>): PersistencePromise; + /** + * Given an iterable, call the given function on each element in the + * collection and wait for all of the resulting concurrent PersistencePromises + * to resolve. + */ + static forEach(collection: { + forEach: (cb: (r: R, s: S) => void) => void; + }, f: ((r: R, s: S) => PersistencePromise) | ((r: R) => PersistencePromise)): PersistencePromise; + static forEach(collection: { + forEach: (cb: (r: R) => void) => void; + }, f: (r: R) => PersistencePromise): PersistencePromise; + /** + * Concurrently map all array elements through asynchronous function. + */ + static mapArray(array: T[], f: (t: T) => PersistencePromise): PersistencePromise; + /** + * An alternative to recursive PersistencePromise calls, that avoids + * potential memory problems from unbounded chains of promises. + * + * The `action` will be called repeatedly while `condition` is true. + */ + static doWhile(condition: () => boolean, action: () => PersistencePromise): PersistencePromise; +} + +/** + * A base class representing a persistence transaction, encapsulating both the + * transaction's sequence numbers as well as a list of onCommitted listeners. + * + * When you call Persistence.runTransaction(), it will create a transaction and + * pass it to your callback. You then pass it to any method that operates + * on persistence. + */ +declare abstract class PersistenceTransaction { + private readonly onCommittedListeners; + abstract readonly currentSequenceNumber: ListenSequenceNumber; + addOnCommittedListener(listener: () => void): void; + raiseOnCommittedEvent(): void; +} + +/** The different modes supported by `Persistence.runTransaction()`. */ +declare type PersistenceTransactionMode = 'readonly' | 'readwrite' | 'readwrite-primary'; + +/** + * Provides a persistent cache backed by IndexedDb to the SDK. + * + * To use, create an instance using the factory function {@link persistentLocalCache()}, then + * set the instance to `FirestoreSettings.cache` and call `initializeFirestore` using + * the settings object. + */ +declare type PersistentLocalCache = { + kind: 'persistent'; + /* Excluded from this release type: _onlineComponentProvider */ + /* Excluded from this release type: _offlineComponentProvider */ +}; + +/** + * Encodes a precondition for a mutation. This follows the model that the + * backend accepts with the special case of an explicit "empty" precondition + * (meaning no precondition). + */ +declare class Precondition { + readonly updateTime?: SnapshotVersion | undefined; + readonly exists?: boolean | undefined; + private constructor(); + /** Creates a new empty Precondition. */ + static none(): Precondition; + /** Creates a new Precondition with an exists flag. */ + static exists(exists: boolean): Precondition; + /** Creates a new Precondition based on a version a document exists at. */ + static updateTime(version: SnapshotVersion): Precondition; + /** Returns whether this Precondition is empty. */ + get isNone(): boolean; + isEqual(other: Precondition): boolean; +} + +/** + * These types primarily exist to support the `UpdateData`, + * `WithFieldValue`, and `PartialWithFieldValue` types and are not consumed + * directly by the end developer. + */ +/** Primitive types. */ +export declare type Primitive = string | number | boolean | undefined | null; + +/* Excluded from this release type: PrivateSettings */ + +/* Excluded from this release type: Property */ + +declare interface ProviderCredentialsSettings { + ['type']: 'provider'; + ['client']: CredentialsProvider; +} + +/** + * A `Query` refers to a query which you can read or listen to. You can also + * construct refined `Query` objects by adding filters and ordering. + */ +export declare class Query { + /** + * If provided, the `FirestoreDataConverter` associated with this instance. + */ + readonly converter: FirestoreDataConverter | null; + readonly _query: Query_2; + /** The type of this Firestore reference. */ + readonly type: 'query' | 'collection'; + /** + * The `Firestore` instance for the Firestore database (useful for performing + * transactions, etc.). + */ + readonly firestore: Firestore; + /** @hideconstructor protected */ + constructor(firestore: Firestore, + /** + * If provided, the `FirestoreDataConverter` associated with this instance. + */ + converter: FirestoreDataConverter | null, _query: Query_2); + /** + * Removes the current converter. + * + * @param converter - `null` removes the current converter. + * @returns A `Query` that does not use a + * converter. + */ + withConverter(converter: null): Query; + /** + * Applies a custom data converter to this query, allowing you to use your own + * custom model objects with Firestore. When you call {@link getDocs} with + * the returned query, the provided converter will convert between Firestore + * data of type `NewDbModelType` and your custom type `NewAppModelType`. + * + * @param converter - Converts objects to and from Firestore. + * @returns A `Query` that uses the provided converter. + */ + withConverter(converter: FirestoreDataConverter): Query; +} + +/** + * Creates a new immutable instance of {@link Query} that is extended to also + * include additional query constraints. + * + * @param query - The {@link Query} instance to use as a base for the new + * constraints. + * @param compositeFilter - The {@link QueryCompositeFilterConstraint} to + * apply. Create {@link QueryCompositeFilterConstraint} using {@link and} or + * {@link or}. + * @param queryConstraints - Additional {@link QueryNonFilterConstraint}s to + * apply (e.g. {@link orderBy}, {@link limit}). + * @throws if any of the provided query constraints cannot be combined with the + * existing or new constraints. + */ +export declare function query(query: Query, compositeFilter: QueryCompositeFilterConstraint, ...queryConstraints: QueryNonFilterConstraint[]): Query; + +/** + * Creates a new immutable instance of {@link Query} that is extended to also + * include additional query constraints. + * + * @param query - The {@link Query} instance to use as a base for the new + * constraints. + * @param queryConstraints - The list of {@link QueryConstraint}s to apply. + * @throws if any of the provided query constraints cannot be combined with the + * existing or new constraints. + */ +export declare function query(query: Query, ...queryConstraints: QueryConstraint[]): Query; + +/** + * The Query interface defines all external properties of a query. + * + * QueryImpl implements this interface to provide memoization for `queryNormalizedOrderBy` + * and `queryToTarget`. + */ +declare interface Query_2 { + readonly path: ResourcePath; + readonly collectionGroup: string | null; + readonly explicitOrderBy: OrderBy[]; + readonly filters: Filter[]; + readonly limit: number | null; + readonly limitType: LimitType; + readonly startAt: Bound | null; + readonly endAt: Bound | null; +} + +/** + * A `QueryCompositeFilterConstraint` is used to narrow the set of documents + * returned by a Firestore query by performing the logical OR or AND of multiple + * {@link QueryFieldFilterConstraint}s or {@link QueryCompositeFilterConstraint}s. + * `QueryCompositeFilterConstraint`s are created by invoking {@link or} or + * {@link and} and can then be passed to {@link (query:1)} to create a new query + * instance that also contains the `QueryCompositeFilterConstraint`. + */ +export declare class QueryCompositeFilterConstraint extends AppliableConstraint { + /** The type of this query constraint */ + readonly type: 'or' | 'and'; + private readonly _queryConstraints; + /* Excluded from this release type: __constructor */ + static _create(type: 'or' | 'and', _queryConstraints: QueryFilterConstraint[]): QueryCompositeFilterConstraint; + _parse(query: Query): Filter; + _apply(query: Query): Query; + _getQueryConstraints(): readonly AppliableConstraint[]; + _getOperator(): CompositeOperator; +} + +/** + * A `QueryConstraint` is used to narrow the set of documents returned by a + * Firestore query. `QueryConstraint`s are created by invoking {@link where}, + * {@link orderBy}, {@link (startAt:1)}, {@link (startAfter:1)}, {@link + * (endBefore:1)}, {@link (endAt:1)}, {@link limit}, {@link limitToLast} and + * can then be passed to {@link (query:1)} to create a new query instance that + * also contains this `QueryConstraint`. + */ +export declare abstract class QueryConstraint extends AppliableConstraint { + /** The type of this query constraint */ + abstract readonly type: QueryConstraintType; + /** + * Takes the provided {@link Query} and returns a copy of the {@link Query} with this + * {@link AppliableConstraint} applied. + */ + abstract _apply(query: Query): Query; +} + +/** Describes the different query constraints available in this SDK. */ +export declare type QueryConstraintType = 'where' | 'orderBy' | 'limit' | 'limitToLast' | 'startAt' | 'startAfter' | 'endAt' | 'endBefore'; + +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A tracker to keep a record of important details during database local query + * execution. + */ +declare class QueryContext { + /** + * Counts the number of documents passed through during local query execution. + */ + private _documentReadCount; + get documentReadCount(): number; + incrementDocumentReadCount(amount: number): void; +} + +/** + * A `QueryDocumentSnapshot` contains data read from a document in your + * Firestore database as part of a query. The document is guaranteed to exist + * and its data can be extracted with `.data()` or `.get()` to get a + * specific field. + * + * A `QueryDocumentSnapshot` offers the same API surface as a + * `DocumentSnapshot`. Since query results contain only existing documents, the + * `exists` property will always be true and `data()` will never return + * 'undefined'. + */ +export declare class QueryDocumentSnapshot extends DocumentSnapshot { + /** + * Retrieves all fields in the document as an `Object`. + * + * @override + * @returns An `Object` containing all fields in the document. + */ + data(): AppModelType; +} + +/** + * A `QueryEndAtConstraint` is used to exclude documents from the end of a + * result set returned by a Firestore query. + * `QueryEndAtConstraint`s are created by invoking {@link (endAt:1)} or + * {@link (endBefore:1)} and can then be passed to {@link (query:1)} to create a new + * query instance that also contains this `QueryEndAtConstraint`. + */ +export declare class QueryEndAtConstraint extends QueryConstraint { + /** The type of this query constraint */ + readonly type: 'endBefore' | 'endAt'; + private readonly _docOrFields; + private readonly _inclusive; + /* Excluded from this release type: __constructor */ + static _create(type: 'endBefore' | 'endAt', _docOrFields: Array>, _inclusive: boolean): QueryEndAtConstraint; + _apply(query: Query): Query; +} + +/** + * Returns true if the provided queries point to the same collection and apply + * the same constraints. + * + * @param left - A `Query` to compare. + * @param right - A `Query` to compare. + * @returns true if the references point to the same location in the same + * Firestore database. + */ +export declare function queryEqual(left: Query, right: Query): boolean; + +/** + * A `QueryFieldFilterConstraint` is used to narrow the set of documents returned by + * a Firestore query by filtering on one or more document fields. + * `QueryFieldFilterConstraint`s are created by invoking {@link where} and can then + * be passed to {@link (query:1)} to create a new query instance that also contains + * this `QueryFieldFilterConstraint`. + */ +export declare class QueryFieldFilterConstraint extends QueryConstraint { + private readonly _field; + private _op; + private _value; + /** The type of this query constraint */ + readonly type = "where"; + /* Excluded from this release type: __constructor */ + static _create(_field: FieldPath_2, _op: Operator, _value: unknown): QueryFieldFilterConstraint; + _apply(query: Query): Query; + _parse(query: Query): FieldFilter; +} + +/** + * `QueryFilterConstraint` is a helper union type that represents + * {@link QueryFieldFilterConstraint} and {@link QueryCompositeFilterConstraint}. + */ +export declare type QueryFilterConstraint = QueryFieldFilterConstraint | QueryCompositeFilterConstraint; + +/** + * A `QueryLimitConstraint` is used to limit the number of documents returned by + * a Firestore query. + * `QueryLimitConstraint`s are created by invoking {@link limit} or + * {@link limitToLast} and can then be passed to {@link (query:1)} to create a new + * query instance that also contains this `QueryLimitConstraint`. + */ +export declare class QueryLimitConstraint extends QueryConstraint { + /** The type of this query constraint */ + readonly type: 'limit' | 'limitToLast'; + private readonly _limit; + private readonly _limitType; + /* Excluded from this release type: __constructor */ + static _create(type: 'limit' | 'limitToLast', _limit: number, _limitType: LimitType): QueryLimitConstraint; + _apply(query: Query): Query; +} + +/** + * `QueryNonFilterConstraint` is a helper union type that represents + * QueryConstraints which are used to narrow or order the set of documents, + * but that do not explicitly filter on a document field. + * `QueryNonFilterConstraint`s are created by invoking {@link orderBy}, + * {@link (startAt:1)}, {@link (startAfter:1)}, {@link (endBefore:1)}, {@link (endAt:1)}, + * {@link limit} or {@link limitToLast} and can then be passed to {@link (query:1)} + * to create a new query instance that also contains the `QueryConstraint`. + */ +export declare type QueryNonFilterConstraint = QueryOrderByConstraint | QueryLimitConstraint | QueryStartAtConstraint | QueryEndAtConstraint; + +/** + * A `QueryOrderByConstraint` is used to sort the set of documents returned by a + * Firestore query. `QueryOrderByConstraint`s are created by invoking + * {@link orderBy} and can then be passed to {@link (query:1)} to create a new query + * instance that also contains this `QueryOrderByConstraint`. + * + * Note: Documents that do not contain the orderBy field will not be present in + * the query result. + */ +export declare class QueryOrderByConstraint extends QueryConstraint { + private readonly _field; + private _direction; + /** The type of this query constraint */ + readonly type = "orderBy"; + /* Excluded from this release type: __constructor */ + static _create(_field: FieldPath_2, _direction: Direction): QueryOrderByConstraint; + _apply(query: Query): Query; +} + +/** + * A `QuerySnapshot` contains zero or more `DocumentSnapshot` objects + * representing the results of a query. The documents can be accessed as an + * array via the `docs` property or enumerated using the `forEach` method. The + * number of documents can be determined via the `empty` and `size` + * properties. + */ +export declare class QuerySnapshot { + readonly _docs: Array>; + /** + * The query on which you called {@link getDocs} in order to get this + * `QuerySnapshot`. + */ + readonly query: Query; + /** @hideconstructor */ + constructor(_query: Query, _docs: Array>); + /** An array of all the documents in the `QuerySnapshot`. */ + get docs(): Array>; + /** The number of documents in the `QuerySnapshot`. */ + get size(): number; + /** True if there are no documents in the `QuerySnapshot`. */ + get empty(): boolean; + /** + * Enumerates all of the documents in the `QuerySnapshot`. + * + * @param callback - A callback to be called with a `QueryDocumentSnapshot` for + * each document in the snapshot. + * @param thisArg - The `this` binding for the callback. + */ + forEach(callback: (result: QueryDocumentSnapshot) => void, thisArg?: unknown): void; +} + +/** + * A `QueryStartAtConstraint` is used to exclude documents from the start of a + * result set returned by a Firestore query. + * `QueryStartAtConstraint`s are created by invoking {@link (startAt:1)} or + * {@link (startAfter:1)} and can then be passed to {@link (query:1)} to create a + * new query instance that also contains this `QueryStartAtConstraint`. + */ +export declare class QueryStartAtConstraint extends QueryConstraint { + /** The type of this query constraint */ + readonly type: 'startAt' | 'startAfter'; + private readonly _docOrFields; + private readonly _inclusive; + /* Excluded from this release type: __constructor */ + static _create(type: 'startAt' | 'startAfter', _docOrFields: Array>, _inclusive: boolean): QueryStartAtConstraint; + _apply(query: Query): Query; +} + +/** The different states of a watch target. */ +declare type QueryTargetState = 'not-current' | 'current' | 'rejected'; + +/** + * Returns true if the provided references are equal. + * + * @param left - A reference to compare. + * @param right - A reference to compare. + * @returns true if the references point to the same location in the same + * Firestore database. + */ +export declare function refEqual(left: DocumentReference | CollectionReference, right: DocumentReference | CollectionReference): boolean; + +/** + * A ReferenceDelegate instance handles all of the hooks into the document-reference lifecycle. This + * includes being added to a target, being removed from a target, being subject to mutation, and + * being mutated by the user. + * + * Different implementations may do different things with each of these events. Not every + * implementation needs to do something with every lifecycle hook. + * + * PORTING NOTE: since sequence numbers are attached to transactions in this + * client, the ReferenceDelegate does not need to deal in transactional + * semantics (onTransactionStarted/Committed()), nor does it need to track and + * generate sequence numbers (getCurrentSequenceNumber()). + */ +declare interface ReferenceDelegate { + /** Notify the delegate that the given document was added to a target. */ + addReference(txn: PersistenceTransaction, targetId: TargetId, doc: DocumentKey): PersistencePromise; + /** Notify the delegate that the given document was removed from a target. */ + removeReference(txn: PersistenceTransaction, targetId: TargetId, doc: DocumentKey): PersistencePromise; + /** + * Notify the delegate that a target was removed. The delegate may, but is not obligated to, + * actually delete the target and associated data. + */ + removeTarget(txn: PersistenceTransaction, targetData: TargetData): PersistencePromise; + /** + * Notify the delegate that a document may no longer be part of any views or + * have any mutations associated. + */ + markPotentiallyOrphaned(txn: PersistenceTransaction, doc: DocumentKey): PersistencePromise; + /** Notify the delegate that a limbo document was updated. */ + updateLimboDocument(txn: PersistenceTransaction, doc: DocumentKey): PersistencePromise; +} + +declare type RejectedHandler = ((reason: Error) => R | PersistencePromise) | null; + +declare type Rejector = (error: Error) => void; + +/** + * Represents cached documents received from the remote backend. + * + * The cache is keyed by DocumentKey and entries in the cache are + * MutableDocuments, meaning we can cache both actual documents as well as + * documents that are known to not exist. + */ +declare interface RemoteDocumentCache { + /** Sets the index manager to use for managing the collectionGroup index. */ + setIndexManager(indexManager: IndexManager): void; + /** + * Looks up an entry in the cache. + * + * @param documentKey - The key of the entry to look up.* + * @returns The cached document entry. Returns an invalid document if the + * document is not cached. + */ + getEntry(transaction: PersistenceTransaction, documentKey: DocumentKey): PersistencePromise; + /** + * Looks up a set of entries in the cache. + * + * @param documentKeys - The keys of the entries to look up. + * @returns The cached document entries indexed by key. If an entry is not + * cached, the corresponding key will be mapped to an invalid document. + */ + getEntries(transaction: PersistenceTransaction, documentKeys: DocumentKeySet): PersistencePromise; + /** + * Returns the documents matching the given query + * + * @param query - The query to match documents against. + * @param offset - The offset to start the scan at (exclusive). + * @param context - A optional tracker to keep a record of important details + * during database local query execution. + * @returns The set of matching documents. + */ + getDocumentsMatchingQuery(transaction: PersistenceTransaction, query: Query_2, offset: IndexOffset, mutatedDocs: OverlayMap, context?: QueryContext): PersistencePromise; + /** + * Looks up the next `limit` documents for a collection group based on the + * provided offset. The ordering is based on the document's read time and key. + * + * @param collectionGroup - The collection group to scan. + * @param offset - The offset to start the scan at (exclusive). + * @param limit - The maximum number of results to return. + * @returns The set of matching documents. + */ + getAllFromCollectionGroup(transaction: PersistenceTransaction, collectionGroup: string, offset: IndexOffset, limit: number): PersistencePromise; + /** + * Provides access to add or update the contents of the cache. The buffer + * handles proper size accounting for the change. + * + * Multi-Tab Note: This should only be called by the primary client. + * + * @param options - Specify `trackRemovals` to create sentinel entries for + * removed documents, which allows removals to be tracked by + * `getNewDocumentChanges()`. + */ + newChangeBuffer(options?: { + trackRemovals: boolean; + }): RemoteDocumentChangeBuffer; + /** + * Get an estimate of the size of the document cache. Note that for eager + * garbage collection, we don't track sizes so this will return 0. + */ + getSize(transaction: PersistenceTransaction): PersistencePromise; +} + +/** + * An in-memory buffer of entries to be written to a RemoteDocumentCache. + * It can be used to batch up a set of changes to be written to the cache, but + * additionally supports reading entries back with the `getEntry()` method, + * falling back to the underlying RemoteDocumentCache if no entry is + * buffered. + * + * Entries added to the cache *must* be read first. This is to facilitate + * calculating the size delta of the pending changes. + * + * PORTING NOTE: This class was implemented then removed from other platforms. + * If byte-counting ends up being needed on the other platforms, consider + * porting this class as part of that implementation work. + */ +declare abstract class RemoteDocumentChangeBuffer { + protected changes: ObjectMap; + private changesApplied; + protected abstract getFromCache(transaction: PersistenceTransaction, documentKey: DocumentKey): PersistencePromise; + protected abstract getAllFromCache(transaction: PersistenceTransaction, documentKeys: DocumentKeySet): PersistencePromise; + protected abstract applyChanges(transaction: PersistenceTransaction): PersistencePromise; + /** + * Buffers a `RemoteDocumentCache.addEntry()` call. + * + * You can only modify documents that have already been retrieved via + * `getEntry()/getEntries()` (enforced via IndexedDbs `apply()`). + */ + addEntry(document: MutableDocument): void; + /** + * Buffers a `RemoteDocumentCache.removeEntry()` call. + * + * You can only remove documents that have already been retrieved via + * `getEntry()/getEntries()` (enforced via IndexedDbs `apply()`). + */ + removeEntry(key: DocumentKey, readTime: SnapshotVersion): void; + /** + * Looks up an entry in the cache. The buffered changes will first be checked, + * and if no buffered change applies, this will forward to + * `RemoteDocumentCache.getEntry()`. + * + * @param transaction - The transaction in which to perform any persistence + * operations. + * @param documentKey - The key of the entry to look up. + * @returns The cached document or an invalid document if we have nothing + * cached. + */ + getEntry(transaction: PersistenceTransaction, documentKey: DocumentKey): PersistencePromise; + /** + * Looks up several entries in the cache, forwarding to + * `RemoteDocumentCache.getEntry()`. + * + * @param transaction - The transaction in which to perform any persistence + * operations. + * @param documentKeys - The keys of the entries to look up. + * @returns A map of cached documents, indexed by key. If an entry cannot be + * found, the corresponding key will be mapped to an invalid document. + */ + getEntries(transaction: PersistenceTransaction, documentKeys: DocumentKeySet): PersistencePromise; + /** + * Applies buffered changes to the underlying RemoteDocumentCache, using + * the provided transaction. + */ + apply(transaction: PersistenceTransaction): PersistencePromise; + /** Helper to assert this.changes is not null */ + protected assertNotApplied(): void; +} + +/** + * An event from the RemoteStore. It is split into targetChanges (changes to the + * state or the set of documents in our watched targets) and documentUpdates + * (changes to the actual documents). + */ +declare class RemoteEvent { + /** + * The snapshot version this event brings us up to, or MIN if not set. + */ + readonly snapshotVersion: SnapshotVersion; + /** + * A map from target to changes to the target. See TargetChange. + */ + readonly targetChanges: Map; + /** + * A map of targets that is known to be inconsistent, and the purpose for + * re-listening. Listens for these targets should be re-established without + * resume tokens. + */ + readonly targetMismatches: SortedMap; + /** + * A set of which documents have changed or been deleted, along with the + * doc's new values (if not deleted). + */ + readonly documentUpdates: MutableDocumentMap; + /** + * A set of which document updates are due only to limbo resolution targets. + */ + readonly resolvedLimboDocuments: DocumentKeySet; + constructor( + /** + * The snapshot version this event brings us up to, or MIN if not set. + */ + snapshotVersion: SnapshotVersion, + /** + * A map from target to changes to the target. See TargetChange. + */ + targetChanges: Map, + /** + * A map of targets that is known to be inconsistent, and the purpose for + * re-listening. Listens for these targets should be re-established without + * resume tokens. + */ + targetMismatches: SortedMap, + /** + * A set of which documents have changed or been deleted, along with the + * doc's new values (if not deleted). + */ + documentUpdates: MutableDocumentMap, + /** + * A set of which document updates are due only to limbo resolution targets. + */ + resolvedLimboDocuments: DocumentKeySet); + /** + * HACK: Views require RemoteEvents in order to determine whether the view is + * CURRENT, but secondary tabs don't receive remote events. So this method is + * used to create a synthesized RemoteEvent that can be used to apply a + * CURRENT status change to a View, for queries executed in a different tab. + */ + static createSynthesizedRemoteEventForCurrentChange(targetId: TargetId, current: boolean, resumeToken: ByteString): RemoteEvent; +} + +/** + * RemoteStore - An interface to remotely stored data, basically providing a + * wrapper around the Datastore that is more reliable for the rest of the + * system. + * + * RemoteStore is responsible for maintaining the connection to the server. + * - maintaining a list of active listens. + * - reconnecting when the connection is dropped. + * - resuming all the active listens on reconnect. + * + * RemoteStore handles all incoming events from the Datastore. + * - listening to the watch stream and repackaging the events as RemoteEvents + * - notifying SyncEngine of any changes to the active listens. + * + * RemoteStore takes writes from other components and handles them reliably. + * - pulling pending mutations from LocalStore and sending them to Datastore. + * - retrying mutations that failed because of network problems. + * - acking mutations to the SyncEngine once they are accepted or rejected. + */ +declare interface RemoteStore { + /** + * SyncEngine to notify of watch and write events. This must be set + * immediately after construction. + */ + remoteSyncer: RemoteSyncer; +} + +/** + * An interface that describes the actions the RemoteStore needs to perform on + * a cooperating synchronization engine. + */ +declare interface RemoteSyncer { + /** + * Applies one remote event to the sync engine, notifying any views of the + * changes, and releasing any pending mutation batches that would become + * visible because of the snapshot version the remote event contains. + */ + applyRemoteEvent?(remoteEvent: RemoteEvent): Promise; + /** + * Rejects the listen for the given targetID. This can be triggered by the + * backend for any active target. + * + * @param targetId - The targetID corresponds to one previously initiated by + * the user as part of TargetData passed to listen() on RemoteStore. + * @param error - A description of the condition that has forced the rejection. + * Nearly always this will be an indication that the user is no longer + * authorized to see the data matching the target. + */ + rejectListen?(targetId: TargetId, error: FirestoreError): Promise; + /** + * Applies the result of a successful write of a mutation batch to the sync + * engine, emitting snapshots in any views that the mutation applies to, and + * removing the batch from the mutation queue. + */ + applySuccessfulWrite?(result: MutationBatchResult): Promise; + /** + * Rejects the batch, removing the batch from the mutation queue, recomputing + * the local view of any documents affected by the batch and then, emitting + * snapshots with the reverted value. + */ + rejectFailedWrite?(batchId: BatchId, error: FirestoreError): Promise; + /** + * Returns the set of remote document keys for the given target ID. This list + * includes the documents that were assigned to the target when we received + * the last snapshot. + */ + getRemoteKeysForTarget?(targetId: TargetId): DocumentKeySet; + /** + * Updates all local state to match the pending mutations for the given user. + * May be called repeatedly for the same user. + */ + handleCredentialChange?(user: User): Promise; +} + +declare type Resolver = (value?: T) => void; + +/* Excluded from this release type: ResourcePath */ + +/** + * Executes the given `updateFunction` and then attempts to commit the changes + * applied within the transaction. If any document read within the transaction + * has changed, Cloud Firestore retries the `updateFunction`. If it fails to + * commit after 5 attempts, the transaction fails. + * + * The maximum number of writes allowed in a single transaction is 500. + * + * @param firestore - A reference to the Firestore database to run this + * transaction against. + * @param updateFunction - The function to execute within the transaction + * context. + * @param options - An options object to configure maximum number of attempts to + * commit. + * @returns If the transaction completed successfully or was explicitly aborted + * (the `updateFunction` returned a failed promise), the promise returned by the + * `updateFunction `is returned here. Otherwise, if the transaction failed, a + * rejected promise with the corresponding failure error is returned. + */ +export declare function runTransaction(firestore: Firestore, updateFunction: (transaction: Transaction) => Promise, options?: TransactionOptions): Promise; + +/** + * Interface to schedule periodic tasks within SDK. + */ +declare interface Scheduler { + readonly started: boolean; + start(): void; + stop(): void; +} + +/** Base interface for the Serializer implementation. */ +declare interface Serializer { + readonly useProto3Json: boolean; +} + +/** + * Returns a sentinel used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link @firebase/firestore/lite#(updateDoc:1)} to + * include a server-generated timestamp in the written data. + */ +export declare function serverTimestamp(): FieldValue; + +declare type ServerTimestampBehavior = 'estimate' | 'previous' | 'none'; + +/** + * Writes to the document referred to by the specified `DocumentReference`. If + * the document does not yet exist, it will be created. + * + * The result of this write will only be reflected in document reads that occur + * after the returned promise resolves. If the client is offline, the + * write fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @param reference - A reference to the document to write. + * @param data - A map of the fields and values for the document. + * @throws Error - If the provided input is not a valid Firestore document. + * @returns A `Promise` resolved once the data has been successfully written + * to the backend. + */ +export declare function setDoc(reference: DocumentReference, data: WithFieldValue): Promise; + +/** + * Writes to the document referred to by the specified `DocumentReference`. If + * the document does not yet exist, it will be created. If you provide `merge` + * or `mergeFields`, the provided data can be merged into an existing document. + * + * The result of this write will only be reflected in document reads that occur + * after the returned promise resolves. If the client is offline, the + * write fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @param reference - A reference to the document to write. + * @param data - A map of the fields and values for the document. + * @param options - An object to configure the set behavior. + * @throws Error - If the provided input is not a valid Firestore document. + * @returns A `Promise` resolved once the data has been successfully written + * to the backend. + */ +export declare function setDoc(reference: DocumentReference, data: PartialWithFieldValue, options: SetOptions): Promise; + +/** + * Sets the verbosity of Cloud Firestore logs (debug, error, or silent). + * + * @param logLevel - The verbosity you set for activity and error logging. Can + * be any of the following values: + * + *

    + *
  • `debug` for the most verbose logging level, primarily for + * debugging.
  • + *
  • `error` to log errors only.
  • + *
  • `silent` to turn off logging.
  • + *
+ */ +export declare function setLogLevel(logLevel: LogLevel): void; + +/** + * An options object that configures the behavior of {@link @firebase/firestore/lite#(setDoc:1)}, {@link + * @firebase/firestore/lite#(WriteBatch.set:1)} and {@link @firebase/firestore/lite#(Transaction.set:1)} calls. These calls can be + * configured to perform granular merges instead of overwriting the target + * documents in their entirety by providing a `SetOptions` with `merge: true`. + * + * @param merge - Changes the behavior of a `setDoc()` call to only replace the + * values specified in its data argument. Fields omitted from the `setDoc()` + * call remain untouched. If your input sets any field to an empty map, all + * nested fields are overwritten. + * @param mergeFields - Changes the behavior of `setDoc()` calls to only replace + * the specified field paths. Any field path that is not specified is ignored + * and remains untouched. If your input sets any field to an empty map, all + * nested fields are overwritten. + */ +export declare type SetOptions = { + readonly merge?: boolean; +} | { + readonly mergeFields?: Array; +}; + +/** + * Specifies custom configurations for your Cloud Firestore instance. + * You must set these before invoking any other methods. + */ +export declare interface Settings { + /** The hostname to connect to. */ + host?: string; + /** Whether to use SSL when connecting. */ + ssl?: boolean; + /** + * Whether to skip nested properties that are set to `undefined` during + * object serialization. If set to `true`, these properties are skipped + * and not written to Firestore. If set to `false` or omitted, the SDK + * throws an exception when it encounters properties of type `undefined`. + */ + ignoreUndefinedProperties?: boolean; +} + +/** + * A `SharedClientState` keeps track of the global state of the mutations + * and query targets for all active clients with the same persistence key (i.e. + * project ID and FirebaseApp name). It relays local changes to other clients + * and updates its local state as new state is observed. + * + * `SharedClientState` is primarily used for synchronization in Multi-Tab + * environments. Each tab is responsible for registering its active query + * targets and mutations. `SharedClientState` will then notify the listener + * assigned to `.syncEngine` for updates to mutations and queries that + * originated in other clients. + * + * To receive notifications, `.syncEngine` and `.onlineStateHandler` has to be + * assigned before calling `start()`. + */ +declare interface SharedClientState { + onlineStateHandler: ((onlineState: OnlineState) => void) | null; + sequenceNumberHandler: ((sequenceNumber: ListenSequenceNumber) => void) | null; + /** Registers the Mutation Batch ID of a newly pending mutation. */ + addPendingMutation(batchId: BatchId): void; + /** + * Records that a pending mutation has been acknowledged or rejected. + * Called by the primary client to notify secondary clients of mutation + * results as they come back from the backend. + */ + updateMutationState(batchId: BatchId, state: 'acknowledged' | 'rejected', error?: FirestoreError): void; + /** + * Associates a new Query Target ID with the local Firestore client. Returns + * the new query state for the query (which can be 'current' if the query is + * already associated with another tab). + * + * If the target id is already associated with local client, the method simply + * returns its `QueryTargetState`. + */ + addLocalQueryTarget(targetId: TargetId, addToActiveTargetIds?: boolean): QueryTargetState; + /** Removes the Query Target ID association from the local client. */ + removeLocalQueryTarget(targetId: TargetId): void; + /** Checks whether the target is associated with the local client. */ + isLocalQueryTarget(targetId: TargetId): boolean; + /** + * Processes an update to a query target. + * + * Called by the primary client to notify secondary clients of document + * changes or state transitions that affect the provided query target. + */ + updateQueryState(targetId: TargetId, state: QueryTargetState, error?: FirestoreError): void; + /** + * Removes the target's metadata entry. + * + * Called by the primary client when all clients stopped listening to a query + * target. + */ + clearQueryState(targetId: TargetId): void; + /** + * Gets the active Query Targets IDs for all active clients. + * + * The implementation for this may require O(n) runtime, where 'n' is the size + * of the result set. + */ + getAllActiveQueryTargets(): SortedSet; + /** + * Checks whether the provided target ID is currently being listened to by + * any of the active clients. + * + * The implementation may require O(n*log m) runtime, where 'n' is the number + * of clients and 'm' the number of targets. + */ + isActiveQueryTarget(targetId: TargetId): boolean; + /** + * Starts the SharedClientState, reads existing client data and registers + * listeners for updates to new and existing clients. + */ + start(): Promise; + /** Shuts down the `SharedClientState` and its listeners. */ + shutdown(): void; + /** + * Changes the active user and removes all existing user-specific data. The + * user change does not call back into SyncEngine (for example, no mutations + * will be marked as removed). + */ + handleUserChange(user: User, removedBatchIds: BatchId[], addedBatchIds: BatchId[]): void; + /** Changes the shared online state of all clients. */ + setOnlineState(onlineState: OnlineState): void; + writeSequenceNumber(sequenceNumber: ListenSequenceNumber): void; + /** + * Notifies other clients when remote documents have changed due to loading + * a bundle. + * + * @param collectionGroups The collection groups affected by this bundle. + */ + notifyBundleLoaded(collectionGroups: Set): void; +} + +/** + * Returns true if the provided snapshots are equal. + * + * @param left - A snapshot to compare. + * @param right - A snapshot to compare. + * @returns true if the snapshots are equal. + */ +export declare function snapshotEqual(left: DocumentSnapshot | QuerySnapshot, right: DocumentSnapshot | QuerySnapshot): boolean; + +/** + * A version of a document in Firestore. This corresponds to the version + * timestamp, such as update_time or read_time. + */ +declare class SnapshotVersion { + private timestamp; + static fromTimestamp(value: Timestamp): SnapshotVersion; + static min(): SnapshotVersion; + static max(): SnapshotVersion; + private constructor(); + compareTo(other: SnapshotVersion): number; + isEqual(other: SnapshotVersion): boolean; + /** Returns a number representation of the version for use in spec tests. */ + toMicroseconds(): number; + toString(): string; + toTimestamp(): Timestamp; +} + +declare class SortedMap { + comparator: Comparator; + root: LLRBNode | LLRBEmptyNode; + constructor(comparator: Comparator, root?: LLRBNode | LLRBEmptyNode); + insert(key: K, value: V): SortedMap; + remove(key: K): SortedMap; + get(key: K): V | null; + indexOf(key: K): number; + isEmpty(): boolean; + get size(): number; + minKey(): K | null; + maxKey(): K | null; + inorderTraversal(action: (k: K, v: V) => T): T; + forEach(fn: (k: K, v: V) => void): void; + toString(): string; + reverseTraversal(action: (k: K, v: V) => T): T; + getIterator(): SortedMapIterator; + getIteratorFrom(key: K): SortedMapIterator; + getReverseIterator(): SortedMapIterator; + getReverseIteratorFrom(key: K): SortedMapIterator; +} + +declare class SortedMapIterator { + private isReverse; + private nodeStack; + constructor(node: LLRBNode | LLRBEmptyNode, startKey: K | null, comparator: Comparator, isReverse: boolean); + getNext(): Entry; + hasNext(): boolean; + peek(): Entry | null; +} + +/** + * SortedSet is an immutable (copy-on-write) collection that holds elements + * in order specified by the provided comparator. + * + * NOTE: if provided comparator returns 0 for two elements, we consider them to + * be equal! + */ +declare class SortedSet { + private comparator; + private data; + constructor(comparator: (left: T, right: T) => number); + has(elem: T): boolean; + first(): T | null; + last(): T | null; + get size(): number; + indexOf(elem: T): number; + /** Iterates elements in order defined by "comparator" */ + forEach(cb: (elem: T) => void): void; + /** Iterates over `elem`s such that: range[0] <= elem < range[1]. */ + forEachInRange(range: [T, T], cb: (elem: T) => void): void; + /** + * Iterates over `elem`s such that: start <= elem until false is returned. + */ + forEachWhile(cb: (elem: T) => boolean, start?: T): void; + /** Finds the least element greater than or equal to `elem`. */ + firstAfterOrEqual(elem: T): T | null; + getIterator(): SortedSetIterator; + getIteratorFrom(key: T): SortedSetIterator; + /** Inserts or updates an element */ + add(elem: T): SortedSet; + /** Deletes an element */ + delete(elem: T): SortedSet; + isEmpty(): boolean; + unionWith(other: SortedSet): SortedSet; + isEqual(other: SortedSet): boolean; + toArray(): T[]; + toString(): string; + private copy; +} + +declare class SortedSetIterator { + private iter; + constructor(iter: SortedMapIterator); + getNext(): T; + hasNext(): boolean; +} + +/** + * Creates a {@link QueryStartAtConstraint} that modifies the result set to + * start after the provided document (exclusive). The starting position is + * relative to the order of the query. The document must contain all of the + * fields provided in the orderBy of the query. + * + * @param snapshot - The snapshot of the document to start after. + * @returns A {@link QueryStartAtConstraint} to pass to `query()` + */ +export declare function startAfter(snapshot: DocumentSnapshot): QueryStartAtConstraint; + +/** + * Creates a {@link QueryStartAtConstraint} that modifies the result set to + * start after the provided fields relative to the order of the query. The order + * of the field values must match the order of the order by clauses of the query. + * + * @param fieldValues - The field values to start this query after, in order + * of the query's order by. + * @returns A {@link QueryStartAtConstraint} to pass to `query()` + */ +export declare function startAfter(...fieldValues: unknown[]): QueryStartAtConstraint; + +/** + * Creates a {@link QueryStartAtConstraint} that modifies the result set to + * start at the provided document (inclusive). The starting position is relative + * to the order of the query. The document must contain all of the fields + * provided in the `orderBy` of this query. + * + * @param snapshot - The snapshot of the document to start at. + * @returns A {@link QueryStartAtConstraint} to pass to `query()`. + */ +export declare function startAt(snapshot: DocumentSnapshot): QueryStartAtConstraint; + +/** + * Creates a {@link QueryStartAtConstraint} that modifies the result set to + * start at the provided fields relative to the order of the query. The order of + * the field values must match the order of the order by clauses of the query. + * + * @param fieldValues - The field values to start this query at, in order + * of the query's order by. + * @returns A {@link QueryStartAtConstraint} to pass to `query()`. + */ +export declare function startAt(...fieldValues: unknown[]): QueryStartAtConstraint; + +declare type StructuredQuery = firestoreV1ApiClientInterfaces.StructuredQuery; + +/** + * Create an AggregateField object that can be used to compute the sum of + * a specified field over a range of documents in the result set of a query. + * @param field Specifies the field to sum across the result set. + */ +export declare function sum(field: string | FieldPath): AggregateField; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * SyncEngine is the central controller in the client SDK architecture. It is + * the glue code between the EventManager, LocalStore, and RemoteStore. Some of + * SyncEngine's responsibilities include: + * 1. Coordinating client requests and remote events between the EventManager + * and the local and remote data stores. + * 2. Managing a View object for each query, providing the unified view between + * the local and remote data stores. + * 3. Notifying the RemoteStore when the LocalStore has new mutations in its + * queue that need sending to the backend. + * + * The SyncEngine’s methods should only ever be called by methods running in the + * global async queue. + * + * PORTING NOTE: On Web, SyncEngine does not have an explicit subscribe() + * function. Instead, it directly depends on EventManager's tree-shakeable API + * (via `ensureWatchStream()`). + */ +declare interface SyncEngine { + isPrimaryClient: boolean; +} + +/** + * A Target represents the WatchTarget representation of a Query, which is used + * by the LocalStore and the RemoteStore to keep track of and to execute + * backend queries. While a Query can represent multiple Targets, each Targets + * maps to a single WatchTarget in RemoteStore and a single TargetData entry + * in persistence. + */ +declare interface Target { + readonly path: ResourcePath; + readonly collectionGroup: string | null; + readonly orderBy: OrderBy[]; + readonly filters: Filter[]; + readonly limit: number | null; + readonly startAt: Bound | null; + readonly endAt: Bound | null; +} + +/** + * Represents cached targets received from the remote backend. + * + * The cache is keyed by `Target` and entries in the cache are `TargetData` + * instances. + */ +declare interface TargetCache { + /** + * A global snapshot version representing the last consistent snapshot we + * received from the backend. This is monotonically increasing and any + * snapshots received from the backend prior to this version (e.g. for targets + * resumed with a resume_token) should be suppressed (buffered) until the + * backend has caught up to this snapshot version again. This prevents our + * cache from ever going backwards in time. + * + * This is updated whenever our we get a TargetChange with a read_time and + * empty target_ids. + */ + getLastRemoteSnapshotVersion(transaction: PersistenceTransaction): PersistencePromise; + /** + * @returns The highest sequence number observed, including any that might be + * persisted on-disk. + */ + getHighestSequenceNumber(transaction: PersistenceTransaction): PersistencePromise; + /** + * Call provided function with each `TargetData` that we have cached. + */ + forEachTarget(txn: PersistenceTransaction, f: (q: TargetData) => void): PersistencePromise; + /** + * Set the highest listen sequence number and optionally updates the + * snapshot version of the last consistent snapshot received from the backend + * (see getLastRemoteSnapshotVersion() for more details). + * + * @param highestListenSequenceNumber - The new maximum listen sequence number. + * @param lastRemoteSnapshotVersion - The new snapshot version. Optional. + */ + setTargetsMetadata(transaction: PersistenceTransaction, highestListenSequenceNumber: number, lastRemoteSnapshotVersion?: SnapshotVersion): PersistencePromise; + /** + * Adds an entry in the cache. + * + * The cache key is extracted from `targetData.target`. The key must not already + * exist in the cache. + * + * @param targetData - A TargetData instance to put in the cache. + */ + addTargetData(transaction: PersistenceTransaction, targetData: TargetData): PersistencePromise; + /** + * Updates an entry in the cache. + * + * The cache key is extracted from `targetData.target`. The entry must already + * exist in the cache, and it will be replaced. + * @param targetData - The TargetData to be replaced into the cache. + */ + updateTargetData(transaction: PersistenceTransaction, targetData: TargetData): PersistencePromise; + /** + * Removes the cached entry for the given target data. It is an error to remove + * a target data that does not exist. + * + * Multi-Tab Note: This operation should only be called by the primary client. + */ + removeTargetData(transaction: PersistenceTransaction, targetData: TargetData): PersistencePromise; + /** + * The number of targets currently in the cache. + */ + getTargetCount(transaction: PersistenceTransaction): PersistencePromise; + /** + * Looks up a TargetData entry by target. + * + * @param target - The query target corresponding to the entry to look up. + * @returns The cached TargetData entry, or null if the cache has no entry for + * the target. + */ + getTargetData(transaction: PersistenceTransaction, target: Target): PersistencePromise; + /** + * Adds the given document keys to cached query results of the given target + * ID. + * + * Multi-Tab Note: This operation should only be called by the primary client. + */ + addMatchingKeys(transaction: PersistenceTransaction, keys: DocumentKeySet, targetId: TargetId): PersistencePromise; + /** + * Removes the given document keys from the cached query results of the + * given target ID. + * + * Multi-Tab Note: This operation should only be called by the primary client. + */ + removeMatchingKeys(transaction: PersistenceTransaction, keys: DocumentKeySet, targetId: TargetId): PersistencePromise; + /** + * Removes all the keys in the query results of the given target ID. + * + * Multi-Tab Note: This operation should only be called by the primary client. + */ + removeMatchingKeysForTargetId(transaction: PersistenceTransaction, targetId: TargetId): PersistencePromise; + /** + * Returns the document keys that match the provided target ID. + */ + getMatchingKeysForTargetId(transaction: PersistenceTransaction, targetId: TargetId): PersistencePromise; + /** + * Returns a new target ID that is higher than any query in the cache. If + * there are no queries in the cache, returns the first valid target ID. + * Allocated target IDs are persisted and `allocateTargetId()` will never + * return the same ID twice. + */ + allocateTargetId(transaction: PersistenceTransaction): PersistencePromise; + containsKey(transaction: PersistenceTransaction, key: DocumentKey): PersistencePromise; +} + +/** + * A TargetChange specifies the set of changes for a specific target as part of + * a RemoteEvent. These changes track which documents are added, modified or + * removed, as well as the target's resume token and whether the target is + * marked CURRENT. + * The actual changes *to* documents are not part of the TargetChange since + * documents may be part of multiple targets. + */ +declare class TargetChange { + /** + * An opaque, server-assigned token that allows watching a query to be resumed + * after disconnecting without retransmitting all the data that matches the + * query. The resume token essentially identifies a point in time from which + * the server should resume sending results. + */ + readonly resumeToken: ByteString; + /** + * The "current" (synced) status of this target. Note that "current" + * has special meaning in the RPC protocol that implies that a target is + * both up-to-date and consistent with the rest of the watch stream. + */ + readonly current: boolean; + /** + * The set of documents that were newly assigned to this target as part of + * this remote event. + */ + readonly addedDocuments: DocumentKeySet; + /** + * The set of documents that were already assigned to this target but received + * an update during this remote event. + */ + readonly modifiedDocuments: DocumentKeySet; + /** + * The set of documents that were removed from this target as part of this + * remote event. + */ + readonly removedDocuments: DocumentKeySet; + constructor( + /** + * An opaque, server-assigned token that allows watching a query to be resumed + * after disconnecting without retransmitting all the data that matches the + * query. The resume token essentially identifies a point in time from which + * the server should resume sending results. + */ + resumeToken: ByteString, + /** + * The "current" (synced) status of this target. Note that "current" + * has special meaning in the RPC protocol that implies that a target is + * both up-to-date and consistent with the rest of the watch stream. + */ + current: boolean, + /** + * The set of documents that were newly assigned to this target as part of + * this remote event. + */ + addedDocuments: DocumentKeySet, + /** + * The set of documents that were already assigned to this target but received + * an update during this remote event. + */ + modifiedDocuments: DocumentKeySet, + /** + * The set of documents that were removed from this target as part of this + * remote event. + */ + removedDocuments: DocumentKeySet); + /** + * This method is used to create a synthesized TargetChanges that can be used to + * apply a CURRENT status change to a View (for queries executed in a different + * tab) or for new queries (to raise snapshots with correct CURRENT status). + */ + static createSynthesizedTargetChangeForCurrentChange(targetId: TargetId, current: boolean, resumeToken: ByteString): TargetChange; +} + +declare type TargetChangeTargetChangeType = 'NO_CHANGE' | 'ADD' | 'REMOVE' | 'CURRENT' | 'RESET'; + +/** + * An immutable set of metadata that the local store tracks for each target. + */ +declare class TargetData { + /** The target being listened to. */ + readonly target: Target; + /** + * The target ID to which the target corresponds; Assigned by the + * LocalStore for user listens and by the SyncEngine for limbo watches. + */ + readonly targetId: TargetId; + /** The purpose of the target. */ + readonly purpose: TargetPurpose; + /** + * The sequence number of the last transaction during which this target data + * was modified. + */ + readonly sequenceNumber: ListenSequenceNumber; + /** The latest snapshot version seen for this target. */ + readonly snapshotVersion: SnapshotVersion; + /** + * The maximum snapshot version at which the associated view + * contained no limbo documents. + */ + readonly lastLimboFreeSnapshotVersion: SnapshotVersion; + /** + * An opaque, server-assigned token that allows watching a target to be + * resumed after disconnecting without retransmitting all the data that + * matches the target. The resume token essentially identifies a point in + * time from which the server should resume sending results. + */ + readonly resumeToken: ByteString; + /** + * The number of documents that last matched the query at the resume token or + * read time. Documents are counted only when making a listen request with + * resume token or read time, otherwise, keep it null. + */ + readonly expectedCount: number | null; + constructor( + /** The target being listened to. */ + target: Target, + /** + * The target ID to which the target corresponds; Assigned by the + * LocalStore for user listens and by the SyncEngine for limbo watches. + */ + targetId: TargetId, + /** The purpose of the target. */ + purpose: TargetPurpose, + /** + * The sequence number of the last transaction during which this target data + * was modified. + */ + sequenceNumber: ListenSequenceNumber, + /** The latest snapshot version seen for this target. */ + snapshotVersion?: SnapshotVersion, + /** + * The maximum snapshot version at which the associated view + * contained no limbo documents. + */ + lastLimboFreeSnapshotVersion?: SnapshotVersion, + /** + * An opaque, server-assigned token that allows watching a target to be + * resumed after disconnecting without retransmitting all the data that + * matches the target. The resume token essentially identifies a point in + * time from which the server should resume sending results. + */ + resumeToken?: ByteString, + /** + * The number of documents that last matched the query at the resume token or + * read time. Documents are counted only when making a listen request with + * resume token or read time, otherwise, keep it null. + */ + expectedCount?: number | null); + /** Creates a new target data instance with an updated sequence number. */ + withSequenceNumber(sequenceNumber: number): TargetData; + /** + * Creates a new target data instance with an updated resume token and + * snapshot version. + */ + withResumeToken(resumeToken: ByteString, snapshotVersion: SnapshotVersion): TargetData; + /** + * Creates a new target data instance with an updated expected count. + */ + withExpectedCount(expectedCount: number): TargetData; + /** + * Creates a new target data instance with an updated last limbo free + * snapshot version number. + */ + withLastLimboFreeSnapshotVersion(lastLimboFreeSnapshotVersion: SnapshotVersion): TargetData; +} + +/** + * A locally-assigned ID used to refer to a target being watched via the + * Watch service. + */ +declare type TargetId = number; + +/** An enumeration of the different purposes we have for targets. */ +declare const enum TargetPurpose { + /** A regular, normal query target. */ + Listen = "TargetPurposeListen", + /** + * The query target was used to refill a query after an existence filter + * mismatch. + */ + ExistenceFilterMismatch = "TargetPurposeExistenceFilterMismatch", + /** + * The query target was used if the query is the result of a false positive in + * the bloom filter. + */ + ExistenceFilterMismatchBloom = "TargetPurposeExistenceFilterMismatchBloom", + /** The query target was used to resolve a limbo document. */ + LimboResolution = "TargetPurposeLimboResolution" +} + +/** + * Terminates the provided `Firestore` instance. + * + * After calling `terminate()` only the `clearIndexedDbPersistence()` functions + * may be used. Any other function will throw a `FirestoreError`. Termination + * does not cancel any pending writes, and any promises that are awaiting a + * response from the server will not be resolved. + * + * To restart after termination, create a new instance of `Firestore` with + * {@link (getFirestore:1)}. + * + * Note: Under normal circumstances, calling `terminate()` is not required. This + * function is useful only when you want to force this instance to release all of + * its resources or in combination with {@link clearIndexedDbPersistence} to + * ensure that all local state is destroyed between test runs. + * + * @param firestore - The `Firestore` instance to terminate. + * @returns A `Promise` that is resolved when the instance has been successfully + * terminated. + */ +export declare function terminate(firestore: Firestore): Promise; + +/** + * Wellknown "timer" IDs used when scheduling delayed operations on the + * AsyncQueue. These IDs can then be used from tests to check for the presence + * of operations or to run them early. + * + * The string values are used when encoding these timer IDs in JSON spec tests. + */ +declare const enum TimerId { + /** All can be used with runDelayedOperationsEarly() to run all timers. */ + All = "all", + /** + * The following 5 timers are used in persistent_stream.ts for the listen and + * write streams. The "Idle" timer is used to close the stream due to + * inactivity. The "ConnectionBackoff" timer is used to restart a stream once + * the appropriate backoff delay has elapsed. The health check is used to mark + * a stream healthy if it has not received an error during its initial setup. + */ + ListenStreamIdle = "listen_stream_idle", + ListenStreamConnectionBackoff = "listen_stream_connection_backoff", + WriteStreamIdle = "write_stream_idle", + WriteStreamConnectionBackoff = "write_stream_connection_backoff", + HealthCheckTimeout = "health_check_timeout", + /** + * A timer used in online_state_tracker.ts to transition from + * OnlineState.Unknown to Offline after a set timeout, rather than waiting + * indefinitely for success or failure. + */ + OnlineStateTimeout = "online_state_timeout", + /** + * A timer used to update the client metadata in IndexedDb, which is used + * to determine the primary leaseholder. + */ + ClientMetadataRefresh = "client_metadata_refresh", + /** A timer used to periodically attempt LRU Garbage collection */ + LruGarbageCollection = "lru_garbage_collection", + /** + * A timer used to retry transactions. Since there can be multiple concurrent + * transactions, multiple of these may be in the queue at a given time. + */ + TransactionRetry = "transaction_retry", + /** + * A timer used to retry operations scheduled via retryable AsyncQueue + * operations. + */ + AsyncQueueRetry = "async_queue_retry", + /** + * A timer used to periodically attempt index backfill. + */ + IndexBackfill = "index_backfill" +} + +/** + * A `Timestamp` represents a point in time independent of any time zone or + * calendar, represented as seconds and fractions of seconds at nanosecond + * resolution in UTC Epoch time. + * + * It is encoded using the Proleptic Gregorian Calendar which extends the + * Gregorian calendar backwards to year one. It is encoded assuming all minutes + * are 60 seconds long, i.e. leap seconds are "smeared" so that no leap second + * table is needed for interpretation. Range is from 0001-01-01T00:00:00Z to + * 9999-12-31T23:59:59.999999999Z. + * + * For examples and further specifications, refer to the + * {@link https://github.com/google/protobuf/blob/master/src/google/protobuf/timestamp.proto | Timestamp definition}. + */ +export declare class Timestamp { + /** + * The number of seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z. + */ + readonly seconds: number; + /** + * The fractions of a second at nanosecond resolution.* + */ + readonly nanoseconds: number; + /** + * Creates a new timestamp with the current date, with millisecond precision. + * + * @returns a new timestamp representing the current date. + */ + static now(): Timestamp; + /** + * Creates a new timestamp from the given date. + * + * @param date - The date to initialize the `Timestamp` from. + * @returns A new `Timestamp` representing the same point in time as the given + * date. + */ + static fromDate(date: Date): Timestamp; + /** + * Creates a new timestamp from the given number of milliseconds. + * + * @param milliseconds - Number of milliseconds since Unix epoch + * 1970-01-01T00:00:00Z. + * @returns A new `Timestamp` representing the same point in time as the given + * number of milliseconds. + */ + static fromMillis(milliseconds: number): Timestamp; + /** + * Creates a new timestamp. + * + * @param seconds - The number of seconds of UTC time since Unix epoch + * 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to + * 9999-12-31T23:59:59Z inclusive. + * @param nanoseconds - The non-negative fractions of a second at nanosecond + * resolution. Negative second values with fractions must still have + * non-negative nanoseconds values that count forward in time. Must be + * from 0 to 999,999,999 inclusive. + */ + constructor( + /** + * The number of seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z. + */ + seconds: number, + /** + * The fractions of a second at nanosecond resolution.* + */ + nanoseconds: number); + /** + * Converts a `Timestamp` to a JavaScript `Date` object. This conversion + * causes a loss of precision since `Date` objects only support millisecond + * precision. + * + * @returns JavaScript `Date` object representing the same point in time as + * this `Timestamp`, with millisecond precision. + */ + toDate(): Date; + /** + * Converts a `Timestamp` to a numeric timestamp (in milliseconds since + * epoch). This operation causes a loss of precision. + * + * @returns The point in time corresponding to this timestamp, represented as + * the number of milliseconds since Unix epoch 1970-01-01T00:00:00Z. + */ + toMillis(): number; + _compareTo(other: Timestamp): number; + /** + * Returns true if this `Timestamp` is equal to the provided one. + * + * @param other - The `Timestamp` to compare against. + * @returns true if this `Timestamp` is equal to the provided one. + */ + isEqual(other: Timestamp): boolean; + /** Returns a textual representation of this `Timestamp`. */ + toString(): string; + static _jsonSchemaVersion: string; + static _jsonSchema: { + type: Property<"string">; + seconds: Property<"number">; + nanoseconds: Property<"number">; + }; + /** + * Returns a JSON-serializable representation of this `Timestamp`. + */ + toJSON(): { + seconds: number; + nanoseconds: number; + type: string; + }; + /** + * Builds a `Timestamp` instance from a JSON object created by {@link Timestamp.toJSON}. + */ + static fromJSON(json: object): Timestamp; + /** + * Converts this object to a primitive string, which allows `Timestamp` objects + * to be compared using the `>`, `<=`, `>=` and `>` operators. + */ + valueOf(): string; +} + +declare type Timestamp_2 = string | { + seconds?: string | number; + nanos?: number; +}; + +declare interface Token { + /** Type of token. */ + type: TokenType; + /** + * The user with which the token is associated (used for persisting user + * state on disk, etc.). + * This will be null for Tokens of the type 'AppCheck'. + */ + user?: User; + /** Header values to set for this token */ + headers: Map; +} + +declare type TokenType = 'OAuth' | 'FirstParty' | 'AppCheck'; + +/** + * A reference to a transaction. + * + * The `Transaction` object passed to a transaction's `updateFunction` provides + * the methods to read and write data within the transaction context. See + * {@link runTransaction}. + */ +export declare class Transaction { + protected readonly _firestore: Firestore; + private readonly _transaction; + private readonly _dataReader; + /** @hideconstructor */ + constructor(_firestore: Firestore, _transaction: Transaction_2); + /** + * Reads the document referenced by the provided {@link DocumentReference}. + * + * @param documentRef - A reference to the document to be read. + * @returns A `DocumentSnapshot` with the read data. + */ + get(documentRef: DocumentReference): Promise>; + /** + * Writes to the document referred to by the provided {@link + * DocumentReference}. If the document does not exist yet, it will be created. + * + * @param documentRef - A reference to the document to be set. + * @param data - An object of the fields and values for the document. + * @throws Error - If the provided input is not a valid Firestore document. + * @returns This `Transaction` instance. Used for chaining method calls. + */ + set(documentRef: DocumentReference, data: WithFieldValue): this; + /** + * Writes to the document referred to by the provided {@link + * DocumentReference}. If the document does not exist yet, it will be created. + * If you provide `merge` or `mergeFields`, the provided data can be merged + * into an existing document. + * + * @param documentRef - A reference to the document to be set. + * @param data - An object of the fields and values for the document. + * @param options - An object to configure the set behavior. + * @throws Error - If the provided input is not a valid Firestore document. + * @returns This `Transaction` instance. Used for chaining method calls. + */ + set(documentRef: DocumentReference, data: PartialWithFieldValue, options: SetOptions): this; + /** + * Updates fields in the document referred to by the provided {@link + * DocumentReference}. The update will fail if applied to a document that does + * not exist. + * + * @param documentRef - A reference to the document to be updated. + * @param data - An object containing the fields and values with which to + * update the document. Fields can contain dots to reference nested fields + * within the document. + * @throws Error - If the provided input is not valid Firestore data. + * @returns This `Transaction` instance. Used for chaining method calls. + */ + update(documentRef: DocumentReference, data: UpdateData): this; + /** + * Updates fields in the document referred to by the provided {@link + * DocumentReference}. The update will fail if applied to a document that does + * not exist. + * + * Nested fields can be updated by providing dot-separated field path + * strings or by providing `FieldPath` objects. + * + * @param documentRef - A reference to the document to be updated. + * @param field - The first field to update. + * @param value - The first value. + * @param moreFieldsAndValues - Additional key/value pairs. + * @throws Error - If the provided input is not valid Firestore data. + * @returns This `Transaction` instance. Used for chaining method calls. + */ + update(documentRef: DocumentReference, field: string | FieldPath, value: unknown, ...moreFieldsAndValues: unknown[]): this; + /** + * Deletes the document referred to by the provided {@link DocumentReference}. + * + * @param documentRef - A reference to the document to be deleted. + * @returns This `Transaction` instance. Used for chaining method calls. + */ + delete(documentRef: DocumentReference): this; +} + +/** + * Internal transaction object responsible for accumulating the mutations to + * perform and the base versions for any documents read. + */ +declare class Transaction_2 { + private datastore; + private readVersions; + private mutations; + private committed; + /** + * A deferred usage error that occurred previously in this transaction that + * will cause the transaction to fail once it actually commits. + */ + private lastTransactionError; + /** + * Set of documents that have been written in the transaction. + * + * When there's more than one write to the same key in a transaction, any + * writes after the first are handled differently. + */ + private writtenDocs; + constructor(datastore: Datastore); + lookup(keys: DocumentKey[]): Promise; + set(key: DocumentKey, data: ParsedSetData): void; + update(key: DocumentKey, data: ParsedUpdateData): void; + delete(key: DocumentKey): void; + commit(): Promise; + private recordVersion; + /** + * Returns the version of this document when it was read in this transaction, + * as a precondition, or no precondition if it was not read. + */ + private precondition; + /** + * Returns the precondition for a document if the operation is an update. + */ + private preconditionForUpdate; + private write; + private ensureCommitNotCalled; +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Options to customize transaction behavior. + */ +export declare interface TransactionOptions { + /** Maximum number of attempts to commit, after which transaction fails. Default is 5. */ + readonly maxAttempts?: number; +} + +/** Used to represent a field transform on a mutation. */ +declare class TransformOperation { + private _; +} + +/* Excluded from this release type: TSType */ + +declare type UnaryFilterOp = 'OPERATOR_UNSPECIFIED' | 'IS_NAN' | 'IS_NULL' | 'IS_NOT_NAN' | 'IS_NOT_NULL'; + +/** + * Given a union type `U = T1 | T2 | ...`, returns an intersected type + * `(T1 & T2 & ...)`. + * + * Uses distributive conditional types and inference from conditional types. + * This works because multiple candidates for the same type variable in + * contra-variant positions causes an intersection type to be inferred. + * https://www.typescriptlang.org/docs/handbook/advanced-types.html#type-inference-in-conditional-types + * https://stackoverflow.com/questions/50374908/transform-union-type-to-intersection-type + */ +export declare type UnionToIntersection = (U extends unknown ? (k: U) => void : never) extends (k: infer I) => void ? I : never; + +/** + * An untyped Firestore Data Converter interface that is shared between the + * lite, firestore-exp and classic SDK. + */ +declare interface UntypedFirestoreDataConverter { + toFirestore(modelObject: WithFieldValue): WithFieldValue; + toFirestore(modelObject: PartialWithFieldValue, options: SetOptions_2): PartialWithFieldValue; + fromFirestore(snapshot: unknown, options?: unknown): AppModelType; +} + +/** + * Update data (for use with {@link (updateDoc:1)}) that consists of field paths + * (e.g. 'foo' or 'foo.baz') mapped to values. Fields that contain dots + * reference nested fields within the document. FieldValues can be passed in + * as property values. + */ +export declare type UpdateData = T extends Primitive ? T : T extends {} ? { + [K in keyof T]?: UpdateData | FieldValue; +} & NestedUpdateFields : Partial; + +/** + * Updates fields in the document referred to by the specified + * `DocumentReference`. The update will fail if applied to a document that does + * not exist. + * + * The result of this update will only be reflected in document reads that occur + * after the returned promise resolves. If the client is offline, the + * update fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @param reference - A reference to the document to update. + * @param data - An object containing the fields and values with which to + * update the document. Fields can contain dots to reference nested fields + * within the document. + * @throws Error - If the provided input is not valid Firestore data. + * @returns A `Promise` resolved once the data has been successfully written + * to the backend. + */ +export declare function updateDoc(reference: DocumentReference, data: UpdateData): Promise; + +/** + * Updates fields in the document referred to by the specified + * `DocumentReference` The update will fail if applied to a document that does + * not exist. + * + * Nested fields can be updated by providing dot-separated field path + * strings or by providing `FieldPath` objects. + * + * The result of this update will only be reflected in document reads that occur + * after the returned promise resolves. If the client is offline, the + * update fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @param reference - A reference to the document to update. + * @param field - The first field to update. + * @param value - The first value. + * @param moreFieldsAndValues - Additional key value pairs. + * @throws Error - If the provided input is not valid Firestore data. + * @returns A `Promise` resolved once the data has been successfully written + * to the backend. + */ +export declare function updateDoc(reference: DocumentReference, field: string | FieldPath, value: unknown, ...moreFieldsAndValues: unknown[]): Promise; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Simple wrapper around a nullable UID. Mostly exists to make code more + * readable. + */ +declare class User { + readonly uid: string | null; + /** A user with a null UID. */ + static readonly UNAUTHENTICATED: User; + static readonly GOOGLE_CREDENTIALS: User; + static readonly FIRST_PARTY: User; + static readonly MOCK_USER: User; + constructor(uid: string | null); + isAuthenticated(): boolean; + /** + * Returns a key representing this user, suitable for inclusion in a + * dictionary. + */ + toKey(): string; + isEqual(otherUser: User): boolean; +} + +declare type Value = firestoreV1ApiClientInterfaces.Value; + +declare type ValueNullValue = 'NULL_VALUE'; + +/** + * Creates a new `VectorValue` constructed with a copy of the given array of numbers. + * + * @param values - Create a `VectorValue` instance with a copy of this array of numbers. + * + * @returns A new `VectorValue` constructed with a copy of the given array of numbers. + */ +export declare function vector(values?: number[]): VectorValue; + +/** + * Represents a vector type in Firestore documents. + * Create an instance with {@link vector}. + * + * @class VectorValue + */ +export declare class VectorValue { + private readonly _values; + /* Excluded from this release type: __constructor */ + /** + * Returns a copy of the raw number array form of the vector. + */ + toArray(): number[]; + /** + * Returns `true` if the two `VectorValue` values have the same raw number arrays, returns `false` otherwise. + */ + isEqual(other: VectorValue): boolean; + static _jsonSchemaVersion: string; + static _jsonSchema: { + type: Property<"string">; + vectorValues: Property<"object">; + }; + /** + * Returns a JSON-serializable representation of this `VectorValue` instance. + * + * @returns a JSON representation of this object. + */ + toJSON(): object; + /** + * Builds a `VectorValue` instance from a JSON object created by {@link VectorValue.toJSON}. + * + * @param json a JSON object represention of a `VectorValue` instance. + * @returns an instance of {@link VectorValue} if the JSON object could be parsed. Throws a + * {@link FirestoreError} if an error occurs. + */ + static fromJSON(json: object): VectorValue; +} + +declare class ViewSnapshot { + readonly query: Query_2; + readonly docs: DocumentSet; + readonly oldDocs: DocumentSet; + readonly docChanges: DocumentViewChange[]; + readonly mutatedKeys: DocumentKeySet; + readonly fromCache: boolean; + readonly syncStateChanged: boolean; + readonly excludesMetadataChanges: boolean; + readonly hasCachedResults: boolean; + constructor(query: Query_2, docs: DocumentSet, oldDocs: DocumentSet, docChanges: DocumentViewChange[], mutatedKeys: DocumentKeySet, fromCache: boolean, syncStateChanged: boolean, excludesMetadataChanges: boolean, hasCachedResults: boolean); + /** Returns a view snapshot as if all documents in the snapshot were added. */ + static fromInitialDocuments(query: Query_2, documents: DocumentSet, mutatedKeys: DocumentKeySet, fromCache: boolean, hasCachedResults: boolean): ViewSnapshot; + get hasPendingWrites(): boolean; + isEqual(other: ViewSnapshot): boolean; +} + +/** + * Creates a {@link QueryFieldFilterConstraint} that enforces that documents + * must contain the specified field and that the value should satisfy the + * relation constraint provided. + * + * @param fieldPath - The path to compare + * @param opStr - The operation string (e.g "<", "<=", "==", "<", + * "<=", "!="). + * @param value - The value for comparison + * @returns The created {@link QueryFieldFilterConstraint}. + */ +export declare function where(fieldPath: string | FieldPath, opStr: WhereFilterOp, value: unknown): QueryFieldFilterConstraint; + +/** + * Filter conditions in a {@link where} clause are specified using the + * strings '<', '<=', '==', '!=', '>=', '>', 'array-contains', 'in', + * 'array-contains-any', and 'not-in'. + */ +export declare type WhereFilterOp = '<' | '<=' | '==' | '!=' | '>=' | '>' | 'array-contains' | 'in' | 'array-contains-any' | 'not-in'; + +/** + * Allows FieldValues to be passed in as a property value while maintaining + * type safety. + */ +export declare type WithFieldValue = T | (T extends Primitive ? T : T extends {} ? { + [K in keyof T]: WithFieldValue | FieldValue; +} : never); + +/** + * A write batch, used to perform multiple writes as a single atomic unit. + * + * A `WriteBatch` object can be acquired by calling {@link writeBatch}. It + * provides methods for adding writes to the write batch. None of the writes + * will be committed (or visible locally) until {@link WriteBatch.commit} is + * called. + */ +export declare class WriteBatch { + private readonly _firestore; + private readonly _commitHandler; + private readonly _dataReader; + private _mutations; + private _committed; + /** @hideconstructor */ + constructor(_firestore: Firestore, _commitHandler: (m: Mutation[]) => Promise); + /** + * Writes to the document referred to by the provided {@link + * DocumentReference}. If the document does not exist yet, it will be created. + * + * @param documentRef - A reference to the document to be set. + * @param data - An object of the fields and values for the document. + * @returns This `WriteBatch` instance. Used for chaining method calls. + */ + set(documentRef: DocumentReference, data: WithFieldValue): WriteBatch; + /** + * Writes to the document referred to by the provided {@link + * DocumentReference}. If the document does not exist yet, it will be created. + * If you provide `merge` or `mergeFields`, the provided data can be merged + * into an existing document. + * + * @param documentRef - A reference to the document to be set. + * @param data - An object of the fields and values for the document. + * @param options - An object to configure the set behavior. + * @throws Error - If the provided input is not a valid Firestore document. + * @returns This `WriteBatch` instance. Used for chaining method calls. + */ + set(documentRef: DocumentReference, data: PartialWithFieldValue, options: SetOptions): WriteBatch; + /** + * Updates fields in the document referred to by the provided {@link + * DocumentReference}. The update will fail if applied to a document that does + * not exist. + * + * @param documentRef - A reference to the document to be updated. + * @param data - An object containing the fields and values with which to + * update the document. Fields can contain dots to reference nested fields + * within the document. + * @throws Error - If the provided input is not valid Firestore data. + * @returns This `WriteBatch` instance. Used for chaining method calls. + */ + update(documentRef: DocumentReference, data: UpdateData): WriteBatch; + /** + * Updates fields in the document referred to by this {@link + * DocumentReference}. The update will fail if applied to a document that does + * not exist. + * + * Nested fields can be update by providing dot-separated field path strings + * or by providing `FieldPath` objects. + * + * @param documentRef - A reference to the document to be updated. + * @param field - The first field to update. + * @param value - The first value. + * @param moreFieldsAndValues - Additional key value pairs. + * @throws Error - If the provided input is not valid Firestore data. + * @returns This `WriteBatch` instance. Used for chaining method calls. + */ + update(documentRef: DocumentReference, field: string | FieldPath, value: unknown, ...moreFieldsAndValues: unknown[]): WriteBatch; + /** + * Deletes the document referred to by the provided {@link DocumentReference}. + * + * @param documentRef - A reference to the document to be deleted. + * @returns This `WriteBatch` instance. Used for chaining method calls. + */ + delete(documentRef: DocumentReference): WriteBatch; + /** + * Commits all of the writes in this write batch as a single atomic unit. + * + * The result of these writes will only be reflected in document reads that + * occur after the returned promise resolves. If the client is offline, the + * write fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @returns A `Promise` resolved once all of the writes in the batch have been + * successfully written to the backend as an atomic unit (note that it won't + * resolve while you're offline). + */ + commit(): Promise; + private _verifyNotCommitted; +} + +/** + * Creates a write batch, used for performing multiple writes as a single + * atomic operation. The maximum number of writes allowed in a single WriteBatch + * is 500. + * + * The result of these writes will only be reflected in document reads that + * occur after the returned promise resolves. If the client is offline, the + * write fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @returns A `WriteBatch` that can be used to atomically execute multiple + * writes. + */ +export declare function writeBatch(firestore: Firestore): WriteBatch; + +export { } -- cgit v1.2.3