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AS,IAAI,OAAO,SAiD1B,OAhDK,KAAK,YAAY,IAAI,EAAY,GAAc,MAAO,KACvD,EAAI,SAAS,QAAQ,0BAA2B,EAAY,sBAAuB,GACnF,KAAK,WACA,cACA,SAAS,aAAa,YAC3B,IACI,MAAM,EAAS,EACT,EAAY,GAAY,GACxB,EAAY,GAAY,EAAS,GACjC,EAAY,IAAI,SAAS,UAAU,CACrC,YAAY,EACZ,UAAW,CAAC,EAAO,EAAU,MACzB,EAAI,SAAS,QAAQ,0BAA2B,EAAY,wBAAyB,GACrF,IACqB,IAAjB,EACA,KAAK,WACA,cACA,SAAS,aAAa,8BAEtB,EAtBS,KAsBwC,GACtD,KAAK,WACA,cACA,SAAS,aAAa,eAAwB,eAEvD,GAAU,IAGlB,EAAO,KAAK,GACZ,MAAM,EAAW,IAAI,OAAO,SACtB,QAAqB,KAAK,kBAAkB,EAAQ,EAAU,EAAY,EAAgB,OAAU,GAa1G,OAZA,EAAa,GAAG,OAAO,KACnB,EAAO,MACP,KAAK,WACA,cACA,SAAS,aAAa,eAAyB,CAChD,CAAC,aAAa,6BAA8B,GAC9C,IAEN,EAAO,QAAQ,GAIR,EAAS,OACpB,CACA,MAAO,GACH,EAAO,OAAO,EAClB,KAEG,EAAO,OAAO,GAE7B,EAEJ,QAAQ,UAAY,UA6CpB,QAAQ,QAAU,UAIlB,MAAM,gBAAkB,OAAO,QAC/B,OAAO,QAAU,UACjB,OAAO,QAAU,OAAO,OAAO,OAAO,QAAS,iBAS/C,OAAO,eAAe,OAAO,QAAS,UAAW,CAG7C,IAAK,IAAM,QAAQ,eAUvB,OAAO,eAAe,OAAO,QAAS,KAAM,CAGxC,IAAK,IAAM,QAAQ,UAUvB,OAAO,eAAe,OAAO,QAAS,aAAc,CAGhD,IAAK,IAAM,QAAQ,cAAc","file":"/npm/@google-cloud/firestore@8.0.0/build/src/index.js","sourceRoot":"","sourcesContent":["/**\n * Minified by jsDelivr using Terser v5.39.0.\n * Original file: /npm/@google-cloud/firestore@8.0.0/build/src/index.js\n *\n * Do NOT use SRI with dynamically generated files! More information: https://www.jsdelivr.com/using-sri-with-dynamic-files\n */\n","\"use strict\";\n/*!\n * Copyright 2017 Google Inc. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.Firestore = exports.DEFAULT_MAX_IDLE_CHANNELS = exports.DEFAULT_MAX_TRANSACTION_ATTEMPTS = exports.MAX_REQUEST_RETRIES = exports.AggregateField = exports.Aggregate = exports.setLogFunction = exports.QueryPartition = exports.CollectionGroup = exports.GeoPoint = exports.FieldPath = exports.DocumentChange = exports.Timestamp = exports.Transaction = exports.WriteResult = exports.WriteBatch = exports.Filter = exports.VectorValue = exports.FieldValue = exports.QueryDocumentSnapshot = exports.DocumentSnapshot = exports.BulkWriter = exports.Query = exports.QuerySnapshot = exports.DocumentReference = exports.CollectionReference = void 0;\nconst stream_1 = require(\"stream\");\nconst url_1 = require(\"url\");\nconst backoff_1 = require(\"./backoff\");\nconst bulk_writer_1 = require(\"./bulk-writer\");\nconst bundle_1 = require(\"./bundle\");\nconst convert_1 = require(\"./convert\");\nconst document_reader_1 = require(\"./document-reader\");\nconst document_1 = require(\"./document\");\nconst logger_1 = require(\"./logger\");\nconst path_1 = require(\"./path\");\nconst pool_1 = require(\"./pool\");\nconst collection_reference_1 = require(\"./reference/collection-reference\");\nconst document_reference_1 = require(\"./reference/document-reference\");\nconst serializer_1 = require(\"./serializer\");\nconst timestamp_1 = require(\"./timestamp\");\nconst transaction_1 = require(\"./transaction\");\nconst util_1 = require(\"./util\");\nconst validate_1 = require(\"./validate\");\nconst write_batch_1 = require(\"./write-batch\");\nconst firestore_client_config_json_1 = require(\"./v1/firestore_client_config.json\");\nconst serviceConfig = firestore_client_config_json_1.interfaces['google.firestore.v1.Firestore'];\nconst collection_group_1 = require(\"./collection-group\");\nObject.defineProperty(exports, \"CollectionGroup\", { enumerable: true, get: function () { return collection_group_1.CollectionGroup; } });\nconst recursive_delete_1 = require(\"./recursive-delete\");\nconst trace_util_1 = require(\"./telemetry/trace-util\");\nconst disabled_trace_util_1 = require(\"./telemetry/disabled-trace-util\");\nconst enabled_trace_util_1 = require(\"./telemetry/enabled-trace-util\");\nvar collection_reference_2 = require(\"./reference/collection-reference\");\nObject.defineProperty(exports, \"CollectionReference\", { enumerable: true, get: function () { return collection_reference_2.CollectionReference; } });\nvar document_reference_2 = require(\"./reference/document-reference\");\nObject.defineProperty(exports, \"DocumentReference\", { enumerable: true, get: function () { return document_reference_2.DocumentReference; } });\nvar query_snapshot_1 = require(\"./reference/query-snapshot\");\nObject.defineProperty(exports, \"QuerySnapshot\", { enumerable: true, get: function () { return query_snapshot_1.QuerySnapshot; } });\nvar query_1 = require(\"./reference/query\");\nObject.defineProperty(exports, \"Query\", { enumerable: true, get: function () { return query_1.Query; } });\nvar bulk_writer_2 = require(\"./bulk-writer\");\nObject.defineProperty(exports, \"BulkWriter\", { enumerable: true, get: function () { return bulk_writer_2.BulkWriter; } });\nvar document_2 = require(\"./document\");\nObject.defineProperty(exports, \"DocumentSnapshot\", { enumerable: true, get: function () { return document_2.DocumentSnapshot; } });\nObject.defineProperty(exports, \"QueryDocumentSnapshot\", { enumerable: true, get: function () { return document_2.QueryDocumentSnapshot; } });\nvar field_value_1 = require(\"./field-value\");\nObject.defineProperty(exports, \"FieldValue\", { enumerable: true, get: function () { return field_value_1.FieldValue; } });\nObject.defineProperty(exports, \"VectorValue\", { enumerable: true, get: function () { return field_value_1.VectorValue; } });\nvar filter_1 = require(\"./filter\");\nObject.defineProperty(exports, \"Filter\", { enumerable: true, get: function () { return filter_1.Filter; } });\nvar write_batch_2 = require(\"./write-batch\");\nObject.defineProperty(exports, \"WriteBatch\", { enumerable: true, get: function () { return write_batch_2.WriteBatch; } });\nObject.defineProperty(exports, \"WriteResult\", { enumerable: true, get: function () { return write_batch_2.WriteResult; } });\nvar transaction_2 = require(\"./transaction\");\nObject.defineProperty(exports, \"Transaction\", { enumerable: true, get: function () { return transaction_2.Transaction; } });\nvar timestamp_2 = require(\"./timestamp\");\nObject.defineProperty(exports, \"Timestamp\", { enumerable: true, get: function () { return timestamp_2.Timestamp; } });\nvar document_change_1 = require(\"./document-change\");\nObject.defineProperty(exports, \"DocumentChange\", { enumerable: true, get: function () { return document_change_1.DocumentChange; } });\nvar path_2 = require(\"./path\");\nObject.defineProperty(exports, \"FieldPath\", { enumerable: true, get: function () { return path_2.FieldPath; } });\nvar geo_point_1 = require(\"./geo-point\");\nObject.defineProperty(exports, \"GeoPoint\", { enumerable: true, get: function () { return geo_point_1.GeoPoint; } });\nvar query_partition_1 = require(\"./query-partition\");\nObject.defineProperty(exports, \"QueryPartition\", { enumerable: true, get: function () { return query_partition_1.QueryPartition; } });\nvar logger_2 = require(\"./logger\");\nObject.defineProperty(exports, \"setLogFunction\", { enumerable: true, get: function () { return logger_2.setLogFunction; } });\nvar aggregate_1 = require(\"./aggregate\");\nObject.defineProperty(exports, \"Aggregate\", { enumerable: true, get: function () { return aggregate_1.Aggregate; } });\nObject.defineProperty(exports, \"AggregateField\", { enumerable: true, get: function () { return aggregate_1.AggregateField; } });\nconst libVersion = require('../../package.json').version;\n(0, logger_1.setLibVersion)(libVersion);\n/*!\n * DO NOT REMOVE THE FOLLOWING NAMESPACE DEFINITIONS\n */\n/**\n * @namespace google.protobuf\n */\n/**\n * @namespace google.rpc\n */\n/**\n * @namespace google.longrunning\n */\n/**\n * @namespace google.firestore.v1\n */\n/**\n * @namespace google.firestore.v1beta1\n */\n/**\n * @namespace google.firestore.admin.v1\n */\n/*!\n * HTTP header for the resource prefix to improve routing and project isolation\n * by the backend.\n */\nconst CLOUD_RESOURCE_HEADER = 'google-cloud-resource-prefix';\n/**\n * The maximum number of times to retry idempotent requests.\n * @private\n */\nexports.MAX_REQUEST_RETRIES = 5;\n/**\n * The maximum number of times to attempt a transaction before failing.\n * @private\n */\nexports.DEFAULT_MAX_TRANSACTION_ATTEMPTS = 5;\n/*!\n * The default number of idle GRPC channel to keep.\n */\nexports.DEFAULT_MAX_IDLE_CHANNELS = 1;\n/*!\n * The maximum number of concurrent requests supported by a single GRPC channel,\n * as enforced by Google's Frontend. If the SDK issues more than 100 concurrent\n * operations, we need to use more than one GAPIC client since these clients\n * multiplex all requests over a single channel.\n */\nconst MAX_CONCURRENT_REQUESTS_PER_CLIENT = 100;\n/**\n * Document data (e.g. for use with\n * [set()]{@link DocumentReference#set}) consisting of fields mapped\n * to values.\n *\n * @typedef {Object.<string, *>} DocumentData\n */\n/**\n * Converter used by [withConverter()]{@link Query#withConverter} to transform\n * user objects of type `AppModelType` into Firestore data of type\n * `DbModelType`.\n *\n * Using the converter allows you to specify generic type arguments when storing\n * and retrieving objects from Firestore.\n *\n * @example\n * ```\n * class Post {\n *   constructor(readonly title: string, readonly author: string) {}\n *\n *   toString(): string {\n *     return this.title + ', by ' + this.author;\n *   }\n * }\n *\n * const postConverter = {\n *   toFirestore(post: Post): FirebaseFirestore.DocumentData {\n *     return {title: post.title, author: post.author};\n *   },\n *   fromFirestore(\n *     snapshot: FirebaseFirestore.QueryDocumentSnapshot\n *   ): Post {\n *     const data = snapshot.data();\n *     return new Post(data.title, data.author);\n *   }\n * };\n *\n * const postSnap = await Firestore()\n *   .collection('posts')\n *   .withConverter(postConverter)\n *   .doc().get();\n * const post = postSnap.data();\n * if (post !== undefined) {\n *   post.title; // string\n *   post.toString(); // Should be defined\n *   post.someNonExistentProperty; // TS error\n * }\n *\n * ```\n * @property {Function} toFirestore Called by the Firestore SDK to convert a\n * custom model object of type `AppModelType` into a plain Javascript object\n * (suitable for writing directly to the Firestore database).\n * @property {Function} fromFirestore Called by the Firestore SDK to convert\n * Firestore data into an object of type `AppModelType`.\n * @typedef {Object} FirestoreDataConverter\n */\n/**\n * Update data (for use with [update]{@link DocumentReference#update})\n * that contains paths mapped to values. Fields that contain dots\n * reference nested fields within the document.\n *\n * You can update a top-level field in your document by using the field name\n * as a key (e.g. `foo`). The provided value completely replaces the contents\n * for this field.\n *\n * You can also update a nested field directly by using its field path as a key\n * (e.g. `foo.bar`). This nested field update replaces the contents at `bar`\n * but does not modify other data under `foo`.\n *\n * @example\n * ```\n * const documentRef = firestore.doc('coll/doc');\n * documentRef.set({a1: {a2: 'val'}, b1: {b2: 'val'}, c1: {c2: 'val'}});\n * documentRef.update({\n *  b1: {b3: 'val'},\n *  'c1.c3': 'val',\n * });\n * // Value is {a1: {a2: 'val'}, b1: {b3: 'val'}, c1: {c2: 'val', c3: 'val'}}\n *\n * ```\n * @typedef {Object.<string, *>} UpdateData\n */\n/**\n * An options object that configures conditional behavior of\n * [update()]{@link DocumentReference#update} and\n * [delete()]{@link DocumentReference#delete} calls in\n * [DocumentReference]{@link DocumentReference},\n * [WriteBatch]{@link WriteBatch}, [BulkWriter]{@link BulkWriter}, and\n * [Transaction]{@link Transaction}. Using Preconditions, these calls\n * can be restricted to only apply to documents that match the specified\n * conditions.\n *\n * @example\n * ```\n * const documentRef = firestore.doc('coll/doc');\n *\n * documentRef.get().then(snapshot => {\n *   const updateTime = snapshot.updateTime;\n *\n *   console.log(`Deleting document at update time: ${updateTime.toDate()}`);\n *   return documentRef.delete({ lastUpdateTime: updateTime });\n * });\n *\n * ```\n * @property {Timestamp} lastUpdateTime The update time to enforce. If set,\n *  enforces that the document was last updated at lastUpdateTime. Fails the\n *  operation if the document was last updated at a different time.\n * @property {boolean} exists If set, enforces that the target document must\n * or must not exist.\n * @typedef {Object} Precondition\n */\n/**\n * An options object that configures the behavior of\n * [set()]{@link DocumentReference#set} calls in\n * [DocumentReference]{@link DocumentReference},\n * [WriteBatch]{@link WriteBatch}, and\n * [Transaction]{@link Transaction}. These calls can be\n * configured to perform granular merges instead of overwriting the target\n * documents in their entirety by providing a SetOptions object with\n * { merge : true }.\n *\n * @property {boolean} merge Changes the behavior of a set() call to only\n * replace the values specified in its data argument. Fields omitted from the\n * set() call remain untouched.\n * @property {Array<(string|FieldPath)>} mergeFields Changes the behavior of\n * set() calls to only replace the specified field paths. Any field path that is\n * not specified is ignored and remains untouched.\n * It is an error to pass a SetOptions object to a set() call that is missing a\n * value for any of the fields specified here.\n * @typedef {Object} SetOptions\n */\n/**\n * An options object that can be used to configure the behavior of\n * [getAll()]{@link Firestore#getAll} calls. By providing a `fieldMask`, these\n * calls can be configured to only return a subset of fields.\n *\n * @property {Array<(string|FieldPath)>} fieldMask Specifies the set of fields\n * to return and reduces the amount of data transmitted by the backend.\n * Adding a field mask does not filter results. Documents do not need to\n * contain values for all the fields in the mask to be part of the result set.\n * @typedef {Object} ReadOptions\n */\n/**\n * An options object to configure throttling on BulkWriter.\n *\n * Whether to disable or configure throttling. By default, throttling is\n * enabled. `throttling` can be set to either a boolean or a config object.\n * Setting it to `true` will use default values. You can override the defaults\n * by setting it to `false` to disable throttling, or by setting the config\n * values to enable throttling with the provided values.\n *\n * @property {boolean|Object} throttling Whether to disable or enable\n * throttling. Throttling is enabled by default, if the field is set to `true`\n * or if any custom throttling options are provided. `{ initialOpsPerSecond:\n * number }` sets the initial maximum number of operations per second allowed by\n * the throttler. If `initialOpsPerSecond` is not set, the default is 500\n * operations per second. `{ maxOpsPerSecond: number }` sets the maximum number\n * of operations per second allowed by the throttler. If `maxOpsPerSecond` is\n * not set, no maximum is enforced.\n * @typedef {Object} BulkWriterOptions\n */\n/**\n * An error thrown when a BulkWriter operation fails.\n *\n * The error used by {@link BulkWriter~shouldRetryCallback} set in\n * {@link BulkWriter#onWriteError}.\n *\n * @property {GrpcStatus} code The status code of the error.\n * @property {string} message The error message of the error.\n * @property {DocumentReference} documentRef The document reference the\n * operation was performed on.\n * @property {'create' | 'set' | 'update' | 'delete'} operationType The type\n * of operation performed.\n * @property {number} failedAttempts How many times this operation has been\n * attempted unsuccessfully.\n * @typedef {Error} BulkWriterError\n */\n/**\n * Status codes returned by GRPC operations.\n *\n * @see https://github.com/grpc/grpc/blob/master/doc/statuscodes.md\n *\n * @enum {number}\n * @typedef {Object} GrpcStatus\n */\n/**\n * The Firestore client represents a Firestore Database and is the entry point\n * for all Firestore operations.\n *\n * @see [Firestore Documentation]{@link https://firebase.google.com/docs/firestore/}\n *\n * @class\n *\n * @example Install the client library with <a href=\"https://www.npmjs.com/\">npm</a>:\n * ```\n * npm install --save @google-cloud/firestore\n *\n * ```\n * @example Import the client library\n * ```\n * var Firestore = require('@google-cloud/firestore');\n *\n * ```\n * @example Create a client that uses <a href=\"https://cloud.google.com/docs/authentication/production#providing_credentials_to_your_application\">Application Default Credentials (ADC)</a>:\n * ```\n * var firestore = new Firestore();\n *\n * ```\n * @example Create a client with <a href=\"https://cloud.google.com/docs/authentication/production#obtaining_and_providing_service_account_credentials_manually\">explicit credentials</a>:\n * ```\n * var firestore = new Firestore({ projectId:\n * 'your-project-id', keyFilename: '/path/to/keyfile.json'\n * });\n *\n * ```\n * @example <caption>include:samples/quickstart.js</caption>\n * region_tag:firestore_quickstart\n * Full quickstart example:\n */\nclass Firestore {\n    /**\n     * A client pool to distribute requests over multiple GAPIC clients in order\n     * to work around a connection limit of 100 concurrent requests per client.\n     * @private\n     * @internal\n     */\n    _clientPool;\n    /**\n     * Preloaded instance of google-gax (full module, with gRPC support).\n     */\n    _gax;\n    /**\n     * Preloaded instance of google-gax HTTP fallback implementation (no gRPC).\n     */\n    _gaxFallback;\n    /**\n     * The configuration options for the GAPIC client.\n     * @private\n     * @internal\n     */\n    _settings = {};\n    /**\n     * Settings for the exponential backoff used by the streaming endpoints.\n     * @private\n     * @internal\n     */\n    _backoffSettings;\n    /**\n     * Whether the initialization settings can still be changed by invoking\n     * `settings()`.\n     * @private\n     * @internal\n     */\n    _settingsFrozen = false;\n    /**\n     * The serializer to use for the Protobuf transformation.\n     * @private\n     * @internal\n     */\n    _serializer = null;\n    /**\n     * The OpenTelemetry tracing utility object.\n     * @private\n     * @internal\n     */\n    _traceUtil;\n    /**\n     * The project ID for this client.\n     *\n     * The project ID is auto-detected during the first request unless a project\n     * ID is passed to the constructor (or provided via `.settings()`).\n     * @private\n     * @internal\n     */\n    _projectId = undefined;\n    /**\n     * The database ID provided via `.settings()`.\n     *\n     * @private\n     * @internal\n     */\n    _databaseId = undefined;\n    /**\n     * Count of listeners that have been registered on the client.\n     *\n     * The client can only be terminated when there are no pending writes or\n     * registered listeners.\n     * @private\n     * @internal\n     */\n    registeredListenersCount = 0;\n    /**\n     * A lazy-loaded BulkWriter instance to be used with recursiveDelete() if no\n     * BulkWriter instance is provided.\n     *\n     * @private\n     * @internal\n     */\n    _bulkWriter;\n    /**\n     * Lazy-load the Firestore's default BulkWriter.\n     *\n     * @private\n     * @internal\n     */\n    getBulkWriter() {\n        if (!this._bulkWriter) {\n            this._bulkWriter = this.bulkWriter();\n        }\n        return this._bulkWriter;\n    }\n    /**\n     * Number of pending operations on the client.\n     *\n     * The client can only be terminated when there are no pending writes or\n     * registered listeners.\n     * @private\n     * @internal\n     */\n    bulkWritersCount = 0;\n    /**\n     * @param {Object=} settings [Configuration object](#/docs).\n     * @param {string=} settings.projectId The project ID from the Google\n     * Developer's Console, e.g. 'grape-spaceship-123'. We will also check the\n     * environment variable GCLOUD_PROJECT for your project ID.  Can be omitted in\n     * environments that support\n     * {@link https://cloud.google.com/docs/authentication Application Default\n     * Credentials}\n     * @param {string=} settings.keyFilename Local file containing the Service\n     * Account credentials as downloaded from the Google Developers Console. Can\n     * be omitted in environments that support\n     * {@link https://cloud.google.com/docs/authentication Application Default\n     * Credentials}. To configure Firestore with custom credentials, use\n     * `settings.credentials` and provide the `client_email` and `private_key` of\n     * your service account.\n     * @param {{client_email:string=, private_key:string=}=} settings.credentials\n     * The `client_email` and `private_key` properties of the service account\n     * to use with your Firestore project. Can be omitted in environments that\n     * support {@link https://cloud.google.com/docs/authentication Application\n     * Default Credentials}. If your credentials are stored in a JSON file, you\n     * can specify a `keyFilename` instead.\n     * @param {string=} settings.host The host to connect to.\n     * @param {boolean=} settings.ssl Whether to use SSL when connecting.\n     * @param {number=} settings.maxIdleChannels The maximum number of idle GRPC\n     * channels to keep. A smaller number of idle channels reduces memory usage\n     * but increases request latency for clients with fluctuating request rates.\n     * If set to 0, shuts down all GRPC channels when the client becomes idle.\n     * Defaults to 1.\n     * @param {boolean=} settings.ignoreUndefinedProperties Whether to skip nested\n     * properties that are set to `undefined` during object serialization. If set\n     * to `true`, these properties are skipped and not written to Firestore. If\n     * set `false` or omitted, the SDK throws an exception when it encounters\n     * properties of type `undefined`.\n     * @param {boolean=} settings.preferRest Whether to force the use of HTTP/1.1 REST\n     * transport until a method that requires gRPC is called. When a method requires gRPC,\n     * this Firestore client will load dependent gRPC libraries and then use gRPC transport\n     * for communication from that point forward. Currently the only operation\n     * that requires gRPC is creating a snapshot listener with the method\n     * `DocumentReference<T>.onSnapshot()`, `CollectionReference<T>.onSnapshot()`, or\n     * `Query<T>.onSnapshot()`. If specified, this setting value will take precedent over the\n     * environment variable `FIRESTORE_PREFER_REST`. If not specified, the\n     * SDK will use the value specified in the environment variable `FIRESTORE_PREFER_REST`.\n     * Valid values of `FIRESTORE_PREFER_REST` are `true` ('1') or `false` (`0`). Values are\n     * not case-sensitive. Any other value for the environment variable will be ignored and\n     * a warning will be logged to the console.\n     */\n    constructor(settings) {\n        const libraryHeader = {\n            libName: 'gccl',\n            libVersion,\n        };\n        if (settings && settings.firebaseVersion) {\n            libraryHeader.libVersion += ' fire/' + settings.firebaseVersion;\n        }\n        if (settings && settings.firebaseAdminVersion) {\n            libraryHeader.libVersion +=\n                ' fire-admin/' + settings.firebaseAdminVersion;\n        }\n        this.validateAndApplySettings({ ...settings, ...libraryHeader });\n        this._traceUtil = this.newTraceUtilInstance(this._settings);\n        const retryConfig = serviceConfig.retry_params.default;\n        this._backoffSettings = {\n            initialDelayMs: retryConfig.initial_retry_delay_millis,\n            maxDelayMs: retryConfig.max_retry_delay_millis,\n            backoffFactor: retryConfig.retry_delay_multiplier,\n        };\n        const maxIdleChannels = this._settings.maxIdleChannels === undefined\n            ? exports.DEFAULT_MAX_IDLE_CHANNELS\n            : this._settings.maxIdleChannels;\n        this._clientPool = new pool_1.ClientPool(MAX_CONCURRENT_REQUESTS_PER_CLIENT, maxIdleChannels, \n        /* clientFactory= */ (requiresGrpc) => {\n            let client;\n            // Use the rest fallback if enabled and if the method does not require GRPC\n            const useFallback = !this._settings.preferRest || requiresGrpc ? false : 'rest';\n            let gax;\n            if (useFallback) {\n                if (!this._gaxFallback) {\n                    gax = this._gaxFallback = require('google-gax/fallback');\n                }\n                else {\n                    gax = this._gaxFallback;\n                }\n            }\n            else {\n                if (!this._gax) {\n                    gax = this._gax = require('google-gax');\n                }\n                else {\n                    gax = this._gax;\n                }\n            }\n            if (this._settings.ssl === false) {\n                const grpcModule = this._settings.grpc ?? require('google-gax').grpc;\n                const sslCreds = grpcModule.credentials.createInsecure();\n                const settings = {\n                    sslCreds,\n                    ...this._settings,\n                    fallback: useFallback,\n                };\n                // Since `ssl === false`, if we're using the GAX fallback then\n                // also set the `protocol` option for GAX fallback to force http\n                if (useFallback) {\n                    settings.protocol = 'http';\n                }\n                client = new module.exports.v1(settings, gax);\n            }\n            else {\n                client = new module.exports.v1({\n                    ...this._settings,\n                    fallback: useFallback,\n                }, gax);\n            }\n            (0, logger_1.logger)('clientFactory', null, 'Initialized Firestore GAPIC Client (useFallback: %s)', useFallback);\n            return client;\n        }, \n        /* clientDestructor= */ client => client.close());\n        (0, logger_1.logger)('Firestore', null, 'Initialized Firestore');\n    }\n    /**\n     * Specifies custom settings to be used to configure the `Firestore`\n     * instance. Can only be invoked once and before any other Firestore method.\n     *\n     * If settings are provided via both `settings()` and the `Firestore`\n     * constructor, both settings objects are merged and any settings provided via\n     * `settings()` take precedence.\n     *\n     * @param {object} settings The settings to use for all Firestore operations.\n     */\n    settings(settings) {\n        (0, validate_1.validateObject)('settings', settings);\n        (0, validate_1.validateString)('settings.projectId', settings.projectId, { optional: true });\n        (0, validate_1.validateString)('settings.databaseId', settings.databaseId, {\n            optional: true,\n        });\n        if (this._settingsFrozen) {\n            throw new Error('Firestore has already been initialized. You can only call ' +\n                'settings() once, and only before calling any other methods on a ' +\n                'Firestore object.');\n        }\n        const mergedSettings = { ...this._settings, ...settings };\n        this.validateAndApplySettings(mergedSettings);\n        this._traceUtil = this.newTraceUtilInstance(this._settings);\n        this._settingsFrozen = true;\n    }\n    validateAndApplySettings(settings) {\n        if (settings.projectId !== undefined) {\n            (0, validate_1.validateString)('settings.projectId', settings.projectId);\n            this._projectId = settings.projectId;\n        }\n        if (settings.databaseId !== undefined) {\n            (0, validate_1.validateString)('settings.databaseId', settings.databaseId);\n            this._databaseId = settings.databaseId;\n        }\n        let url = null;\n        // If preferRest is not specified in settings, but is set as environment variable,\n        // then use the environment variable value.\n        const preferRestEnvValue = (0, util_1.tryGetPreferRestEnvironmentVariable)();\n        if (settings.preferRest === undefined && preferRestEnvValue !== undefined) {\n            settings = {\n                ...settings,\n                preferRest: preferRestEnvValue,\n            };\n        }\n        // If the environment variable is set, it should always take precedence\n        // over any user passed in settings.\n        if (process.env.FIRESTORE_EMULATOR_HOST) {\n            (0, validate_1.validateHost)('FIRESTORE_EMULATOR_HOST', process.env.FIRESTORE_EMULATOR_HOST);\n            settings = {\n                ...settings,\n                host: process.env.FIRESTORE_EMULATOR_HOST,\n                ssl: false,\n            };\n            url = new url_1.URL(`http://${settings.host}`);\n        }\n        else if (settings.host !== undefined) {\n            (0, validate_1.validateHost)('settings.host', settings.host);\n            url = new url_1.URL(`http://${settings.host}`);\n        }\n        // Only store the host if a valid value was provided in `host`.\n        if (url !== null) {\n            if ((settings.servicePath !== undefined &&\n                settings.servicePath !== url.hostname) ||\n                (settings.apiEndpoint !== undefined &&\n                    settings.apiEndpoint !== url.hostname)) {\n                // eslint-disable-next-line no-console\n                console.warn(`The provided host (${url.hostname}) in \"settings\" does not ` +\n                    `match the existing host (${settings.servicePath ?? settings.apiEndpoint}). Using the provided host.`);\n            }\n            settings.servicePath = url.hostname;\n            if (url.port !== '' && settings.port === undefined) {\n                settings.port = Number(url.port);\n            }\n            // We need to remove the `host` and `apiEndpoint` setting, in case a user\n            // calls `settings()`, which will compare the the provided `host` to the\n            // existing hostname stored on `servicePath`.\n            delete settings.host;\n            delete settings.apiEndpoint;\n        }\n        if (settings.ssl !== undefined) {\n            (0, validate_1.validateBoolean)('settings.ssl', settings.ssl);\n        }\n        if (settings.maxIdleChannels !== undefined) {\n            (0, validate_1.validateInteger)('settings.maxIdleChannels', settings.maxIdleChannels, {\n                minValue: 0,\n            });\n        }\n        this._settings = settings;\n        this._settings.toJSON = function () {\n            const temp = Object.assign({}, this);\n            if (temp.credentials) {\n                temp.credentials = { private_key: '***', client_email: '***' };\n            }\n            return temp;\n        };\n        this._serializer = new serializer_1.Serializer(this);\n    }\n    newTraceUtilInstance(settings) {\n        let createEnabledInstance = true;\n        // The environment variable can override options to enable/disable telemetry collection.\n        if ('FIRESTORE_ENABLE_TRACING' in process.env) {\n            const enableTracingEnvVar = process.env.FIRESTORE_ENABLE_TRACING.toLowerCase();\n            if (enableTracingEnvVar === 'on' || enableTracingEnvVar === 'true') {\n                createEnabledInstance = true;\n            }\n            if (enableTracingEnvVar === 'off' || enableTracingEnvVar === 'false') {\n                createEnabledInstance = false;\n            }\n        }\n        if (createEnabledInstance) {\n            return new enabled_trace_util_1.EnabledTraceUtil(settings);\n        }\n        else {\n            return new disabled_trace_util_1.DisabledTraceUtil();\n        }\n    }\n    /**\n     * Returns the Project ID for this Firestore instance. Validates that\n     * `initializeIfNeeded()` was called before.\n     *\n     * @private\n     * @internal\n     */\n    get projectId() {\n        if (this._projectId === undefined) {\n            throw new Error('INTERNAL ERROR: Client is not yet ready to issue requests.');\n        }\n        return this._projectId;\n    }\n    /**\n     * Returns the Database ID for this Firestore instance.\n     */\n    get databaseId() {\n        return this._databaseId || path_1.DEFAULT_DATABASE_ID;\n    }\n    /**\n     * Returns the root path of the database. Validates that\n     * `initializeIfNeeded()` was called before.\n     *\n     * @private\n     * @internal\n     */\n    get formattedName() {\n        return `projects/${this.projectId}/databases/${this.databaseId}`;\n    }\n    /**\n     * Gets a [DocumentReference]{@link DocumentReference} instance that\n     * refers to the document at the specified path.\n     *\n     * @param {string} documentPath A slash-separated path to a document.\n     * @returns {DocumentReference} The\n     * [DocumentReference]{@link DocumentReference} instance.\n     *\n     * @example\n     * ```\n     * let documentRef = firestore.doc('collection/document');\n     * console.log(`Path of document is ${documentRef.path}`);\n     * ```\n     */\n    doc(documentPath) {\n        (0, path_1.validateResourcePath)('documentPath', documentPath);\n        const path = path_1.ResourcePath.EMPTY.append(documentPath);\n        if (!path.isDocument) {\n            throw new Error(`Value for argument \"documentPath\" must point to a document, but was \"${documentPath}\". Your path does not contain an even number of components.`);\n        }\n        return new document_reference_1.DocumentReference(this, path);\n    }\n    /**\n     * Gets a [CollectionReference]{@link CollectionReference} instance\n     * that refers to the collection at the specified path.\n     *\n     * @param {string} collectionPath A slash-separated path to a collection.\n     * @returns {CollectionReference} The\n     * [CollectionReference]{@link CollectionReference} instance.\n     *\n     * @example\n     * ```\n     * let collectionRef = firestore.collection('collection');\n     *\n     * // Add a document with an auto-generated ID.\n     * collectionRef.add({foo: 'bar'}).then((documentRef) => {\n     *   console.log(`Added document at ${documentRef.path})`);\n     * });\n     * ```\n     */\n    collection(collectionPath) {\n        (0, path_1.validateResourcePath)('collectionPath', collectionPath);\n        const path = path_1.ResourcePath.EMPTY.append(collectionPath);\n        if (!path.isCollection) {\n            throw new Error(`Value for argument \"collectionPath\" must point to a collection, but was \"${collectionPath}\". Your path does not contain an odd number of components.`);\n        }\n        return new collection_reference_1.CollectionReference(this, path);\n    }\n    /**\n     * Creates and returns a new Query that includes all documents in the\n     * database that are contained in a collection or subcollection with the\n     * given collectionId.\n     *\n     * @param {string} collectionId Identifies the collections to query over.\n     * Every collection or subcollection with this ID as the last segment of its\n     * path will be included. Cannot contain a slash.\n     * @returns {CollectionGroup} The created CollectionGroup.\n     *\n     * @example\n     * ```\n     * let docA = firestore.doc('mygroup/docA').set({foo: 'bar'});\n     * let docB = firestore.doc('abc/def/mygroup/docB').set({foo: 'bar'});\n     *\n     * Promise.all([docA, docB]).then(() => {\n     *    let query = firestore.collectionGroup('mygroup');\n     *    query = query.where('foo', '==', 'bar');\n     *    return query.get().then(snapshot => {\n     *       console.log(`Found ${snapshot.size} documents.`);\n     *    });\n     * });\n     * ```\n     */\n    collectionGroup(collectionId) {\n        if (collectionId.indexOf('/') !== -1) {\n            throw new Error(`Invalid collectionId '${collectionId}'. Collection IDs must not contain '/'.`);\n        }\n        return new collection_group_1.CollectionGroup(this, collectionId, /* converter= */ undefined);\n    }\n    /**\n     * Creates a [WriteBatch]{@link WriteBatch}, used for performing\n     * multiple writes as a single atomic operation.\n     *\n     * @returns {WriteBatch} A WriteBatch that operates on this Firestore\n     * client.\n     *\n     * @example\n     * ```\n     * let writeBatch = firestore.batch();\n     *\n     * // Add two documents in an atomic batch.\n     * let data = { foo: 'bar' };\n     * writeBatch.set(firestore.doc('col/doc1'), data);\n     * writeBatch.set(firestore.doc('col/doc2'), data);\n     *\n     * writeBatch.commit().then(res => {\n     *   console.log('Successfully executed batch.');\n     * });\n     * ```\n     */\n    batch() {\n        return new write_batch_1.WriteBatch(this);\n    }\n    /**\n     * Creates a [BulkWriter]{@link BulkWriter}, used for performing\n     * multiple writes in parallel. Gradually ramps up writes as specified\n     * by the 500/50/5 rule.\n     *\n     * If you pass [BulkWriterOptions]{@link BulkWriterOptions}, you can\n     * configure the throttling rates for the created BulkWriter.\n     *\n     * @see [500/50/5 Documentation]{@link https://firebase.google.com/docs/firestore/best-practices#ramping_up_traffic}\n     *\n     * @param {BulkWriterOptions=} options BulkWriter options.\n     * @returns {BulkWriter} A BulkWriter that operates on this Firestore\n     * client.\n     *\n     * @example\n     * ```\n     * let bulkWriter = firestore.bulkWriter();\n     *\n     * bulkWriter.create(firestore.doc('col/doc1'), {foo: 'bar'})\n     *   .then(res => {\n     *     console.log(`Added document at ${res.writeTime}`);\n     *   });\n     * bulkWriter.update(firestore.doc('col/doc2'), {foo: 'bar'})\n     *   .then(res => {\n     *     console.log(`Updated document at ${res.writeTime}`);\n     *   });\n     * bulkWriter.delete(firestore.doc('col/doc3'))\n     *   .then(res => {\n     *     console.log(`Deleted document at ${res.writeTime}`);\n     *   });\n     * await bulkWriter.close().then(() => {\n     *   console.log('Executed all writes');\n     * });\n     * ```\n     */\n    bulkWriter(options) {\n        return new bulk_writer_1.BulkWriter(this, options);\n    }\n    /** @private */\n    snapshot_(documentOrName, readTime, encoding) {\n        // TODO: Assert that Firestore Project ID is valid.\n        let convertTimestamp;\n        let convertFields;\n        if (encoding === undefined || encoding === 'protobufJS') {\n            convertTimestamp = data => data;\n            convertFields = data => data;\n        }\n        else if (encoding === 'json') {\n            // Google Cloud Functions calls us with Proto3 JSON format data, which we\n            // must convert to Protobuf JS.\n            convertTimestamp = convert_1.timestampFromJson;\n            convertFields = convert_1.fieldsFromJson;\n        }\n        else {\n            throw new Error('Unsupported encoding format. Expected \"json\" or \"protobufJS\", ' +\n                `but was \"${encoding}\".`);\n        }\n        let ref;\n        let document;\n        if (typeof documentOrName === 'string') {\n            ref = new document_reference_1.DocumentReference(this, path_1.QualifiedResourcePath.fromSlashSeparatedString(documentOrName));\n            document = new document_1.DocumentSnapshotBuilder(ref);\n        }\n        else {\n            ref = new document_reference_1.DocumentReference(this, path_1.QualifiedResourcePath.fromSlashSeparatedString(documentOrName.name));\n            document = new document_1.DocumentSnapshotBuilder(ref);\n            document.fieldsProto = documentOrName.fields\n                ? convertFields(documentOrName.fields)\n                : {};\n            document.createTime = timestamp_1.Timestamp.fromProto(convertTimestamp(documentOrName.createTime, 'documentOrName.createTime'));\n            document.updateTime = timestamp_1.Timestamp.fromProto(convertTimestamp(documentOrName.updateTime, 'documentOrName.updateTime'));\n        }\n        if (readTime) {\n            document.readTime = timestamp_1.Timestamp.fromProto(convertTimestamp(readTime, 'readTime'));\n        }\n        return document.build();\n    }\n    /**\n     * Creates a new `BundleBuilder` instance to package selected Firestore data into\n     * a bundle.\n     *\n     * @param bundleId. The id of the bundle. When loaded on clients, client SDKs use this id\n     * and the timestamp associated with the built bundle to tell if it has been loaded already.\n     * If not specified, a random identifier will be used.\n     */\n    bundle(name) {\n        return new bundle_1.BundleBuilder(name || (0, util_1.autoId)());\n    }\n    /**\n     * Function executed by {@link Firestore#runTransaction} within the transaction\n     * context.\n     *\n     * @callback Firestore~updateFunction\n     * @template T\n     * @param {Transaction} transaction The transaction object for this\n     * transaction.\n     * @returns {Promise<T>} The promise returned at the end of the transaction.\n     * This promise will be returned by {@link Firestore#runTransaction} if the\n     * transaction completed successfully.\n     */\n    /**\n     * Options object for {@link Firestore#runTransaction} to configure a\n     * read-only transaction.\n     *\n     * @param {true} readOnly Set to true to indicate a read-only transaction.\n     * @param {Timestamp=} readTime If specified, documents are read at the given\n     * time. This may not be more than 60 seconds in the past from when the\n     * request is processed by the server.\n     * @typedef {Object} Firestore~ReadOnlyTransactionOptions\n     */\n    /**\n     * Options object for {@link Firestore#runTransaction} to configure a\n     * read-write transaction.\n     *\n     * @param {false=} readOnly Set to false or omit to indicate a read-write\n     * transaction.\n     * @param {number=} maxAttempts The maximum number of attempts for this\n     * transaction. Defaults to 5.\n     * @typedef {Object} Firestore~ReadWriteTransactionOptions\n     */\n    /**\n     * Executes the given updateFunction and commits the changes applied within\n     * the transaction.\n     *\n     * You can use the transaction object passed to 'updateFunction' to read and\n     * modify Firestore documents under lock. You have to perform all reads before\n     * before you perform any write.\n     *\n     * Transactions can be performed as read-only or read-write transactions. By\n     * default, transactions are executed in read-write mode.\n     *\n     * A read-write transaction obtains a pessimistic lock on all documents that\n     * are read during the transaction. These locks block other transactions,\n     * batched writes, and other non-transactional writes from changing that\n     * document. Any writes in a read-write transactions are committed once\n     * 'updateFunction' resolves, which also releases all locks.\n     *\n     * If a read-write transaction fails with contention, the transaction is\n     * retried up to five times. The `updateFunction` is invoked once for each\n     * attempt.\n     *\n     * Read-only transactions do not lock documents. They can be used to read\n     * documents at a consistent snapshot in time, which may be up to 60 seconds\n     * in the past. Read-only transactions are not retried.\n     *\n     * Transactions time out after 60 seconds if no documents are read.\n     * Transactions that are not committed within than 270 seconds are also\n     * aborted. Any remaining locks are released when a transaction times out.\n     *\n     * @template T\n     * @param {Firestore~updateFunction} updateFunction The user function to\n     * execute within the transaction context.\n     * @param {\n     * Firestore~ReadWriteTransactionOptions|Firestore~ReadOnlyTransactionOptions=\n     * } transactionOptions Transaction options.\n     * @returns {Promise<T>} If the transaction completed successfully or was\n     * explicitly aborted (by the updateFunction returning a failed Promise), the\n     * Promise returned by the updateFunction will be returned here. Else if the\n     * transaction failed, a rejected Promise with the corresponding failure\n     * error will be returned.\n     *\n     * @example\n     * ```\n     * let counterTransaction = firestore.runTransaction(transaction => {\n     *   let documentRef = firestore.doc('col/doc');\n     *   return transaction.get(documentRef).then(doc => {\n     *     if (doc.exists) {\n     *       let count =  doc.get('count') || 0;\n     *       if (count > 10) {\n     *         return Promise.reject('Reached maximum count');\n     *       }\n     *       transaction.update(documentRef, { count: ++count });\n     *       return Promise.resolve(count);\n     *     }\n     *\n     *     transaction.create(documentRef, { count: 1 });\n     *     return Promise.resolve(1);\n     *   });\n     * });\n     *\n     * counterTransaction.then(res => {\n     *   console.log(`Count updated to ${res}`);\n     * });\n     * ```\n     */\n    runTransaction(updateFunction, transactionOptions) {\n        (0, validate_1.validateFunction)('updateFunction', updateFunction);\n        const tag = (0, util_1.requestTag)();\n        if (transactionOptions) {\n            (0, validate_1.validateObject)('transactionOptions', transactionOptions);\n            (0, validate_1.validateBoolean)('transactionOptions.readOnly', transactionOptions.readOnly, { optional: true });\n            if (transactionOptions.readOnly) {\n                (0, validate_1.validateTimestamp)('transactionOptions.readTime', transactionOptions.readTime, { optional: true });\n            }\n            else {\n                (0, validate_1.validateInteger)('transactionOptions.maxAttempts', transactionOptions.maxAttempts, { optional: true, minValue: 1 });\n            }\n        }\n        const transaction = new transaction_1.Transaction(this, tag, transactionOptions);\n        return this.initializeIfNeeded(tag).then(() => transaction.runTransaction(updateFunction));\n    }\n    /**\n     * Fetches the root collections that are associated with this Firestore\n     * database.\n     *\n     * @returns {Promise.<Array.<CollectionReference>>} A Promise that resolves\n     * with an array of CollectionReferences.\n     *\n     * @example\n     * ```\n     * firestore.listCollections().then(collections => {\n     *   for (let collection of collections) {\n     *     console.log(`Found collection with id: ${collection.id}`);\n     *   }\n     * });\n     * ```\n     */\n    listCollections() {\n        const rootDocument = new document_reference_1.DocumentReference(this, path_1.ResourcePath.EMPTY);\n        return rootDocument.listCollections();\n    }\n    /**\n     * Retrieves multiple documents from Firestore.\n     *\n     * The first argument is required and must be of type `DocumentReference`\n     * followed by any additional `DocumentReference` documents. If used, the\n     * optional `ReadOptions` must be the last argument.\n     *\n     * @param {...DocumentReference|ReadOptions} documentRefsOrReadOptions The\n     * `DocumentReferences` to receive, followed by an optional field mask.\n     * @returns {Promise<Array.<DocumentSnapshot>>} A Promise that\n     * contains an array with the resulting document snapshots.\n     *\n     * @example\n     * ```\n     * let docRef1 = firestore.doc('col/doc1');\n     * let docRef2 = firestore.doc('col/doc2');\n     *\n     * firestore.getAll(docRef1, docRef2, { fieldMask: ['user'] }).then(docs => {\n     *   console.log(`First document: ${JSON.stringify(docs[0])}`);\n     *   console.log(`Second document: ${JSON.stringify(docs[1])}`);\n     * });\n     * ```\n     */\n    getAll(...documentRefsOrReadOptions) {\n        return this._traceUtil.startActiveSpan(trace_util_1.SPAN_NAME_BATCH_GET_DOCUMENTS, () => {\n            (0, validate_1.validateMinNumberOfArguments)('Firestore.getAll', documentRefsOrReadOptions, 1);\n            const { documents, fieldMask } = (0, transaction_1.parseGetAllArguments)(documentRefsOrReadOptions);\n            this._traceUtil.currentSpan().setAttributes({\n                [trace_util_1.ATTRIBUTE_KEY_IS_TRANSACTIONAL]: false,\n                [trace_util_1.ATTRIBUTE_KEY_DOC_COUNT]: documents.length,\n            });\n            const tag = (0, util_1.requestTag)();\n            // Capture the error stack to preserve stack tracing across async calls.\n            const stack = Error().stack;\n            return this.initializeIfNeeded(tag)\n                .then(() => {\n                const reader = new document_reader_1.DocumentReader(this, documents, fieldMask);\n                return reader.get(tag);\n            })\n                .catch(err => {\n                throw (0, util_1.wrapError)(err, stack);\n            });\n        });\n    }\n    /**\n     * Registers a listener on this client, incrementing the listener count. This\n     * is used to verify that all listeners are unsubscribed when terminate() is\n     * called.\n     *\n     * @private\n     * @internal\n     */\n    registerListener() {\n        this.registeredListenersCount += 1;\n    }\n    /**\n     * Unregisters a listener on this client, decrementing the listener count.\n     * This is used to verify that all listeners are unsubscribed when terminate()\n     * is called.\n     *\n     * @private\n     * @internal\n     */\n    unregisterListener() {\n        this.registeredListenersCount -= 1;\n    }\n    /**\n     * Increments the number of open BulkWriter instances. This is used to verify\n     * that all pending operations are complete when terminate() is called.\n     *\n     * @private\n     * @internal\n     */\n    _incrementBulkWritersCount() {\n        this.bulkWritersCount += 1;\n    }\n    /**\n     * Decrements the number of open BulkWriter instances. This is used to verify\n     * that all pending operations are complete when terminate() is called.\n     *\n     * @private\n     * @internal\n     */\n    _decrementBulkWritersCount() {\n        this.bulkWritersCount -= 1;\n    }\n    /**\n     * Recursively deletes all documents and subcollections at and under the\n     * specified level.\n     *\n     * If any delete fails, the promise is rejected with an error message\n     * containing the number of failed deletes and the stack trace of the last\n     * failed delete. The provided reference is deleted regardless of whether\n     * all deletes succeeded.\n     *\n     * `recursiveDelete()` uses a BulkWriter instance with default settings to\n     * perform the deletes. To customize throttling rates or add success/error\n     * callbacks, pass in a custom BulkWriter instance.\n     *\n     * @param ref The reference of a document or collection to delete.\n     * @param bulkWriter A custom BulkWriter instance used to perform the\n     * deletes.\n     * @return A promise that resolves when all deletes have been performed.\n     * The promise is rejected if any of the deletes fail.\n     *\n     * @example\n     * ```\n     * // Recursively delete a reference and log the references of failures.\n     * const bulkWriter = firestore.bulkWriter();\n     * bulkWriter\n     *   .onWriteError((error) => {\n     *     if (\n     *       error.failedAttempts < MAX_RETRY_ATTEMPTS\n     *     ) {\n     *       return true;\n     *     } else {\n     *       console.log('Failed write at document: ', error.documentRef.path);\n     *       return false;\n     *     }\n     *   });\n     * await firestore.recursiveDelete(docRef, bulkWriter);\n     * ```\n     */\n    recursiveDelete(ref, bulkWriter) {\n        return this._recursiveDelete(ref, recursive_delete_1.RECURSIVE_DELETE_MAX_PENDING_OPS, recursive_delete_1.RECURSIVE_DELETE_MIN_PENDING_OPS, bulkWriter);\n    }\n    /**\n     * This overload is not private in order to test the query resumption with\n     * startAfter() once the RecursiveDelete instance has MAX_PENDING_OPS pending.\n     *\n     * @private\n     * @internal\n     */\n    // Visible for testing\n    _recursiveDelete(ref, maxPendingOps, minPendingOps, bulkWriter) {\n        const writer = bulkWriter ?? this.getBulkWriter();\n        const deleter = new recursive_delete_1.RecursiveDelete(this, writer, ref, maxPendingOps, minPendingOps);\n        return deleter.run();\n    }\n    /**\n     * Terminates the Firestore client and closes all open streams.\n     *\n     * @return A Promise that resolves when the client is terminated.\n     */\n    async terminate() {\n        if (this._bulkWriter) {\n            await this._bulkWriter.close();\n            this._bulkWriter = undefined;\n        }\n        if (this.registeredListenersCount > 0 || this.bulkWritersCount > 0) {\n            return Promise.reject('All onSnapshot() listeners must be unsubscribed, and all BulkWriter ' +\n                'instances must be closed before terminating the client. ' +\n                `There are ${this.registeredListenersCount} active listeners and ` +\n                `${this.bulkWritersCount} open BulkWriter instances.`);\n        }\n        return this._clientPool.terminate();\n    }\n    /**\n     * Returns the Project ID to serve as the JSON representation of this\n     * Firestore instance.\n     *\n     * @return An object that contains the project ID (or `undefined` if not yet\n     * available).\n     */\n    toJSON() {\n        return { projectId: this._projectId };\n    }\n    /**\n     * Initializes the client if it is not already initialized. All methods in the\n     * SDK can be used after this method completes.\n     *\n     * @private\n     * @internal\n     * @param requestTag A unique client-assigned identifier that caused this\n     * initialization.\n     * @return A Promise that resolves when the client is initialized.\n     */\n    async initializeIfNeeded(requestTag) {\n        this._settingsFrozen = true;\n        if (this._settings.ssl === false) {\n            // If SSL is false, we assume that we are talking to the emulator. We\n            // provide an Authorization header by default so that the connection is\n            // recognized as admin in Firestore Emulator. (If for some reason we're\n            // not connecting to the emulator, then this will result in denials with\n            // invalid token, rather than behave like clients not logged in. The user\n            // can then provide their own Authorization header, which will take\n            // precedence).\n            this._settings.customHeaders = {\n                Authorization: 'Bearer owner',\n                ...this._settings.customHeaders,\n            };\n        }\n        if (this._projectId === undefined) {\n            try {\n                this._projectId = await this._clientPool.run(requestTag, \n                /* requiresGrpc= */ false, gapicClient => gapicClient.getProjectId());\n                (0, logger_1.logger)('Firestore.initializeIfNeeded', null, 'Detected project ID: %s', this._projectId);\n                // If the project ID was undefined when the TraceUtil was set up, we\n                // need to record it.\n                this._traceUtil.recordProjectId(this.projectId);\n            }\n            catch (err) {\n                (0, logger_1.logger)('Firestore.initializeIfNeeded', null, 'Failed to detect project ID: %s', err);\n                return Promise.reject(err);\n            }\n        }\n    }\n    /**\n     * Returns GAX call options that set the cloud resource header.\n     * @private\n     * @internal\n     */\n    createCallOptions(methodName, retryCodes) {\n        const callOptions = {\n            otherArgs: {\n                headers: {\n                    [CLOUD_RESOURCE_HEADER]: this.formattedName,\n                    ...this._settings.customHeaders,\n                    ...this._settings[methodName]?.customHeaders,\n                },\n            },\n        };\n        if (retryCodes) {\n            const retryParams = (0, util_1.getRetryParams)(methodName);\n            callOptions.retry = new (require('google-gax/fallback').RetryOptions)(retryCodes, retryParams);\n        }\n        return callOptions;\n    }\n    /**\n     * A function returning a Promise that can be retried.\n     *\n     * @private\n     * @internal\n     * @callback retryFunction\n     * @returns {Promise} A Promise indicating the function's success.\n     */\n    /**\n     * Helper method that retries failed Promises.\n     *\n     * If 'delayMs' is specified, waits 'delayMs' between invocations. Otherwise,\n     * schedules the first attempt immediately, and then waits 100 milliseconds\n     * for further attempts.\n     *\n     * @private\n     * @internal\n     * @param methodName Name of the Veneer API endpoint that takes a request\n     * and GAX options.\n     * @param requestTag A unique client-assigned identifier for this request.\n     * @param func Method returning a Promise than can be retried.\n     * @returns A Promise with the function's result if successful within\n     * `attemptsRemaining`. Otherwise, returns the last rejected Promise.\n     */\n    async _retry(methodName, requestTag, func) {\n        const backoff = new backoff_1.ExponentialBackoff();\n        let lastError = undefined;\n        for (let attempt = 0; attempt < exports.MAX_REQUEST_RETRIES; ++attempt) {\n            if (lastError) {\n                (0, logger_1.logger)('Firestore._retry', requestTag, 'Retrying request that failed with error:', lastError);\n            }\n            try {\n                await backoff.backoffAndWait();\n                return await func();\n            }\n            catch (err) {\n                lastError = err;\n                if ((0, util_1.isPermanentRpcError)(err, methodName)) {\n                    break;\n                }\n            }\n        }\n        (0, logger_1.logger)('Firestore._retry', requestTag, 'Request failed with error:', lastError);\n        return Promise.reject(lastError);\n    }\n    /**\n     * Waits for the provided stream to become active and returns a paused but\n     * healthy stream. If an error occurs before the first byte is read, the\n     * method rejects the returned Promise.\n     *\n     * @private\n     * @internal\n     * @param backendStream The Node stream to monitor.\n     * @param lifetime A Promise that resolves when the stream receives an 'end',\n     * 'close' or 'finish' message.\n     * @param requestTag A unique client-assigned identifier for this request.\n     * @param request If specified, the request that should be written to the\n     * stream after opening.\n     * @returns A guaranteed healthy stream that should be used instead of\n     * `backendStream`.\n     */\n    _initializeStream(backendStream, lifetime, requestTag, request) {\n        const resultStream = new stream_1.PassThrough({ objectMode: true });\n        resultStream.pause();\n        /**\n         * Whether we have resolved the Promise and returned the stream to the\n         * caller.\n         */\n        let streamInitialized = false;\n        return new Promise((resolve, reject) => {\n            function streamReady() {\n                if (!streamInitialized) {\n                    streamInitialized = true;\n                    (0, logger_1.logger)('Firestore._initializeStream', requestTag, 'Stream ready');\n                    resolve(resultStream);\n                }\n            }\n            function streamEnded() {\n                (0, logger_1.logger)('Firestore._initializeStream', requestTag, 'Received stream end');\n                resultStream.unpipe(backendStream);\n                resolve(resultStream);\n                lifetime.resolve();\n            }\n            function streamFailed(err) {\n                if (!streamInitialized) {\n                    // If we receive an error before we were able to receive any data,\n                    // reject this stream.\n                    (0, logger_1.logger)('Firestore._initializeStream', requestTag, 'Received initial error:', err);\n                    reject(err);\n                }\n                else {\n                    (0, logger_1.logger)('Firestore._initializeStream', requestTag, 'Received stream error:', err);\n                    // We execute the forwarding of the 'error' event via setImmediate() as\n                    // V8 guarantees that the Promise chain returned from this method\n                    // is resolved before any code executed via setImmediate(). This\n                    // allows the caller to attach an error handler.\n                    setImmediate(() => {\n                        resultStream.emit('error', err);\n                    });\n                }\n            }\n            backendStream.on('data', () => streamReady());\n            backendStream.on('error', err => streamFailed(err));\n            backendStream.on('end', () => streamEnded());\n            backendStream.on('close', () => streamEnded());\n            backendStream.on('finish', () => streamEnded());\n            backendStream.pipe(resultStream);\n            if (request) {\n                (0, logger_1.logger)('Firestore._initializeStream', requestTag, 'Sending request: %j', request);\n                backendStream.write(request, 'utf-8', err => {\n                    if (err) {\n                        streamFailed(err);\n                    }\n                    else {\n                        (0, logger_1.logger)('Firestore._initializeStream', requestTag, 'Marking stream as healthy');\n                        streamReady();\n                    }\n                });\n            }\n        });\n    }\n    /**\n     * A funnel for all non-streaming API requests, assigning a project ID where\n     * necessary within the request options.\n     *\n     * @private\n     * @internal\n     * @param methodName Name of the Veneer API endpoint that takes a request\n     * and GAX options.\n     * @param request The Protobuf request to send.\n     * @param requestTag A unique client-assigned identifier for this request.\n     * @param retryCodes If provided, a custom list of retry codes. If not\n     * provided, retry is based on the behavior as defined in the ServiceConfig.\n     * @returns A Promise with the request result.\n     */\n    request(methodName, request, requestTag, retryCodes) {\n        const callOptions = this.createCallOptions(methodName, retryCodes);\n        return this._clientPool.run(requestTag, \n        /* requiresGrpc= */ false, async (gapicClient) => {\n            try {\n                (0, logger_1.logger)('Firestore.request', requestTag, 'Sending request: %j', request);\n                const [result] = await gapicClient[methodName](request, callOptions);\n                (0, logger_1.logger)('Firestore.request', requestTag, 'Received response: %j', result);\n                return result;\n            }\n            catch (err) {\n                (0, logger_1.logger)('Firestore.request', requestTag, 'Received error:', err);\n                return Promise.reject(err);\n            }\n        });\n    }\n    /**\n     * A funnel for streaming API requests, assigning a project ID where necessary\n     * within the request options.\n     *\n     * The stream is returned in paused state and needs to be resumed once all\n     * listeners are attached.\n     *\n     * @private\n     * @internal\n     * @param methodName Name of the streaming Veneer API endpoint that\n     * takes a request and GAX options.\n     * @param bidrectional Whether the request is bidirectional (true) or\n     * unidirectional (false_\n     * @param request The Protobuf request to send.\n     * @param requestTag A unique client-assigned identifier for this request.\n     * @returns A Promise with the resulting read-only stream.\n     */\n    requestStream(methodName, bidrectional, request, requestTag) {\n        const callOptions = this.createCallOptions(methodName);\n        const bidirectional = methodName === 'listen';\n        let numResponses = 0;\n        const NUM_RESPONSES_PER_TRACE_EVENT = 100;\n        return this._retry(methodName, requestTag, () => {\n            const result = new util_1.Deferred();\n            void this._clientPool.run(requestTag, bidrectional, async (gapicClient) => {\n                (0, logger_1.logger)('Firestore.requestStream', requestTag, 'Sending request: %j', request);\n                this._traceUtil\n                    .currentSpan()\n                    .addEvent(`Firestore.${methodName}: Start`);\n                try {\n                    const stream = bidirectional\n                        ? gapicClient[methodName](callOptions)\n                        : gapicClient[methodName](request, callOptions);\n                    const logStream = new stream_1.Transform({\n                        objectMode: true,\n                        transform: (chunk, encoding, callback) => {\n                            (0, logger_1.logger)('Firestore.requestStream', requestTag, 'Received response: %j', chunk);\n                            numResponses++;\n                            if (numResponses === 1) {\n                                this._traceUtil\n                                    .currentSpan()\n                                    .addEvent(`Firestore.${methodName}: First response received`);\n                            }\n                            else if (numResponses % NUM_RESPONSES_PER_TRACE_EVENT === 0) {\n                                this._traceUtil\n                                    .currentSpan()\n                                    .addEvent(`Firestore.${methodName}: Received ${numResponses} responses`);\n                            }\n                            callback();\n                        },\n                    });\n                    stream.pipe(logStream);\n                    const lifetime = new util_1.Deferred();\n                    const resultStream = await this._initializeStream(stream, lifetime, requestTag, bidirectional ? request : undefined);\n                    resultStream.on('end', () => {\n                        stream.end();\n                        this._traceUtil\n                            .currentSpan()\n                            .addEvent(`Firestore.${methodName}: Completed`, {\n                            [trace_util_1.ATTRIBUTE_KEY_NUM_RESPONSES]: numResponses,\n                        });\n                    });\n                    result.resolve(resultStream);\n                    // While we return the stream to the callee early, we don't want to\n                    // release the GAPIC client until the callee has finished processing the\n                    // stream.\n                    return lifetime.promise;\n                }\n                catch (e) {\n                    result.reject(e);\n                }\n            });\n            return result.promise;\n        });\n    }\n}\nexports.Firestore = Firestore;\n/**\n * A logging function that takes a single string.\n *\n * @callback Firestore~logFunction\n * @param {string} Log message\n */\n// tslint:disable-next-line:no-default-export\n/**\n * The default export of the `@google-cloud/firestore` package is the\n * {@link Firestore} class.\n *\n * See {@link Firestore} and {@link ClientConfig} for client methods and\n * configuration options.\n *\n * @module {Firestore} @google-cloud/firestore\n * @alias nodejs-firestore\n *\n * @example Install the client library with <a href=\"https://www.npmjs.com/\">npm</a>:\n * ```\n * npm install --save @google-cloud/firestore\n *\n * ```\n * @example Import the client library\n * ```\n * var Firestore = require('@google-cloud/firestore');\n *\n * ```\n * @example Create a client that uses <a href=\"https://cloud.google.com/docs/authentication/production#providing_credentials_to_your_application\">Application Default Credentials (ADC)</a>:\n * ```\n * var firestore = new Firestore();\n *\n * ```\n * @example Create a client with <a href=\"https://cloud.google.com/docs/authentication/production#obtaining_and_providing_service_account_credentials_manually\">explicit credentials</a>:\n * ```\n * var firestore = new Firestore({ projectId:\n *   'your-project-id', keyFilename: '/path/to/keyfile.json'\n * });\n *\n * ```\n * @example <caption>include:samples/quickstart.js</caption>\n * region_tag:firestore_quickstart\n * Full quickstart example:\n */\n// tslint:disable-next-line:no-default-export\nexports.default = Firestore;\n// Horrible hack to ensure backwards compatibility with <= 17.0, which allows\n// users to call the default constructor via\n// `const Fs = require(`@google-cloud/firestore`); new Fs()`;\nconst existingExports = module.exports;\nmodule.exports = Firestore;\nmodule.exports = Object.assign(module.exports, existingExports);\n/**\n * {@link v1beta1} factory function.\n *\n * @private\n * @internal\n * @name Firestore.v1beta1\n * @type {function}\n */\nObject.defineProperty(module.exports, 'v1beta1', {\n    // The v1beta1 module is very large. To avoid pulling it in from static\n    // scope, we lazy-load the module.\n    get: () => require('./v1beta1'),\n});\n/**\n * {@link v1} factory function.\n *\n * @private\n * @internal\n * @name Firestore.v1\n * @type {function}\n */\nObject.defineProperty(module.exports, 'v1', {\n    // The v1 module is very large. To avoid pulling it in from static\n    // scope, we lazy-load  the module.\n    get: () => require('./v1'),\n});\n/**\n * {@link Status} factory function.\n *\n * @private\n * @internal\n * @name Firestore.GrpcStatus\n * @type {function}\n */\nObject.defineProperty(module.exports, 'GrpcStatus', {\n    // The gax module is very large. To avoid pulling it in from static\n    // scope, we lazy-load the module.\n    get: () => require('google-gax').Status,\n});\n"]}