google-cloud 0.0.1-preview.1

Google Cloud clients: Firestore, Cloud Storage, Cloud DNS and Cloud KMS

Readme Files Dependencies Versions

google-cloud#

Google Cloud client libraries for Zena, built on wasi:http and @zena/protobuf so they compile for WebAssembly component targets as well as the zena CLI host.

Installation#

zena pkg add @zena/google-cloud

Libraries#

  • google-cloud/firestore — Firestore document, collection, query, batch, and transaction client.
  • google-cloud/storage — Cloud Storage client for reading, writing, stating, and deleting objects.
  • google-cloud/dns — Cloud DNS client for managing record sets in a managed zone.
  • google-cloud/kms — Cloud KMS client for asymmetric signing and symmetric encryption/decryption.
  • google-cloud/auth — Default credentials and project ID discovery from the GCE metadata server or environment variables.
  • google-cloud/firestore-v1 and google-cloud/storage-v2 — Generated protobuf messages and low-level service clients for google.firestore.v1 and google.storage.v2.
  • google-cloud/testing/fake-kms and google-cloud/testing/firestore-emulator — Test helpers for in-process fake Cloud KMS and the Firestore emulator.

Firestore#

import { Direction, Fields, Firestore, Operator, integerValue } from 'google-cloud/firestore';

let db = await Firestore.connect();

let post = db.collection('posts').doc('hello');
await post.set(new Fields().string('title', 'Hello').integer('views', 0));

let snapshot = await post.get();
if (let (true, views) = snapshot.getInteger('views')) {
  await post.update(new Fields().integer('views', views + 1));
}

let popular = await db.collection('posts')
  .where('views', Operator.GreaterThan, integerValue(100))
  .orderBy('views', Direction.Descending)
  .limit(10)
  .get();
for (let p in popular) {
  console.log(p.id);
}

Firestore.connect() discovers the project and credentials as described under Credentials and talks gRPC to the API. new Firestore({projectId, databaseId?, transport}) accepts explicit configuration instead.

  • References: db.collection(path), db.doc(path), collection.doc(id), doc.collection(id). collection.add(fields) creates a document with a random ID.
  • Writes: set replaces a document, create fails with ALREADY_EXISTS when it exists, update sets the named top-level fields and fails with NOT_FOUND when it does not exist, and delete removes it. Errors are RpcErrors carrying the google.rpc.Code.
  • Transforms (applied by the server when the write commits): Fields.serverTimestamp, increment, incrementDouble, maximum, minimum, arrayUnion, and arrayRemove. In an update, deleteField removes a field. They apply to top-level fields and work in batches and transactions as well: post.update(new Fields().increment('views', 1).serverTimestamp('seen')).
  • Reads: get() returns a DocumentSnapshot, whose exists is false for a missing document. getString, getInteger, getDouble, and getBoolean take a field path such as author.name and return (true, value) or (false, _) when the field is absent or of another type. get(path) returns the raw Value. db.getAll(refs) reads several documents in one call in the order given.
  • Queries: where, orderBy, limit, offset, and select each return a new query. get() collects the results; stream() yields each document as it arrives (for await); count() counts them on the server.
  • Cursors: startAt, startAfter, endAt, and endBefore take values for the orderings or a DocumentSnapshot.
  • Batches & Transactions: db.batch() collects writes and commits them in one call. db.runTransaction(body) runs body with a Transaction, retrying up to five times on contention and rolling back if body throws.
  • Deadlines: Firestore.connect({timeout: milliseconds(10000)}) gives each call a deadline, failing with DEADLINE_EXCEEDED if exceeded.
let total = await db.runTransaction<i64>(async (tx: Transaction): Future<i64> => {
  let counter = db.doc('counters/visits');
  let snapshot = await tx.get(counter);
  var n: i64 = 0;
  if (let (true, stored) = snapshot.getInteger('n')) {
    n = stored;
  }
  tx.set(counter, new Fields().integer('n', n + 1));
  return n + 1;
});

Transports & Emulator#

  • Firestore.connect() uses gRPC (protobuf/grpc) over HTTP/2. When FIRESTORE_EMULATOR_HOST is set to host:port, Firestore.connect() connects to the Firestore emulator over cleartext HTTP/2 with the owner token.
  • Firestore.connectFallback() uses Google's gRPC fallback protocol (protobuf/fallback), which works on HTTP/1.1-only wasi:http hosts such as stock wasmtime serve.
  • new Firestore({projectId, transport}) accepts any ProtoTransport.

Cloud Storage#

import { Storage } from 'google-cloud/storage';

let bucket = Storage.connect().bucket('my-bucket');
await bucket.write('notes/hello.txt', bytes, 'text/plain');
let read = await bucket.read('notes/hello.txt'); // null when absent
let object = await bucket.stat('notes/hello.txt'); // metadata, or null
await bucket.delete('notes/hello.txt'); // true if deleted

Storage.connect() uses the default credentials and talks gRPC to the Cloud Storage API (write streams data in chunks of at most 2 MiB). new Storage(transport) accepts any ProtoTransport, and storage.client exposes the generated StorageClient.

Cloud DNS#

import { CloudDns, RecordSet } from 'google-cloud/dns';

let zone = CloudDns.connect('my-project', 'my-zone');
await zone.put(new RecordSet('_atproto.alice.example.com.', 'TXT', 300, ['"did=did:plc:..."']));
let set = await zone.get('_atproto.alice.example.com.', 'TXT'); // null when absent
await zone.delete('_atproto.alice.example.com.', 'TXT'); // true if deleted

CloudDns uses the Cloud DNS REST API (https://dns.googleapis.com/dns/v1) with default credentials. Names are fully qualified (ending in a .), and put creates or replaces the record set of that name and type.

Cloud KMS#

import { sha256 } from 'zena:crypto';
import { CloudKms, ecPointFromPem } from 'google-cloud/kms';

// Asymmetric signing
let signingKey = CloudKms.connect(
  'projects/p/locations/l/keyRings/r/cryptoKeys/k/cryptoKeyVersions/1'
);
let derSignature = await signingKey.asymmetricSign(sha256(message));
let pubKey = await signingKey.publicKey();
let uncompressedPoint = ecPointFromPem(pubKey.pem);

// Symmetric encryption (AEAD)
let symmetricKey = CloudKms.connect('projects/p/locations/l/keyRings/r/cryptoKeys/s');
let ciphertext = await symmetricKey.encrypt(plaintext, additionalData);
let decrypted = await symmetricKey.decrypt(ciphertext, additionalData);

Credentials#

defaultCredentials() (google-cloud/auth):

  • GOOGLE_OAUTH_ACCESS_TOKEN, when set in the environment, is used directly (for local runs: GOOGLE_OAUTH_ACCESS_TOKEN=$(gcloud auth print-access-token)).
  • Otherwise, the GCE metadata server (at GCE_METADATA_HOST when set, or metadata.google.internal) supplies tokens for the default service account, caching each token until a minute before it expires.

defaultProjectId() reads GOOGLE_CLOUD_PROJECT or GCLOUD_PROJECT when set, falling back to the metadata server.

License#

MIT

280.8 KiB Raw
/** Generated from google/firestore/v1/firestore.proto by the Zena protobuf generator. Do not edit. */

import {
  ProtoBytes,
  ProtoList,
  ProtoMap,
  ProtoStream,
  ProtoTransport,
  ProtoView,
  ProtoWriter,
  RoutingHeader,
  RpcMetadata,
  RpcMethod,
  WIRE_LEN,
  WIRE_VARINT
} from 'protobuf/runtime';

/**
 * The type of change.
 *
 * Protobuf: `google.firestore.v1.TargetChange.TargetChangeType`.
 */
export enum TargetChangeTargetChangeType {
  /** No change has occurred. Used only to send an updated `resume_token`. */
  NoChange = 0,
  /** The targets have been added. */
  Add = 1,
  /** The targets have been removed. */
  Remove = 2,
  /**
   * The targets reflect all changes committed before the targets were added
   * to the stream.
   *
   * This will be sent after or with a `read_time` that is greater than or
   * equal to the time at which the targets were added.
   *
   * Listeners can wait for this change if read-after-write semantics
   * are desired.
   */
  Current = 3,
  /**
   * The targets have been reset, and a new initial state for the targets
   * will be returned in subsequent changes.
   *
   * After the initial state is complete, `CURRENT` will be returned even
   * if the target was previously indicated to be `CURRENT`.
   */
  Reset = 4
}

/**
 * The type of concurrency control mode for transactions.
 *
 * Protobuf: `google.firestore.v1.TransactionOptions.ConcurrencyMode`.
 */
export enum TransactionOptionsConcurrencyMode {
  /** Start the transaction with the database-level default concurrency mode. */
  ConcurrencyModeUnspecified = 0,
  /** Use optimistic concurrency control for the new transaction. */
  Optimistic = 1,
  /** Use pessimistic concurrency control for the new transaction. */
  Pessimistic = 2
}

/**
 * A composite filter operator.
 *
 * Protobuf: `google.firestore.v1.StructuredQuery.CompositeFilter.Operator`.
 */
export enum StructuredQueryCompositeFilterOperator {
  /** Unspecified. This value must not be used. */
  OperatorUnspecified = 0,
  /** Documents are required to satisfy all of the combined filters. */
  And = 1,
  /** Documents are required to satisfy at least one of the combined filters. */
  Or = 2
}

/**
 * A field filter operator.
 *
 * Protobuf: `google.firestore.v1.StructuredQuery.FieldFilter.Operator`.
 */
export enum StructuredQueryFieldFilterOperator {
  /** Unspecified. This value must not be used. */
  OperatorUnspecified = 0,
  /**
   * The given `field` is less than the given `value`.
   *
   * Requires:
   *
   * * That `field` come first in `order_by`.
   */
  LessThan = 1,
  /**
   * The given `field` is less than or equal to the given `value`.
   *
   * Requires:
   *
   * * That `field` come first in `order_by`.
   */
  LessThanOrEqual = 2,
  /**
   * The given `field` is greater than the given `value`.
   *
   * Requires:
   *
   * * That `field` come first in `order_by`.
   */
  GreaterThan = 3,
  /**
   * The given `field` is greater than or equal to the given `value`.
   *
   * Requires:
   *
   * * That `field` come first in `order_by`.
   */
  GreaterThanOrEqual = 4,
  /** The given `field` is equal to the given `value`. */
  Equal = 5,
  /**
   * The given `field` is not equal to the given `value`.
   *
   * Requires:
   *
   * * No other `NOT_EQUAL`, `NOT_IN`, `IS_NOT_NULL`, or `IS_NOT_NAN`.
   * * That `field` comes first in the `order_by`.
   */
  NotEqual = 6,
  /** The given `field` is an array that contains the given `value`. */
  ArrayContains = 7,
  /**
   * The given `field` is equal to at least one value in the given array.
   *
   * Requires:
   *
   * * That `value` is a non-empty `ArrayValue`, subject to disjunction
   *   limits.
   * * No `NOT_IN` filters in the same query.
   */
  In = 8,
  /**
   * The given `field` is an array that contains any of the values in the
   * given array.
   *
   * Requires:
   *
   * * That `value` is a non-empty `ArrayValue`, subject to disjunction
   *   limits.
   * * No other `ARRAY_CONTAINS_ANY` filters within the same disjunction.
   * * No `NOT_IN` filters in the same query.
   */
  ArrayContainsAny = 9,
  /**
   * The value of the `field` is not in the given array.
   *
   * Requires:
   *
   * * That `value` is a non-empty `ArrayValue` with at most 10 values.
   * * No other `OR`, `IN`, `ARRAY_CONTAINS_ANY`, `NOT_IN`, `NOT_EQUAL`,
   *   `IS_NOT_NULL`, or `IS_NOT_NAN`.
   * * That `field` comes first in the `order_by`.
   */
  NotIn = 10
}

/**
 * A unary operator.
 *
 * Protobuf: `google.firestore.v1.StructuredQuery.UnaryFilter.Operator`.
 */
export enum StructuredQueryUnaryFilterOperator {
  /** Unspecified. This value must not be used. */
  OperatorUnspecified = 0,
  /** The given `field` is equal to `NaN`. */
  IsNan = 2,
  /** The given `field` is equal to `NULL`. */
  IsNull = 3,
  /**
   * The given `field` is not equal to `NaN`.
   *
   * Requires:
   *
   * * No other `NOT_EQUAL`, `NOT_IN`, `IS_NOT_NULL`, or `IS_NOT_NAN`.
   * * That `field` comes first in the `order_by`.
   */
  IsNotNan = 4,
  /**
   * The given `field` is not equal to `NULL`.
   *
   * Requires:
   *
   * * A single `NOT_EQUAL`, `NOT_IN`, `IS_NOT_NULL`, or `IS_NOT_NAN`.
   * * That `field` comes first in the `order_by`.
   */
  IsNotNull = 5
}

/**
 * The distance measure to use when comparing vectors.
 *
 * Protobuf: `google.firestore.v1.StructuredQuery.FindNearest.DistanceMeasure`.
 */
export enum StructuredQueryFindNearestDistanceMeasure {
  /** Should not be set. */
  DistanceMeasureUnspecified = 0,
  /**
   * Measures the EUCLIDEAN distance between the vectors. See
   * [Euclidean](https://en.wikipedia.org/wiki/Euclidean_distance) to learn
   * more. The resulting distance decreases the more similar two vectors
   * are.
   */
  Euclidean = 1,
  /**
   * COSINE distance compares vectors based on the angle between them, which
   * allows you to measure similarity that isn't based on the vectors
   * magnitude. We recommend using DOT_PRODUCT with unit normalized vectors
   * instead of COSINE distance, which is mathematically equivalent with
   * better performance. See [Cosine
   * Similarity](https://en.wikipedia.org/wiki/Cosine_similarity) to learn
   * more about COSINE similarity and COSINE distance. The resulting
   * COSINE distance decreases the more similar two vectors are.
   */
  Cosine = 2,
  /**
   * Similar to cosine but is affected by the magnitude of the vectors. See
   * [Dot Product](https://en.wikipedia.org/wiki/Dot_product) to learn more.
   * The resulting distance increases the more similar two vectors are.
   */
  DotProduct = 3
}

/**
 * A sort direction.
 *
 * Protobuf: `google.firestore.v1.StructuredQuery.Direction`.
 */
export enum StructuredQueryDirection {
  /** Unspecified. */
  DirectionUnspecified = 0,
  /** Ascending. */
  Ascending = 1,
  /** Descending. */
  Descending = 2
}

/**
 * A value that is calculated by the server.
 *
 * Protobuf: `google.firestore.v1.DocumentTransform.FieldTransform.ServerValue`.
 */
export enum DocumentTransformFieldTransformServerValue {
  /** Unspecified. This value must not be used. */
  ServerValueUnspecified = 0,
  /**
   * The time at which the server processed the request, with millisecond
   * precision. If used on multiple fields (same or different documents) in
   * a transaction, all the fields will get the same server timestamp.
   */
  RequestTime = 1
}

/**
 * Represents a JSON `null`.
 *
 * `NullValue` is a sentinel, using an enum with only one value to represent
 * the null value for the `Value` type union.
 *
 * A field of type `NullValue` with any value other than `0` is considered
 * invalid. Most ProtoJSON serializers will emit a `Value` with a `null_value`
 * set as a JSON `null` regardless of the integer value, and so will round trip
 * to a `0` value.
 *
 * Protobuf: `google.protobuf.NullValue`.
 */
export enum NullValue {
  /** Null value. */
  NullValue = 0
}

/**
 * The consistency mode for this transaction.
 * If not set, defaults to strong consistency.
 *
 * The member of `google.firestore.v1.GetDocumentRequest.consistency_selector` that is set, as `GetDocumentRequest.consistencySelector` reads it.
 */
export sealed class GetDocumentRequestConsistencySelector {
  case GetDocumentRequestTransaction(value: ProtoBytes)
  case GetDocumentRequestReadTime(value: Timestamp)
  case GetDocumentRequestConsistencySelectorNotSet
}

/** The fields of a `google.firestore.v1.GetDocumentRequest` to encode, for `GetDocumentRequest.of`. */
export type GetDocumentRequestInit = {
  name: String,
  mask?: DocumentMask,
  transaction?: ByteArray | ProtoBytes,
  readTime?: Timestamp,
  requestOptions?: RequestOptions,
};

/**
 * The request for
 * [Firestore.GetDocument][google.firestore.v1.Firestore.GetDocument].
 *
 * Protobuf: `google.firestore.v1.GetDocumentRequest`.
 */
export final class GetDocumentRequest {
  #m: ProtoView;

  /** A message over `m`, which must hold an encoded `google.firestore.v1.GetDocumentRequest`. */
  new(m: ProtoView) : #m = m;

  /** Decodes `bytes`. Fields are decoded as they are read. */
  static decode(bytes: ByteArray): GetDocumentRequest {
    return new GetDocumentRequest(ProtoView.of(bytes));
  }

  /** Encodes `init` as a `google.firestore.v1.GetDocumentRequest`. */
  static of(init: GetDocumentRequestInit): GetDocumentRequest {
    let w = new ProtoWriter();
    let f1 = init.name;
    w.string(1, f1);
    if (let {mask as f2} = init) {
      w.message(2, f2.protoView);
    }
    if (let {transaction as f3} = init) {
      w.bytes(3, f3);
    }
    if (let {readTime as f5} = init) {
      w.message(5, f5.protoView);
    }
    if (let {requestOptions as f10} = init) {
      w.message(10, f10.protoView);
    }
    return new GetDocumentRequest(w.finish());
  }

  /** The encoded message. */
  protoView: ProtoView {
    get { return this.#m; }
  }

  /**
   * Required. The resource name of the Document to get. In the format:
   * `projects/{project_id}/databases/{database_id}/documents/{document_path}`.
   */
  name: String {
    get { return this.#m.string(1); }
  }

  /**
   * The fields to return. If not set, returns all fields.
   *
   * If the document has a field that is not present in this mask, that field
   * will not be returned in the response.
   */
  mask: DocumentMask | null {
    get {
      let m = this.#m.message(2);
      return if (m == null) null else new DocumentMask(m as ProtoView);
    }
  }

  /** Reads the document in a transaction. */
  transaction: ProtoBytes {
    get {
      if (this.#whichConsistencySelector() != 3) {
        return ProtoBytes.empty();
      }
      return this.#m.bytes(3);
    }
  }

  /** Whether `transaction` is set. */
  hasTransaction: boolean {
    get { return this.#whichConsistencySelector() == 3; }
  }

  /**
   * Reads the version of the document at the given time.
   *
   * This must be a microsecond precision timestamp within the past one hour,
   * or if Point-in-Time Recovery is enabled, can additionally be a whole
   * minute timestamp within the past 7 days.
   */
  readTime: Timestamp | null {
    get {
      if (this.#whichConsistencySelector() != 5) {
        return null;
      }
      let m = this.#m.message(5);
      return if (m == null) null else new Timestamp(m as ProtoView);
    }
  }

  /** Optional. Any additional options for the request. */
  requestOptions: RequestOptions | null {
    get {
      let m = this.#m.message(10);
      return if (m == null) null else new RequestOptions(m as ProtoView);
    }
  }

  /** The member of `consistency_selector` that is set. */
  consistencySelector: GetDocumentRequestConsistencySelector {
    get {
      let which = this.#whichConsistencySelector();
      if (which == 3) {
        return new GetDocumentRequestTransaction(this.#m.bytes(3));
      }
      if (which == 5) {
        return new GetDocumentRequestReadTime(new Timestamp(this.#m.message(5) as ProtoView));
      }
      return new GetDocumentRequestConsistencySelectorNotSet();
    }
  }

  #whichConsistencySelector(): i32 {
    return this.#m.whichOf([3, 5]);
  }
}

/**
 * The consistency mode for this transaction.
 * If not set, defaults to strong consistency.
 *
 * The member of `google.firestore.v1.ListDocumentsRequest.consistency_selector` that is set, as `ListDocumentsRequest.consistencySelector` reads it.
 */
export sealed class ListDocumentsRequestConsistencySelector {
  case ListDocumentsRequestTransaction(value: ProtoBytes)
  case ListDocumentsRequestReadTime(value: Timestamp)
  case ListDocumentsRequestConsistencySelectorNotSet
}

/** The fields of a `google.firestore.v1.ListDocumentsRequest` to encode, for `ListDocumentsRequest.of`. */
export type ListDocumentsRequestInit = {
  parent: String,
  collectionId?: String,
  pageSize?: i32,
  pageToken?: String,
  orderBy?: String,
  mask?: DocumentMask,
  transaction?: ByteArray | ProtoBytes,
  readTime?: Timestamp,
  showMissing?: boolean,
  requestOptions?: RequestOptions,
};

/**
 * The request for
 * [Firestore.ListDocuments][google.firestore.v1.Firestore.ListDocuments].
 *
 * Protobuf: `google.firestore.v1.ListDocumentsRequest`.
 */
export final class ListDocumentsRequest {
  #m: ProtoView;

  /** A message over `m`, which must hold an encoded `google.firestore.v1.ListDocumentsRequest`. */
  new(m: ProtoView) : #m = m;

  /** Decodes `bytes`. Fields are decoded as they are read. */
  static decode(bytes: ByteArray): ListDocumentsRequest {
    return new ListDocumentsRequest(ProtoView.of(bytes));
  }

  /** Encodes `init` as a `google.firestore.v1.ListDocumentsRequest`. */
  static of(init: ListDocumentsRequestInit): ListDocumentsRequest {
    let w = new ProtoWriter();
    let f1 = init.parent;
    w.string(1, f1);
    if (let {collectionId as f2} = init) {
      w.string(2, f2);
    }
    if (let {pageSize as f3} = init) {
      w.int32(3, f3);
    }
    if (let {pageToken as f4} = init) {
      w.string(4, f4);
    }
    if (let {orderBy as f6} = init) {
      w.string(6, f6);
    }
    if (let {mask as f7} = init) {
      w.message(7, f7.protoView);
    }
    if (let {transaction as f8} = init) {
      w.bytes(8, f8);
    }
    if (let {readTime as f10} = init) {
      w.message(10, f10.protoView);
    }
    if (let {showMissing as f12} = init) {
      w.bool(12, f12);
    }
    if (let {requestOptions as f13} = init) {
      w.message(13, f13.protoView);
    }
    return new ListDocumentsRequest(w.finish());
  }

  /** The encoded message. */
  protoView: ProtoView {
    get { return this.#m; }
  }

  /**
   * Required. The parent resource name. In the format:
   * `projects/{project_id}/databases/{database_id}/documents` or
   * `projects/{project_id}/databases/{database_id}/documents/{document_path}`.
   *
   * For example:
   * `projects/my-project/databases/my-database/documents` or
   * `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom`
   */
  parent: String {
    get { return this.#m.string(1); }
  }

  /**
   * Optional. The collection ID, relative to `parent`, to list.
   *
   * For example: `chatrooms` or `messages`.
   *
   * This is optional, and when not provided, Firestore will list documents
   * from all collections under the provided `parent`.
   */
  collectionId: String {
    get { return this.#m.string(2); }
  }

  /**
   * Optional. The maximum number of documents to return in a single response.
   *
   * Firestore may return fewer than this value.
   */
  pageSize: i32 {
    get { return this.#m.int32(3); }
  }

  /**
   * Optional. A page token, received from a previous `ListDocuments` response.
   *
   * Provide this to retrieve the subsequent page. When paginating, all other
   * parameters (with the exception of `page_size`) must match the values set
   * in the request that generated the page token.
   */
  pageToken: String {
    get { return this.#m.string(4); }
  }

  /**
   * Optional. The optional ordering of the documents to return.
   *
   * For example: `priority desc, __name__ desc`.
   *
   * This mirrors the [`ORDER BY`][google.firestore.v1.StructuredQuery.order_by]
   * used in Firestore queries but in a string representation. When absent,
   * documents are ordered based on `__name__ ASC`.
   */
  orderBy: String {
    get { return this.#m.string(6); }
  }

  /**
   * Optional. The fields to return. If not set, returns all fields.
   *
   * If a document has a field that is not present in this mask, that field
   * will not be returned in the response.
   */
  mask: DocumentMask | null {
    get {
      let m = this.#m.message(7);
      return if (m == null) null else new DocumentMask(m as ProtoView);
    }
  }

  /** Perform the read as part of an already active transaction. */
  transaction: ProtoBytes {
    get {
      if (this.#whichConsistencySelector() != 8) {
        return ProtoBytes.empty();
      }
      return this.#m.bytes(8);
    }
  }

  /** Whether `transaction` is set. */
  hasTransaction: boolean {
    get { return this.#whichConsistencySelector() == 8; }
  }

  /**
   * Perform the read at the provided time.
   *
   * This must be a microsecond precision timestamp within the past one hour,
   * or if Point-in-Time Recovery is enabled, can additionally be a whole
   * minute timestamp within the past 7 days.
   */
  readTime: Timestamp | null {
    get {
      if (this.#whichConsistencySelector() != 10) {
        return null;
      }
      let m = this.#m.message(10);
      return if (m == null) null else new Timestamp(m as ProtoView);
    }
  }

  /**
   * If the list should show missing documents.
   *
   * A document is missing if it does not exist, but there are sub-documents
   * nested underneath it. When true, such missing documents will be returned
   * with a key but will not have fields,
   * [`create_time`][google.firestore.v1.Document.create_time], or
   * [`update_time`][google.firestore.v1.Document.update_time] set.
   *
   * Requests with `show_missing` may not specify `where` or `order_by`.
   */
  showMissing: boolean {
    get { return this.#m.bool(12); }
  }

  /** Optional. Any additional options for the request. */
  requestOptions: RequestOptions | null {
    get {
      let m = this.#m.message(13);
      return if (m == null) null else new RequestOptions(m as ProtoView);
    }
  }

  /** The member of `consistency_selector` that is set. */
  consistencySelector: ListDocumentsRequestConsistencySelector {
    get {
      let which = this.#whichConsistencySelector();
      if (which == 8) {
        return new ListDocumentsRequestTransaction(this.#m.bytes(8));
      }
      if (which == 10) {
        return new ListDocumentsRequestReadTime(new Timestamp(this.#m.message(10) as ProtoView));
      }
      return new ListDocumentsRequestConsistencySelectorNotSet();
    }
  }

  #whichConsistencySelector(): i32 {
    return this.#m.whichOf([8, 10]);
  }
}

/** The fields of a `google.firestore.v1.ListDocumentsResponse` to encode, for `ListDocumentsResponse.of`. */
export type ListDocumentsResponseInit = {
  documents?: Array<Document>,
  nextPageToken?: String,
};

/**
 * The response for
 * [Firestore.ListDocuments][google.firestore.v1.Firestore.ListDocuments].
 *
 * Protobuf: `google.firestore.v1.ListDocumentsResponse`.
 */
export final class ListDocumentsResponse {
  #m: ProtoView;

  /** A message over `m`, which must hold an encoded `google.firestore.v1.ListDocumentsResponse`. */
  new(m: ProtoView) : #m = m;

  /** Decodes `bytes`. Fields are decoded as they are read. */
  static decode(bytes: ByteArray): ListDocumentsResponse {
    return new ListDocumentsResponse(ProtoView.of(bytes));
  }

  /** Encodes `init` as a `google.firestore.v1.ListDocumentsResponse`. */
  static of(init: ListDocumentsResponseInit): ListDocumentsResponse {
    let w = new ProtoWriter();
    if (let {documents as f1} = init) {
      for (let item in f1) {
        w.message(1, item.protoView);
      }
    }
    if (let {nextPageToken as f2} = init) {
      w.string(2, f2);
    }
    return new ListDocumentsResponse(w.finish());
  }

  /** The encoded message. */
  protoView: ProtoView {
    get { return this.#m; }
  }

  /** The Documents found. */
  documents: ProtoList<Document> {
    get { return this.#m.repeated(1, WIRE_LEN, (v, p) => new Document(v.messageAt(p))); }
  }

  /**
   * A token to retrieve the next page of documents.
   *
   * If this field is omitted, there are no subsequent pages.
   */
  nextPageToken: String {
    get { return this.#m.string(2); }
  }
}

/** The fields of a `google.firestore.v1.CreateDocumentRequest` to encode, for `CreateDocumentRequest.of`. */
export type CreateDocumentRequestInit = {
  parent: String,
  collectionId: String,
  documentId?: String,
  document: Document,
  mask?: DocumentMask,
  requestOptions?: RequestOptions,
};

/**
 * The request for
 * [Firestore.CreateDocument][google.firestore.v1.Firestore.CreateDocument].
 *
 * Protobuf: `google.firestore.v1.CreateDocumentRequest`.
 */
export final class CreateDocumentRequest {
  #m: ProtoView;

  /** A message over `m`, which must hold an encoded `google.firestore.v1.CreateDocumentRequest`. */
  new(m: ProtoView) : #m = m;

  /** Decodes `bytes`. Fields are decoded as they are read. */
  static decode(bytes: ByteArray): CreateDocumentRequest {
    return new CreateDocumentRequest(ProtoView.of(bytes));
  }

  /** Encodes `init` as a `google.firestore.v1.CreateDocumentRequest`. */
  static of(init: CreateDocumentRequestInit): CreateDocumentRequest {
    let w = new ProtoWriter();
    let f1 = init.parent;
    w.string(1, f1);
    let f2 = init.collectionId;
    w.string(2, f2);
    if (let {documentId as f3} = init) {
      w.string(3, f3);
    }
    let f4 = init.document;
    w.message(4, f4.protoView);
    if (let {mask as f5} = init) {
      w.message(5, f5.protoView);
    }
    if (let {requestOptions as f6} = init) {
      w.message(6, f6.protoView);
    }
    return new CreateDocumentRequest(w.finish());
  }

  /** The encoded message. */
  protoView: ProtoView {
    get { return this.#m; }
  }

  /**
   * Required. The parent resource. For example:
   * `projects/{project_id}/databases/{database_id}/documents` or
   * `projects/{project_id}/databases/{database_id}/documents/chatrooms/{chatroom_id}`
   */
  parent: String {
    get { return this.#m.string(1); }
  }

  /**
   * Required. The collection ID, relative to `parent`, to list. For example:
   * `chatrooms`.
   */
  collectionId: String {
    get { return this.#m.string(2); }
  }

  /**
   * The client-assigned document ID to use for this document.
   *
   * Optional. If not specified, an ID will be assigned by the service.
   */
  documentId: String {
    get { return this.#m.string(3); }
  }

  /** Required. The document to create. `name` must not be set. */
  document: Document | null {
    get {
      let m = this.#m.message(4);
      return if (m == null) null else new Document(m as ProtoView);
    }
  }

  /**
   * The fields to return. If not set, returns all fields.
   *
   * If the document has a field that is not present in this mask, that field
   * will not be returned in the response.
   */
  mask: DocumentMask | null {
    get {
      let m = this.#m.message(5);
      return if (m == null) null else new DocumentMask(m as ProtoView);
    }
  }

  /** Optional. Any additional options for the request. */
  requestOptions: RequestOptions | null {
    get {
      let m = this.#m.message(6);
      return if (m == null) null else new RequestOptions(m as ProtoView);
    }
  }
}

/** The fields of a `google.firestore.v1.UpdateDocumentRequest` to encode, for `UpdateDocumentRequest.of`. */
export type UpdateDocumentRequestInit = {
  document: Document,
  updateMask?: DocumentMask,
  mask?: DocumentMask,
  currentDocument?: Precondition,
  requestOptions?: RequestOptions,
};

/**
 * The request for
 * [Firestore.UpdateDocument][google.firestore.v1.Firestore.UpdateDocument].
 *
 * Protobuf: `google.firestore.v1.UpdateDocumentRequest`.
 */
export final class UpdateDocumentRequest {
  #m: ProtoView;

  /** A message over `m`, which must hold an encoded `google.firestore.v1.UpdateDocumentRequest`. */
  new(m: ProtoView) : #m = m;

  /** Decodes `bytes`. Fields are decoded as they are read. */
  static decode(bytes: ByteArray): UpdateDocumentRequest {
    return new UpdateDocumentRequest(ProtoView.of(bytes));
  }

  /** Encodes `init` as a `google.firestore.v1.UpdateDocumentRequest`. */
  static of(init: UpdateDocumentRequestInit): UpdateDocumentRequest {
    let w = new ProtoWriter();
    let f1 = init.document;
    w.message(1, f1.protoView);
    if (let {updateMask as f2} = init) {
      w.message(2, f2.protoView);
    }
    if (let {mask as f3} = init) {
      w.message(3, f3.protoView);
    }
    if (let {currentDocument as f4} = init) {
      w.message(4, f4.protoView);
    }
    if (let {requestOptions as f5} = init) {
      w.message(5, f5.protoView);
    }
    return new UpdateDocumentRequest(w.finish());
  }

  /** The encoded message. */
  protoView: ProtoView {
    get { return this.#m; }
  }

  /**
   * Required. The updated document.
   * Creates the document if it does not already exist.
   */
  document: Document | null {
    get {
      let m = this.#m.message(1);
      return if (m == null) null else new Document(m as ProtoView);
    }
  }

  /**
   * The fields to update.
   * None of the field paths in the mask may contain a reserved name.
   *
   * If the document exists on the server and has fields not referenced in the
   * mask, they are left unchanged.
   * Fields referenced in the mask, but not present in the input document, are
   * deleted from the document on the server.
   */
  updateMask: DocumentMask | null {
    get {
      let m = this.#m.message(2);
      return if (m == null) null else new DocumentMask(m as ProtoView);
    }
  }

  /**
   * The fields to return. If not set, returns all fields.
   *
   * If the document has a field that is not present in this mask, that field
   * will not be returned in the response.
   */
  mask: DocumentMask | null {
    get {
      let m = this.#m.message(3);
      return if (m == null) null else new DocumentMask(m as ProtoView);
    }
  }

  /**
   * An optional precondition on the document.
   * The request will fail if this is set and not met by the target document.
   */
  currentDocument: Precondition | null {
    get {
      let m = this.#m.message(4);
      return if (m == null) null else new Precondition(m as ProtoView);
    }
  }

  /** Optional. Any additional options for the request. */
  requestOptions: RequestOptions | null {
    get {
      let m = this.#m.message(5);
      return if (m == null) null else new RequestOptions(m as ProtoView);
    }
  }
}

/** The fields of a `google.firestore.v1.DeleteDocumentRequest` to encode, for `DeleteDocumentRequest.of`. */
export type DeleteDocumentRequestInit = {
  name: String,
  currentDocument?: Precondition,
  requestOptions?: RequestOptions,
};

/**
 * The request for
 * [Firestore.DeleteDocument][google.firestore.v1.Firestore.DeleteDocument].
 *
 * Protobuf: `google.firestore.v1.DeleteDocumentRequest`.
 */
export final class DeleteDocumentRequest {
  #m: ProtoView;

  /** A message over `m`, which must hold an encoded `google.firestore.v1.DeleteDocumentRequest`. */
  new(m: ProtoView) : #m = m;

  /** Decodes `bytes`. Fields are decoded as they are read. */
  static decode(bytes: ByteArray): DeleteDocumentRequest {
    return new DeleteDocumentRequest(ProtoView.of(bytes));
  }

  /** Encodes `init` as a `google.firestore.v1.DeleteDocumentRequest`. */
  static of(init: DeleteDocumentRequestInit): DeleteDocumentRequest {
    let w = new ProtoWriter();
    let f1 = init.name;
    w.string(1, f1);
    if (let {currentDocument as f2} = init) {
      w.message(2, f2.protoView);
    }
    if (let {requestOptions as f3} = init) {
      w.message(3, f3.protoView);
    }
    return new DeleteDocumentRequest(w.finish());
  }

  /** The encoded message. */
  protoView: ProtoView {
    get { return this.#m; }
  }

  /**
   * Required. The resource name of the Document to delete. In the format:
   * `projects/{project_id}/databases/{database_id}/documents/{document_path}`.
   */
  name: String {
    get { return this.#m.string(1); }
  }

  /**
   * An optional precondition on the document.
   * The request will fail if this is set and not met by the target document.
   */
  currentDocument: Precondition | null {
    get {
      let m = this.#m.message(2);
      return if (m == null) null else new Precondition(m as ProtoView);
    }
  }

  /** Optional. Any additional options for the request. */
  requestOptions: RequestOptions | null {
    get {
      let m = this.#m.message(3);
      return if (m == null) null else new RequestOptions(m as ProtoView);
    }
  }
}

/**
 * The consistency mode for this transaction.
 * If not set, defaults to strong consistency.
 *
 * The member of `google.firestore.v1.BatchGetDocumentsRequest.consistency_selector` that is set, as `BatchGetDocumentsRequest.consistencySelector` reads it.
 */
export sealed class BatchGetDocumentsRequestConsistencySelector {
  case BatchGetDocumentsRequestTransaction(value: ProtoBytes)
  case BatchGetDocumentsRequestNewTransaction(value: TransactionOptions)
  case BatchGetDocumentsRequestReadTime(value: Timestamp)
  case BatchGetDocumentsRequestConsistencySelectorNotSet
}

/** The fields of a `google.firestore.v1.BatchGetDocumentsRequest` to encode, for `BatchGetDocumentsRequest.of`. */
export type BatchGetDocumentsRequestInit = {
  database: String,
  documents?: Array<String>,
  mask?: DocumentMask,
  transaction?: ByteArray | ProtoBytes,
  newTransaction?: TransactionOptions,
  readTime?: Timestamp,
  requestOptions?: RequestOptions,
};

/**
 * The request for
 * [Firestore.BatchGetDocuments][google.firestore.v1.Firestore.BatchGetDocuments].
 *
 * Protobuf: `google.firestore.v1.BatchGetDocumentsRequest`.
 */
export final class BatchGetDocumentsRequest {
  #m: ProtoView;

  /** A message over `m`, which must hold an encoded `google.firestore.v1.BatchGetDocumentsRequest`. */
  new(m: ProtoView) : #m = m;

  /** Decodes `bytes`. Fields are decoded as they are read. */
  static decode(bytes: ByteArray): BatchGetDocumentsRequest {
    return new BatchGetDocumentsRequest(ProtoView.of(bytes));
  }

  /** Encodes `init` as a `google.firestore.v1.BatchGetDocumentsRequest`. */
  static of(init: BatchGetDocumentsRequestInit): BatchGetDocumentsRequest {
    let w = new ProtoWriter();
    let f1 = init.database;
    w.string(1, f1);
    if (let {documents as f2} = init) {
      for (let item in f2) {
        w.string(2, item);
      }
    }
    if (let {mask as f3} = init) {
      w.message(3, f3.protoView);
    }
    if (let {transaction as f4} = init) {
      w.bytes(4, f4);
    }
    if (let {newTransaction as f5} = init) {
      w.message(5, f5.protoView);
    }
    if (let {readTime as f7} = init) {
      w.message(7, f7.protoView);
    }
    if (let {requestOptions as f8} = init) {
      w.message(8, f8.protoView);
    }
    return new BatchGetDocumentsRequest(w.finish());
  }

  /** The encoded message. */
  protoView: ProtoView {
    get { return this.#m; }
  }

  /**
   * Required. The database name. In the format:
   * `projects/{project_id}/databases/{database_id}`.
   */
  database: String {
    get { return this.#m.string(1); }
  }

  /**
   * The names of the documents to retrieve. In the format:
   * `projects/{project_id}/databases/{database_id}/documents/{document_path}`.
   * The request will fail if any of the document is not a child resource of the
   * given `database`. Duplicate names will be elided.
   */
  documents: ProtoList<String> {
    get { return this.#m.repeated(2, WIRE_LEN, (v, p) => v.stringAt(p)); }
  }

  /**
   * The fields to return. If not set, returns all fields.
   *
   * If a document has a field that is not present in this mask, that field will
   * not be returned in the response.
   */
  mask: DocumentMask | null {
    get {
      let m = this.#m.message(3);
      return if (m == null) null else new DocumentMask(m as ProtoView);
    }
  }

  /** Reads documents in a transaction. */
  transaction: ProtoBytes {
    get {
      if (this.#whichConsistencySelector() != 4) {
        return ProtoBytes.empty();
      }
      return this.#m.bytes(4);
    }
  }

  /** Whether `transaction` is set. */
  hasTransaction: boolean {
    get { return this.#whichConsistencySelector() == 4; }
  }

  /**
   * Starts a new transaction and reads the documents.
   * Defaults to a read-only transaction.
   * The new transaction ID will be returned as the first response in the
   * stream.
   */
  newTransaction: TransactionOptions | null {
    get {
      if (this.#whichConsistencySelector() != 5) {
        return null;
      }
      let m = this.#m.message(5);
      return if (m == null) null else new TransactionOptions(m as ProtoView);
    }
  }

  /**
   * Reads documents as they were at the given time.
   *
   * This must be a microsecond precision timestamp within the past one hour,
   * or if Point-in-Time Recovery is enabled, can additionally be a whole
   * minute timestamp within the past 7 days.
   */
  readTime: Timestamp | null {
    get {
      if (this.#whichConsistencySelector() != 7) {
        return null;
      }
      let m = this.#m.message(7);
      return if (m == null) null else new Timestamp(m as ProtoView);
    }
  }

  /** Optional. Any additional options for the request. */
  requestOptions: RequestOptions | null {
    get {
      let m = this.#m.message(8);
      return if (m == null) null else new RequestOptions(m as ProtoView);
    }
  }

  /** The member of `consistency_selector` that is set. */
  consistencySelector: BatchGetDocumentsRequestConsistencySelector {
    get {
      let which = this.#whichConsistencySelector();
      if (which == 4) {
        return new BatchGetDocumentsRequestTransaction(this.#m.bytes(4));
      }
      if (which == 5) {
        return new BatchGetDocumentsRequestNewTransaction(new TransactionOptions(this.#m.message(5) as ProtoView));
      }
      if (which == 7) {
        return new BatchGetDocumentsRequestReadTime(new Timestamp(this.#m.message(7) as ProtoView));
      }
      return new BatchGetDocumentsRequestConsistencySelectorNotSet();
    }
  }

  #whichConsistencySelector(): i32 {
    return this.#m.whichOf([4, 5, 7]);
  }
}

/**
 * A single result.
 * This can be empty if the server is just returning a transaction.
 *
 * The member of `google.firestore.v1.BatchGetDocumentsResponse.result` that is set, as `BatchGetDocumentsResponse.result` reads it.
 */
export sealed class BatchGetDocumentsResponseResult {
  case BatchGetDocumentsResponseFound(value: Document)
  case BatchGetDocumentsResponseMissing(value: String)
  case BatchGetDocumentsResponseResultNotSet
}

/** The fields of a `google.firestore.v1.BatchGetDocumentsResponse` to encode, for `BatchGetDocumentsResponse.of`. */
export type BatchGetDocumentsResponseInit = {
  found?: Document,
  missing?: String,
  transaction?: ByteArray | ProtoBytes,
  readTime?: Timestamp,
};

/**
 * The streamed response for
 * [Firestore.BatchGetDocuments][google.firestore.v1.Firestore.BatchGetDocuments].
 *
 * Protobuf: `google.firestore.v1.BatchGetDocumentsResponse`.
 */
export final class BatchGetDocumentsResponse {
  #m: ProtoView;

  /** A message over `m`, which must hold an encoded `google.firestore.v1.BatchGetDocumentsResponse`. */
  new(m: ProtoView) : #m = m;

  /** Decodes `bytes`. Fields are decoded as they are read. */
  static decode(bytes: ByteArray): BatchGetDocumentsResponse {
    return new BatchGetDocumentsResponse(ProtoView.of(bytes));
  }

  /** Encodes `init` as a `google.firestore.v1.BatchGetDocumentsResponse`. */
  static of(init: BatchGetDocumentsResponseInit): BatchGetDocumentsResponse {
    let w = new ProtoWriter();
    if (let {found as f1} = init) {
      w.message(1, f1.protoView);
    }
    if (let {missing as f2} = init) {
      w.string(2, f2);
    }
    if (let {transaction as f3} = init) {
      w.bytes(3, f3);
    }
    if (let {readTime as f4} = init) {
      w.message(4, f4.protoView);
    }
    return new BatchGetDocumentsResponse(w.finish());
  }

  /** The encoded message. */
  protoView: ProtoView {
    get { return this.#m; }
  }

  /** A document that was requested. */
  found: Document | null {
    get {
      if (this.#whichResult() != 1) {
        return null;
      }
      let m = this.#m.message(1);
      return if (m == null) null else new Document(m as ProtoView);
    }
  }

  /**
   * A document name that was requested but does not exist. In the format:
   * `projects/{project_id}/databases/{database_id}/documents/{document_path}`.
   */
  missing: String {
    get {
      if (this.#whichResult() != 2) {
        return '';
      }
      return this.#m.string(2);
    }
  }

  /** Whether `missing` is set. */
  hasMissing: boolean {
    get { return this.#whichResult() == 2; }
  }

  /**
   * The transaction that was started as part of this request.
   * Will only be set in the first response, and only if
   * [BatchGetDocumentsRequest.new_transaction][google.firestore.v1.BatchGetDocumentsRequest.new_transaction]
   * was set in the request.
   */
  transaction: ProtoBytes {
    get { return this.#m.bytes(3); }
  }

  /**
   * The time at which the document was read.
   * This may be monotically increasing, in this case the previous documents in
   * the result stream are guaranteed not to have changed between their
   * read_time and this one.
   */
  readTime: Timestamp | null {
    get {
      let m = this.#m.message(4);
      return if (m == null) null else new Timestamp(m as ProtoView);
    }
  }

  /** The member of `result` that is set. */
  result: BatchGetDocumentsResponseResult {
    get {
      let which = this.#whichResult();
      if (which == 1) {
        return new BatchGetDocumentsResponseFound(new Document(this.#m.message(1) as ProtoView));
      }
      if (which == 2) {
        return new BatchGetDocumentsResponseMissing(this.#m.string(2));
      }
      return new BatchGetDocumentsResponseResultNotSet();
    }
  }

  #whichResult(): i32 {
    return this.#m.whichOf([1, 2]);
  }
}

/** The fields of a `google.firestore.v1.BeginTransactionRequest` to encode, for `BeginTransactionRequest.of`. */
export type BeginTransactionRequestInit = {
  database: String,
  options?: TransactionOptions,
  requestOptions?: RequestOptions,
};

/**
 * The request for
 * [Firestore.BeginTransaction][google.firestore.v1.Firestore.BeginTransaction].
 *
 * Protobuf: `google.firestore.v1.BeginTransactionRequest`.
 */
export final class BeginTransactionRequest {
  #m: ProtoView;

  /** A message over `m`, which must hold an encoded `google.firestore.v1.BeginTransactionRequest`. */
  new(m: ProtoView) : #m = m;

  /** Decodes `bytes`. Fields are decoded as they are read. */
  static decode(bytes: ByteArray): BeginTransactionRequest {
    return new BeginTransactionRequest(ProtoView.of(bytes));
  }

  /** Encodes `init` as a `google.firestore.v1.BeginTransactionRequest`. */
  static of(init: BeginTransactionRequestInit): BeginTransactionRequest {
    let w = new ProtoWriter();
    let f1 = init.database;
    w.string(1, f1);
    if (let {options as f2} = init) {
      w.message(2, f2.protoView);
    }
    if (let {requestOptions as f3} = init) {
      w.message(3, f3.protoView);
    }
    return new BeginTransactionRequest(w.finish());
  }

  /** The encoded message. */
  protoView: ProtoView {
    get { return this.#m; }
  }

  /**
   * Required. The database name. In the format:
   * `projects/{project_id}/databases/{database_id}`.
   */
  database: String {
    get { return this.#m.string(1); }
  }

  /**
   * The options for the transaction.
   * Defaults to a read-write transaction.
   */
  options: TransactionOptions | null {
    get {
      let m = this.#m.message(2);
      return if (m == null) null else new TransactionOptions(m as ProtoView);
    }
  }

  /** Optional. Any additional options for the request. */
  requestOptions: RequestOptions | null {
    get {
      let m = this.#m.message(3);
      return if (m == null) null else new RequestOptions(m as ProtoView);
    }
  }
}

/** The fields of a `google.firestore.v1.BeginTransactionResponse` to encode, for `BeginTransactionResponse.of`. */
export type BeginTransactionResponseInit = {
  transaction?: ByteArray | ProtoBytes,
};

/**
 * The response for
 * [Firestore.BeginTransaction][google.firestore.v1.Firestore.BeginTransaction].
 *
 * Protobuf: `google.firestore.v1.BeginTransactionResponse`.
 */
export final class BeginTransactionResponse {
  #m: ProtoView;

  /** A message over `m`, which must hold an encoded `google.firestore.v1.BeginTransactionResponse`. */
  new(m: ProtoView) : #m = m;

  /** Decodes `bytes`. Fields are decoded as they are read. */
  static decode(bytes: ByteArray): BeginTransactionResponse {
    return new BeginTransactionResponse(ProtoView.of(bytes));
  }

  /** Encodes `init` as a `google.firestore.v1.BeginTransactionResponse`. */
  static of(init: BeginTransactionResponseInit): BeginTransactionResponse {
    let w = new ProtoWriter();
    if (let {transaction as f1} = init) {
      w.bytes(1, f1);
    }
    return new BeginTransactionResponse(w.finish());
  }

  /** The encoded message. */
  protoView: ProtoView {
    get { return this.#m; }
  }

  /** The transaction that was started. */
  transaction: ProtoBytes {
    get { return this.#m.bytes(1); }
  }
}

/** The fields of a `google.firestore.v1.CommitRequest` to encode, for `CommitRequest.of`. */
export type CommitRequestInit = {
  database: String,
  writes?: Array<Write>,
  transaction?: ByteArray | ProtoBytes,
  requestOptions?: RequestOptions,
};

/**
 * The request for [Firestore.Commit][google.firestore.v1.Firestore.Commit].
 *
 * Protobuf: `google.firestore.v1.CommitRequest`.
 */
export final class CommitRequest {
  #m: ProtoView;

  /** A message over `m`, which must hold an encoded `google.firestore.v1.CommitRequest`. */
  new(m: ProtoView) : #m = m;

  /** Decodes `bytes`. Fields are decoded as they are read. */
  static decode(bytes: ByteArray): CommitRequest {
    return new CommitRequest(ProtoView.of(bytes));
  }

  /** Encodes `init` as a `google.firestore.v1.CommitRequest`. */
  static of(init: CommitRequestInit): CommitRequest {
    let w = new ProtoWriter();
    let f1 = init.database;
    w.string(1, f1);
    if (let {writes as f2} = init) {
      for (let item in f2) {
        w.message(2, item.protoView);
      }
    }
    if (let {transaction as f3} = init) {
      w.bytes(3, f3);
    }
    if (let {requestOptions as f4} = init) {
      w.message(4, f4.protoView);
    }
    return new CommitRequest(w.finish());
  }

  /** The encoded message. */
  protoView: ProtoView {
    get { return this.#m; }
  }

  /**
   * Required. The database name. In the format:
   * `projects/{project_id}/databases/{database_id}`.
   */
  database: String {
    get { return this.#m.string(1); }
  }

  /**
   * The writes to apply.
   *
   * Always executed atomically and in order.
   */
  writes: ProtoList<Write> {
    get { return this.#m.repeated(2, WIRE_LEN, (v, p) => new Write(v.messageAt(p))); }
  }

  /** If set, applies all writes in this transaction, and commits it. */
  transaction: ProtoBytes {
    get { return this.#m.bytes(3); }
  }

  /** Optional. Any additional options for the request. */
  requestOptions: RequestOptions | null {
    get {
      let m = this.#m.message(4);
      return if (m == null) null else new RequestOptions(m as ProtoView);
    }
  }
}

/** The fields of a `google.firestore.v1.CommitResponse` to encode, for `CommitResponse.of`. */
export type CommitResponseInit = {
  writeResults?: Array<WriteResult>,
  commitTime?: Timestamp,
};

/**
 * The response for [Firestore.Commit][google.firestore.v1.Firestore.Commit].
 *
 * Protobuf: `google.firestore.v1.CommitResponse`.
 */
export final class CommitResponse {
  #m: ProtoView;

  /** A message over `m`, which must hold an encoded `google.firestore.v1.CommitResponse`. */
  new(m: ProtoView) : #m = m;

  /** Decodes `bytes`. Fields are decoded as they are read. */
  static decode(bytes: ByteArray): CommitResponse {
    return new CommitResponse(ProtoView.of(bytes));
  }

  /** Encodes `init` as a `google.firestore.v1.CommitResponse`. */
  static of(init: CommitResponseInit): CommitResponse {
    let w = new ProtoWriter();
    if (let {writeResults as f1} = init) {
      for (let item in f1) {
        w.message(1, item.protoView);
      }
    }
    if (let {commitTime as f2} = init) {
      w.message(2, f2.protoView);
    }
    return new CommitResponse(w.finish());
  }

  /** The encoded message. */
  protoView: ProtoView {
    get { return this.#m; }
  }

  /**
   * The result of applying the writes.
   *
   * This i-th write result corresponds to the i-th write in the
   * request.
   */
  writeResults: ProtoList<WriteResult> {
    get { return this.#m.repeated(1, WIRE_LEN, (v, p) => new WriteResult(v.messageAt(p))); }
  }

  /**
   * The time at which the commit occurred. Any read with an equal or greater
   * `read_time` is guaranteed to see the effects of the commit.
   */
  commitTime: Timestamp | null {
    get {
      let m = this.#m.message(2);
      return if (m == null) null else new Timestamp(m as ProtoView);
    }
  }
}

/** The fields of a `google.firestore.v1.RollbackRequest` to encode, for `RollbackRequest.of`. */
export type RollbackRequestInit = {
  database: String,
  transaction: ByteArray | ProtoBytes,
  requestOptions?: RequestOptions,
};

/**
 * The request for [Firestore.Rollback][google.firestore.v1.Firestore.Rollback].
 *
 * Protobuf: `google.firestore.v1.RollbackRequest`.
 */
export final class RollbackRequest {
  #m: ProtoView;

  /** A message over `m`, which must hold an encoded `google.firestore.v1.RollbackRequest`. */
  new(m: ProtoView) : #m = m;

  /** Decodes `bytes`. Fields are decoded as they are read. */
  static decode(bytes: ByteArray): RollbackRequest {
    return new RollbackRequest(ProtoView.of(bytes));
  }

  /** Encodes `init` as a `google.firestore.v1.RollbackRequest`. */
  static of(init: RollbackRequestInit): RollbackRequest {
    let w = new ProtoWriter();
    let f1 = init.database;
    w.string(1, f1);
    let f2 = init.transaction;
    w.bytes(2, f2);
    if (let {requestOptions as f3} = init) {
      w.message(3, f3.protoView);
    }
    return new RollbackRequest(w.finish());
  }

  /** The encoded message. */
  protoView: ProtoView {
    get { return this.#m; }
  }

  /**
   * Required. The database name. In the format:
   * `projects/{project_id}/databases/{database_id}`.
   */
  database: String {
    get { return this.#m.string(1); }
  }

  /** Required. The transaction to roll back. */
  transaction: ProtoBytes {
    get { return this.#m.bytes(2); }
  }

  /** Optional. Any additional options for the request. */
  requestOptions: RequestOptions | null {
    get {
      let m = this.#m.message(3);
      return if (m == null) null else new RequestOptions(m as ProtoView);
    }
  }
}

/**
 * The query to run.
 *
 * The member of `google.firestore.v1.RunQueryRequest.query_type` that is set, as `RunQueryRequest.queryType` reads it.
 */
export sealed class RunQueryRequestQueryType {
  case RunQueryRequestStructuredQuery(value: StructuredQuery)
  case RunQueryRequestQueryTypeNotSet
}

/**
 * The consistency mode for this transaction.
 * If not set, defaults to strong consistency.
 *
 * The member of `google.firestore.v1.RunQueryRequest.consistency_selector` that is set, as `RunQueryRequest.consistencySelector` reads it.
 */
export sealed class RunQueryRequestConsistencySelector {
  case RunQueryRequestTransaction(value: ProtoBytes)
  case RunQueryRequestNewTransaction(value: TransactionOptions)
  case RunQueryRequestReadTime(value: Timestamp)
  case RunQueryRequestConsistencySelectorNotSet
}

/** The fields of a `google.firestore.v1.RunQueryRequest` to encode, for `RunQueryRequest.of`. */
export type RunQueryRequestInit = {
  parent: String,
  structuredQuery?: StructuredQuery,
  transaction?: ByteArray | ProtoBytes,
  newTransaction?: TransactionOptions,
  readTime?: Timestamp,
  explainOptions?: ExplainOptions,
  requestOptions?: RequestOptions,
};

/**
 * The request for [Firestore.RunQuery][google.firestore.v1.Firestore.RunQuery].
 *
 * Protobuf: `google.firestore.v1.RunQueryRequest`.
 */
export final class RunQueryRequest {
  #m: ProtoView;

  /** A message over `m`, which must hold an encoded `google.firestore.v1.RunQueryRequest`. */
  new(m: ProtoView) : #m = m;

  /** Decodes `bytes`. Fields are decoded as they are read. */
  static decode(bytes: ByteArray): RunQueryRequest {
    return new RunQueryRequest(ProtoView.of(bytes));
  }

  /** Encodes `init` as a `google.firestore.v1.RunQueryRequest`. */
  static of(init: RunQueryRequestInit): RunQueryRequest {
    let w = new ProtoWriter();
    let f1 = init.parent;
    w.string(1, f1);
    if (let {structuredQuery as f2} = init) {
      w.message(2, f2.protoView);
    }
    if (let {transaction as f5} = init) {
      w.bytes(5, f5);
    }
    if (let {newTransaction as f6} = init) {
      w.message(6, f6.protoView);
    }
    if (let {readTime as f7} = init) {
      w.message(7, f7.protoView);
    }
    if (let {explainOptions as f10} = init) {
      w.message(10, f10.protoView);
    }
    if (let {requestOptions as f11} = init) {
      w.message(11, f11.protoView);
    }
    return new RunQueryRequest(w.finish());
  }

  /** The encoded message. */
  protoView: ProtoView {
    get { return this.#m; }
  }

  /**
   * Required. The parent resource name. In the format:
   * `projects/{project_id}/databases/{database_id}/documents` or
   * `projects/{project_id}/databases/{database_id}/documents/{document_path}`.
   * For example:
   * `projects/my-project/databases/my-database/documents` or
   * `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom`
   */
  parent: String {
    get { return this.#m.string(1); }
  }

  /** A structured query. */
  structuredQuery: StructuredQuery | null {
    get {
      if (this.#whichQueryType() != 2) {
        return null;
      }
      let m = this.#m.message(2);
      return if (m == null) null else new StructuredQuery(m as ProtoView);
    }
  }

  /**
   * Run the query within an already active transaction.
   *
   * The value here is the opaque transaction ID to execute the query in.
   */
  transaction: ProtoBytes {
    get {
      if (this.#whichConsistencySelector() != 5) {
        return ProtoBytes.empty();
      }
      return this.#m.bytes(5);
    }
  }

  /** Whether `transaction` is set. */
  hasTransaction: boolean {
    get { return this.#whichConsistencySelector() == 5; }
  }

  /**
   * Starts a new transaction and reads the documents.
   * Defaults to a read-only transaction.
   * The new transaction ID will be returned as the first response in the
   * stream.
   */
  newTransaction: TransactionOptions | null {
    get {
      if (this.#whichConsistencySelector() != 6) {
        return null;
      }
      let m = this.#m.message(6);
      return if (m == null) null else new TransactionOptions(m as ProtoView);
    }
  }

  /**
   * Reads documents as they were at the given time.
   *
   * This must be a microsecond precision timestamp within the past one hour,
   * or if Point-in-Time Recovery is enabled, can additionally be a whole
   * minute timestamp within the past 7 days.
   */
  readTime: Timestamp | null {
    get {
      if (this.#whichConsistencySelector() != 7) {
        return null;
      }
      let m = this.#m.message(7);
      return if (m == null) null else new Timestamp(m as ProtoView);
    }
  }

  /**
   * Optional. Explain options for the query. If set, additional query
   * statistics will be returned. If not, only query results will be returned.
   */
  explainOptions: ExplainOptions | null {
    get {
      let m = this.#m.message(10);
      return if (m == null) null else new ExplainOptions(m as ProtoView);
    }
  }

  /** Optional. Any additional options for the request. */
  requestOptions: RequestOptions | null {
    get {
      let m = this.#m.message(11);
      return if (m == null) null else new RequestOptions(m as ProtoView);
    }
  }

  /** The member of `query_type` that is set. */
  queryType: RunQueryRequestQueryType {
    get {
      let which = this.#whichQueryType();
      if (which == 2) {
        return new RunQueryRequestStructuredQuery(new StructuredQuery(this.#m.message(2) as ProtoView));
      }
      return new RunQueryRequestQueryTypeNotSet();
    }
  }

  #whichQueryType(): i32 {
    return this.#m.whichOf([2]);
  }

  /** The member of `consistency_selector` that is set. */
  consistencySelector: RunQueryRequestConsistencySelector {
    get {
      let which = this.#whichConsistencySelector();
      if (which == 5) {
        return new RunQueryRequestTransaction(this.#m.bytes(5));
      }
      if (which == 6) {
        return new RunQueryRequestNewTransaction(new TransactionOptions(this.#m.message(6) as ProtoView));
      }
      if (which == 7) {
        return new RunQueryRequestReadTime(new Timestamp(this.#m.message(7) as ProtoView));
      }
      return new RunQueryRequestConsistencySelectorNotSet();
    }
  }

  #whichConsistencySelector(): i32 {
    return this.#m.whichOf([5, 6, 7]);
  }
}

/**
 * The continuation mode for the query. If present, it indicates the current
 * query response stream has finished. This can be set with or without a
 * `document` present, but when set, no more results are returned.
 *
 * The member of `google.firestore.v1.RunQueryResponse.continuation_selector` that is set, as `RunQueryResponse.continuationSelector` reads it.
 */
export sealed class RunQueryResponseContinuationSelector {
  case RunQueryResponseDone(value: boolean)
  case RunQueryResponseContinuationSelectorNotSet
}

/** The fields of a `google.firestore.v1.RunQueryResponse` to encode, for `RunQueryResponse.of`. */
export type RunQueryResponseInit = {
  transaction?: ByteArray | ProtoBytes,
  document?: Document,
  readTime?: Timestamp,
  skippedResults?: i32,
  done?: boolean,
  explainMetrics?: ExplainMetrics,
};

/**
 * The response for
 * [Firestore.RunQuery][google.firestore.v1.Firestore.RunQuery].
 *
 * Protobuf: `google.firestore.v1.RunQueryResponse`.
 */
export final class RunQueryResponse {
  #m: ProtoView;

  /** A message over `m`, which must hold an encoded `google.firestore.v1.RunQueryResponse`. */
  new(m: ProtoView) : #m = m;

  /** Decodes `bytes`. Fields are decoded as they are read. */
  static decode(bytes: ByteArray): RunQueryResponse {
    return new RunQueryResponse(ProtoView.of(bytes));
  }

  /** Encodes `init` as a `google.firestore.v1.RunQueryResponse`. */
  static of(init: RunQueryResponseInit): RunQueryResponse {
    let w = new ProtoWriter();
    if (let {transaction as f2} = init) {
      w.bytes(2, f2);
    }
    if (let {document as f1} = init) {
      w.message(1, f1.protoView);
    }
    if (let {readTime as f3} = init) {
      w.message(3, f3.protoView);
    }
    if (let {skippedResults as f4} = init) {
      w.int32(4, f4);
    }
    if (let {done as f6} = init) {
      w.bool(6, f6);
    }
    if (let {explainMetrics as f11} = init) {
      w.message(11, f11.protoView);
    }
    return new RunQueryResponse(w.finish());
  }

  /** The encoded message. */
  protoView: ProtoView {
    get { return this.#m; }
  }

  /**
   * The transaction that was started as part of this request.
   * Can only be set in the first response, and only if
   * [RunQueryRequest.new_transaction][google.firestore.v1.RunQueryRequest.new_transaction]
   * was set in the request. If set, no other fields will be set in this
   * response.
   */
  transaction: ProtoBytes {
    get { return this.#m.bytes(2); }
  }

  /** A query result, not set when reporting partial progress. */
  document: Document | null {
    get {
      let m = this.#m.message(1);
      return if (m == null) null else new Document(m as ProtoView);
    }
  }

  /**
   * The time at which the document was read. This may be monotonically
   * increasing; in this case, the previous documents in the result stream are
   * guaranteed not to have changed between their `read_time` and this one.
   *
   * If the query returns no results, a response with `read_time` and no
   * `document` will be sent, and this represents the time at which the query
   * was run.
   */
  readTime: Timestamp | null {
    get {
      let m = this.#m.message(3);
      return if (m == null) null else new Timestamp(m as ProtoView);
    }
  }

  /**
   * The number of results that have been skipped due to an offset between
   * the last response and the current response.
   */
  skippedResults: i32 {
    get { return this.#m.int32(4); }
  }

  /**
   * If present, Firestore has completely finished the request and no more
   * documents will be returned.
   */
  done: boolean {
    get {
      if (this.#whichContinuationSelector() != 6) {
        return false;
      }
      return this.#m.bool(6);
    }
  }

  /** Whether `done` is set. */
  hasDone: boolean {
    get { return this.#whichContinuationSelector() == 6; }
  }

  /**
   * Query explain metrics. This is only present when the
   * [RunQueryRequest.explain_options][google.firestore.v1.RunQueryRequest.explain_options]
   * is provided, and it is sent only once with the last response in the stream.
   */
  explainMetrics: ExplainMetrics | null {
    get {
      let m = this.#m.message(11);
      return if (m == null) null else new ExplainMetrics(m as ProtoView);
    }
  }

  /** The member of `continuation_selector` that is set. */
  continuationSelector: RunQueryResponseContinuationSelector {
    get {
      let which = this.#whichContinuationSelector();
      if (which == 6) {
        return new RunQueryResponseDone(this.#m.bool(6));
      }
      return new RunQueryResponseContinuationSelectorNotSet();
    }
  }

  #whichContinuationSelector(): i32 {
    return this.#m.whichOf([6]);
  }
}

/** The member of `google.firestore.v1.ExecutePipelineRequest.pipeline_type` that is set, as `ExecutePipelineRequest.pipelineType` reads it. */
export sealed class ExecutePipelineRequestPipelineType {
  case ExecutePipelineRequestStructuredPipeline(value: StructuredPipeline)
  case ExecutePipelineRequestPipelineTypeNotSet
}

/**
 * Optional consistency arguments, defaults to strong consistency.
 *
 * The member of `google.firestore.v1.ExecutePipelineRequest.consistency_selector` that is set, as `ExecutePipelineRequest.consistencySelector` reads it.
 */
export sealed class ExecutePipelineRequestConsistencySelector {
  case ExecutePipelineRequestTransaction(value: ProtoBytes)
  case ExecutePipelineRequestNewTransaction(value: TransactionOptions)
  case ExecutePipelineRequestReadTime(value: Timestamp)
  case ExecutePipelineRequestConsistencySelectorNotSet
}

/** The fields of a `google.firestore.v1.ExecutePipelineRequest` to encode, for `ExecutePipelineRequest.of`. */
export type ExecutePipelineRequestInit = {
  database: String,
  structuredPipeline?: StructuredPipeline,
  transaction?: ByteArray | ProtoBytes,
  newTransaction?: TransactionOptions,
  readTime?: Timestamp,
  autoCommitTransaction?: boolean,
  requestOptions?: RequestOptions,
};

/**
 * The request for
 * [Firestore.ExecutePipeline][google.firestore.v1.Firestore.ExecutePipeline].
 *
 * Protobuf: `google.firestore.v1.ExecutePipelineRequest`.
 */
export final class ExecutePipelineRequest {
  #m: ProtoView;

  /** A message over `m`, which must hold an encoded `google.firestore.v1.ExecutePipelineRequest`. */
  new(m: ProtoView) : #m = m;

  /** Decodes `bytes`. Fields are decoded as they are read. */
  static decode(bytes: ByteArray): ExecutePipelineRequest {
    return new ExecutePipelineRequest(ProtoView.of(bytes));
  }

  /** Encodes `init` as a `google.firestore.v1.ExecutePipelineRequest`. */
  static of(init: ExecutePipelineRequestInit): ExecutePipelineRequest {
    let w = new ProtoWriter();
    let f1 = init.database;
    w.string(1, f1);
    if (let {structuredPipeline as f2} = init) {
      w.message(2, f2.protoView);
    }
    if (let {transaction as f5} = init) {
      w.bytes(5, f5);
    }
    if (let {newTransaction as f6} = init) {
      w.message(6, f6.protoView);
    }
    if (let {readTime as f7} = init) {
      w.message(7, f7.protoView);
    }
    if (let {autoCommitTransaction as f9} = init) {
      w.bool(9, f9);
    }
    if (let {requestOptions as f10} = init) {
      w.message(10, f10.protoView);
    }
    return new ExecutePipelineRequest(w.finish());
  }

  /** The encoded message. */
  protoView: ProtoView {
    get { return this.#m; }
  }

  /**
   * Required. Database identifier, in the form
   * `projects/{project}/databases/{database}`.
   */
  database: String {
    get { return this.#m.string(1); }
  }

  /** A pipelined operation. */
  structuredPipeline: StructuredPipeline | null {
    get {
      if (this.#whichPipelineType() != 2) {
        return null;
      }
      let m = this.#m.message(2);
      return if (m == null) null else new StructuredPipeline(m as ProtoView);
    }
  }

  /**
   * Run the query within an already active transaction.
   *
   * The value here is the opaque transaction ID to execute the query in.
   */
  transaction: ProtoBytes {
    get {
      if (this.#whichConsistencySelector() != 5) {
        return ProtoBytes.empty();
      }
      return this.#m.bytes(5);
    }
  }

  /** Whether `transaction` is set. */
  hasTransaction: boolean {
    get { return this.#whichConsistencySelector() == 5; }
  }

  /**
   * Execute the pipeline in a new transaction.
   *
   * The identifier of the newly created transaction will be returned in the
   * first response on the stream. This defaults to a read-only transaction.
   */
  newTransaction: TransactionOptions | null {
    get {
      if (this.#whichConsistencySelector() != 6) {
        return null;
      }
      let m = this.#m.message(6);
      return if (m == null) null else new TransactionOptions(m as ProtoView);
    }
  }

  /**
   * Execute the pipeline in a snapshot transaction at the given time.
   *
   * This must be a microsecond precision timestamp within the past one hour,
   * or if Point-in-Time Recovery is enabled, can additionally be a whole
   * minute timestamp within the past 7 days.
   */
  readTime: Timestamp | null {
    get {
      if (this.#whichConsistencySelector() != 7) {
        return null;
      }
      let m = this.#m.message(7);
      return if (m == null) null else new Timestamp(m as ProtoView);
    }
  }

  /**
   * Optional. Automatically commits the transaction after the pipeline has been
   * executed. Only permitted in combination with `transaction` or
   * `new_transaction`.
   */
  autoCommitTransaction: boolean {
    get { return this.#m.bool(9); }
  }

  /** Optional. Any additional options for the request. */
  requestOptions: RequestOptions | null {
    get {
      let m = this.#m.message(10);
      return if (m == null) null else new RequestOptions(m as ProtoView);
    }
  }

  /** The member of `pipeline_type` that is set. */
  pipelineType: ExecutePipelineRequestPipelineType {
    get {
      let which = this.#whichPipelineType();
      if (which == 2) {
        return new ExecutePipelineRequestStructuredPipeline(new StructuredPipeline(this.#m.message(2) as ProtoView));
      }
      return new ExecutePipelineRequestPipelineTypeNotSet();
    }
  }

  #whichPipelineType(): i32 {
    return this.#m.whichOf([2]);
  }

  /** The member of `consistency_selector` that is set. */
  consistencySelector: ExecutePipelineRequestConsistencySelector {
    get {
      let which = this.#whichConsistencySelector();
      if (which == 5) {
        return new ExecutePipelineRequestTransaction(this.#m.bytes(5));
      }
      if (which == 6) {
        return new ExecutePipelineRequestNewTransaction(new TransactionOptions(this.#m.message(6) as ProtoView));
      }
      if (which == 7) {
        return new ExecutePipelineRequestReadTime(new Timestamp(this.#m.message(7) as ProtoView));
      }
      return new ExecutePipelineRequestConsistencySelectorNotSet();
    }
  }

  #whichConsistencySelector(): i32 {
    return this.#m.whichOf([5, 6, 7]);
  }
}

/** The fields of a `google.firestore.v1.ExecutePipelineResponse` to encode, for `ExecutePipelineResponse.of`. */
export type ExecutePipelineResponseInit = {
  transaction?: ByteArray | ProtoBytes,
  results?: Array<Document>,
  executionTime?: Timestamp,
  explainStats?: ExplainStats,
};

/**
 * The response for [Firestore.Execute][].
 *
 * Protobuf: `google.firestore.v1.ExecutePipelineResponse`.
 */
export final class ExecutePipelineResponse {
  #m: ProtoView;

  /** A message over `m`, which must hold an encoded `google.firestore.v1.ExecutePipelineResponse`. */
  new(m: ProtoView) : #m = m;

  /** Decodes `bytes`. Fields are decoded as they are read. */
  static decode(bytes: ByteArray): ExecutePipelineResponse {
    return new ExecutePipelineResponse(ProtoView.of(bytes));
  }

  /** Encodes `init` as a `google.firestore.v1.ExecutePipelineResponse`. */
  static of(init: ExecutePipelineResponseInit): ExecutePipelineResponse {
    let w = new ProtoWriter();
    if (let {transaction as f1} = init) {
      w.bytes(1, f1);
    }
    if (let {results as f2} = init) {
      for (let item in f2) {
        w.message(2, item.protoView);
      }
    }
    if (let {executionTime as f3} = init) {
      w.message(3, f3.protoView);
    }
    if (let {explainStats as f4} = init) {
      w.message(4, f4.protoView);
    }
    return new ExecutePipelineResponse(w.finish());
  }

  /** The encoded message. */
  protoView: ProtoView {
    get { return this.#m; }
  }

  /**
   * Newly created transaction identifier.
   *
   * This field is only specified as part of the first response from the server,
   * alongside the `results` field when the original request specified
   * [ExecuteRequest.new_transaction][].
   */
  transaction: ProtoBytes {
    get { return this.#m.bytes(1); }
  }

  /**
   * An ordered batch of results returned executing a pipeline.
   *
   * The batch size is variable, and can even be zero for when only a partial
   * progress message is returned.
   *
   * The fields present in the returned documents are only those that were
   * explicitly requested in the pipeline, this includes those like
   * [`__name__`][google.firestore.v1.Document.name] and
   * [`__update_time__`][google.firestore.v1.Document.update_time]. This is
   * explicitly a divergence from `Firestore.RunQuery` / `Firestore.GetDocument`
   * RPCs which always return such fields even when they are not specified in
   * the [`mask`][google.firestore.v1.DocumentMask].
   */
  results: ProtoList<Document> {
    get { return this.#m.repeated(2, WIRE_LEN, (v, p) => new Document(v.messageAt(p))); }
  }

  /**
   * The time at which the results are valid.
   *
   * This is a (not strictly) monotonically increasing value across multiple
   * responses in the same stream. The API guarantees that all previously
   * returned results are still valid at the latest `execution_time`. This
   * allows the API consumer to treat the query if it ran at the latest
   * `execution_time` returned.
   *
   * If the query returns no results, a response with `execution_time` and no
   * `results` will be sent, and this represents the time at which the operation
   * was run.
   */
  executionTime: Timestamp | null {
    get {
      let m = this.#m.message(3);
      return if (m == null) null else new Timestamp(m as ProtoView);
    }
  }

  /**
   * Query explain stats.
   *
   * This is present on the **last** response if the request configured explain
   * to run in 'analyze' or 'explain' mode in the pipeline options. If the query
   * does not return any results, a response with `explain_stats` and no
   * `results` will still be sent.
   */
  explainStats: ExplainStats | null {
    get {
      let m = this.#m.message(4);
      return if (m == null) null else new ExplainStats(m as ProtoView);
    }
  }
}

/**
 * The query to run.
 *
 * The member of `google.firestore.v1.RunAggregationQueryRequest.query_type` that is set, as `RunAggregationQueryRequest.queryType` reads it.
 */
export sealed class RunAggregationQueryRequestQueryType {
  case RunAggregationQueryRequestStructuredAggregationQuery(value: StructuredAggregationQuery)
  case RunAggregationQueryRequestQueryTypeNotSet
}

/**
 * The consistency mode for the query, defaults to strong consistency.
 *
 * The member of `google.firestore.v1.RunAggregationQueryRequest.consistency_selector` that is set, as `RunAggregationQueryRequest.consistencySelector` reads it.
 */
export sealed class RunAggregationQueryRequestConsistencySelector {
  case RunAggregationQueryRequestTransaction(value: ProtoBytes)
  case RunAggregationQueryRequestNewTransaction(value: TransactionOptions)
  case RunAggregationQueryRequestReadTime(value: Timestamp)
  case RunAggregationQueryRequestConsistencySelectorNotSet
}

/** The fields of a `google.firestore.v1.RunAggregationQueryRequest` to encode, for `RunAggregationQueryRequest.of`. */
export type RunAggregationQueryRequestInit = {
  parent: String,
  structuredAggregationQuery?: StructuredAggregationQuery,
  transaction?: ByteArray | ProtoBytes,
  newTransaction?: TransactionOptions,
  readTime?: Timestamp,
  explainOptions?: ExplainOptions,
  requestOptions?: RequestOptions,
};

/**
 * The request for
 * [Firestore.RunAggregationQuery][google.firestore.v1.Firestore.RunAggregationQuery].
 *
 * Protobuf: `google.firestore.v1.RunAggregationQueryRequest`.
 */
export final class RunAggregationQueryRequest {
  #m: ProtoView;

  /** A message over `m`, which must hold an encoded `google.firestore.v1.RunAggregationQueryRequest`. */
  new(m: ProtoView) : #m = m;

  /** Decodes `bytes`. Fields are decoded as they are read. */
  static decode(bytes: ByteArray): RunAggregationQueryRequest {
    return new RunAggregationQueryRequest(ProtoView.of(bytes));
  }

  /** Encodes `init` as a `google.firestore.v1.RunAggregationQueryRequest`. */
  static of(init: RunAggregationQueryRequestInit): RunAggregationQueryRequest {
    let w = new ProtoWriter();
    let f1 = init.parent;
    w.string(1, f1);
    if (let {structuredAggregationQuery as f2} = init) {
      w.message(2, f2.protoView);
    }
    if (let {transaction as f4} = init) {
      w.bytes(4, f4);
    }
    if (let {newTransaction as f5} = init) {
      w.message(5, f5.protoView);
    }
    if (let {readTime as f6} = init) {
      w.message(6, f6.protoView);
    }
    if (let {explainOptions as f8} = init) {
      w.message(8, f8.protoView);
    }
    if (let {requestOptions as f9} = init) {
      w.message(9, f9.protoView);
    }
    return new RunAggregationQueryRequest(w.finish());
  }

  /** The encoded message. */
  protoView: ProtoView {
    get { return this.#m; }
  }

  /**
   * Required. The parent resource name. In the format:
   * `projects/{project_id}/databases/{database_id}/documents` or
   * `projects/{project_id}/databases/{database_id}/documents/{document_path}`.
   * For example:
   * `projects/my-project/databases/my-database/documents` or
   * `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom`
   */
  parent: String {
    get { return this.#m.string(1); }
  }

  /** An aggregation query. */
  structuredAggregationQuery: StructuredAggregationQuery | null {
    get {
      if (this.#whichQueryType() != 2) {
        return null;
      }
      let m = this.#m.message(2);
      return if (m == null) null else new StructuredAggregationQuery(m as ProtoView);
    }
  }

  /**
   * Run the aggregation within an already active transaction.
   *
   * The value here is the opaque transaction ID to execute the query in.
   */
  transaction: ProtoBytes {
    get {
      if (this.#whichConsistencySelector() != 4) {
        return ProtoBytes.empty();
      }
      return this.#m.bytes(4);
    }
  }

  /** Whether `transaction` is set. */
  hasTransaction: boolean {
    get { return this.#whichConsistencySelector() == 4; }
  }

  /**
   * Starts a new transaction as part of the query, defaulting to read-only.
   *
   * The new transaction ID will be returned as the first response in the
   * stream.
   */
  newTransaction: TransactionOptions | null {
    get {
      if (this.#whichConsistencySelector() != 5) {
        return null;
      }
      let m = this.#m.message(5);
      return if (m == null) null else new TransactionOptions(m as ProtoView);
    }
  }

  /**
   * Executes the query at the given timestamp.
   *
   * This must be a microsecond precision timestamp within the past one hour,
   * or if Point-in-Time Recovery is enabled, can additionally be a whole
   * minute timestamp within the past 7 days.
   */
  readTime: Timestamp | null {
    get {
      if (this.#whichConsistencySelector() != 6) {
        return null;
      }
      let m = this.#m.message(6);
      return if (m == null) null else new Timestamp(m as ProtoView);
    }
  }

  /**
   * Optional. Explain options for the query. If set, additional query
   * statistics will be returned. If not, only query results will be returned.
   */
  explainOptions: ExplainOptions | null {
    get {
      let m = this.#m.message(8);
      return if (m == null) null else new ExplainOptions(m as ProtoView);
    }
  }

  /** Optional. Any additional options for the request. */
  requestOptions: RequestOptions | null {
    get {
      let m = this.#m.message(9);
      return if (m == null) null else new RequestOptions(m as ProtoView);
    }
  }

  /** The member of `query_type` that is set. */
  queryType: RunAggregationQueryRequestQueryType {
    get {
      let which = this.#whichQueryType();
      if (which == 2) {
        return new RunAggregationQueryRequestStructuredAggregationQuery(new StructuredAggregationQuery(this.#m.message(2) as ProtoView));
      }
      return new RunAggregationQueryRequestQueryTypeNotSet();
    }
  }

  #whichQueryType(): i32 {
    return this.#m.whichOf([2]);
  }

  /** The member of `consistency_selector` that is set. */
  consistencySelector: RunAggregationQueryRequestConsistencySelector {
    get {
      let which = this.#whichConsistencySelector();
      if (which == 4) {
        return new RunAggregationQueryRequestTransaction(this.#m.bytes(4));
      }
      if (which == 5) {
        return new RunAggregationQueryRequestNewTransaction(new TransactionOptions(this.#m.message(5) as ProtoView));
      }
      if (which == 6) {
        return new RunAggregationQueryRequestReadTime(new Timestamp(this.#m.message(6) as ProtoView));
      }
      return new RunAggregationQueryRequestConsistencySelectorNotSet();
    }
  }

  #whichConsistencySelector(): i32 {
    return this.#m.whichOf([4, 5, 6]);
  }
}

/** The fields of a `google.firestore.v1.RunAggregationQueryResponse` to encode, for `RunAggregationQueryResponse.of`. */
export type RunAggregationQueryResponseInit = {
  result?: AggregationResult,
  transaction?: ByteArray | ProtoBytes,
  readTime?: Timestamp,
  explainMetrics?: ExplainMetrics,
};

/**
 * The response for
 * [Firestore.RunAggregationQuery][google.firestore.v1.Firestore.RunAggregationQuery].
 *
 * Protobuf: `google.firestore.v1.RunAggregationQueryResponse`.
 */
export final class RunAggregationQueryResponse {
  #m: ProtoView;

  /** A message over `m`, which must hold an encoded `google.firestore.v1.RunAggregationQueryResponse`. */
  new(m: ProtoView) : #m = m;

  /** Decodes `bytes`. Fields are decoded as they are read. */
  static decode(bytes: ByteArray): RunAggregationQueryResponse {
    return new RunAggregationQueryResponse(ProtoView.of(bytes));
  }

  /** Encodes `init` as a `google.firestore.v1.RunAggregationQueryResponse`. */
  static of(init: RunAggregationQueryResponseInit): RunAggregationQueryResponse {
    let w = new ProtoWriter();
    if (let {result as f1} = init) {
      w.message(1, f1.protoView);
    }
    if (let {transaction as f2} = init) {
      w.bytes(2, f2);
    }
    if (let {readTime as f3} = init) {
      w.message(3, f3.protoView);
    }
    if (let {explainMetrics as f10} = init) {
      w.message(10, f10.protoView);
    }
    return new RunAggregationQueryResponse(w.finish());
  }

  /** The encoded message. */
  protoView: ProtoView {
    get { return this.#m; }
  }

  /**
   * A single aggregation result.
   *
   * Not present when reporting partial progress.
   */
  result: AggregationResult | null {
    get {
      let m = this.#m.message(1);
      return if (m == null) null else new AggregationResult(m as ProtoView);
    }
  }

  /**
   * The transaction that was started as part of this request.
   *
   * Only present on the first response when the request requested to start
   * a new transaction.
   */
  transaction: ProtoBytes {
    get { return this.#m.bytes(2); }
  }

  /**
   * The time at which the aggregate result was computed. This is always
   * monotonically increasing; in this case, the previous AggregationResult in
   * the result stream are guaranteed not to have changed between their
   * `read_time` and this one.
   *
   * If the query returns no results, a response with `read_time` and no
   * `result` will be sent, and this represents the time at which the query
   * was run.
   */
  readTime: Timestamp | null {
    get {
      let m = this.#m.message(3);
      return if (m == null) null else new Timestamp(m as ProtoView);
    }
  }

  /**
   * Query explain metrics. This is only present when the
   * [RunAggregationQueryRequest.explain_options][google.firestore.v1.RunAggregationQueryRequest.explain_options]
   * is provided, and it is sent only once with the last response in the stream.
   */
  explainMetrics: ExplainMetrics | null {
    get {
      let m = this.#m.message(10);
      return if (m == null) null else new ExplainMetrics(m as ProtoView);
    }
  }
}

/**
 * The query to partition.
 *
 * The member of `google.firestore.v1.PartitionQueryRequest.query_type` that is set, as `PartitionQueryRequest.queryType` reads it.
 */
export sealed class PartitionQueryRequestQueryType {
  case PartitionQueryRequestStructuredQuery(value: StructuredQuery)
  case PartitionQueryRequestQueryTypeNotSet
}

/**
 * The consistency mode for this request.
 * If not set, defaults to strong consistency.
 *
 * The member of `google.firestore.v1.PartitionQueryRequest.consistency_selector` that is set, as `PartitionQueryRequest.consistencySelector` reads it.
 */
export sealed class PartitionQueryRequestConsistencySelector {
  case PartitionQueryRequestReadTime(value: Timestamp)
  case PartitionQueryRequestConsistencySelectorNotSet
}

/** The fields of a `google.firestore.v1.PartitionQueryRequest` to encode, for `PartitionQueryRequest.of`. */
export type PartitionQueryRequestInit = {
  parent: String,
  structuredQuery?: StructuredQuery,
  partitionCount?: i64,
  pageToken?: String,
  pageSize?: i32,
  readTime?: Timestamp,
  requestOptions?: RequestOptions,
};

/**
 * The request for
 * [Firestore.PartitionQuery][google.firestore.v1.Firestore.PartitionQuery].
 *
 * Protobuf: `google.firestore.v1.PartitionQueryRequest`.
 */
export final class PartitionQueryRequest {
  #m: ProtoView;

  /** A message over `m`, which must hold an encoded `google.firestore.v1.PartitionQueryRequest`. */
  new(m: ProtoView) : #m = m;

  /** Decodes `bytes`. Fields are decoded as they are read. */
  static decode(bytes: ByteArray): PartitionQueryRequest {
    return new PartitionQueryRequest(ProtoView.of(bytes));
  }

  /** Encodes `init` as a `google.firestore.v1.PartitionQueryRequest`. */
  static of(init: PartitionQueryRequestInit): PartitionQueryRequest {
    let w = new ProtoWriter();
    let f1 = init.parent;
    w.string(1, f1);
    if (let {structuredQuery as f2} = init) {
      w.message(2, f2.protoView);
    }
    if (let {partitionCount as f3} = init) {
      w.int64(3, f3);
    }
    if (let {pageToken as f4} = init) {
      w.string(4, f4);
    }
    if (let {pageSize as f5} = init) {
      w.int32(5, f5);
    }
    if (let {readTime as f6} = init) {
      w.message(6, f6.protoView);
    }
    if (let {requestOptions as f7} = init) {
      w.message(7, f7.protoView);
    }
    return new PartitionQueryRequest(w.finish());
  }

  /** The encoded message. */
  protoView: ProtoView {
    get { return this.#m; }
  }

  /**
   * Required. The parent resource name. In the format:
   * `projects/{project_id}/databases/{database_id}/documents`.
   * Document resource names are not supported; only database resource names
   * can be specified.
   */
  parent: String {
    get { return this.#m.string(1); }
  }

  /**
   * A structured query.
   * Query must specify collection with all descendants and be ordered by name
   * ascending. Other filters, order bys, limits, offsets, and start/end
   * cursors are not supported.
   */
  structuredQuery: StructuredQuery | null {
    get {
      if (this.#whichQueryType() != 2) {
        return null;
      }
      let m = this.#m.message(2);
      return if (m == null) null else new StructuredQuery(m as ProtoView);
    }
  }

  /**
   * The desired maximum number of partition points.
   * The partitions may be returned across multiple pages of results.
   * The number must be positive. The actual number of partitions
   * returned may be fewer.
   *
   * For example, this may be set to one fewer than the number of parallel
   * queries to be run, or in running a data pipeline job, one fewer than the
   * number of workers or compute instances available.
   */
  partitionCount: i64 {
    get { return this.#m.int64(3); }
  }

  /**
   * The `next_page_token` value returned from a previous call to
   * PartitionQuery that may be used to get an additional set of results.
   * There are no ordering guarantees between sets of results. Thus, using
   * multiple sets of results will require merging the different result sets.
   *
   * For example, two subsequent calls using a page_token may return:
   *
   *  * cursor B, cursor M, cursor Q
   *  * cursor A, cursor U, cursor W
   *
   * To obtain a complete result set ordered with respect to the results of the
   * query supplied to PartitionQuery, the results sets should be merged:
   * cursor A, cursor B, cursor M, cursor Q, cursor U, cursor W
   */
  pageToken: String {
    get { return this.#m.string(4); }
  }

  /**
   * The maximum number of partitions to return in this call, subject to
   * `partition_count`.
   *
   * For example, if `partition_count` = 10 and `page_size` = 8, the first call
   * to PartitionQuery will return up to 8 partitions and a `next_page_token`
   * if more results exist. A second call to PartitionQuery will return up to
   * 2 partitions, to complete the total of 10 specified in `partition_count`.
   */
  pageSize: i32 {
    get { return this.#m.int32(5); }
  }

  /**
   * Reads documents as they were at the given time.
   *
   * This must be a microsecond precision timestamp within the past one hour,
   * or if Point-in-Time Recovery is enabled, can additionally be a whole
   * minute timestamp within the past 7 days.
   */
  readTime: Timestamp | null {
    get {
      if (this.#whichConsistencySelector() != 6) {
        return null;
      }
      let m = this.#m.message(6);
      return if (m == null) null else new Timestamp(m as ProtoView);
    }
  }

  /** Optional. Any additional options for the request. */
  requestOptions: RequestOptions | null {
    get {
      let m = this.#m.message(7);
      return if (m == null) null else new RequestOptions(m as ProtoView);
    }
  }

  /** The member of `query_type` that is set. */
  queryType: PartitionQueryRequestQueryType {
    get {
      let which = this.#whichQueryType();
      if (which == 2) {
        return new PartitionQueryRequestStructuredQuery(new StructuredQuery(this.#m.message(2) as ProtoView));
      }
      return new PartitionQueryRequestQueryTypeNotSet();
    }
  }

  #whichQueryType(): i32 {
    return this.#m.whichOf([2]);
  }

  /** The member of `consistency_selector` that is set. */
  consistencySelector: PartitionQueryRequestConsistencySelector {
    get {
      let which = this.#whichConsistencySelector();
      if (which == 6) {
        return new PartitionQueryRequestReadTime(new Timestamp(this.#m.message(6) as ProtoView));
      }
      return new PartitionQueryRequestConsistencySelectorNotSet();
    }
  }

  #whichConsistencySelector(): i32 {
    return this.#m.whichOf([6]);
  }
}

/** The fields of a `google.firestore.v1.PartitionQueryResponse` to encode, for `PartitionQueryResponse.of`. */
export type PartitionQueryResponseInit = {
  partitions?: Array<Cursor>,
  nextPageToken?: String,
};

/**
 * The response for
 * [Firestore.PartitionQuery][google.firestore.v1.Firestore.PartitionQuery].
 *
 * Protobuf: `google.firestore.v1.PartitionQueryResponse`.
 */
export final class PartitionQueryResponse {
  #m: ProtoView;

  /** A message over `m`, which must hold an encoded `google.firestore.v1.PartitionQueryResponse`. */
  new(m: ProtoView) : #m = m;

  /** Decodes `bytes`. Fields are decoded as they are read. */
  static decode(bytes: ByteArray): PartitionQueryResponse {
    return new PartitionQueryResponse(ProtoView.of(bytes));
  }

  /** Encodes `init` as a `google.firestore.v1.PartitionQueryResponse`. */
  static of(init: PartitionQueryResponseInit): PartitionQueryResponse {
    let w = new ProtoWriter();
    if (let {partitions as f1} = init) {
      for (let item in f1) {
        w.message(1, item.protoView);
      }
    }
    if (let {nextPageToken as f2} = init) {
      w.string(2, f2);
    }
    return new PartitionQueryResponse(w.finish());
  }

  /** The encoded message. */
  protoView: ProtoView {
    get { return this.#m; }
  }

  /**
   * Partition results.
   * Each partition is a split point that can be used by RunQuery as a starting
   * or end point for the query results. The RunQuery requests must be made with
   * the same query supplied to this PartitionQuery request. The partition
   * cursors will be ordered according to same ordering as the results of the
   * query supplied to PartitionQuery.
   *
   * For example, if a PartitionQuery request returns partition cursors A and B,
   * running the following three queries will return the entire result set of
   * the original query:
   *
   *  * query, end_at A
   *  * query, start_at A, end_at B
   *  * query, start_at B
   *
   * An empty result may indicate that the query has too few results to be
   * partitioned, or that the query is not yet supported for partitioning.
   */
  partitions: ProtoList<Cursor> {
    get { return this.#m.repeated(1, WIRE_LEN, (v, p) => new Cursor(v.messageAt(p))); }
  }

  /**
   * A page token that may be used to request an additional set of results, up
   * to the number specified by `partition_count` in the PartitionQuery request.
   * If blank, there are no more results.
   */
  nextPageToken: String {
    get { return this.#m.string(2); }
  }
}

/** The fields of a `google.firestore.v1.WriteRequest` to encode, for `WriteRequest.of`. */
export type WriteRequestInit = {
  database: String,
  streamId?: String,
  writes?: Array<Write>,
  streamToken?: ByteArray | ProtoBytes,
  labels?: Map<String, String>,
  requestOptions?: RequestOptions,
};

/**
 * The request for [Firestore.Write][google.firestore.v1.Firestore.Write].
 *
 * The first request creates a stream, or resumes an existing one from a token.
 *
 * When creating a new stream, the server replies with a response containing
 * only an ID and a token, to use in the next request.
 *
 * When resuming a stream, the server first streams any responses later than the
 * given token, then a response containing only an up-to-date token, to use in
 * the next request.
 *
 * Protobuf: `google.firestore.v1.WriteRequest`.
 */
export final class WriteRequest {
  #m: ProtoView;

  /** A message over `m`, which must hold an encoded `google.firestore.v1.WriteRequest`. */
  new(m: ProtoView) : #m = m;

  /** Decodes `bytes`. Fields are decoded as they are read. */
  static decode(bytes: ByteArray): WriteRequest {
    return new WriteRequest(ProtoView.of(bytes));
  }

  /** Encodes `init` as a `google.firestore.v1.WriteRequest`. */
  static of(init: WriteRequestInit): WriteRequest {
    let w = new ProtoWriter();
    let f1 = init.database;
    w.string(1, f1);
    if (let {streamId as f2} = init) {
      w.string(2, f2);
    }
    if (let {writes as f3} = init) {
      for (let item in f3) {
        w.message(3, item.protoView);
      }
    }
    if (let {streamToken as f4} = init) {
      w.bytes(4, f4);
    }
    if (let {labels as f5} = init) {
      for (let entry in f5) {
        let e = new ProtoWriter();
        e.string(1, entry.key);
        e.string(2, entry.value);
        w.message(5, e.finish());
      }
    }
    if (let {requestOptions as f6} = init) {
      w.message(6, f6.protoView);
    }
    return new WriteRequest(w.finish());
  }

  /** The encoded message. */
  protoView: ProtoView {
    get { return this.#m; }
  }

  /**
   * Required. The database name. In the format:
   * `projects/{project_id}/databases/{database_id}`.
   * This is only required in the first message.
   */
  database: String {
    get { return this.#m.string(1); }
  }

  /**
   * The ID of the write stream to resume.
   * This may only be set in the first message. When left empty, a new write
   * stream will be created.
   */
  streamId: String {
    get { return this.#m.string(2); }
  }

  /**
   * The writes to apply.
   *
   * Always executed atomically and in order.
   * This must be empty on the first request.
   * This may be empty on the last request.
   * This must not be empty on all other requests.
   */
  writes: ProtoList<Write> {
    get { return this.#m.repeated(3, WIRE_LEN, (v, p) => new Write(v.messageAt(p))); }
  }

  /**
   * A stream token that was previously sent by the server.
   *
   * The client should set this field to the token from the most recent
   * [WriteResponse][google.firestore.v1.WriteResponse] it has received. This
   * acknowledges that the client has received responses up to this token. After
   * sending this token, earlier tokens may not be used anymore.
   *
   * The server may close the stream if there are too many unacknowledged
   * responses.
   *
   * Leave this field unset when creating a new stream. To resume a stream at
   * a specific point, set this field and the `stream_id` field.
   *
   * Leave this field unset when creating a new stream.
   */
  streamToken: ProtoBytes {
    get { return this.#m.bytes(4); }
  }

  /** Labels associated with this write request. */
  labels: ProtoMap<String, String> {
    get { return this.#m.map(5, (e) => e.string(1), (e) => e.string(2)); }
  }

  /** Optional. Any additional options for the request. */
  requestOptions: RequestOptions | null {
    get {
      let m = this.#m.message(6);
      return if (m == null) null else new RequestOptions(m as ProtoView);
    }
  }
}

/** The fields of a `google.firestore.v1.WriteResponse` to encode, for `WriteResponse.of`. */
export type WriteResponseInit = {
  streamId?: String,
  streamToken?: ByteArray | ProtoBytes,
  writeResults?: Array<WriteResult>,
  commitTime?: Timestamp,
};

/**
 * The response for [Firestore.Write][google.firestore.v1.Firestore.Write].
 *
 * Protobuf: `google.firestore.v1.WriteResponse`.
 */
export final class WriteResponse {
  #m: ProtoView;

  /** A message over `m`, which must hold an encoded `google.firestore.v1.WriteResponse`. */
  new(m: ProtoView) : #m = m;

  /** Decodes `bytes`. Fields are decoded as they are read. */
  static decode(bytes: ByteArray): WriteResponse {
    return new WriteResponse(ProtoView.of(bytes));
  }

  /** Encodes `init` as a `google.firestore.v1.WriteResponse`. */
  static of(init: WriteResponseInit): WriteResponse {
    let w = new ProtoWriter();
    if (let {streamId as f1} = init) {
      w.string(1, f1);
    }
    if (let {streamToken as f2} = init) {
      w.bytes(2, f2);
    }
    if (let {writeResults as f3} = init) {
      for (let item in f3) {
        w.message(3, item.protoView);
      }
    }
    if (let {commitTime as f4} = init) {
      w.message(4, f4.protoView);
    }
    return new WriteResponse(w.finish());
  }

  /** The encoded message. */
  protoView: ProtoView {
    get { return this.#m; }
  }

  /**
   * The ID of the stream.
   * Only set on the first message, when a new stream was created.
   */
  streamId: String {
    get { return this.#m.string(1); }
  }

  /**
   * A token that represents the position of this response in the stream.
   * This can be used by a client to resume the stream at this point.
   *
   * This field is always set.
   */
  streamToken: ProtoBytes {
    get { return this.#m.bytes(2); }
  }

  /**
   * The result of applying the writes.
   *
   * This i-th write result corresponds to the i-th write in the
   * request.
   */
  writeResults: ProtoList<WriteResult> {
    get { return this.#m.repeated(3, WIRE_LEN, (v, p) => new WriteResult(v.messageAt(p))); }
  }

  /**
   * The time at which the commit occurred. Any read with an equal or greater
   * `read_time` is guaranteed to see the effects of the write.
   */
  commitTime: Timestamp | null {
    get {
      let m = this.#m.message(4);
      return if (m == null) null else new Timestamp(m as ProtoView);
    }
  }
}

/**
 * The supported target changes.
 *
 * The member of `google.firestore.v1.ListenRequest.target_change` that is set, as `ListenRequest.targetChange` reads it.
 */
export sealed class ListenRequestTargetChange {
  case ListenRequestAddTarget(value: Target)
  case ListenRequestRemoveTarget(value: i32)
  case ListenRequestTargetChangeNotSet
}

/** The fields of a `google.firestore.v1.ListenRequest` to encode, for `ListenRequest.of`. */
export type ListenRequestInit = {
  database: String,
  addTarget?: Target,
  removeTarget?: i32,
  labels?: Map<String, String>,
  requestOptions?: RequestOptions,
};

/**
 * A request for [Firestore.Listen][google.firestore.v1.Firestore.Listen]
 *
 * Protobuf: `google.firestore.v1.ListenRequest`.
 */
export final class ListenRequest {
  #m: ProtoView;

  /** A message over `m`, which must hold an encoded `google.firestore.v1.ListenRequest`. */
  new(m: ProtoView) : #m = m;

  /** Decodes `bytes`. Fields are decoded as they are read. */
  static decode(bytes: ByteArray): ListenRequest {
    return new ListenRequest(ProtoView.of(bytes));
  }

  /** Encodes `init` as a `google.firestore.v1.ListenRequest`. */
  static of(init: ListenRequestInit): ListenRequest {
    let w = new ProtoWriter();
    let f1 = init.database;
    w.string(1, f1);
    if (let {addTarget as f2} = init) {
      w.message(2, f2.protoView);
    }
    if (let {removeTarget as f3} = init) {
      w.int32(3, f3);
    }
    if (let {labels as f4} = init) {
      for (let entry in f4) {
        let e = new ProtoWriter();
        e.string(1, entry.key);
        e.string(2, entry.value);
        w.message(4, e.finish());
      }
    }
    if (let {requestOptions as f5} = init) {
      w.message(5, f5.protoView);
    }
    return new ListenRequest(w.finish());
  }

  /** The encoded message. */
  protoView: ProtoView {
    get { return this.#m; }
  }

  /**
   * Required. The database name. In the format:
   * `projects/{project_id}/databases/{database_id}`.
   */
  database: String {
    get { return this.#m.string(1); }
  }

  /** A target to add to this stream. */
  addTarget: Target | null {
    get {
      if (this.#whichTargetChange() != 2) {
        return null;
      }
      let m = this.#m.message(2);
      return if (m == null) null else new Target(m as ProtoView);
    }
  }

  /** The ID of a target to remove from this stream. */
  removeTarget: i32 {
    get {
      if (this.#whichTargetChange() != 3) {
        return 0;
      }
      return this.#m.int32(3);
    }
  }

  /** Whether `removeTarget` is set. */
  hasRemoveTarget: boolean {
    get { return this.#whichTargetChange() == 3; }
  }

  /** Labels associated with this target change. */
  labels: ProtoMap<String, String> {
    get { return this.#m.map(4, (e) => e.string(1), (e) => e.string(2)); }
  }

  /** Optional. Any additional options for the request. */
  requestOptions: RequestOptions | null {
    get {
      let m = this.#m.message(5);
      return if (m == null) null else new RequestOptions(m as ProtoView);
    }
  }

  /** The member of `target_change` that is set. */
  targetChange: ListenRequestTargetChange {
    get {
      let which = this.#whichTargetChange();
      if (which == 2) {
        return new ListenRequestAddTarget(new Target(this.#m.message(2) as ProtoView));
      }
      if (which == 3) {
        return new ListenRequestRemoveTarget(this.#m.int32(3));
      }
      return new ListenRequestTargetChangeNotSet();
    }
  }

  #whichTargetChange(): i32 {
    return this.#m.whichOf([2, 3]);
  }
}

/**
 * The supported responses.
 *
 * The member of `google.firestore.v1.ListenResponse.response_type` that is set, as `ListenResponse.responseType` reads it.
 */
export sealed class ListenResponseResponseType {
  case ListenResponseTargetChange(value: TargetChange)
  case ListenResponseDocumentChange(value: DocumentChange)
  case ListenResponseDocumentDelete(value: DocumentDelete)
  case ListenResponseDocumentRemove(value: DocumentRemove)
  case ListenResponseFilter(value: ExistenceFilter)
  case ListenResponseResponseTypeNotSet
}

/** The fields of a `google.firestore.v1.ListenResponse` to encode, for `ListenResponse.of`. */
export type ListenResponseInit = {
  targetChange?: TargetChange,
  documentChange?: DocumentChange,
  documentDelete?: DocumentDelete,
  documentRemove?: DocumentRemove,
  filter?: ExistenceFilter,
};

/**
 * The response for [Firestore.Listen][google.firestore.v1.Firestore.Listen].
 *
 * Protobuf: `google.firestore.v1.ListenResponse`.
 */
export final class ListenResponse {
  #m: ProtoView;

  /** A message over `m`, which must hold an encoded `google.firestore.v1.ListenResponse`. */
  new(m: ProtoView) : #m = m;

  /** Decodes `bytes`. Fields are decoded as they are read. */
  static decode(bytes: ByteArray): ListenResponse {
    return new ListenResponse(ProtoView.of(bytes));
  }

  /** Encodes `init` as a `google.firestore.v1.ListenResponse`. */
  static of(init: ListenResponseInit): ListenResponse {
    let w = new ProtoWriter();
    if (let {targetChange as f2} = init) {
      w.message(2, f2.protoView);
    }
    if (let {documentChange as f3} = init) {
      w.message(3, f3.protoView);
    }
    if (let {documentDelete as f4} = init) {
      w.message(4, f4.protoView);
    }
    if (let {documentRemove as f6} = init) {
      w.message(6, f6.protoView);
    }
    if (let {filter as f5} = init) {
      w.message(5, f5.protoView);
    }
    return new ListenResponse(w.finish());
  }

  /** The encoded message. */
  protoView: ProtoView {
    get { return this.#m; }
  }

  /** Targets have changed. */
  targetChange: TargetChange | null {
    get {
      if (this.#whichResponseType() != 2) {
        return null;
      }
      let m = this.#m.message(2);
      return if (m == null) null else new TargetChange(m as ProtoView);
    }
  }

  /** A [Document][google.firestore.v1.Document] has changed. */
  documentChange: DocumentChange | null {
    get {
      if (this.#whichResponseType() != 3) {
        return null;
      }
      let m = this.#m.message(3);
      return if (m == null) null else new DocumentChange(m as ProtoView);
    }
  }

  /** A [Document][google.firestore.v1.Document] has been deleted. */
  documentDelete: DocumentDelete | null {
    get {
      if (this.#whichResponseType() != 4) {
        return null;
      }
      let m = this.#m.message(4);
      return if (m == null) null else new DocumentDelete(m as ProtoView);
    }
  }

  /**
   * A [Document][google.firestore.v1.Document] has been removed from a target
   * (because it is no longer relevant to that target).
   */
  documentRemove: DocumentRemove | null {
    get {
      if (this.#whichResponseType() != 6) {
        return null;
      }
      let m = this.#m.message(6);
      return if (m == null) null else new DocumentRemove(m as ProtoView);
    }
  }

  /**
   * A filter to apply to the set of documents previously returned for the
   * given target.
   *
   * Returned when documents may have been removed from the given target, but
   * the exact documents are unknown.
   */
  filter: ExistenceFilter | null {
    get {
      if (this.#whichResponseType() != 5) {
        return null;
      }
      let m = this.#m.message(5);
      return if (m == null) null else new ExistenceFilter(m as ProtoView);
    }
  }

  /** The member of `response_type` that is set. */
  responseType: ListenResponseResponseType {
    get {
      let which = this.#whichResponseType();
      if (which == 2) {
        return new ListenResponseTargetChange(new TargetChange(this.#m.message(2) as ProtoView));
      }
      if (which == 3) {
        return new ListenResponseDocumentChange(new DocumentChange(this.#m.message(3) as ProtoView));
      }
      if (which == 4) {
        return new ListenResponseDocumentDelete(new DocumentDelete(this.#m.message(4) as ProtoView));
      }
      if (which == 6) {
        return new ListenResponseDocumentRemove(new DocumentRemove(this.#m.message(6) as ProtoView));
      }
      if (which == 5) {
        return new ListenResponseFilter(new ExistenceFilter(this.#m.message(5) as ProtoView));
      }
      return new ListenResponseResponseTypeNotSet();
    }
  }

  #whichResponseType(): i32 {
    return this.#m.whichOf([2, 3, 4, 6, 5]);
  }
}

/**
 * The type of target to listen to.
 *
 * The member of `google.firestore.v1.Target.target_type` that is set, as `Target.targetType` reads it.
 */
export sealed class TargetTargetType {
  case TargetQuery(value: TargetQueryTarget)
  case TargetDocuments(value: TargetDocumentsTarget)
  case TargetTargetTypeNotSet
}

/**
 * When to start listening.
 *
 * If specified, only the matching Documents that have been updated AFTER the
 * `resume_token` or `read_time` will be returned. Otherwise, all matching
 * Documents are returned before any subsequent changes.
 *
 * The member of `google.firestore.v1.Target.resume_type` that is set, as `Target.resumeType` reads it.
 */
export sealed class TargetResumeType {
  case TargetResumeToken(value: ProtoBytes)
  case TargetReadTime(value: Timestamp)
  case TargetResumeTypeNotSet
}

/** The fields of a `google.firestore.v1.Target` to encode, for `Target.of`. */
export type TargetInit = {
  query?: TargetQueryTarget,
  documents?: TargetDocumentsTarget,
  resumeToken?: ByteArray | ProtoBytes,
  readTime?: Timestamp,
  targetId?: i32,
  once?: boolean,
  expectedCount?: Int32Value,
};

/**
 * A specification of a set of documents to listen to.
 *
 * Protobuf: `google.firestore.v1.Target`.
 */
export final class Target {
  #m: ProtoView;

  /** A message over `m`, which must hold an encoded `google.firestore.v1.Target`. */
  new(m: ProtoView) : #m = m;

  /** Decodes `bytes`. Fields are decoded as they are read. */
  static decode(bytes: ByteArray): Target {
    return new Target(ProtoView.of(bytes));
  }

  /** Encodes `init` as a `google.firestore.v1.Target`. */
  static of(init: TargetInit): Target {
    let w = new ProtoWriter();
    if (let {query as f2} = init) {
      w.message(2, f2.protoView);
    }
    if (let {documents as f3} = init) {
      w.message(3, f3.protoView);
    }
    if (let {resumeToken as f4} = init) {
      w.bytes(4, f4);
    }
    if (let {readTime as f11} = init) {
      w.message(11, f11.protoView);
    }
    if (let {targetId as f5} = init) {
      w.int32(5, f5);
    }
    if (let {once as f6} = init) {
      w.bool(6, f6);
    }
    if (let {expectedCount as f12} = init) {
      w.message(12, f12.protoView);
    }
    return new Target(w.finish());
  }

  /** The encoded message. */
  protoView: ProtoView {
    get { return this.#m; }
  }

  /** A target specified by a query. */
  query: TargetQueryTarget | null {
    get {
      if (this.#whichTargetType() != 2) {
        return null;
      }
      let m = this.#m.message(2);
      return if (m == null) null else new TargetQueryTarget(m as ProtoView);
    }
  }

  /** A target specified by a set of document names. */
  documents: TargetDocumentsTarget | null {
    get {
      if (this.#whichTargetType() != 3) {
        return null;
      }
      let m = this.#m.message(3);
      return if (m == null) null else new TargetDocumentsTarget(m as ProtoView);
    }
  }

  /**
   * A resume token from a prior
   * [TargetChange][google.firestore.v1.TargetChange] for an identical target.
   *
   * Using a resume token with a different target is unsupported and may fail.
   */
  resumeToken: ProtoBytes {
    get {
      if (this.#whichResumeType() != 4) {
        return ProtoBytes.empty();
      }
      return this.#m.bytes(4);
    }
  }

  /** Whether `resumeToken` is set. */
  hasResumeToken: boolean {
    get { return this.#whichResumeType() == 4; }
  }

  /**
   * Start listening after a specific `read_time`.
   *
   * The client must know the state of matching documents at this time.
   */
  readTime: Timestamp | null {
    get {
      if (this.#whichResumeType() != 11) {
        return null;
      }
      let m = this.#m.message(11);
      return if (m == null) null else new Timestamp(m as ProtoView);
    }
  }

  /**
   * The target ID that identifies the target on the stream. Must be a positive
   * number and non-zero.
   *
   * If `target_id` is 0 (or unspecified), the server will assign an ID for this
   * target and return that in a `TargetChange::ADD` event. Once a target with
   * `target_id=0` is added, all subsequent targets must also have
   * `target_id=0`. If an `AddTarget` request with `target_id != 0` is
   * sent to the server after a target with `target_id=0` is added, the server
   * will immediately send a response with a `TargetChange::Remove` event.
   *
   * Note that if the client sends multiple `AddTarget` requests
   * without an ID, the order of IDs returned in `TargetChange.target_ids` are
   * undefined. Therefore, clients should provide a target ID instead of relying
   * on the server to assign one.
   *
   * If `target_id` is non-zero, there must not be an existing active target on
   * this stream with the same ID.
   */
  targetId: i32 {
    get { return this.#m.int32(5); }
  }

  /** If the target should be removed once it is current and consistent. */
  once: boolean {
    get { return this.#m.bool(6); }
  }

  /**
   * The number of documents that last matched the query at the resume token or
   * read time.
   *
   * This value is only relevant when a `resume_type` is provided. This value
   * being present and greater than zero signals that the client wants
   * `ExistenceFilter.unchanged_names` to be included in the response.
   */
  expectedCount: Int32Value | null {
    get {
      let m = this.#m.message(12);
      return if (m == null) null else new Int32Value(m as ProtoView);
    }
  }

  /** The member of `target_type` that is set. */
  targetType: TargetTargetType {
    get {
      let which = this.#whichTargetType();
      if (which == 2) {
        return new TargetQuery(new TargetQueryTarget(this.#m.message(2) as ProtoView));
      }
      if (which == 3) {
        return new TargetDocuments(new TargetDocumentsTarget(this.#m.message(3) as ProtoView));
      }
      return new TargetTargetTypeNotSet();
    }
  }

  #whichTargetType(): i32 {
    return this.#m.whichOf([2, 3]);
  }

  /** The member of `resume_type` that is set. */
  resumeType: TargetResumeType {
    get {
      let which = this.#whichResumeType();
      if (which == 4) {
        return new TargetResumeToken(this.#m.bytes(4));
      }
      if (which == 11) {
        return new TargetReadTime(new Timestamp(this.#m.message(11) as ProtoView));
      }
      return new TargetResumeTypeNotSet();
    }
  }

  #whichResumeType(): i32 {
    return this.#m.whichOf([4, 11]);
  }
}

/** The fields of a `google.firestore.v1.Target.DocumentsTarget` to encode, for `TargetDocumentsTarget.of`. */
export type TargetDocumentsTargetInit = {
  documents?: Array<String>,
};

/**
 * A target specified by a set of documents names.
 *
 * Protobuf: `google.firestore.v1.Target.DocumentsTarget`.
 */
export final class TargetDocumentsTarget {
  #m: ProtoView;

  /** A message over `m`, which must hold an encoded `google.firestore.v1.Target.DocumentsTarget`. */
  new(m: ProtoView) : #m = m;

  /** Decodes `bytes`. Fields are decoded as they are read. */
  static decode(bytes: ByteArray): TargetDocumentsTarget {
    return new TargetDocumentsTarget(ProtoView.of(bytes));
  }

  /** Encodes `init` as a `google.firestore.v1.Target.DocumentsTarget`. */
  static of(init: TargetDocumentsTargetInit): TargetDocumentsTarget {
    let w = new ProtoWriter();
    if (let {documents as f2} = init) {
      for (let item in f2) {
        w.string(2, item);
      }
    }
    return new TargetDocumentsTarget(w.finish());
  }

  /** The encoded message. */
  protoView: ProtoView {
    get { return this.#m; }
  }

  /**
   * The names of the documents to retrieve. In the format:
   * `projects/{project_id}/databases/{database_id}/documents/{document_path}`.
   * The request will fail if any of the document is not a child resource of
   * the given `database`. Duplicate names will be elided.
   */
  documents: ProtoList<String> {
    get { return this.#m.repeated(2, WIRE_LEN, (v, p) => v.stringAt(p)); }
  }
}

/**
 * The query to run.
 *
 * The member of `google.firestore.v1.Target.QueryTarget.query_type` that is set, as `TargetQueryTarget.queryType` reads it.
 */
export sealed class TargetQueryTargetQueryType {
  case TargetQueryTargetStructuredQuery(value: StructuredQuery)
  case TargetQueryTargetQueryTypeNotSet
}

/** The fields of a `google.firestore.v1.Target.QueryTarget` to encode, for `TargetQueryTarget.of`. */
export type TargetQueryTargetInit = {
  parent?: String,
  structuredQuery?: StructuredQuery,
};

/**
 * A target specified by a query.
 *
 * Protobuf: `google.firestore.v1.Target.QueryTarget`.
 */
export final class TargetQueryTarget {
  #m: ProtoView;

  /** A message over `m`, which must hold an encoded `google.firestore.v1.Target.QueryTarget`. */
  new(m: ProtoView) : #m = m;

  /** Decodes `bytes`. Fields are decoded as they are read. */
  static decode(bytes: ByteArray): TargetQueryTarget {
    return new TargetQueryTarget(ProtoView.of(bytes));
  }

  /** Encodes `init` as a `google.firestore.v1.Target.QueryTarget`. */
  static of(init: TargetQueryTargetInit): TargetQueryTarget {
    let w = new ProtoWriter();
    if (let {parent as f1} = init) {
      w.string(1, f1);
    }
    if (let {structuredQuery as f2} = init) {
      w.message(2, f2.protoView);
    }
    return new TargetQueryTarget(w.finish());
  }

  /** The encoded message. */
  protoView: ProtoView {
    get { return this.#m; }
  }

  /**
   * The parent resource name. In the format:
   * `projects/{project_id}/databases/{database_id}/documents` or
   * `projects/{project_id}/databases/{database_id}/documents/{document_path}`.
   * For example:
   * `projects/my-project/databases/my-database/documents` or
   * `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom`
   */
  parent: String {
    get { return this.#m.string(1); }
  }

  /** A structured query. */
  structuredQuery: StructuredQuery | null {
    get {
      if (this.#whichQueryType() != 2) {
        return null;
      }
      let m = this.#m.message(2);
      return if (m == null) null else new StructuredQuery(m as ProtoView);
    }
  }

  /** The member of `query_type` that is set. */
  queryType: TargetQueryTargetQueryType {
    get {
      let which = this.#whichQueryType();
      if (which == 2) {
        return new TargetQueryTargetStructuredQuery(new StructuredQuery(this.#m.message(2) as ProtoView));
      }
      return new TargetQueryTargetQueryTypeNotSet();
    }
  }

  #whichQueryType(): i32 {
    return this.#m.whichOf([2]);
  }
}

/** The fields of a `google.firestore.v1.TargetChange` to encode, for `TargetChange.of`. */
export type TargetChangeInit = {
  targetChangeType?: TargetChangeTargetChangeType,
  targetIds?: Array<i32>,
  cause?: Status,
  resumeToken?: ByteArray | ProtoBytes,
  readTime?: Timestamp,
};

/**
 * Targets being watched have changed.
 *
 * Protobuf: `google.firestore.v1.TargetChange`.
 */
export final class TargetChange {
  #m: ProtoView;

  /** A message over `m`, which must hold an encoded `google.firestore.v1.TargetChange`. */
  new(m: ProtoView) : #m = m;

  /** Decodes `bytes`. Fields are decoded as they are read. */
  static decode(bytes: ByteArray): TargetChange {
    return new TargetChange(ProtoView.of(bytes));
  }

  /** Encodes `init` as a `google.firestore.v1.TargetChange`. */
  static of(init: TargetChangeInit): TargetChange {
    let w = new ProtoWriter();
    if (let {targetChangeType as f1} = init) {
      w.int32(1, f1 as i32);
    }
    if (let {targetIds as f2} = init) {
      w.packed(2, f2, (pw, pv) => pw.rawInt32(pv));
    }
    if (let {cause as f3} = init) {
      w.message(3, f3.protoView);
    }
    if (let {resumeToken as f4} = init) {
      w.bytes(4, f4);
    }
    if (let {readTime as f6} = init) {
      w.message(6, f6.protoView);
    }
    return new TargetChange(w.finish());
  }

  /** The encoded message. */
  protoView: ProtoView {
    get { return this.#m; }
  }

  /** The type of change that occurred. */
  targetChangeType: TargetChangeTargetChangeType {
    get { return this.#m.int32(1) as TargetChangeTargetChangeType; }
  }

  /**
   * The target IDs of targets that have changed.
   *
   * If empty, the change applies to all targets.
   *
   * The order of the target IDs is not defined.
   */
  targetIds: ProtoList<i32> {
    get { return this.#m.repeated(2, WIRE_VARINT, (v, p) => v.int32At(p)); }
  }

  /** The error that resulted in this change, if applicable. */
  cause: Status | null {
    get {
      let m = this.#m.message(3);
      return if (m == null) null else new Status(m as ProtoView);
    }
  }

  /**
   * A token that can be used to resume the stream for the given `target_ids`,
   * or all targets if `target_ids` is empty.
   *
   * Not set on every target change.
   */
  resumeToken: ProtoBytes {
    get { return this.#m.bytes(4); }
  }

  /**
   * The consistent `read_time` for the given `target_ids` (omitted when the
   * target_ids are not at a consistent snapshot).
   *
   * The stream is guaranteed to send a `read_time` with `target_ids` empty
   * whenever the entire stream reaches a new consistent snapshot. ADD,
   * CURRENT, and RESET messages are guaranteed to (eventually) result in a
   * new consistent snapshot (while NO_CHANGE and REMOVE messages are not).
   *
   * For a given stream, `read_time` is guaranteed to be monotonically
   * increasing.
   */
  readTime: Timestamp | null {
    get {
      let m = this.#m.message(6);
      return if (m == null) null else new Timestamp(m as ProtoView);
    }
  }
}

/**
 * The consistency mode for this request.
 * If not set, defaults to strong consistency.
 *
 * The member of `google.firestore.v1.ListCollectionIdsRequest.consistency_selector` that is set, as `ListCollectionIdsRequest.consistencySelector` reads it.
 */
export sealed class ListCollectionIdsRequestConsistencySelector {
  case ListCollectionIdsRequestReadTime(value: Timestamp)
  case ListCollectionIdsRequestConsistencySelectorNotSet
}

/** The fields of a `google.firestore.v1.ListCollectionIdsRequest` to encode, for `ListCollectionIdsRequest.of`. */
export type ListCollectionIdsRequestInit = {
  parent: String,
  pageSize?: i32,
  pageToken?: String,
  readTime?: Timestamp,
  requestOptions?: RequestOptions,
};

/**
 * The request for
 * [Firestore.ListCollectionIds][google.firestore.v1.Firestore.ListCollectionIds].
 *
 * Protobuf: `google.firestore.v1.ListCollectionIdsRequest`.
 */
export final class ListCollectionIdsRequest {
  #m: ProtoView;

  /** A message over `m`, which must hold an encoded `google.firestore.v1.ListCollectionIdsRequest`. */
  new(m: ProtoView) : #m = m;

  /** Decodes `bytes`. Fields are decoded as they are read. */
  static decode(bytes: ByteArray): ListCollectionIdsRequest {
    return new ListCollectionIdsRequest(ProtoView.of(bytes));
  }

  /** Encodes `init` as a `google.firestore.v1.ListCollectionIdsRequest`. */
  static of(init: ListCollectionIdsRequestInit): ListCollectionIdsRequest {
    let w = new ProtoWriter();
    let f1 = init.parent;
    w.string(1, f1);
    if (let {pageSize as f2} = init) {
      w.int32(2, f2);
    }
    if (let {pageToken as f3} = init) {
      w.string(3, f3);
    }
    if (let {readTime as f4} = init) {
      w.message(4, f4.protoView);
    }
    if (let {requestOptions as f5} = init) {
      w.message(5, f5.protoView);
    }
    return new ListCollectionIdsRequest(w.finish());
  }

  /** The encoded message. */
  protoView: ProtoView {
    get { return this.#m; }
  }

  /**
   * Required. The parent document. In the format:
   * `projects/{project_id}/databases/{database_id}/documents/{document_path}`.
   * For example:
   * `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom`
   *
   * Use `projects/{project_id}/databases/{database_id}/documents` to list
   * top-level collections.
   */
  parent: String {
    get { return this.#m.string(1); }
  }

  /** The maximum number of results to return. */
  pageSize: i32 {
    get { return this.#m.int32(2); }
  }

  /**
   * A page token. Must be a value from
   * [ListCollectionIdsResponse][google.firestore.v1.ListCollectionIdsResponse].
   */
  pageToken: String {
    get { return this.#m.string(3); }
  }

  /**
   * Reads documents as they were at the given time.
   *
   * This must be a microsecond precision timestamp within the past one hour,
   * or if Point-in-Time Recovery is enabled, can additionally be a whole
   * minute timestamp within the past 7 days.
   */
  readTime: Timestamp | null {
    get {
      if (this.#whichConsistencySelector() != 4) {
        return null;
      }
      let m = this.#m.message(4);
      return if (m == null) null else new Timestamp(m as ProtoView);
    }
  }

  /** Optional. Any additional options for the request. */
  requestOptions: RequestOptions | null {
    get {
      let m = this.#m.message(5);
      return if (m == null) null else new RequestOptions(m as ProtoView);
    }
  }

  /** The member of `consistency_selector` that is set. */
  consistencySelector: ListCollectionIdsRequestConsistencySelector {
    get {
      let which = this.#whichConsistencySelector();
      if (which == 4) {
        return new ListCollectionIdsRequestReadTime(new Timestamp(this.#m.message(4) as ProtoView));
      }
      return new ListCollectionIdsRequestConsistencySelectorNotSet();
    }
  }

  #whichConsistencySelector(): i32 {
    return this.#m.whichOf([4]);
  }
}

/** The fields of a `google.firestore.v1.ListCollectionIdsResponse` to encode, for `ListCollectionIdsResponse.of`. */
export type ListCollectionIdsResponseInit = {
  collectionIds?: Array<String>,
  nextPageToken?: String,
};

/**
 * The response from
 * [Firestore.ListCollectionIds][google.firestore.v1.Firestore.ListCollectionIds].
 *
 * Protobuf: `google.firestore.v1.ListCollectionIdsResponse`.
 */
export final class ListCollectionIdsResponse {
  #m: ProtoView;

  /** A message over `m`, which must hold an encoded `google.firestore.v1.ListCollectionIdsResponse`. */
  new(m: ProtoView) : #m = m;

  /** Decodes `bytes`. Fields are decoded as they are read. */
  static decode(bytes: ByteArray): ListCollectionIdsResponse {
    return new ListCollectionIdsResponse(ProtoView.of(bytes));
  }

  /** Encodes `init` as a `google.firestore.v1.ListCollectionIdsResponse`. */
  static of(init: ListCollectionIdsResponseInit): ListCollectionIdsResponse {
    let w = new ProtoWriter();
    if (let {collectionIds as f1} = init) {
      for (let item in f1) {
        w.string(1, item);
      }
    }
    if (let {nextPageToken as f2} = init) {
      w.string(2, f2);
    }
    return new ListCollectionIdsResponse(w.finish());
  }

  /** The encoded message. */
  protoView: ProtoView {
    get { return this.#m; }
  }

  /** The collection ids. */
  collectionIds: ProtoList<String> {
    get { return this.#m.repeated(1, WIRE_LEN, (v, p) => v.stringAt(p)); }
  }

  /** A page token that may be used to continue the list. */
  nextPageToken: String {
    get { return this.#m.string(2); }
  }
}

/** The fields of a `google.firestore.v1.BatchWriteRequest` to encode, for `BatchWriteRequest.of`. */
export type BatchWriteRequestInit = {
  database: String,
  writes?: Array<Write>,
  labels?: Map<String, String>,
  requestOptions?: RequestOptions,
};

/**
 * The request for
 * [Firestore.BatchWrite][google.firestore.v1.Firestore.BatchWrite].
 *
 * Protobuf: `google.firestore.v1.BatchWriteRequest`.
 */
export final class BatchWriteRequest {
  #m: ProtoView;

  /** A message over `m`, which must hold an encoded `google.firestore.v1.BatchWriteRequest`. */
  new(m: ProtoView) : #m = m;

  /** Decodes `bytes`. Fields are decoded as they are read. */
  static decode(bytes: ByteArray): BatchWriteRequest {
    return new BatchWriteRequest(ProtoView.of(bytes));
  }

  /** Encodes `init` as a `google.firestore.v1.BatchWriteRequest`. */
  static of(init: BatchWriteRequestInit): BatchWriteRequest {
    let w = new ProtoWriter();
    let f1 = init.database;
    w.string(1, f1);
    if (let {writes as f2} = init) {
      for (let item in f2) {
        w.message(2, item.protoView);
      }
    }
    if (let {labels as f3} = init) {
      for (let entry in f3) {
        let e = new ProtoWriter();
        e.string(1, entry.key);
        e.string(2, entry.value);
        w.message(3, e.finish());
      }
    }
    if (let {requestOptions as f4} = init) {
      w.message(4, f4.protoView);
    }
    return new BatchWriteRequest(w.finish());
  }

  /** The encoded message. */
  protoView: ProtoView {
    get { return this.#m; }
  }

  /**
   * Required. The database name. In the format:
   * `projects/{project_id}/databases/{database_id}`.
   */
  database: String {
    get { return this.#m.string(1); }
  }

  /**
   * The writes to apply.
   *
   * Method does not apply writes atomically and does not guarantee ordering.
   * Each write succeeds or fails independently. You cannot write to the same
   * document more than once per request.
   */
  writes: ProtoList<Write> {
    get { return this.#m.repeated(2, WIRE_LEN, (v, p) => new Write(v.messageAt(p))); }
  }

  /** Labels associated with this batch write. */
  labels: ProtoMap<String, String> {
    get { return this.#m.map(3, (e) => e.string(1), (e) => e.string(2)); }
  }

  /** Optional. Any additional options for the request. */
  requestOptions: RequestOptions | null {
    get {
      let m = this.#m.message(4);
      return if (m == null) null else new RequestOptions(m as ProtoView);
    }
  }
}

/** The fields of a `google.firestore.v1.BatchWriteResponse` to encode, for `BatchWriteResponse.of`. */
export type BatchWriteResponseInit = {
  writeResults?: Array<WriteResult>,
  status?: Array<Status>,
};

/**
 * The response from
 * [Firestore.BatchWrite][google.firestore.v1.Firestore.BatchWrite].
 *
 * Protobuf: `google.firestore.v1.BatchWriteResponse`.
 */
export final class BatchWriteResponse {
  #m: ProtoView;

  /** A message over `m`, which must hold an encoded `google.firestore.v1.BatchWriteResponse`. */
  new(m: ProtoView) : #m = m;

  /** Decodes `bytes`. Fields are decoded as they are read. */
  static decode(bytes: ByteArray): BatchWriteResponse {
    return new BatchWriteResponse(ProtoView.of(bytes));
  }

  /** Encodes `init` as a `google.firestore.v1.BatchWriteResponse`. */
  static of(init: BatchWriteResponseInit): BatchWriteResponse {
    let w = new ProtoWriter();
    if (let {writeResults as f1} = init) {
      for (let item in f1) {
        w.message(1, item.protoView);
      }
    }
    if (let {status as f2} = init) {
      for (let item in f2) {
        w.message(2, item.protoView);
      }
    }
    return new BatchWriteResponse(w.finish());
  }

  /** The encoded message. */
  protoView: ProtoView {
    get { return this.#m; }
  }

  /**
   * The result of applying the writes.
   *
   * This i-th write result corresponds to the i-th write in the
   * request.
   */
  writeResults: ProtoList<WriteResult> {
    get { return this.#m.repeated(1, WIRE_LEN, (v, p) => new WriteResult(v.messageAt(p))); }
  }

  /**
   * The status of applying the writes.
   *
   * This i-th write status corresponds to the i-th write in the
   * request.
   */
  status: ProtoList<Status> {
    get { return this.#m.repeated(2, WIRE_LEN, (v, p) => new Status(v.messageAt(p))); }
  }
}

/** The fields of a `google.firestore.v1.AggregationResult` to encode, for `AggregationResult.of`. */
export type AggregationResultInit = {
  aggregateFields?: Map<String, Value>,
};

/**
 * The result of a single bucket from a Firestore aggregation query.
 *
 * The keys of `aggregate_fields` are the same for all results in an aggregation
 * query, unlike document queries which can have different fields present for
 * each result.
 *
 * Protobuf: `google.firestore.v1.AggregationResult`.
 */
export final class AggregationResult {
  #m: ProtoView;

  /** A message over `m`, which must hold an encoded `google.firestore.v1.AggregationResult`. */
  new(m: ProtoView) : #m = m;

  /** Decodes `bytes`. Fields are decoded as they are read. */
  static decode(bytes: ByteArray): AggregationResult {
    return new AggregationResult(ProtoView.of(bytes));
  }

  /** Encodes `init` as a `google.firestore.v1.AggregationResult`. */
  static of(init: AggregationResultInit): AggregationResult {
    let w = new ProtoWriter();
    if (let {aggregateFields as f2} = init) {
      for (let entry in f2) {
        let e = new ProtoWriter();
        e.string(1, entry.key);
        e.message(2, entry.value.protoView);
        w.message(2, e.finish());
      }
    }
    return new AggregationResult(w.finish());
  }

  /** The encoded message. */
  protoView: ProtoView {
    get { return this.#m; }
  }

  /**
   * The result of the aggregation functions, ex: `COUNT(*) AS total_docs`.
   *
   * The key is the
   * [alias][google.firestore.v1.StructuredAggregationQuery.Aggregation.alias]
   * assigned to the aggregation function on input and the size of this map
   * equals the number of aggregation functions in the query.
   */
  aggregateFields: ProtoMap<String, Value> {
    get { return this.#m.map(2, (e) => e.string(1), (e) => new Value(e.messageOrEmpty(2))); }
  }
}

/** The fields of a `google.firestore.v1.DocumentMask` to encode, for `DocumentMask.of`. */
export type DocumentMaskInit = {
  fieldPaths?: Array<String>,
};

/**
 * A set of field paths on a document.
 * Used to restrict a get or update operation on a document to a subset of its
 * fields.
 * This is different from standard field masks, as this is always scoped to a
 * [Document][google.firestore.v1.Document], and takes in account the dynamic
 * nature of [Value][google.firestore.v1.Value].
 *
 * Protobuf: `google.firestore.v1.DocumentMask`.
 */
export final class DocumentMask {
  #m: ProtoView;

  /** A message over `m`, which must hold an encoded `google.firestore.v1.DocumentMask`. */
  new(m: ProtoView) : #m = m;

  /** Decodes `bytes`. Fields are decoded as they are read. */
  static decode(bytes: ByteArray): DocumentMask {
    return new DocumentMask(ProtoView.of(bytes));
  }

  /** Encodes `init` as a `google.firestore.v1.DocumentMask`. */
  static of(init: DocumentMaskInit): DocumentMask {
    let w = new ProtoWriter();
    if (let {fieldPaths as f1} = init) {
      for (let item in f1) {
        w.string(1, item);
      }
    }
    return new DocumentMask(w.finish());
  }

  /** The encoded message. */
  protoView: ProtoView {
    get { return this.#m; }
  }

  /**
   * The list of field paths in the mask. See
   * [Document.fields][google.firestore.v1.Document.fields] for a field path
   * syntax reference.
   */
  fieldPaths: ProtoList<String> {
    get { return this.#m.repeated(1, WIRE_LEN, (v, p) => v.stringAt(p)); }
  }
}

/**
 * The type of precondition.
 *
 * The member of `google.firestore.v1.Precondition.condition_type` that is set, as `Precondition.conditionType` reads it.
 */
export sealed class PreconditionConditionType {
  case PreconditionExists(value: boolean)
  case PreconditionUpdateTime(value: Timestamp)
  case PreconditionConditionTypeNotSet
}

/** The fields of a `google.firestore.v1.Precondition` to encode, for `Precondition.of`. */
export type PreconditionInit = {
  exists?: boolean,
  updateTime?: Timestamp,
};

/**
 * A precondition on a document, used for conditional operations.
 *
 * Protobuf: `google.firestore.v1.Precondition`.
 */
export final class Precondition {
  #m: ProtoView;

  /** A message over `m`, which must hold an encoded `google.firestore.v1.Precondition`. */
  new(m: ProtoView) : #m = m;

  /** Decodes `bytes`. Fields are decoded as they are read. */
  static decode(bytes: ByteArray): Precondition {
    return new Precondition(ProtoView.of(bytes));
  }

  /** Encodes `init` as a `google.firestore.v1.Precondition`. */
  static of(init: PreconditionInit): Precondition {
    let w = new ProtoWriter();
    if (let {exists as f1} = init) {
      w.bool(1, f1);
    }
    if (let {updateTime as f2} = init) {
      w.message(2, f2.protoView);
    }
    return new Precondition(w.finish());
  }

  /** The encoded message. */
  protoView: ProtoView {
    get { return this.#m; }
  }

  /**
   * When set to `true`, the target document must exist.
   * When set to `false`, the target document must not exist.
   */
  exists: boolean {
    get {
      if (this.#whichConditionType() != 1) {
        return false;
      }
      return this.#m.bool(1);
    }
  }

  /** Whether `exists` is set. */
  hasExists: boolean {
    get { return this.#whichConditionType() == 1; }
  }

  /**
   * When set, the target document must exist and have been last updated at
   * that time. Timestamp must be microsecond aligned.
   */
  updateTime: Timestamp | null {
    get {
      if (this.#whichConditionType() != 2) {
        return null;
      }
      let m = this.#m.message(2);
      return if (m == null) null else new Timestamp(m as ProtoView);
    }
  }

  /** The member of `condition_type` that is set. */
  conditionType: PreconditionConditionType {
    get {
      let which = this.#whichConditionType();
      if (which == 1) {
        return new PreconditionExists(this.#m.bool(1));
      }
      if (which == 2) {
        return new PreconditionUpdateTime(new Timestamp(this.#m.message(2) as ProtoView));
      }
      return new PreconditionConditionTypeNotSet();
    }
  }

  #whichConditionType(): i32 {
    return this.#m.whichOf([1, 2]);
  }
}

/**
 * The mode of the transaction.
 *
 * The member of `google.firestore.v1.TransactionOptions.mode` that is set, as `TransactionOptions.mode` reads it.
 */
export sealed class TransactionOptionsMode {
  case TransactionOptionsModeReadOnly(value: TransactionOptionsReadOnly)
  case TransactionOptionsModeReadWrite(value: TransactionOptionsReadWrite)
  case TransactionOptionsModeNotSet
}

/** The fields of a `google.firestore.v1.TransactionOptions` to encode, for `TransactionOptions.of`. */
export type TransactionOptionsInit = {
  readOnly?: TransactionOptionsReadOnly,
  readWrite?: TransactionOptionsReadWrite,
};

/**
 * Options for creating a new transaction.
 *
 * Protobuf: `google.firestore.v1.TransactionOptions`.
 */
export final class TransactionOptions {
  #m: ProtoView;

  /** A message over `m`, which must hold an encoded `google.firestore.v1.TransactionOptions`. */
  new(m: ProtoView) : #m = m;

  /** Decodes `bytes`. Fields are decoded as they are read. */
  static decode(bytes: ByteArray): TransactionOptions {
    return new TransactionOptions(ProtoView.of(bytes));
  }

  /** Encodes `init` as a `google.firestore.v1.TransactionOptions`. */
  static of(init: TransactionOptionsInit): TransactionOptions {
    let w = new ProtoWriter();
    if (let {readOnly as f2} = init) {
      w.message(2, f2.protoView);
    }
    if (let {readWrite as f3} = init) {
      w.message(3, f3.protoView);
    }
    return new TransactionOptions(w.finish());
  }

  /** The encoded message. */
  protoView: ProtoView {
    get { return this.#m; }
  }

  /** The transaction can only be used for read operations. */
  readOnly: TransactionOptionsReadOnly | null {
    get {
      if (this.#whichMode() != 2) {
        return null;
      }
      let m = this.#m.message(2);
      return if (m == null) null else new TransactionOptionsReadOnly(m as ProtoView);
    }
  }

  /** The transaction can be used for both read and write operations. */
  readWrite: TransactionOptionsReadWrite | null {
    get {
      if (this.#whichMode() != 3) {
        return null;
      }
      let m = this.#m.message(3);
      return if (m == null) null else new TransactionOptionsReadWrite(m as ProtoView);
    }
  }

  /** The member of `mode` that is set. */
  mode: TransactionOptionsMode {
    get {
      let which = this.#whichMode();
      if (which == 2) {
        return new TransactionOptionsModeReadOnly(new TransactionOptionsReadOnly(this.#m.message(2) as ProtoView));
      }
      if (which == 3) {
        return new TransactionOptionsModeReadWrite(new TransactionOptionsReadWrite(this.#m.message(3) as ProtoView));
      }
      return new TransactionOptionsModeNotSet();
    }
  }

  #whichMode(): i32 {
    return this.#m.whichOf([2, 3]);
  }
}

/** The fields of a `google.firestore.v1.TransactionOptions.ReadWrite` to encode, for `TransactionOptionsReadWrite.of`. */
export type TransactionOptionsReadWriteInit = {
  retryTransaction?: ByteArray | ProtoBytes,
  concurrencyMode?: TransactionOptionsConcurrencyMode,
};

/**
 * Options for a transaction that can be used to read and write documents.
 *
 * Protobuf: `google.firestore.v1.TransactionOptions.ReadWrite`.
 */
export final class TransactionOptionsReadWrite {
  #m: ProtoView;

  /** A message over `m`, which must hold an encoded `google.firestore.v1.TransactionOptions.ReadWrite`. */
  new(m: ProtoView) : #m = m;

  /** Decodes `bytes`. Fields are decoded as they are read. */
  static decode(bytes: ByteArray): TransactionOptionsReadWrite {
    return new TransactionOptionsReadWrite(ProtoView.of(bytes));
  }

  /** Encodes `init` as a `google.firestore.v1.TransactionOptions.ReadWrite`. */
  static of(init: TransactionOptionsReadWriteInit): TransactionOptionsReadWrite {
    let w = new ProtoWriter();
    if (let {retryTransaction as f1} = init) {
      w.bytes(1, f1);
    }
    if (let {concurrencyMode as f2} = init) {
      w.int32(2, f2 as i32);
    }
    return new TransactionOptionsReadWrite(w.finish());
  }

  /** The encoded message. */
  protoView: ProtoView {
    get { return this.#m; }
  }

  /** An optional transaction to retry. */
  retryTransaction: ProtoBytes {
    get { return this.#m.bytes(1); }
  }

  /**
   * Optional. The concurrency control mode to use for this transaction.
   *
   * A database is able to use different concurrency modes for different
   * transactions simultaneously.
   *
   * 3rd party auth requests are only allowed to create optimistic
   * read-write transactions and must specify that here even if the
   * database-level setting is already configured to optimistic.
   */
  concurrencyMode: TransactionOptionsConcurrencyMode {
    get { return this.#m.int32(2) as TransactionOptionsConcurrencyMode; }
  }
}

/**
 * The consistency mode for this transaction. If not set, defaults to strong
 * consistency.
 *
 * The member of `google.firestore.v1.TransactionOptions.ReadOnly.consistency_selector` that is set, as `TransactionOptionsReadOnly.consistencySelector` reads it.
 */
export sealed class TransactionOptionsReadOnlyConsistencySelector {
  case TransactionOptionsReadOnlyReadTime(value: Timestamp)
  case TransactionOptionsReadOnlyConsistencySelectorNotSet
}

/** The fields of a `google.firestore.v1.TransactionOptions.ReadOnly` to encode, for `TransactionOptionsReadOnly.of`. */
export type TransactionOptionsReadOnlyInit = {
  readTime?: Timestamp,
};

/**
 * Options for a transaction that can only be used to read documents.
 *
 * Protobuf: `google.firestore.v1.TransactionOptions.ReadOnly`.
 */
export final class TransactionOptionsReadOnly {
  #m: ProtoView;

  /** A message over `m`, which must hold an encoded `google.firestore.v1.TransactionOptions.ReadOnly`. */
  new(m: ProtoView) : #m = m;

  /** Decodes `bytes`. Fields are decoded as they are read. */
  static decode(bytes: ByteArray): TransactionOptionsReadOnly {
    return new TransactionOptionsReadOnly(ProtoView.of(bytes));
  }

  /** Encodes `init` as a `google.firestore.v1.TransactionOptions.ReadOnly`. */
  static of(init: TransactionOptionsReadOnlyInit): TransactionOptionsReadOnly {
    let w = new ProtoWriter();
    if (let {readTime as f2} = init) {
      w.message(2, f2.protoView);
    }
    return new TransactionOptionsReadOnly(w.finish());
  }

  /** The encoded message. */
  protoView: ProtoView {
    get { return this.#m; }
  }

  /**
   * Reads documents at the given time.
   *
   * This must be a microsecond precision timestamp within the past one
   * hour, or if Point-in-Time Recovery is enabled, can additionally be a
   * whole minute timestamp within the past 7 days.
   */
  readTime: Timestamp | null {
    get {
      if (this.#whichConsistencySelector() != 2) {
        return null;
      }
      let m = this.#m.message(2);
      return if (m == null) null else new Timestamp(m as ProtoView);
    }
  }

  /** The member of `consistency_selector` that is set. */
  consistencySelector: TransactionOptionsReadOnlyConsistencySelector {
    get {
      let which = this.#whichConsistencySelector();
      if (which == 2) {
        return new TransactionOptionsReadOnlyReadTime(new Timestamp(this.#m.message(2) as ProtoView));
      }
      return new TransactionOptionsReadOnlyConsistencySelectorNotSet();
    }
  }

  #whichConsistencySelector(): i32 {
    return this.#m.whichOf([2]);
  }
}

/** The fields of a `google.firestore.v1.RequestOptions` to encode, for `RequestOptions.of`. */
export type RequestOptionsInit = {
  requestTags?: Array<String>,
};

/**
 * Options for a server request.
 *
 * Protobuf: `google.firestore.v1.RequestOptions`.
 */
export final class RequestOptions {
  #m: ProtoView;

  /** A message over `m`, which must hold an encoded `google.firestore.v1.RequestOptions`. */
  new(m: ProtoView) : #m = m;

  /** Decodes `bytes`. Fields are decoded as they are read. */
  static decode(bytes: ByteArray): RequestOptions {
    return new RequestOptions(ProtoView.of(bytes));
  }

  /** Encodes `init` as a `google.firestore.v1.RequestOptions`. */
  static of(init: RequestOptionsInit): RequestOptions {
    let w = new ProtoWriter();
    if (let {requestTags as f1} = init) {
      for (let item in f1) {
        w.string(1, item);
      }
    }
    return new RequestOptions(w.finish());
  }

  /** The encoded message. */
  protoView: ProtoView {
    get { return this.#m; }
  }

  /** The request tags for the request. */
  requestTags: ProtoList<String> {
    get { return this.#m.repeated(1, WIRE_LEN, (v, p) => v.stringAt(p)); }
  }
}

/** The fields of a `google.firestore.v1.Document` to encode, for `Document.of`. */
export type DocumentInit = {
  name?: String,
  fields?: Map<String, Value>,
  createTime?: Timestamp,
  updateTime?: Timestamp,
};

/**
 * A Firestore document.
 *
 * Must not exceed 1 MiB - 4 bytes.
 *
 * Protobuf: `google.firestore.v1.Document`.
 */
export final class Document {
  #m: ProtoView;

  /** A message over `m`, which must hold an encoded `google.firestore.v1.Document`. */
  new(m: ProtoView) : #m = m;

  /** Decodes `bytes`. Fields are decoded as they are read. */
  static decode(bytes: ByteArray): Document {
    return new Document(ProtoView.of(bytes));
  }

  /** Encodes `init` as a `google.firestore.v1.Document`. */
  static of(init: DocumentInit): Document {
    let w = new ProtoWriter();
    if (let {name as f1} = init) {
      w.string(1, f1);
    }
    if (let {fields as f2} = init) {
      for (let entry in f2) {
        let e = new ProtoWriter();
        e.string(1, entry.key);
        e.message(2, entry.value.protoView);
        w.message(2, e.finish());
      }
    }
    if (let {createTime as f3} = init) {
      w.message(3, f3.protoView);
    }
    if (let {updateTime as f4} = init) {
      w.message(4, f4.protoView);
    }
    return new Document(w.finish());
  }

  /** The encoded message. */
  protoView: ProtoView {
    get { return this.#m; }
  }

  /**
   * The resource name of the document, for example
   * `projects/{project_id}/databases/{database_id}/documents/{document_path}`.
   */
  name: String {
    get { return this.#m.string(1); }
  }

  /**
   * The document's fields.
   *
   * The map keys represent field names.
   *
   * Field names matching the regular expression `__.*__` are reserved. Reserved
   * field names are forbidden except in certain documented contexts. The field
   * names, represented as UTF-8, must not exceed 1,500 bytes and cannot be
   * empty.
   *
   * Field paths may be used in other contexts to refer to structured fields
   * defined here. For `map_value`, the field path is represented by a
   * dot-delimited (`.`) string of segments. Each segment is either a simple
   * field name (defined below) or a quoted field name. For example, the
   * structured field `"foo" : { map_value: { "x&y" : { string_value: "hello"
   * }}}` would be represented by the field path `` foo.`x&y` ``.
   *
   * A simple field name contains only characters `a` to `z`, `A` to `Z`,
   * `0` to `9`, or `_`, and must not start with `0` to `9`. For example,
   * `foo_bar_17`.
   *
   * A quoted field name starts and ends with `` ` `` and
   * may contain any character. Some characters, including `` ` ``, must be
   * escaped using a `\`. For example, `` `x&y` `` represents `x&y` and
   * `` `bak\`tik` `` represents `` bak`tik ``.
   */
  fields: ProtoMap<String, Value> {
    get { return this.#m.map(2, (e) => e.string(1), (e) => new Value(e.messageOrEmpty(2))); }
  }

  /**
   * Output only. The time at which the document was created.
   *
   * This value increases monotonically when a document is deleted then
   * recreated. It can also be compared to values from other documents and
   * the `read_time` of a query.
   */
  createTime: Timestamp | null {
    get {
      let m = this.#m.message(3);
      return if (m == null) null else new Timestamp(m as ProtoView);
    }
  }

  /**
   * Output only. The time at which the document was last changed.
   *
   * This value is initially set to the `create_time` then increases
   * monotonically with each change to the document. It can also be
   * compared to values from other documents and the `read_time` of a query.
   */
  updateTime: Timestamp | null {
    get {
      let m = this.#m.message(4);
      return if (m == null) null else new Timestamp(m as ProtoView);
    }
  }
}

/**
 * Must have a value set.
 *
 * The member of `google.firestore.v1.Value.value_type` that is set, as `Value.valueType` reads it.
 */
export sealed class ValueValueType {
  case ValueNullValue(value: NullValue)
  case ValueBooleanValue(value: boolean)
  case ValueIntegerValue(value: i64)
  case ValueDoubleValue(value: f64)
  case ValueTimestampValue(value: Timestamp)
  case ValueStringValue(value: String)
  case ValueBytesValue(value: ProtoBytes)
  case ValueReferenceValue(value: String)
  case ValueGeoPointValue(value: LatLng)
  case ValueArrayValue(value: ArrayValue)
  case ValueMapValue(value: MapValue)
  case ValueFieldReferenceValue(value: String)
  case ValueVariableReferenceValue(value: String)
  case ValueFunctionValue(value: Function)
  case ValuePipelineValue(value: Pipeline)
  case ValueValueTypeNotSet
}

/** The fields of a `google.firestore.v1.Value` to encode, for `Value.of`. */
export type ValueInit = {
  nullValue?: NullValue,
  booleanValue?: boolean,
  integerValue?: i64,
  doubleValue?: f64,
  timestampValue?: Timestamp,
  stringValue?: String,
  bytesValue?: ByteArray | ProtoBytes,
  referenceValue?: String,
  geoPointValue?: LatLng,
  arrayValue?: ArrayValue,
  mapValue?: MapValue,
  fieldReferenceValue?: String,
  variableReferenceValue?: String,
  functionValue?: Function,
  pipelineValue?: Pipeline,
};

/**
 * A message that can hold any of the supported value types.
 *
 * Protobuf: `google.firestore.v1.Value`.
 */
export final class Value {
  #m: ProtoView;

  /** A message over `m`, which must hold an encoded `google.firestore.v1.Value`. */
  new(m: ProtoView) : #m = m;

  /** Decodes `bytes`. Fields are decoded as they are read. */
  static decode(bytes: ByteArray): Value {
    return new Value(ProtoView.of(bytes));
  }

  /** Encodes `init` as a `google.firestore.v1.Value`. */
  static of(init: ValueInit): Value {
    let w = new ProtoWriter();
    if (let {nullValue as f11} = init) {
      w.int32(11, f11 as i32);
    }
    if (let {booleanValue as f1} = init) {
      w.bool(1, f1);
    }
    if (let {integerValue as f2} = init) {
      w.int64(2, f2);
    }
    if (let {doubleValue as f3} = init) {
      w.double(3, f3);
    }
    if (let {timestampValue as f10} = init) {
      w.message(10, f10.protoView);
    }
    if (let {stringValue as f17} = init) {
      w.string(17, f17);
    }
    if (let {bytesValue as f18} = init) {
      w.bytes(18, f18);
    }
    if (let {referenceValue as f5} = init) {
      w.string(5, f5);
    }
    if (let {geoPointValue as f8} = init) {
      w.message(8, f8.protoView);
    }
    if (let {arrayValue as f9} = init) {
      w.message(9, f9.protoView);
    }
    if (let {mapValue as f6} = init) {
      w.message(6, f6.protoView);
    }
    if (let {fieldReferenceValue as f19} = init) {
      w.string(19, f19);
    }
    if (let {variableReferenceValue as f22} = init) {
      w.string(22, f22);
    }
    if (let {functionValue as f20} = init) {
      w.message(20, f20.protoView);
    }
    if (let {pipelineValue as f21} = init) {
      w.message(21, f21.protoView);
    }
    return new Value(w.finish());
  }

  /** The encoded message. */
  protoView: ProtoView {
    get { return this.#m; }
  }

  /** A null value. */
  nullValue: NullValue {
    get {
      if (this.#whichValueType() != 11) {
        return 0 as NullValue;
      }
      return this.#m.int32(11) as NullValue;
    }
  }

  /** Whether `nullValue` is set. */
  hasNullValue: boolean {
    get { return this.#whichValueType() == 11; }
  }

  /** A boolean value. */
  booleanValue: boolean {
    get {
      if (this.#whichValueType() != 1) {
        return false;
      }
      return this.#m.bool(1);
    }
  }

  /** Whether `booleanValue` is set. */
  hasBooleanValue: boolean {
    get { return this.#whichValueType() == 1; }
  }

  /** An integer value. */
  integerValue: i64 {
    get {
      if (this.#whichValueType() != 2) {
        return 0;
      }
      return this.#m.int64(2);
    }
  }

  /** Whether `integerValue` is set. */
  hasIntegerValue: boolean {
    get { return this.#whichValueType() == 2; }
  }

  /** A double value. */
  doubleValue: f64 {
    get {
      if (this.#whichValueType() != 3) {
        return 0.0;
      }
      return this.#m.double(3);
    }
  }

  /** Whether `doubleValue` is set. */
  hasDoubleValue: boolean {
    get { return this.#whichValueType() == 3; }
  }

  /**
   * A timestamp value.
   *
   * Precise only to microseconds. When stored, any additional precision is
   * rounded down.
   */
  timestampValue: Timestamp | null {
    get {
      if (this.#whichValueType() != 10) {
        return null;
      }
      let m = this.#m.message(10);
      return if (m == null) null else new Timestamp(m as ProtoView);
    }
  }

  /**
   * A string value.
   *
   * The string, represented as UTF-8, must not exceed 1 MiB - 89 bytes.
   * Only the first 1,500 bytes of the UTF-8 representation are considered by
   * queries.
   */
  stringValue: String {
    get {
      if (this.#whichValueType() != 17) {
        return '';
      }
      return this.#m.string(17);
    }
  }

  /** Whether `stringValue` is set. */
  hasStringValue: boolean {
    get { return this.#whichValueType() == 17; }
  }

  /**
   * A bytes value.
   *
   * Must not exceed 1 MiB - 89 bytes.
   * Only the first 1,500 bytes are considered by queries.
   */
  bytesValue: ProtoBytes {
    get {
      if (this.#whichValueType() != 18) {
        return ProtoBytes.empty();
      }
      return this.#m.bytes(18);
    }
  }

  /** Whether `bytesValue` is set. */
  hasBytesValue: boolean {
    get { return this.#whichValueType() == 18; }
  }

  /**
   * A reference to a document. For example:
   * `projects/{project_id}/databases/{database_id}/documents/{document_path}`.
   */
  referenceValue: String {
    get {
      if (this.#whichValueType() != 5) {
        return '';
      }
      return this.#m.string(5);
    }
  }

  /** Whether `referenceValue` is set. */
  hasReferenceValue: boolean {
    get { return this.#whichValueType() == 5; }
  }

  /** A geo point value representing a point on the surface of Earth. */
  geoPointValue: LatLng | null {
    get {
      if (this.#whichValueType() != 8) {
        return null;
      }
      let m = this.#m.message(8);
      return if (m == null) null else new LatLng(m as ProtoView);
    }
  }

  /**
   * An array value.
   *
   * Cannot directly contain another array value, though can contain a
   * map which contains another array.
   */
  arrayValue: ArrayValue | null {
    get {
      if (this.#whichValueType() != 9) {
        return null;
      }
      let m = this.#m.message(9);
      return if (m == null) null else new ArrayValue(m as ProtoView);
    }
  }

  /** A map value. */
  mapValue: MapValue | null {
    get {
      if (this.#whichValueType() != 6) {
        return null;
      }
      let m = this.#m.message(6);
      return if (m == null) null else new MapValue(m as ProtoView);
    }
  }

  /**
   * Value which references a field.
   *
   * This is considered relative (vs absolute) since it only refers to a field
   * and not a field within a particular document.
   *
   * **Requires:**
   *
   * * Must follow [field reference][FieldReference.field_path] limitations.
   *
   * * Not allowed to be used when writing documents.
   */
  fieldReferenceValue: String {
    get {
      if (this.#whichValueType() != 19) {
        return '';
      }
      return this.#m.string(19);
    }
  }

  /** Whether `fieldReferenceValue` is set. */
  hasFieldReferenceValue: boolean {
    get { return this.#whichValueType() == 19; }
  }

  /**
   * Pointer to a variable defined elsewhere in a pipeline.
   *
   * Unlike `field_reference_value` which references a field within a
   * document, this refers to a variable, defined in a separate namespace than
   * the fields of a document.
   */
  variableReferenceValue: String {
    get {
      if (this.#whichValueType() != 22) {
        return '';
      }
      return this.#m.string(22);
    }
  }

  /** Whether `variableReferenceValue` is set. */
  hasVariableReferenceValue: boolean {
    get { return this.#whichValueType() == 22; }
  }

  /**
   * A value that represents an unevaluated expression.
   *
   * **Requires:**
   *
   * * Not allowed to be used when writing documents.
   */
  functionValue: Function | null {
    get {
      if (this.#whichValueType() != 20) {
        return null;
      }
      let m = this.#m.message(20);
      return if (m == null) null else new Function(m as ProtoView);
    }
  }

  /**
   * A value that represents an unevaluated pipeline.
   *
   * **Requires:**
   *
   * * Not allowed to be used when writing documents.
   */
  pipelineValue: Pipeline | null {
    get {
      if (this.#whichValueType() != 21) {
        return null;
      }
      let m = this.#m.message(21);
      return if (m == null) null else new Pipeline(m as ProtoView);
    }
  }

  /** The member of `value_type` that is set. */
  valueType: ValueValueType {
    get {
      let which = this.#whichValueType();
      if (which == 11) {
        return new ValueNullValue(this.#m.int32(11) as NullValue);
      }
      if (which == 1) {
        return new ValueBooleanValue(this.#m.bool(1));
      }
      if (which == 2) {
        return new ValueIntegerValue(this.#m.int64(2));
      }
      if (which == 3) {
        return new ValueDoubleValue(this.#m.double(3));
      }
      if (which == 10) {
        return new ValueTimestampValue(new Timestamp(this.#m.message(10) as ProtoView));
      }
      if (which == 17) {
        return new ValueStringValue(this.#m.string(17));
      }
      if (which == 18) {
        return new ValueBytesValue(this.#m.bytes(18));
      }
      if (which == 5) {
        return new ValueReferenceValue(this.#m.string(5));
      }
      if (which == 8) {
        return new ValueGeoPointValue(new LatLng(this.#m.message(8) as ProtoView));
      }
      if (which == 9) {
        return new ValueArrayValue(new ArrayValue(this.#m.message(9) as ProtoView));
      }
      if (which == 6) {
        return new ValueMapValue(new MapValue(this.#m.message(6) as ProtoView));
      }
      if (which == 19) {
        return new ValueFieldReferenceValue(this.#m.string(19));
      }
      if (which == 22) {
        return new ValueVariableReferenceValue(this.#m.string(22));
      }
      if (which == 20) {
        return new ValueFunctionValue(new Function(this.#m.message(20) as ProtoView));
      }
      if (which == 21) {
        return new ValuePipelineValue(new Pipeline(this.#m.message(21) as ProtoView));
      }
      return new ValueValueTypeNotSet();
    }
  }

  #whichValueType(): i32 {
    return this.#m.whichOf([11, 1, 2, 3, 10, 17, 18, 5, 8, 9, 6, 19, 22, 20, 21]);
  }
}

/** The fields of a `google.firestore.v1.ArrayValue` to encode, for `ArrayValue.of`. */
export type ArrayValueInit = {
  values?: Array<Value>,
};

/**
 * An array value.
 *
 * Protobuf: `google.firestore.v1.ArrayValue`.
 */
export final class ArrayValue {
  #m: ProtoView;

  /** A message over `m`, which must hold an encoded `google.firestore.v1.ArrayValue`. */
  new(m: ProtoView) : #m = m;

  /** Decodes `bytes`. Fields are decoded as they are read. */
  static decode(bytes: ByteArray): ArrayValue {
    return new ArrayValue(ProtoView.of(bytes));
  }

  /** Encodes `init` as a `google.firestore.v1.ArrayValue`. */
  static of(init: ArrayValueInit): ArrayValue {
    let w = new ProtoWriter();
    if (let {values as f1} = init) {
      for (let item in f1) {
        w.message(1, item.protoView);
      }
    }
    return new ArrayValue(w.finish());
  }

  /** The encoded message. */
  protoView: ProtoView {
    get { return this.#m; }
  }

  /** Values in the array. */
  values: ProtoList<Value> {
    get { return this.#m.repeated(1, WIRE_LEN, (v, p) => new Value(v.messageAt(p))); }
  }
}

/** The fields of a `google.firestore.v1.MapValue` to encode, for `MapValue.of`. */
export type MapValueInit = {
  fields?: Map<String, Value>,
};

/**
 * A map value.
 *
 * Protobuf: `google.firestore.v1.MapValue`.
 */
export final class MapValue {
  #m: ProtoView;

  /** A message over `m`, which must hold an encoded `google.firestore.v1.MapValue`. */
  new(m: ProtoView) : #m = m;

  /** Decodes `bytes`. Fields are decoded as they are read. */
  static decode(bytes: ByteArray): MapValue {
    return new MapValue(ProtoView.of(bytes));
  }

  /** Encodes `init` as a `google.firestore.v1.MapValue`. */
  static of(init: MapValueInit): MapValue {
    let w = new ProtoWriter();
    if (let {fields as f1} = init) {
      for (let entry in f1) {
        let e = new ProtoWriter();
        e.string(1, entry.key);
        e.message(2, entry.value.protoView);
        w.message(1, e.finish());
      }
    }
    return new MapValue(w.finish());
  }

  /** The encoded message. */
  protoView: ProtoView {
    get { return this.#m; }
  }

  /**
   * The map's fields.
   *
   * The map keys represent field names. Field names matching the regular
   * expression `__.*__` are reserved. Reserved field names are forbidden except
   * in certain documented contexts. The map keys, represented as UTF-8, must
   * not exceed 1,500 bytes and cannot be empty.
   */
  fields: ProtoMap<String, Value> {
    get { return this.#m.map(1, (e) => e.string(1), (e) => new Value(e.messageOrEmpty(2))); }
  }
}

/** The fields of a `google.firestore.v1.Function` to encode, for `Function.of`. */
export type FunctionInit = {
  name: String,
  args?: Array<Value>,
  options?: Map<String, Value>,
};

/**
 * Represents an unevaluated scalar expression.
 *
 * For example, the expression `like(user_name, "%alice%")` is represented as:
 *
 * ```
 * name: "like"
 * args { field_reference: "user_name" }
 * args { string_value: "%alice%" }
 * ```
 *
 * Protobuf: `google.firestore.v1.Function`.
 */
export final class Function {
  #m: ProtoView;

  /** A message over `m`, which must hold an encoded `google.firestore.v1.Function`. */
  new(m: ProtoView) : #m = m;

  /** Decodes `bytes`. Fields are decoded as they are read. */
  static decode(bytes: ByteArray): Function {
    return new Function(ProtoView.of(bytes));
  }

  /** Encodes `init` as a `google.firestore.v1.Function`. */
  static of(init: FunctionInit): Function {
    let w = new ProtoWriter();
    let f1 = init.name;
    w.string(1, f1);
    if (let {args as f2} = init) {
      for (let item in f2) {
        w.message(2, item.protoView);
      }
    }
    if (let {options as f3} = init) {
      for (let entry in f3) {
        let e = new ProtoWriter();
        e.string(1, entry.key);
        e.message(2, entry.value.protoView);
        w.message(3, e.finish());
      }
    }
    return new Function(w.finish());
  }

  /** The encoded message. */
  protoView: ProtoView {
    get { return this.#m; }
  }

  /**
   * Required. The name of the function to evaluate.
   *
   * **Requires:**
   *
   * * must be in snake case (lower case with underscore separator).
   */
  name: String {
    get { return this.#m.string(1); }
  }

  /** Optional. Ordered list of arguments the given function expects. */
  args: ProtoList<Value> {
    get { return this.#m.repeated(2, WIRE_LEN, (v, p) => new Value(v.messageAt(p))); }
  }

  /** Optional. Optional named arguments that certain functions may support. */
  options: ProtoMap<String, Value> {
    get { return this.#m.map(3, (e) => e.string(1), (e) => new Value(e.messageOrEmpty(2))); }
  }
}

/** The fields of a `google.firestore.v1.Pipeline` to encode, for `Pipeline.of`. */
export type PipelineInit = {
  stages?: Array<PipelineStage>,
};

/**
 * A Firestore query represented as an ordered list of operations / stages.
 *
 * Protobuf: `google.firestore.v1.Pipeline`.
 */
export final class Pipeline {
  #m: ProtoView;

  /** A message over `m`, which must hold an encoded `google.firestore.v1.Pipeline`. */
  new(m: ProtoView) : #m = m;

  /** Decodes `bytes`. Fields are decoded as they are read. */
  static decode(bytes: ByteArray): Pipeline {
    return new Pipeline(ProtoView.of(bytes));
  }

  /** Encodes `init` as a `google.firestore.v1.Pipeline`. */
  static of(init: PipelineInit): Pipeline {
    let w = new ProtoWriter();
    if (let {stages as f1} = init) {
      for (let item in f1) {
        w.message(1, item.protoView);
      }
    }
    return new Pipeline(w.finish());
  }

  /** The encoded message. */
  protoView: ProtoView {
    get { return this.#m; }
  }

  /** Required. Ordered list of stages to evaluate. */
  stages: ProtoList<PipelineStage> {
    get { return this.#m.repeated(1, WIRE_LEN, (v, p) => new PipelineStage(v.messageAt(p))); }
  }
}

/** The fields of a `google.firestore.v1.Pipeline.Stage` to encode, for `PipelineStage.of`. */
export type PipelineStageInit = {
  name: String,
  args?: Array<Value>,
  options?: Map<String, Value>,
};

/**
 * A single operation within a pipeline.
 *
 * A stage is made up of a unique name, and a list of arguments. The exact
 * number of arguments & types is dependent on the stage type.
 *
 * To give an example, the stage `filter(state = "MD")` would be encoded as:
 *
 * ```
 * name: "filter"
 * args {
 *   function_value {
 *     name: "eq"
 *     args { field_reference_value: "state" }
 *     args { string_value: "MD" }
 *   }
 * }
 * ```
 *
 * See public documentation for the full list.
 *
 * Protobuf: `google.firestore.v1.Pipeline.Stage`.
 */
export final class PipelineStage {
  #m: ProtoView;

  /** A message over `m`, which must hold an encoded `google.firestore.v1.Pipeline.Stage`. */
  new(m: ProtoView) : #m = m;

  /** Decodes `bytes`. Fields are decoded as they are read. */
  static decode(bytes: ByteArray): PipelineStage {
    return new PipelineStage(ProtoView.of(bytes));
  }

  /** Encodes `init` as a `google.firestore.v1.Pipeline.Stage`. */
  static of(init: PipelineStageInit): PipelineStage {
    let w = new ProtoWriter();
    let f1 = init.name;
    w.string(1, f1);
    if (let {args as f2} = init) {
      for (let item in f2) {
        w.message(2, item.protoView);
      }
    }
    if (let {options as f3} = init) {
      for (let entry in f3) {
        let e = new ProtoWriter();
        e.string(1, entry.key);
        e.message(2, entry.value.protoView);
        w.message(3, e.finish());
      }
    }
    return new PipelineStage(w.finish());
  }

  /** The encoded message. */
  protoView: ProtoView {
    get { return this.#m; }
  }

  /**
   * Required. The name of the stage to evaluate.
   *
   * **Requires:**
   *
   * * must be in snake case (lower case with underscore separator).
   */
  name: String {
    get { return this.#m.string(1); }
  }

  /** Optional. Ordered list of arguments the given stage expects. */
  args: ProtoList<Value> {
    get { return this.#m.repeated(2, WIRE_LEN, (v, p) => new Value(v.messageAt(p))); }
  }

  /** Optional. Optional named arguments that certain functions may support. */
  options: ProtoMap<String, Value> {
    get { return this.#m.map(3, (e) => e.string(1), (e) => new Value(e.messageOrEmpty(2))); }
  }
}

/** The fields of a `google.firestore.v1.ExplainStats` to encode, for `ExplainStats.of`. */
export type ExplainStatsInit = {
  data?: Any,
};

/**
 * Pipeline explain stats.
 *
 * Depending on the explain options in the original request, this can contain
 * the optimized plan and / or execution stats.
 *
 * Protobuf: `google.firestore.v1.ExplainStats`.
 */
export final class ExplainStats {
  #m: ProtoView;

  /** A message over `m`, which must hold an encoded `google.firestore.v1.ExplainStats`. */
  new(m: ProtoView) : #m = m;

  /** Decodes `bytes`. Fields are decoded as they are read. */
  static decode(bytes: ByteArray): ExplainStats {
    return new ExplainStats(ProtoView.of(bytes));
  }

  /** Encodes `init` as a `google.firestore.v1.ExplainStats`. */
  static of(init: ExplainStatsInit): ExplainStats {
    let w = new ProtoWriter();
    if (let {data as f1} = init) {
      w.message(1, f1.protoView);
    }
    return new ExplainStats(w.finish());
  }

  /** The encoded message. */
  protoView: ProtoView {
    get { return this.#m; }
  }

  /**
   * The format depends on the `output_format` options in the request.
   *
   * Currently there are two supported options: `TEXT` and `JSON`.
   * Both supply a `google.protobuf.StringValue`.
   */
  data: Any | null {
    get {
      let m = this.#m.message(1);
      return if (m == null) null else new Any(m as ProtoView);
    }
  }
}

/** The fields of a `google.firestore.v1.StructuredPipeline` to encode, for `StructuredPipeline.of`. */
export type StructuredPipelineInit = {
  pipeline: Pipeline,
  options?: Map<String, Value>,
};

/**
 * A Firestore query represented as an ordered list of operations / stages.
 *
 * This is considered the top-level function which plans and executes a query.
 * It is logically equivalent to `query(stages, options)`, but prevents the
 * client from having to build a function wrapper.
 *
 * Protobuf: `google.firestore.v1.StructuredPipeline`.
 */
export final class StructuredPipeline {
  #m: ProtoView;

  /** A message over `m`, which must hold an encoded `google.firestore.v1.StructuredPipeline`. */
  new(m: ProtoView) : #m = m;

  /** Decodes `bytes`. Fields are decoded as they are read. */
  static decode(bytes: ByteArray): StructuredPipeline {
    return new StructuredPipeline(ProtoView.of(bytes));
  }

  /** Encodes `init` as a `google.firestore.v1.StructuredPipeline`. */
  static of(init: StructuredPipelineInit): StructuredPipeline {
    let w = new ProtoWriter();
    let f1 = init.pipeline;
    w.message(1, f1.protoView);
    if (let {options as f2} = init) {
      for (let entry in f2) {
        let e = new ProtoWriter();
        e.string(1, entry.key);
        e.message(2, entry.value.protoView);
        w.message(2, e.finish());
      }
    }
    return new StructuredPipeline(w.finish());
  }

  /** The encoded message. */
  protoView: ProtoView {
    get { return this.#m; }
  }

  /** Required. The pipeline query to execute. */
  pipeline: Pipeline | null {
    get {
      let m = this.#m.message(1);
      return if (m == null) null else new Pipeline(m as ProtoView);
    }
  }

  /** Optional. Optional query-level arguments. */
  options: ProtoMap<String, Value> {
    get { return this.#m.map(2, (e) => e.string(1), (e) => new Value(e.messageOrEmpty(2))); }
  }
}

/** The fields of a `google.firestore.v1.StructuredQuery` to encode, for `StructuredQuery.of`. */
export type StructuredQueryInit = {
  select?: StructuredQueryProjection,
  from?: Array<StructuredQueryCollectionSelector>,
  where?: StructuredQueryFilter,
  orderBy?: Array<StructuredQueryOrder>,
  startAt?: Cursor,
  endAt?: Cursor,
  offset?: i32,
  limit?: Int32Value,
  findNearest?: StructuredQueryFindNearest,
};

/**
 * A Firestore query.
 *
 * The query stages are executed in the following order:
 * 1. from
 * 2. where
 * 3. select
 * 4. order_by + start_at + end_at
 * 5. offset
 * 6. limit
 * 7. find_nearest
 *
 * Protobuf: `google.firestore.v1.StructuredQuery`.
 */
export final class StructuredQuery {
  #m: ProtoView;

  /** A message over `m`, which must hold an encoded `google.firestore.v1.StructuredQuery`. */
  new(m: ProtoView) : #m = m;

  /** Decodes `bytes`. Fields are decoded as they are read. */
  static decode(bytes: ByteArray): StructuredQuery {
    return new StructuredQuery(ProtoView.of(bytes));
  }

  /** Encodes `init` as a `google.firestore.v1.StructuredQuery`. */
  static of(init: StructuredQueryInit): StructuredQuery {
    let w = new ProtoWriter();
    if (let {select as f1} = init) {
      w.message(1, f1.protoView);
    }
    if (let {from as f2} = init) {
      for (let item in f2) {
        w.message(2, item.protoView);
      }
    }
    if (let {where as f3} = init) {
      w.message(3, f3.protoView);
    }
    if (let {orderBy as f4} = init) {
      for (let item in f4) {
        w.message(4, item.protoView);
      }
    }
    if (let {startAt as f7} = init) {
      w.message(7, f7.protoView);
    }
    if (let {endAt as f8} = init) {
      w.message(8, f8.protoView);
    }
    if (let {offset as f6} = init) {
      w.int32(6, f6);
    }
    if (let {limit as f5} = init) {
      w.message(5, f5.protoView);
    }
    if (let {findNearest as f9} = init) {
      w.message(9, f9.protoView);
    }
    return new StructuredQuery(w.finish());
  }

  /** The encoded message. */
  protoView: ProtoView {
    get { return this.#m; }
  }

  /**
   * Optional sub-set of the fields to return.
   *
   * This acts as a [DocumentMask][google.firestore.v1.DocumentMask] over the
   * documents returned from a query. When not set, assumes that the caller
   * wants all fields returned.
   */
  select: StructuredQueryProjection | null {
    get {
      let m = this.#m.message(1);
      return if (m == null) null else new StructuredQueryProjection(m as ProtoView);
    }
  }

  /** The collections to query. */
  from: ProtoList<StructuredQueryCollectionSelector> {
    get { return this.#m.repeated(2, WIRE_LEN, (v, p) => new StructuredQueryCollectionSelector(v.messageAt(p))); }
  }

  /** The filter to apply. */
  where: StructuredQueryFilter | null {
    get {
      let m = this.#m.message(3);
      return if (m == null) null else new StructuredQueryFilter(m as ProtoView);
    }
  }

  /**
   * The order to apply to the query results.
   *
   * Callers can provide a full ordering, a partial ordering, or no ordering at
   * all. While Firestore will always respect the provided order, the behavior
   * for queries without a full ordering is different per database edition:
   *
   * In Standard edition, Firestore guarantees a stable ordering through the
   * following rules:
   *
   *  * The `order_by` is required to reference all fields used with an
   *    inequality filter.
   *  * All fields that are required to be in the `order_by` but are not already
   *    present are appended in lexicographical ordering of the field name.
   *  * If an order on `__name__` is not specified, it is appended by default.
   *
   * Fields are appended with the same sort direction as the last order
   * specified, or 'ASCENDING' if no order was specified. For example:
   *
   *  * `ORDER BY a` becomes `ORDER BY a ASC, __name__ ASC`
   *  * `ORDER BY a DESC` becomes `ORDER BY a DESC, __name__ DESC`
   *  * `WHERE a > 1` becomes `WHERE a > 1 ORDER BY a ASC, __name__ ASC`
   *  * `WHERE __name__ > ... AND a > 1` becomes
   *     `WHERE __name__ > ... AND a > 1 ORDER BY a ASC, __name__ ASC`
   *
   * In Enterprise edition, Firestore does not guarantee a stable ordering.
   * Instead it will pick the most efficient ordering based on the indexes
   * available at the time of query execution. This will result in a different
   * ordering for queries that are otherwise identical. To ensure a stable
   * ordering, always include a unique field in the `order_by` clause, such as
   * `__name__`.
   */
  orderBy: ProtoList<StructuredQueryOrder> {
    get { return this.#m.repeated(4, WIRE_LEN, (v, p) => new StructuredQueryOrder(v.messageAt(p))); }
  }

  /**
   * A potential prefix of a position in the result set to start the query at.
   *
   * The ordering of the result set is based on the `ORDER BY` clause of the
   * original query.
   *
   * ```
   * SELECT * FROM k WHERE a = 1 AND b > 2 ORDER BY b ASC, __name__ ASC;
   * ```
   *
   * This query's results are ordered by `(b ASC, __name__ ASC)`.
   *
   * Cursors can reference either the full ordering or a prefix of the location,
   * though it cannot reference more fields than what are in the provided
   * `ORDER BY`.
   *
   * Continuing off the example above, attaching the following start cursors
   * will have varying impact:
   *
   * - `START BEFORE (2, /k/123)`: start the query right before `a = 1 AND
   *    b > 2 AND __name__ > /k/123`.
   * - `START AFTER (10)`: start the query right after `a = 1 AND b > 10`.
   *
   * Unlike `OFFSET` which requires scanning over the first N results to skip,
   * a start cursor allows the query to begin at a logical position. This
   * position is not required to match an actual result, it will scan forward
   * from this position to find the next document.
   *
   * Requires:
   *
   * * The number of values cannot be greater than the number of fields
   *   specified in the `ORDER BY` clause.
   */
  startAt: Cursor | null {
    get {
      let m = this.#m.message(7);
      return if (m == null) null else new Cursor(m as ProtoView);
    }
  }

  /**
   * A potential prefix of a position in the result set to end the query at.
   *
   * This is similar to `START_AT` but with it controlling the end position
   * rather than the start position.
   *
   * Requires:
   *
   * * The number of values cannot be greater than the number of fields
   *   specified in the `ORDER BY` clause.
   */
  endAt: Cursor | null {
    get {
      let m = this.#m.message(8);
      return if (m == null) null else new Cursor(m as ProtoView);
    }
  }

  /**
   * The number of documents to skip before returning the first result.
   *
   * This applies after the constraints specified by the `WHERE`, `START AT`, &
   * `END AT` but before the `LIMIT` clause.
   *
   * Requires:
   *
   * * The value must be greater than or equal to zero if specified.
   */
  offset: i32 {
    get { return this.#m.int32(6); }
  }

  /**
   * The maximum number of results to return.
   *
   * Applies after all other constraints.
   *
   * Requires:
   *
   * * The value must be greater than or equal to zero if specified.
   */
  limit: Int32Value | null {
    get {
      let m = this.#m.message(5);
      return if (m == null) null else new Int32Value(m as ProtoView);
    }
  }

  /**
   * Optional. A potential nearest neighbors search.
   *
   * Applies after all other filters and ordering.
   *
   * Finds the closest vector embeddings to the given query vector.
   */
  findNearest: StructuredQueryFindNearest | null {
    get {
      let m = this.#m.message(9);
      return if (m == null) null else new StructuredQueryFindNearest(m as ProtoView);
    }
  }
}

/** The fields of a `google.firestore.v1.StructuredQuery.CollectionSelector` to encode, for `StructuredQueryCollectionSelector.of`. */
export type StructuredQueryCollectionSelectorInit = {
  collectionId?: String,
  allDescendants?: boolean,
};

/**
 * A selection of a collection, such as `messages as m1`.
 *
 * Protobuf: `google.firestore.v1.StructuredQuery.CollectionSelector`.
 */
export final class StructuredQueryCollectionSelector {
  #m: ProtoView;

  /** A message over `m`, which must hold an encoded `google.firestore.v1.StructuredQuery.CollectionSelector`. */
  new(m: ProtoView) : #m = m;

  /** Decodes `bytes`. Fields are decoded as they are read. */
  static decode(bytes: ByteArray): StructuredQueryCollectionSelector {
    return new StructuredQueryCollectionSelector(ProtoView.of(bytes));
  }

  /** Encodes `init` as a `google.firestore.v1.StructuredQuery.CollectionSelector`. */
  static of(init: StructuredQueryCollectionSelectorInit): StructuredQueryCollectionSelector {
    let w = new ProtoWriter();
    if (let {collectionId as f2} = init) {
      w.string(2, f2);
    }
    if (let {allDescendants as f3} = init) {
      w.bool(3, f3);
    }
    return new StructuredQueryCollectionSelector(w.finish());
  }

  /** The encoded message. */
  protoView: ProtoView {
    get { return this.#m; }
  }

  /**
   * The collection ID.
   * When set, selects only collections with this ID.
   */
  collectionId: String {
    get { return this.#m.string(2); }
  }

  /**
   * When false, selects only collections that are immediate children of
   * the `parent` specified in the containing `RunQueryRequest`.
   * When true, selects all descendant collections.
   */
  allDescendants: boolean {
    get { return this.#m.bool(3); }
  }
}

/**
 * The type of filter.
 *
 * The member of `google.firestore.v1.StructuredQuery.Filter.filter_type` that is set, as `StructuredQueryFilter.filterType` reads it.
 */
export sealed class StructuredQueryFilterFilterType {
  case StructuredQueryFilterCompositeFilter(value: StructuredQueryCompositeFilter)
  case StructuredQueryFilterFieldFilter(value: StructuredQueryFieldFilter)
  case StructuredQueryFilterUnaryFilter(value: StructuredQueryUnaryFilter)
  case StructuredQueryFilterFilterTypeNotSet
}

/** The fields of a `google.firestore.v1.StructuredQuery.Filter` to encode, for `StructuredQueryFilter.of`. */
export type StructuredQueryFilterInit = {
  compositeFilter?: StructuredQueryCompositeFilter,
  fieldFilter?: StructuredQueryFieldFilter,
  unaryFilter?: StructuredQueryUnaryFilter,
};

/**
 * A filter.
 *
 * Protobuf: `google.firestore.v1.StructuredQuery.Filter`.
 */
export final class StructuredQueryFilter {
  #m: ProtoView;

  /** A message over `m`, which must hold an encoded `google.firestore.v1.StructuredQuery.Filter`. */
  new(m: ProtoView) : #m = m;

  /** Decodes `bytes`. Fields are decoded as they are read. */
  static decode(bytes: ByteArray): StructuredQueryFilter {
    return new StructuredQueryFilter(ProtoView.of(bytes));
  }

  /** Encodes `init` as a `google.firestore.v1.StructuredQuery.Filter`. */
  static of(init: StructuredQueryFilterInit): StructuredQueryFilter {
    let w = new ProtoWriter();
    if (let {compositeFilter as f1} = init) {
      w.message(1, f1.protoView);
    }
    if (let {fieldFilter as f2} = init) {
      w.message(2, f2.protoView);
    }
    if (let {unaryFilter as f3} = init) {
      w.message(3, f3.protoView);
    }
    return new StructuredQueryFilter(w.finish());
  }

  /** The encoded message. */
  protoView: ProtoView {
    get { return this.#m; }
  }

  /** A composite filter. */
  compositeFilter: StructuredQueryCompositeFilter | null {
    get {
      if (this.#whichFilterType() != 1) {
        return null;
      }
      let m = this.#m.message(1);
      return if (m == null) null else new StructuredQueryCompositeFilter(m as ProtoView);
    }
  }

  /** A filter on a document field. */
  fieldFilter: StructuredQueryFieldFilter | null {
    get {
      if (this.#whichFilterType() != 2) {
        return null;
      }
      let m = this.#m.message(2);
      return if (m == null) null else new StructuredQueryFieldFilter(m as ProtoView);
    }
  }

  /** A filter that takes exactly one argument. */
  unaryFilter: StructuredQueryUnaryFilter | null {
    get {
      if (this.#whichFilterType() != 3) {
        return null;
      }
      let m = this.#m.message(3);
      return if (m == null) null else new StructuredQueryUnaryFilter(m as ProtoView);
    }
  }

  /** The member of `filter_type` that is set. */
  filterType: StructuredQueryFilterFilterType {
    get {
      let which = this.#whichFilterType();
      if (which == 1) {
        return new StructuredQueryFilterCompositeFilter(new StructuredQueryCompositeFilter(this.#m.message(1) as ProtoView));
      }
      if (which == 2) {
        return new StructuredQueryFilterFieldFilter(new StructuredQueryFieldFilter(this.#m.message(2) as ProtoView));
      }
      if (which == 3) {
        return new StructuredQueryFilterUnaryFilter(new StructuredQueryUnaryFilter(this.#m.message(3) as ProtoView));
      }
      return new StructuredQueryFilterFilterTypeNotSet();
    }
  }

  #whichFilterType(): i32 {
    return this.#m.whichOf([1, 2, 3]);
  }
}

/** The fields of a `google.firestore.v1.StructuredQuery.CompositeFilter` to encode, for `StructuredQueryCompositeFilter.of`. */
export type StructuredQueryCompositeFilterInit = {
  op?: StructuredQueryCompositeFilterOperator,
  filters?: Array<StructuredQueryFilter>,
};

/**
 * A filter that merges multiple other filters using the given operator.
 *
 * Protobuf: `google.firestore.v1.StructuredQuery.CompositeFilter`.
 */
export final class StructuredQueryCompositeFilter {
  #m: ProtoView;

  /** A message over `m`, which must hold an encoded `google.firestore.v1.StructuredQuery.CompositeFilter`. */
  new(m: ProtoView) : #m = m;

  /** Decodes `bytes`. Fields are decoded as they are read. */
  static decode(bytes: ByteArray): StructuredQueryCompositeFilter {
    return new StructuredQueryCompositeFilter(ProtoView.of(bytes));
  }

  /** Encodes `init` as a `google.firestore.v1.StructuredQuery.CompositeFilter`. */
  static of(init: StructuredQueryCompositeFilterInit): StructuredQueryCompositeFilter {
    let w = new ProtoWriter();
    if (let {op as f1} = init) {
      w.int32(1, f1 as i32);
    }
    if (let {filters as f2} = init) {
      for (let item in f2) {
        w.message(2, item.protoView);
      }
    }
    return new StructuredQueryCompositeFilter(w.finish());
  }

  /** The encoded message. */
  protoView: ProtoView {
    get { return this.#m; }
  }

  /** The operator for combining multiple filters. */
  op: StructuredQueryCompositeFilterOperator {
    get { return this.#m.int32(1) as StructuredQueryCompositeFilterOperator; }
  }

  /**
   * The list of filters to combine.
   *
   * Requires:
   *
   * * At least one filter is present.
   */
  filters: ProtoList<StructuredQueryFilter> {
    get { return this.#m.repeated(2, WIRE_LEN, (v, p) => new StructuredQueryFilter(v.messageAt(p))); }
  }
}

/** The fields of a `google.firestore.v1.StructuredQuery.FieldFilter` to encode, for `StructuredQueryFieldFilter.of`. */
export type StructuredQueryFieldFilterInit = {
  field?: StructuredQueryFieldReference,
  op?: StructuredQueryFieldFilterOperator,
  value?: Value,
};

/**
 * A filter on a specific field.
 *
 * Protobuf: `google.firestore.v1.StructuredQuery.FieldFilter`.
 */
export final class StructuredQueryFieldFilter {
  #m: ProtoView;

  /** A message over `m`, which must hold an encoded `google.firestore.v1.StructuredQuery.FieldFilter`. */
  new(m: ProtoView) : #m = m;

  /** Decodes `bytes`. Fields are decoded as they are read. */
  static decode(bytes: ByteArray): StructuredQueryFieldFilter {
    return new StructuredQueryFieldFilter(ProtoView.of(bytes));
  }

  /** Encodes `init` as a `google.firestore.v1.StructuredQuery.FieldFilter`. */
  static of(init: StructuredQueryFieldFilterInit): StructuredQueryFieldFilter {
    let w = new ProtoWriter();
    if (let {field as f1} = init) {
      w.message(1, f1.protoView);
    }
    if (let {op as f2} = init) {
      w.int32(2, f2 as i32);
    }
    if (let {value as f3} = init) {
      w.message(3, f3.protoView);
    }
    return new StructuredQueryFieldFilter(w.finish());
  }

  /** The encoded message. */
  protoView: ProtoView {
    get { return this.#m; }
  }

  /** The field to filter by. */
  field: StructuredQueryFieldReference | null {
    get {
      let m = this.#m.message(1);
      return if (m == null) null else new StructuredQueryFieldReference(m as ProtoView);
    }
  }

  /** The operator to filter by. */
  op: StructuredQueryFieldFilterOperator {
    get { return this.#m.int32(2) as StructuredQueryFieldFilterOperator; }
  }

  /** The value to compare to. */
  value: Value | null {
    get {
      let m = this.#m.message(3);
      return if (m == null) null else new Value(m as ProtoView);
    }
  }
}

/**
 * The argument to the filter.
 *
 * The member of `google.firestore.v1.StructuredQuery.UnaryFilter.operand_type` that is set, as `StructuredQueryUnaryFilter.operandType` reads it.
 */
export sealed class StructuredQueryUnaryFilterOperandType {
  case StructuredQueryUnaryFilterField(value: StructuredQueryFieldReference)
  case StructuredQueryUnaryFilterOperandTypeNotSet
}

/** The fields of a `google.firestore.v1.StructuredQuery.UnaryFilter` to encode, for `StructuredQueryUnaryFilter.of`. */
export type StructuredQueryUnaryFilterInit = {
  op?: StructuredQueryUnaryFilterOperator,
  field?: StructuredQueryFieldReference,
};

/**
 * A filter with a single operand.
 *
 * Protobuf: `google.firestore.v1.StructuredQuery.UnaryFilter`.
 */
export final class StructuredQueryUnaryFilter {
  #m: ProtoView;

  /** A message over `m`, which must hold an encoded `google.firestore.v1.StructuredQuery.UnaryFilter`. */
  new(m: ProtoView) : #m = m;

  /** Decodes `bytes`. Fields are decoded as they are read. */
  static decode(bytes: ByteArray): StructuredQueryUnaryFilter {
    return new StructuredQueryUnaryFilter(ProtoView.of(bytes));
  }

  /** Encodes `init` as a `google.firestore.v1.StructuredQuery.UnaryFilter`. */
  static of(init: StructuredQueryUnaryFilterInit): StructuredQueryUnaryFilter {
    let w = new ProtoWriter();
    if (let {op as f1} = init) {
      w.int32(1, f1 as i32);
    }
    if (let {field as f2} = init) {
      w.message(2, f2.protoView);
    }
    return new StructuredQueryUnaryFilter(w.finish());
  }

  /** The encoded message. */
  protoView: ProtoView {
    get { return this.#m; }
  }

  /** The unary operator to apply. */
  op: StructuredQueryUnaryFilterOperator {
    get { return this.#m.int32(1) as StructuredQueryUnaryFilterOperator; }
  }

  /** The field to which to apply the operator. */
  field: StructuredQueryFieldReference | null {
    get {
      if (this.#whichOperandType() != 2) {
        return null;
      }
      let m = this.#m.message(2);
      return if (m == null) null else new StructuredQueryFieldReference(m as ProtoView);
    }
  }

  /** The member of `operand_type` that is set. */
  operandType: StructuredQueryUnaryFilterOperandType {
    get {
      let which = this.#whichOperandType();
      if (which == 2) {
        return new StructuredQueryUnaryFilterField(new StructuredQueryFieldReference(this.#m.message(2) as ProtoView));
      }
      return new StructuredQueryUnaryFilterOperandTypeNotSet();
    }
  }

  #whichOperandType(): i32 {
    return this.#m.whichOf([2]);
  }
}

/** The fields of a `google.firestore.v1.StructuredQuery.Order` to encode, for `StructuredQueryOrder.of`. */
export type StructuredQueryOrderInit = {
  field?: StructuredQueryFieldReference,
  direction?: StructuredQueryDirection,
};

/**
 * An order on a field.
 *
 * Protobuf: `google.firestore.v1.StructuredQuery.Order`.
 */
export final class StructuredQueryOrder {
  #m: ProtoView;

  /** A message over `m`, which must hold an encoded `google.firestore.v1.StructuredQuery.Order`. */
  new(m: ProtoView) : #m = m;

  /** Decodes `bytes`. Fields are decoded as they are read. */
  static decode(bytes: ByteArray): StructuredQueryOrder {
    return new StructuredQueryOrder(ProtoView.of(bytes));
  }

  /** Encodes `init` as a `google.firestore.v1.StructuredQuery.Order`. */
  static of(init: StructuredQueryOrderInit): StructuredQueryOrder {
    let w = new ProtoWriter();
    if (let {field as f1} = init) {
      w.message(1, f1.protoView);
    }
    if (let {direction as f2} = init) {
      w.int32(2, f2 as i32);
    }
    return new StructuredQueryOrder(w.finish());
  }

  /** The encoded message. */
  protoView: ProtoView {
    get { return this.#m; }
  }

  /** The field to order by. */
  field: StructuredQueryFieldReference | null {
    get {
      let m = this.#m.message(1);
      return if (m == null) null else new StructuredQueryFieldReference(m as ProtoView);
    }
  }

  /** The direction to order by. Defaults to `ASCENDING`. */
  direction: StructuredQueryDirection {
    get { return this.#m.int32(2) as StructuredQueryDirection; }
  }
}

/** The fields of a `google.firestore.v1.StructuredQuery.FieldReference` to encode, for `StructuredQueryFieldReference.of`. */
export type StructuredQueryFieldReferenceInit = {
  fieldPath?: String,
};

/**
 * A reference to a field in a document, ex: `stats.operations`.
 *
 * Protobuf: `google.firestore.v1.StructuredQuery.FieldReference`.
 */
export final class StructuredQueryFieldReference {
  #m: ProtoView;

  /** A message over `m`, which must hold an encoded `google.firestore.v1.StructuredQuery.FieldReference`. */
  new(m: ProtoView) : #m = m;

  /** Decodes `bytes`. Fields are decoded as they are read. */
  static decode(bytes: ByteArray): StructuredQueryFieldReference {
    return new StructuredQueryFieldReference(ProtoView.of(bytes));
  }

  /** Encodes `init` as a `google.firestore.v1.StructuredQuery.FieldReference`. */
  static of(init: StructuredQueryFieldReferenceInit): StructuredQueryFieldReference {
    let w = new ProtoWriter();
    if (let {fieldPath as f2} = init) {
      w.string(2, f2);
    }
    return new StructuredQueryFieldReference(w.finish());
  }

  /** The encoded message. */
  protoView: ProtoView {
    get { return this.#m; }
  }

  /**
   * A reference to a field in a document.
   *
   * Requires:
   *
   * * MUST be a dot-delimited (`.`) string of segments, where each segment
   * conforms to [document field name][google.firestore.v1.Document.fields]
   * limitations.
   */
  fieldPath: String {
    get { return this.#m.string(2); }
  }
}

/** The fields of a `google.firestore.v1.StructuredQuery.Projection` to encode, for `StructuredQueryProjection.of`. */
export type StructuredQueryProjectionInit = {
  fields?: Array<StructuredQueryFieldReference>,
};

/**
 * The projection of document's fields to return.
 *
 * Protobuf: `google.firestore.v1.StructuredQuery.Projection`.
 */
export final class StructuredQueryProjection {
  #m: ProtoView;

  /** A message over `m`, which must hold an encoded `google.firestore.v1.StructuredQuery.Projection`. */
  new(m: ProtoView) : #m = m;

  /** Decodes `bytes`. Fields are decoded as they are read. */
  static decode(bytes: ByteArray): StructuredQueryProjection {
    return new StructuredQueryProjection(ProtoView.of(bytes));
  }

  /** Encodes `init` as a `google.firestore.v1.StructuredQuery.Projection`. */
  static of(init: StructuredQueryProjectionInit): StructuredQueryProjection {
    let w = new ProtoWriter();
    if (let {fields as f2} = init) {
      for (let item in f2) {
        w.message(2, item.protoView);
      }
    }
    return new StructuredQueryProjection(w.finish());
  }

  /** The encoded message. */
  protoView: ProtoView {
    get { return this.#m; }
  }

  /**
   * The fields to return.
   *
   * If empty, all fields are returned. To only return the name
   * of the document, use `['__name__']`.
   */
  fields: ProtoList<StructuredQueryFieldReference> {
    get { return this.#m.repeated(2, WIRE_LEN, (v, p) => new StructuredQueryFieldReference(v.messageAt(p))); }
  }
}

/** The fields of a `google.firestore.v1.StructuredQuery.FindNearest` to encode, for `StructuredQueryFindNearest.of`. */
export type StructuredQueryFindNearestInit = {
  vectorField: StructuredQueryFieldReference,
  queryVector: Value,
  distanceMeasure: StructuredQueryFindNearestDistanceMeasure,
  limit: Int32Value,
  distanceResultField?: String,
  distanceThreshold?: DoubleValue,
};

/**
 * Nearest Neighbors search config. The ordering provided by FindNearest
 * supersedes the order_by stage. If multiple documents have the same vector
 * distance, the returned document order is not guaranteed to be stable
 * between queries.
 *
 * Protobuf: `google.firestore.v1.StructuredQuery.FindNearest`.
 */
export final class StructuredQueryFindNearest {
  #m: ProtoView;

  /** A message over `m`, which must hold an encoded `google.firestore.v1.StructuredQuery.FindNearest`. */
  new(m: ProtoView) : #m = m;

  /** Decodes `bytes`. Fields are decoded as they are read. */
  static decode(bytes: ByteArray): StructuredQueryFindNearest {
    return new StructuredQueryFindNearest(ProtoView.of(bytes));
  }

  /** Encodes `init` as a `google.firestore.v1.StructuredQuery.FindNearest`. */
  static of(init: StructuredQueryFindNearestInit): StructuredQueryFindNearest {
    let w = new ProtoWriter();
    let f1 = init.vectorField;
    w.message(1, f1.protoView);
    let f2 = init.queryVector;
    w.message(2, f2.protoView);
    let f3 = init.distanceMeasure;
    w.int32(3, f3 as i32);
    let f4 = init.limit;
    w.message(4, f4.protoView);
    if (let {distanceResultField as f5} = init) {
      w.string(5, f5);
    }
    if (let {distanceThreshold as f6} = init) {
      w.message(6, f6.protoView);
    }
    return new StructuredQueryFindNearest(w.finish());
  }

  /** The encoded message. */
  protoView: ProtoView {
    get { return this.#m; }
  }

  /**
   * Required. An indexed vector field to search upon. Only documents which
   * contain vectors whose dimensionality match the query_vector can be
   * returned.
   */
  vectorField: StructuredQueryFieldReference | null {
    get {
      let m = this.#m.message(1);
      return if (m == null) null else new StructuredQueryFieldReference(m as ProtoView);
    }
  }

  /**
   * Required. The query vector that we are searching on. Must be a vector of
   * no more than 2048 dimensions.
   */
  queryVector: Value | null {
    get {
      let m = this.#m.message(2);
      return if (m == null) null else new Value(m as ProtoView);
    }
  }

  /** Required. The distance measure to use, required. */
  distanceMeasure: StructuredQueryFindNearestDistanceMeasure {
    get { return this.#m.int32(3) as StructuredQueryFindNearestDistanceMeasure; }
  }

  /**
   * Required. The number of nearest neighbors to return. Must be a positive
   * integer of no more than 1000.
   */
  limit: Int32Value | null {
    get {
      let m = this.#m.message(4);
      return if (m == null) null else new Int32Value(m as ProtoView);
    }
  }

  /**
   * Optional. Optional name of the field to output the result of the vector
   * distance calculation. Must conform to [document field
   * name][google.firestore.v1.Document.fields] limitations.
   */
  distanceResultField: String {
    get { return this.#m.string(5); }
  }

  /**
   * Optional. Option to specify a threshold for which no less similar
   * documents will be returned. The behavior of the specified
   * `distance_measure` will affect the meaning of the distance threshold.
   * Since DOT_PRODUCT distances increase when the vectors are more similar,
   * the comparison is inverted.
   *
   * * For EUCLIDEAN, COSINE: `WHERE distance <= distance_threshold`
   * * For DOT_PRODUCT:       `WHERE distance >= distance_threshold`
   */
  distanceThreshold: DoubleValue | null {
    get {
      let m = this.#m.message(6);
      return if (m == null) null else new DoubleValue(m as ProtoView);
    }
  }
}

/**
 * The base query to aggregate over.
 *
 * The member of `google.firestore.v1.StructuredAggregationQuery.query_type` that is set, as `StructuredAggregationQuery.queryType` reads it.
 */
export sealed class StructuredAggregationQueryQueryType {
  case StructuredAggregationQueryStructuredQuery(value: StructuredQuery)
  case StructuredAggregationQueryQueryTypeNotSet
}

/** The fields of a `google.firestore.v1.StructuredAggregationQuery` to encode, for `StructuredAggregationQuery.of`. */
export type StructuredAggregationQueryInit = {
  structuredQuery?: StructuredQuery,
  aggregations?: Array<StructuredAggregationQueryAggregation>,
};

/**
 * Firestore query for running an aggregation over a
 * [StructuredQuery][google.firestore.v1.StructuredQuery].
 *
 * Protobuf: `google.firestore.v1.StructuredAggregationQuery`.
 */
export final class StructuredAggregationQuery {
  #m: ProtoView;

  /** A message over `m`, which must hold an encoded `google.firestore.v1.StructuredAggregationQuery`. */
  new(m: ProtoView) : #m = m;

  /** Decodes `bytes`. Fields are decoded as they are read. */
  static decode(bytes: ByteArray): StructuredAggregationQuery {
    return new StructuredAggregationQuery(ProtoView.of(bytes));
  }

  /** Encodes `init` as a `google.firestore.v1.StructuredAggregationQuery`. */
  static of(init: StructuredAggregationQueryInit): StructuredAggregationQuery {
    let w = new ProtoWriter();
    if (let {structuredQuery as f1} = init) {
      w.message(1, f1.protoView);
    }
    if (let {aggregations as f3} = init) {
      for (let item in f3) {
        w.message(3, item.protoView);
      }
    }
    return new StructuredAggregationQuery(w.finish());
  }

  /** The encoded message. */
  protoView: ProtoView {
    get { return this.#m; }
  }

  /** Nested structured query. */
  structuredQuery: StructuredQuery | null {
    get {
      if (this.#whichQueryType() != 1) {
        return null;
      }
      let m = this.#m.message(1);
      return if (m == null) null else new StructuredQuery(m as ProtoView);
    }
  }

  /**
   * Optional. Series of aggregations to apply over the results of the
   * `structured_query`.
   *
   * Requires:
   *
   * * A minimum of one and maximum of five aggregations per query.
   */
  aggregations: ProtoList<StructuredAggregationQueryAggregation> {
    get { return this.#m.repeated(3, WIRE_LEN, (v, p) => new StructuredAggregationQueryAggregation(v.messageAt(p))); }
  }

  /** The member of `query_type` that is set. */
  queryType: StructuredAggregationQueryQueryType {
    get {
      let which = this.#whichQueryType();
      if (which == 1) {
        return new StructuredAggregationQueryStructuredQuery(new StructuredQuery(this.#m.message(1) as ProtoView));
      }
      return new StructuredAggregationQueryQueryTypeNotSet();
    }
  }

  #whichQueryType(): i32 {
    return this.#m.whichOf([1]);
  }
}

/**
 * The type of aggregation to perform, required.
 *
 * The member of `google.firestore.v1.StructuredAggregationQuery.Aggregation.operator` that is set, as `StructuredAggregationQueryAggregation.operator` reads it.
 */
export sealed class StructuredAggregationQueryAggregationOperator {
  case StructuredAggregationQueryAggregationOperatorCount(value: StructuredAggregationQueryAggregationCount)
  case StructuredAggregationQueryAggregationOperatorSum(value: StructuredAggregationQueryAggregationSum)
  case StructuredAggregationQueryAggregationOperatorAvg(value: StructuredAggregationQueryAggregationAvg)
  case StructuredAggregationQueryAggregationOperatorNotSet
}

/** The fields of a `google.firestore.v1.StructuredAggregationQuery.Aggregation` to encode, for `StructuredAggregationQueryAggregation.of`. */
export type StructuredAggregationQueryAggregationInit = {
  count?: StructuredAggregationQueryAggregationCount,
  sum?: StructuredAggregationQueryAggregationSum,
  avg?: StructuredAggregationQueryAggregationAvg,
  alias?: String,
};

/**
 * Defines an aggregation that produces a single result.
 *
 * Protobuf: `google.firestore.v1.StructuredAggregationQuery.Aggregation`.
 */
export final class StructuredAggregationQueryAggregation {
  #m: ProtoView;

  /** A message over `m`, which must hold an encoded `google.firestore.v1.StructuredAggregationQuery.Aggregation`. */
  new(m: ProtoView) : #m = m;

  /** Decodes `bytes`. Fields are decoded as they are read. */
  static decode(bytes: ByteArray): StructuredAggregationQueryAggregation {
    return new StructuredAggregationQueryAggregation(ProtoView.of(bytes));
  }

  /** Encodes `init` as a `google.firestore.v1.StructuredAggregationQuery.Aggregation`. */
  static of(init: StructuredAggregationQueryAggregationInit): StructuredAggregationQueryAggregation {
    let w = new ProtoWriter();
    if (let {count as f1} = init) {
      w.message(1, f1.protoView);
    }
    if (let {sum as f2} = init) {
      w.message(2, f2.protoView);
    }
    if (let {avg as f3} = init) {
      w.message(3, f3.protoView);
    }
    if (let {alias as f7} = init) {
      w.string(7, f7);
    }
    return new StructuredAggregationQueryAggregation(w.finish());
  }

  /** The encoded message. */
  protoView: ProtoView {
    get { return this.#m; }
  }

  /** Count aggregator. */
  count: StructuredAggregationQueryAggregationCount | null {
    get {
      if (this.#whichOperator() != 1) {
        return null;
      }
      let m = this.#m.message(1);
      return if (m == null) null else new StructuredAggregationQueryAggregationCount(m as ProtoView);
    }
  }

  /** Sum aggregator. */
  sum: StructuredAggregationQueryAggregationSum | null {
    get {
      if (this.#whichOperator() != 2) {
        return null;
      }
      let m = this.#m.message(2);
      return if (m == null) null else new StructuredAggregationQueryAggregationSum(m as ProtoView);
    }
  }

  /** Average aggregator. */
  avg: StructuredAggregationQueryAggregationAvg | null {
    get {
      if (this.#whichOperator() != 3) {
        return null;
      }
      let m = this.#m.message(3);
      return if (m == null) null else new StructuredAggregationQueryAggregationAvg(m as ProtoView);
    }
  }

  /**
   * Optional. Optional name of the field to store the result of the
   * aggregation into.
   *
   * If not provided, Firestore will pick a default name following the format
   * `field_<incremental_id++>`. For example:
   *
   * ```
   * AGGREGATE
   *   COUNT_UP_TO(1) AS count_up_to_1,
   *   COUNT_UP_TO(2),
   *   COUNT_UP_TO(3) AS count_up_to_3,
   *   COUNT(*)
   * OVER (
   *   ...
   * );
   * ```
   *
   * becomes:
   *
   * ```
   * AGGREGATE
   *   COUNT_UP_TO(1) AS count_up_to_1,
   *   COUNT_UP_TO(2) AS field_1,
   *   COUNT_UP_TO(3) AS count_up_to_3,
   *   COUNT(*) AS field_2
   * OVER (
   *   ...
   * );
   * ```
   *
   * Requires:
   *
   * * Must be unique across all aggregation aliases.
   * * Conform to [document field name][google.firestore.v1.Document.fields]
   * limitations.
   */
  alias: String {
    get { return this.#m.string(7); }
  }

  /** The member of `operator` that is set. */
  operator_: StructuredAggregationQueryAggregationOperator {
    get {
      let which = this.#whichOperator();
      if (which == 1) {
        return new StructuredAggregationQueryAggregationOperatorCount(new StructuredAggregationQueryAggregationCount(this.#m.message(1) as ProtoView));
      }
      if (which == 2) {
        return new StructuredAggregationQueryAggregationOperatorSum(new StructuredAggregationQueryAggregationSum(this.#m.message(2) as ProtoView));
      }
      if (which == 3) {
        return new StructuredAggregationQueryAggregationOperatorAvg(new StructuredAggregationQueryAggregationAvg(this.#m.message(3) as ProtoView));
      }
      return new StructuredAggregationQueryAggregationOperatorNotSet();
    }
  }

  #whichOperator(): i32 {
    return this.#m.whichOf([1, 2, 3]);
  }
}

/** The fields of a `google.firestore.v1.StructuredAggregationQuery.Aggregation.Count` to encode, for `StructuredAggregationQueryAggregationCount.of`. */
export type StructuredAggregationQueryAggregationCountInit = {
  upTo?: Int64Value,
};

/**
 * Count of documents that match the query.
 *
 * The `COUNT(*)` aggregation function operates on the entire document
 * so it does not require a field reference.
 *
 * Protobuf: `google.firestore.v1.StructuredAggregationQuery.Aggregation.Count`.
 */
export final class StructuredAggregationQueryAggregationCount {
  #m: ProtoView;

  /** A message over `m`, which must hold an encoded `google.firestore.v1.StructuredAggregationQuery.Aggregation.Count`. */
  new(m: ProtoView) : #m = m;

  /** Decodes `bytes`. Fields are decoded as they are read. */
  static decode(bytes: ByteArray): StructuredAggregationQueryAggregationCount {
    return new StructuredAggregationQueryAggregationCount(ProtoView.of(bytes));
  }

  /** Encodes `init` as a `google.firestore.v1.StructuredAggregationQuery.Aggregation.Count`. */
  static of(init: StructuredAggregationQueryAggregationCountInit): StructuredAggregationQueryAggregationCount {
    let w = new ProtoWriter();
    if (let {upTo as f1} = init) {
      w.message(1, f1.protoView);
    }
    return new StructuredAggregationQueryAggregationCount(w.finish());
  }

  /** The encoded message. */
  protoView: ProtoView {
    get { return this.#m; }
  }

  /**
   * Optional. Optional constraint on the maximum number of documents to
   * count.
   *
   * This provides a way to set an upper bound on the number of documents
   * to scan, limiting latency, and cost.
   *
   * Unspecified is interpreted as no bound.
   *
   * High-Level Example:
   *
   * ```
   * AGGREGATE COUNT_UP_TO(1000) OVER ( SELECT * FROM k );
   * ```
   *
   * Requires:
   *
   * * Must be greater than zero when present.
   */
  upTo: Int64Value | null {
    get {
      let m = this.#m.message(1);
      return if (m == null) null else new Int64Value(m as ProtoView);
    }
  }
}

/** The fields of a `google.firestore.v1.StructuredAggregationQuery.Aggregation.Sum` to encode, for `StructuredAggregationQueryAggregationSum.of`. */
export type StructuredAggregationQueryAggregationSumInit = {
  field?: StructuredQueryFieldReference,
};

/**
 * Sum of the values of the requested field.
 *
 * * Only numeric values will be aggregated. All non-numeric values
 * including `NULL` are skipped.
 *
 * * If the aggregated values contain `NaN`, returns `NaN`. Infinity math
 * follows IEEE-754 standards.
 *
 * * If the aggregated value set is empty, returns 0.
 *
 * * Returns a 64-bit integer if all aggregated numbers are integers and the
 * sum result does not overflow. Otherwise, the result is returned as a
 * double. Note that even if all the aggregated values are integers, the
 * result is returned as a double if it cannot fit within a 64-bit signed
 * integer. When this occurs, the returned value will lose precision.
 *
 * * When underflow occurs, floating-point aggregation is non-deterministic.
 * This means that running the same query repeatedly without any changes to
 * the underlying values could produce slightly different results each
 * time. In those cases, values should be stored as integers over
 * floating-point numbers.
 *
 * Protobuf: `google.firestore.v1.StructuredAggregationQuery.Aggregation.Sum`.
 */
export final class StructuredAggregationQueryAggregationSum {
  #m: ProtoView;

  /** A message over `m`, which must hold an encoded `google.firestore.v1.StructuredAggregationQuery.Aggregation.Sum`. */
  new(m: ProtoView) : #m = m;

  /** Decodes `bytes`. Fields are decoded as they are read. */
  static decode(bytes: ByteArray): StructuredAggregationQueryAggregationSum {
    return new StructuredAggregationQueryAggregationSum(ProtoView.of(bytes));
  }

  /** Encodes `init` as a `google.firestore.v1.StructuredAggregationQuery.Aggregation.Sum`. */
  static of(init: StructuredAggregationQueryAggregationSumInit): StructuredAggregationQueryAggregationSum {
    let w = new ProtoWriter();
    if (let {field as f1} = init) {
      w.message(1, f1.protoView);
    }
    return new StructuredAggregationQueryAggregationSum(w.finish());
  }

  /** The encoded message. */
  protoView: ProtoView {
    get { return this.#m; }
  }

  /** The field to aggregate on. */
  field: StructuredQueryFieldReference | null {
    get {
      let m = this.#m.message(1);
      return if (m == null) null else new StructuredQueryFieldReference(m as ProtoView);
    }
  }
}

/** The fields of a `google.firestore.v1.StructuredAggregationQuery.Aggregation.Avg` to encode, for `StructuredAggregationQueryAggregationAvg.of`. */
export type StructuredAggregationQueryAggregationAvgInit = {
  field?: StructuredQueryFieldReference,
};

/**
 * Average of the values of the requested field.
 *
 * * Only numeric values will be aggregated. All non-numeric values
 * including `NULL` are skipped.
 *
 * * If the aggregated values contain `NaN`, returns `NaN`. Infinity math
 * follows IEEE-754 standards.
 *
 * * If the aggregated value set is empty, returns `NULL`.
 *
 * * Always returns the result as a double.
 *
 * Protobuf: `google.firestore.v1.StructuredAggregationQuery.Aggregation.Avg`.
 */
export final class StructuredAggregationQueryAggregationAvg {
  #m: ProtoView;

  /** A message over `m`, which must hold an encoded `google.firestore.v1.StructuredAggregationQuery.Aggregation.Avg`. */
  new(m: ProtoView) : #m = m;

  /** Decodes `bytes`. Fields are decoded as they are read. */
  static decode(bytes: ByteArray): StructuredAggregationQueryAggregationAvg {
    return new StructuredAggregationQueryAggregationAvg(ProtoView.of(bytes));
  }

  /** Encodes `init` as a `google.firestore.v1.StructuredAggregationQuery.Aggregation.Avg`. */
  static of(init: StructuredAggregationQueryAggregationAvgInit): StructuredAggregationQueryAggregationAvg {
    let w = new ProtoWriter();
    if (let {field as f1} = init) {
      w.message(1, f1.protoView);
    }
    return new StructuredAggregationQueryAggregationAvg(w.finish());
  }

  /** The encoded message. */
  protoView: ProtoView {
    get { return this.#m; }
  }

  /** The field to aggregate on. */
  field: StructuredQueryFieldReference | null {
    get {
      let m = this.#m.message(1);
      return if (m == null) null else new StructuredQueryFieldReference(m as ProtoView);
    }
  }
}

/** The fields of a `google.firestore.v1.Cursor` to encode, for `Cursor.of`. */
export type CursorInit = {
  values?: Array<Value>,
  before?: boolean,
};

/**
 * A position in a query result set.
 *
 * Protobuf: `google.firestore.v1.Cursor`.
 */
export final class Cursor {
  #m: ProtoView;

  /** A message over `m`, which must hold an encoded `google.firestore.v1.Cursor`. */
  new(m: ProtoView) : #m = m;

  /** Decodes `bytes`. Fields are decoded as they are read. */
  static decode(bytes: ByteArray): Cursor {
    return new Cursor(ProtoView.of(bytes));
  }

  /** Encodes `init` as a `google.firestore.v1.Cursor`. */
  static of(init: CursorInit): Cursor {
    let w = new ProtoWriter();
    if (let {values as f1} = init) {
      for (let item in f1) {
        w.message(1, item.protoView);
      }
    }
    if (let {before as f2} = init) {
      w.bool(2, f2);
    }
    return new Cursor(w.finish());
  }

  /** The encoded message. */
  protoView: ProtoView {
    get { return this.#m; }
  }

  /**
   * The values that represent a position, in the order they appear in
   * the order by clause of a query.
   *
   * Can contain fewer values than specified in the order by clause.
   */
  values: ProtoList<Value> {
    get { return this.#m.repeated(1, WIRE_LEN, (v, p) => new Value(v.messageAt(p))); }
  }

  /**
   * If the position is just before or just after the given values, relative
   * to the sort order defined by the query.
   */
  before: boolean {
    get { return this.#m.bool(2); }
  }
}

/** The fields of a `google.firestore.v1.ExplainOptions` to encode, for `ExplainOptions.of`. */
export type ExplainOptionsInit = {
  analyze?: boolean,
};

/**
 * Explain options for the query.
 *
 * Protobuf: `google.firestore.v1.ExplainOptions`.
 */
export final class ExplainOptions {
  #m: ProtoView;

  /** A message over `m`, which must hold an encoded `google.firestore.v1.ExplainOptions`. */
  new(m: ProtoView) : #m = m;

  /** Decodes `bytes`. Fields are decoded as they are read. */
  static decode(bytes: ByteArray): ExplainOptions {
    return new ExplainOptions(ProtoView.of(bytes));
  }

  /** Encodes `init` as a `google.firestore.v1.ExplainOptions`. */
  static of(init: ExplainOptionsInit): ExplainOptions {
    let w = new ProtoWriter();
    if (let {analyze as f1} = init) {
      w.bool(1, f1);
    }
    return new ExplainOptions(w.finish());
  }

  /** The encoded message. */
  protoView: ProtoView {
    get { return this.#m; }
  }

  /**
   * Optional. Whether to execute this query.
   *
   * When false (the default), the query will be planned, returning only
   * metrics from the planning stages.
   *
   * When true, the query will be planned and executed, returning the full
   * query results along with both planning and execution stage metrics.
   */
  analyze: boolean {
    get { return this.#m.bool(1); }
  }
}

/** The fields of a `google.firestore.v1.ExplainMetrics` to encode, for `ExplainMetrics.of`. */
export type ExplainMetricsInit = {
  planSummary?: PlanSummary,
  executionStats?: ExecutionStats,
};

/**
 * Explain metrics for the query.
 *
 * Protobuf: `google.firestore.v1.ExplainMetrics`.
 */
export final class ExplainMetrics {
  #m: ProtoView;

  /** A message over `m`, which must hold an encoded `google.firestore.v1.ExplainMetrics`. */
  new(m: ProtoView) : #m = m;

  /** Decodes `bytes`. Fields are decoded as they are read. */
  static decode(bytes: ByteArray): ExplainMetrics {
    return new ExplainMetrics(ProtoView.of(bytes));
  }

  /** Encodes `init` as a `google.firestore.v1.ExplainMetrics`. */
  static of(init: ExplainMetricsInit): ExplainMetrics {
    let w = new ProtoWriter();
    if (let {planSummary as f1} = init) {
      w.message(1, f1.protoView);
    }
    if (let {executionStats as f2} = init) {
      w.message(2, f2.protoView);
    }
    return new ExplainMetrics(w.finish());
  }

  /** The encoded message. */
  protoView: ProtoView {
    get { return this.#m; }
  }

  /** Planning phase information for the query. */
  planSummary: PlanSummary | null {
    get {
      let m = this.#m.message(1);
      return if (m == null) null else new PlanSummary(m as ProtoView);
    }
  }

  /**
   * Aggregated stats from the execution of the query. Only present when
   * [ExplainOptions.analyze][google.firestore.v1.ExplainOptions.analyze] is set
   * to true.
   */
  executionStats: ExecutionStats | null {
    get {
      let m = this.#m.message(2);
      return if (m == null) null else new ExecutionStats(m as ProtoView);
    }
  }
}

/** The fields of a `google.firestore.v1.PlanSummary` to encode, for `PlanSummary.of`. */
export type PlanSummaryInit = {
  indexesUsed?: Array<Struct>,
};

/**
 * Planning phase information for the query.
 *
 * Protobuf: `google.firestore.v1.PlanSummary`.
 */
export final class PlanSummary {
  #m: ProtoView;

  /** A message over `m`, which must hold an encoded `google.firestore.v1.PlanSummary`. */
  new(m: ProtoView) : #m = m;

  /** Decodes `bytes`. Fields are decoded as they are read. */
  static decode(bytes: ByteArray): PlanSummary {
    return new PlanSummary(ProtoView.of(bytes));
  }

  /** Encodes `init` as a `google.firestore.v1.PlanSummary`. */
  static of(init: PlanSummaryInit): PlanSummary {
    let w = new ProtoWriter();
    if (let {indexesUsed as f1} = init) {
      for (let item in f1) {
        w.message(1, item.protoView);
      }
    }
    return new PlanSummary(w.finish());
  }

  /** The encoded message. */
  protoView: ProtoView {
    get { return this.#m; }
  }

  /**
   * The indexes selected for the query. For example:
   *  [
   *    {"query_scope": "Collection", "properties": "(foo ASC, __name__ ASC)"},
   *    {"query_scope": "Collection", "properties": "(bar ASC, __name__ ASC)"}
   *  ]
   */
  indexesUsed: ProtoList<Struct> {
    get { return this.#m.repeated(1, WIRE_LEN, (v, p) => new Struct(v.messageAt(p))); }
  }
}

/** The fields of a `google.firestore.v1.ExecutionStats` to encode, for `ExecutionStats.of`. */
export type ExecutionStatsInit = {
  resultsReturned?: i64,
  executionDuration?: Duration,
  readOperations?: i64,
  debugStats?: Struct,
};

/**
 * Execution statistics for the query.
 *
 * Protobuf: `google.firestore.v1.ExecutionStats`.
 */
export final class ExecutionStats {
  #m: ProtoView;

  /** A message over `m`, which must hold an encoded `google.firestore.v1.ExecutionStats`. */
  new(m: ProtoView) : #m = m;

  /** Decodes `bytes`. Fields are decoded as they are read. */
  static decode(bytes: ByteArray): ExecutionStats {
    return new ExecutionStats(ProtoView.of(bytes));
  }

  /** Encodes `init` as a `google.firestore.v1.ExecutionStats`. */
  static of(init: ExecutionStatsInit): ExecutionStats {
    let w = new ProtoWriter();
    if (let {resultsReturned as f1} = init) {
      w.int64(1, f1);
    }
    if (let {executionDuration as f3} = init) {
      w.message(3, f3.protoView);
    }
    if (let {readOperations as f4} = init) {
      w.int64(4, f4);
    }
    if (let {debugStats as f5} = init) {
      w.message(5, f5.protoView);
    }
    return new ExecutionStats(w.finish());
  }

  /** The encoded message. */
  protoView: ProtoView {
    get { return this.#m; }
  }

  /**
   * Total number of results returned, including documents, projections,
   * aggregation results, keys.
   */
  resultsReturned: i64 {
    get { return this.#m.int64(1); }
  }

  /** Total time to execute the query in the backend. */
  executionDuration: Duration | null {
    get {
      let m = this.#m.message(3);
      return if (m == null) null else new Duration(m as ProtoView);
    }
  }

  /** Total billable read operations. */
  readOperations: i64 {
    get { return this.#m.int64(4); }
  }

  /**
   * Debugging statistics from the execution of the query. Note that the
   * debugging stats are subject to change as Firestore evolves. It could
   * include:
   *  {
   *    "indexes_entries_scanned": "1000",
   *    "documents_scanned": "20",
   *    "billing_details" : {
   *       "documents_billable": "20",
   *       "index_entries_billable": "1000",
   *       "min_query_cost": "0"
   *    }
   *  }
   */
  debugStats: Struct | null {
    get {
      let m = this.#m.message(5);
      return if (m == null) null else new Struct(m as ProtoView);
    }
  }
}

/**
 * The operation to execute.
 *
 * The member of `google.firestore.v1.Write.operation` that is set, as `Write.operation` reads it.
 */
export sealed class WriteOperation {
  case WriteUpdate(value: Document)
  case WriteDelete(value: String)
  case WriteTransform(value: DocumentTransform)
  case WriteOperationNotSet
}

/** The fields of a `google.firestore.v1.Write` to encode, for `Write.of`. */
export type WriteInit = {
  update?: Document,
  delete?: String,
  transform?: DocumentTransform,
  updateMask?: DocumentMask,
  updateTransforms?: Array<DocumentTransformFieldTransform>,
  currentDocument?: Precondition,
};

/**
 * A write on a document.
 *
 * Protobuf: `google.firestore.v1.Write`.
 */
export final class Write {
  #m: ProtoView;

  /** A message over `m`, which must hold an encoded `google.firestore.v1.Write`. */
  new(m: ProtoView) : #m = m;

  /** Decodes `bytes`. Fields are decoded as they are read. */
  static decode(bytes: ByteArray): Write {
    return new Write(ProtoView.of(bytes));
  }

  /** Encodes `init` as a `google.firestore.v1.Write`. */
  static of(init: WriteInit): Write {
    let w = new ProtoWriter();
    if (let {update as f1} = init) {
      w.message(1, f1.protoView);
    }
    if (let {delete as f2} = init) {
      w.string(2, f2);
    }
    if (let {transform as f6} = init) {
      w.message(6, f6.protoView);
    }
    if (let {updateMask as f3} = init) {
      w.message(3, f3.protoView);
    }
    if (let {updateTransforms as f7} = init) {
      for (let item in f7) {
        w.message(7, item.protoView);
      }
    }
    if (let {currentDocument as f4} = init) {
      w.message(4, f4.protoView);
    }
    return new Write(w.finish());
  }

  /** The encoded message. */
  protoView: ProtoView {
    get { return this.#m; }
  }

  /** A document to write. */
  update: Document | null {
    get {
      if (this.#whichOperation() != 1) {
        return null;
      }
      let m = this.#m.message(1);
      return if (m == null) null else new Document(m as ProtoView);
    }
  }

  /**
   * A document name to delete. In the format:
   * `projects/{project_id}/databases/{database_id}/documents/{document_path}`.
   */
  delete: String {
    get {
      if (this.#whichOperation() != 2) {
        return '';
      }
      return this.#m.string(2);
    }
  }

  /** Whether `delete` is set. */
  hasDelete: boolean {
    get { return this.#whichOperation() == 2; }
  }

  /** Applies a transformation to a document. */
  transform: DocumentTransform | null {
    get {
      if (this.#whichOperation() != 6) {
        return null;
      }
      let m = this.#m.message(6);
      return if (m == null) null else new DocumentTransform(m as ProtoView);
    }
  }

  /**
   * The fields to update in this write.
   *
   * This field can be set only when the operation is `update`.
   * If the mask is not set for an `update` and the document exists, any
   * existing data will be overwritten.
   * If the mask is set and the document on the server has fields not covered by
   * the mask, they are left unchanged.
   * Fields referenced in the mask, but not present in the input document, are
   * deleted from the document on the server.
   * The field paths in this mask must not contain a reserved field name.
   */
  updateMask: DocumentMask | null {
    get {
      let m = this.#m.message(3);
      return if (m == null) null else new DocumentMask(m as ProtoView);
    }
  }

  /**
   * The transforms to perform after update.
   *
   * This field can be set only when the operation is `update`. If present, this
   * write is equivalent to performing `update` and `transform` to the same
   * document atomically and in order.
   */
  updateTransforms: ProtoList<DocumentTransformFieldTransform> {
    get { return this.#m.repeated(7, WIRE_LEN, (v, p) => new DocumentTransformFieldTransform(v.messageAt(p))); }
  }

  /**
   * An optional precondition on the document.
   *
   * The write will fail if this is set and not met by the target document.
   */
  currentDocument: Precondition | null {
    get {
      let m = this.#m.message(4);
      return if (m == null) null else new Precondition(m as ProtoView);
    }
  }

  /** The member of `operation` that is set. */
  operation: WriteOperation {
    get {
      let which = this.#whichOperation();
      if (which == 1) {
        return new WriteUpdate(new Document(this.#m.message(1) as ProtoView));
      }
      if (which == 2) {
        return new WriteDelete(this.#m.string(2));
      }
      if (which == 6) {
        return new WriteTransform(new DocumentTransform(this.#m.message(6) as ProtoView));
      }
      return new WriteOperationNotSet();
    }
  }

  #whichOperation(): i32 {
    return this.#m.whichOf([1, 2, 6]);
  }
}

/** The fields of a `google.firestore.v1.DocumentTransform` to encode, for `DocumentTransform.of`. */
export type DocumentTransformInit = {
  document?: String,
  fieldTransforms?: Array<DocumentTransformFieldTransform>,
};

/**
 * A transformation of a document.
 *
 * Protobuf: `google.firestore.v1.DocumentTransform`.
 */
export final class DocumentTransform {
  #m: ProtoView;

  /** A message over `m`, which must hold an encoded `google.firestore.v1.DocumentTransform`. */
  new(m: ProtoView) : #m = m;

  /** Decodes `bytes`. Fields are decoded as they are read. */
  static decode(bytes: ByteArray): DocumentTransform {
    return new DocumentTransform(ProtoView.of(bytes));
  }

  /** Encodes `init` as a `google.firestore.v1.DocumentTransform`. */
  static of(init: DocumentTransformInit): DocumentTransform {
    let w = new ProtoWriter();
    if (let {document as f1} = init) {
      w.string(1, f1);
    }
    if (let {fieldTransforms as f2} = init) {
      for (let item in f2) {
        w.message(2, item.protoView);
      }
    }
    return new DocumentTransform(w.finish());
  }

  /** The encoded message. */
  protoView: ProtoView {
    get { return this.#m; }
  }

  /** The name of the document to transform. */
  document: String {
    get { return this.#m.string(1); }
  }

  /**
   * The list of transformations to apply to the fields of the document, in
   * order.
   * This must not be empty.
   */
  fieldTransforms: ProtoList<DocumentTransformFieldTransform> {
    get { return this.#m.repeated(2, WIRE_LEN, (v, p) => new DocumentTransformFieldTransform(v.messageAt(p))); }
  }
}

/**
 * The transformation to apply on the field.
 *
 * The member of `google.firestore.v1.DocumentTransform.FieldTransform.transform_type` that is set, as `DocumentTransformFieldTransform.transformType` reads it.
 */
export sealed class DocumentTransformFieldTransformTransformType {
  case DocumentTransformFieldTransformSetToServerValue(value: DocumentTransformFieldTransformServerValue)
  case DocumentTransformFieldTransformIncrement(value: Value)
  case DocumentTransformFieldTransformMaximum(value: Value)
  case DocumentTransformFieldTransformMinimum(value: Value)
  case DocumentTransformFieldTransformAppendMissingElements(value: ArrayValue)
  case DocumentTransformFieldTransformRemoveAllFromArray(value: ArrayValue)
  case DocumentTransformFieldTransformTransformTypeNotSet
}

/** The fields of a `google.firestore.v1.DocumentTransform.FieldTransform` to encode, for `DocumentTransformFieldTransform.of`. */
export type DocumentTransformFieldTransformInit = {
  fieldPath?: String,
  setToServerValue?: DocumentTransformFieldTransformServerValue,
  increment?: Value,
  maximum?: Value,
  minimum?: Value,
  appendMissingElements?: ArrayValue,
  removeAllFromArray?: ArrayValue,
};

/**
 * A transformation of a field of the document.
 *
 * Protobuf: `google.firestore.v1.DocumentTransform.FieldTransform`.
 */
export final class DocumentTransformFieldTransform {
  #m: ProtoView;

  /** A message over `m`, which must hold an encoded `google.firestore.v1.DocumentTransform.FieldTransform`. */
  new(m: ProtoView) : #m = m;

  /** Decodes `bytes`. Fields are decoded as they are read. */
  static decode(bytes: ByteArray): DocumentTransformFieldTransform {
    return new DocumentTransformFieldTransform(ProtoView.of(bytes));
  }

  /** Encodes `init` as a `google.firestore.v1.DocumentTransform.FieldTransform`. */
  static of(init: DocumentTransformFieldTransformInit): DocumentTransformFieldTransform {
    let w = new ProtoWriter();
    if (let {fieldPath as f1} = init) {
      w.string(1, f1);
    }
    if (let {setToServerValue as f2} = init) {
      w.int32(2, f2 as i32);
    }
    if (let {increment as f3} = init) {
      w.message(3, f3.protoView);
    }
    if (let {maximum as f4} = init) {
      w.message(4, f4.protoView);
    }
    if (let {minimum as f5} = init) {
      w.message(5, f5.protoView);
    }
    if (let {appendMissingElements as f6} = init) {
      w.message(6, f6.protoView);
    }
    if (let {removeAllFromArray as f7} = init) {
      w.message(7, f7.protoView);
    }
    return new DocumentTransformFieldTransform(w.finish());
  }

  /** The encoded message. */
  protoView: ProtoView {
    get { return this.#m; }
  }

  /**
   * The path of the field. See
   * [Document.fields][google.firestore.v1.Document.fields] for the field path
   * syntax reference.
   */
  fieldPath: String {
    get { return this.#m.string(1); }
  }

  /** Sets the field to the given server value. */
  setToServerValue: DocumentTransformFieldTransformServerValue {
    get {
      if (this.#whichTransformType() != 2) {
        return 0 as DocumentTransformFieldTransformServerValue;
      }
      return this.#m.int32(2) as DocumentTransformFieldTransformServerValue;
    }
  }

  /** Whether `setToServerValue` is set. */
  hasSetToServerValue: boolean {
    get { return this.#whichTransformType() == 2; }
  }

  /**
   * Adds the given value to the field's current value.
   *
   * This must be an integer or a double value.
   * If the field is not an integer or double, or if the field does not yet
   * exist, the transformation will set the field to the given value.
   * If either of the given value or the current field value are doubles,
   * both values will be interpreted as doubles. Double arithmetic and
   * representation of double values follow IEEE 754 semantics.
   * If there is positive/negative integer overflow, the field is resolved
   * to the largest magnitude positive/negative integer.
   */
  increment: Value | null {
    get {
      if (this.#whichTransformType() != 3) {
        return null;
      }
      let m = this.#m.message(3);
      return if (m == null) null else new Value(m as ProtoView);
    }
  }

  /**
   * Sets the field to the maximum of its current value and the given value.
   *
   * This must be an integer or a double value.
   * If the field is not an integer or double, or if the field does not yet
   * exist, the transformation will set the field to the given value.
   * If a maximum operation is applied where the field and the input value
   * are of mixed types (that is - one is an integer and one is a double)
   * the field takes on the type of the larger operand. If the operands are
   * equivalent (e.g. 3 and 3.0), the field does not change.
   * 0, 0.0, and -0.0 are all zero. The maximum of a zero stored value and
   * zero input value is always the stored value.
   * The maximum of any numeric value x and NaN is NaN.
   */
  maximum: Value | null {
    get {
      if (this.#whichTransformType() != 4) {
        return null;
      }
      let m = this.#m.message(4);
      return if (m == null) null else new Value(m as ProtoView);
    }
  }

  /**
   * Sets the field to the minimum of its current value and the given value.
   *
   * This must be an integer or a double value.
   * If the field is not an integer or double, or if the field does not yet
   * exist, the transformation will set the field to the input value.
   * If a minimum operation is applied where the field and the input value
   * are of mixed types (that is - one is an integer and one is a double)
   * the field takes on the type of the smaller operand. If the operands are
   * equivalent (e.g. 3 and 3.0), the field does not change.
   * 0, 0.0, and -0.0 are all zero. The minimum of a zero stored value and
   * zero input value is always the stored value.
   * The minimum of any numeric value x and NaN is NaN.
   */
  minimum: Value | null {
    get {
      if (this.#whichTransformType() != 5) {
        return null;
      }
      let m = this.#m.message(5);
      return if (m == null) null else new Value(m as ProtoView);
    }
  }

  /**
   * Append the given elements in order if they are not already present in
   * the current field value.
   * If the field is not an array, or if the field does not yet exist, it is
   * first set to the empty array.
   *
   * Equivalent numbers of different types (e.g. 3L and 3.0) are
   * considered equal when checking if a value is missing.
   * NaN is equal to NaN, and Null is equal to Null.
   * If the input contains multiple equivalent values, only the first will
   * be considered.
   *
   * The corresponding transform_result will be the null value.
   */
  appendMissingElements: ArrayValue | null {
    get {
      if (this.#whichTransformType() != 6) {
        return null;
      }
      let m = this.#m.message(6);
      return if (m == null) null else new ArrayValue(m as ProtoView);
    }
  }

  /**
   * Remove all of the given elements from the array in the field.
   * If the field is not an array, or if the field does not yet exist, it is
   * set to the empty array.
   *
   * Equivalent numbers of the different types (e.g. 3L and 3.0) are
   * considered equal when deciding whether an element should be removed.
   * NaN is equal to NaN, and Null is equal to Null.
   * This will remove all equivalent values if there are duplicates.
   *
   * The corresponding transform_result will be the null value.
   */
  removeAllFromArray: ArrayValue | null {
    get {
      if (this.#whichTransformType() != 7) {
        return null;
      }
      let m = this.#m.message(7);
      return if (m == null) null else new ArrayValue(m as ProtoView);
    }
  }

  /** The member of `transform_type` that is set. */
  transformType: DocumentTransformFieldTransformTransformType {
    get {
      let which = this.#whichTransformType();
      if (which == 2) {
        return new DocumentTransformFieldTransformSetToServerValue(this.#m.int32(2) as DocumentTransformFieldTransformServerValue);
      }
      if (which == 3) {
        return new DocumentTransformFieldTransformIncrement(new Value(this.#m.message(3) as ProtoView));
      }
      if (which == 4) {
        return new DocumentTransformFieldTransformMaximum(new Value(this.#m.message(4) as ProtoView));
      }
      if (which == 5) {
        return new DocumentTransformFieldTransformMinimum(new Value(this.#m.message(5) as ProtoView));
      }
      if (which == 6) {
        return new DocumentTransformFieldTransformAppendMissingElements(new ArrayValue(this.#m.message(6) as ProtoView));
      }
      if (which == 7) {
        return new DocumentTransformFieldTransformRemoveAllFromArray(new ArrayValue(this.#m.message(7) as ProtoView));
      }
      return new DocumentTransformFieldTransformTransformTypeNotSet();
    }
  }

  #whichTransformType(): i32 {
    return this.#m.whichOf([2, 3, 4, 5, 6, 7]);
  }
}

/** The fields of a `google.firestore.v1.WriteResult` to encode, for `WriteResult.of`. */
export type WriteResultInit = {
  updateTime?: Timestamp,
  transformResults?: Array<Value>,
};

/**
 * The result of applying a write.
 *
 * Protobuf: `google.firestore.v1.WriteResult`.
 */
export final class WriteResult {
  #m: ProtoView;

  /** A message over `m`, which must hold an encoded `google.firestore.v1.WriteResult`. */
  new(m: ProtoView) : #m = m;

  /** Decodes `bytes`. Fields are decoded as they are read. */
  static decode(bytes: ByteArray): WriteResult {
    return new WriteResult(ProtoView.of(bytes));
  }

  /** Encodes `init` as a `google.firestore.v1.WriteResult`. */
  static of(init: WriteResultInit): WriteResult {
    let w = new ProtoWriter();
    if (let {updateTime as f1} = init) {
      w.message(1, f1.protoView);
    }
    if (let {transformResults as f2} = init) {
      for (let item in f2) {
        w.message(2, item.protoView);
      }
    }
    return new WriteResult(w.finish());
  }

  /** The encoded message. */
  protoView: ProtoView {
    get { return this.#m; }
  }

  /**
   * The last update time of the document after applying the write. Not set
   * after a `delete`.
   *
   * If the write did not actually change the document, this will be the
   * previous update_time.
   */
  updateTime: Timestamp | null {
    get {
      let m = this.#m.message(1);
      return if (m == null) null else new Timestamp(m as ProtoView);
    }
  }

  /**
   * The results of applying each
   * [DocumentTransform.FieldTransform][google.firestore.v1.DocumentTransform.FieldTransform],
   * in the same order.
   */
  transformResults: ProtoList<Value> {
    get { return this.#m.repeated(2, WIRE_LEN, (v, p) => new Value(v.messageAt(p))); }
  }
}

/** The fields of a `google.firestore.v1.DocumentChange` to encode, for `DocumentChange.of`. */
export type DocumentChangeInit = {
  document?: Document,
  targetIds?: Array<i32>,
  removedTargetIds?: Array<i32>,
};

/**
 * A [Document][google.firestore.v1.Document] has changed.
 *
 * May be the result of multiple [writes][google.firestore.v1.Write], including
 * deletes, that ultimately resulted in a new value for the
 * [Document][google.firestore.v1.Document].
 *
 * Multiple [DocumentChange][google.firestore.v1.DocumentChange] messages may be
 * returned for the same logical change, if multiple targets are affected.
 *
 * Protobuf: `google.firestore.v1.DocumentChange`.
 */
export final class DocumentChange {
  #m: ProtoView;

  /** A message over `m`, which must hold an encoded `google.firestore.v1.DocumentChange`. */
  new(m: ProtoView) : #m = m;

  /** Decodes `bytes`. Fields are decoded as they are read. */
  static decode(bytes: ByteArray): DocumentChange {
    return new DocumentChange(ProtoView.of(bytes));
  }

  /** Encodes `init` as a `google.firestore.v1.DocumentChange`. */
  static of(init: DocumentChangeInit): DocumentChange {
    let w = new ProtoWriter();
    if (let {document as f1} = init) {
      w.message(1, f1.protoView);
    }
    if (let {targetIds as f5} = init) {
      w.packed(5, f5, (pw, pv) => pw.rawInt32(pv));
    }
    if (let {removedTargetIds as f6} = init) {
      w.packed(6, f6, (pw, pv) => pw.rawInt32(pv));
    }
    return new DocumentChange(w.finish());
  }

  /** The encoded message. */
  protoView: ProtoView {
    get { return this.#m; }
  }

  /**
   * The new state of the [Document][google.firestore.v1.Document].
   *
   * If `mask` is set, contains only fields that were updated or added.
   */
  document: Document | null {
    get {
      let m = this.#m.message(1);
      return if (m == null) null else new Document(m as ProtoView);
    }
  }

  /** A set of target IDs of targets that match this document. */
  targetIds: ProtoList<i32> {
    get { return this.#m.repeated(5, WIRE_VARINT, (v, p) => v.int32At(p)); }
  }

  /** A set of target IDs for targets that no longer match this document. */
  removedTargetIds: ProtoList<i32> {
    get { return this.#m.repeated(6, WIRE_VARINT, (v, p) => v.int32At(p)); }
  }
}

/** The fields of a `google.firestore.v1.DocumentDelete` to encode, for `DocumentDelete.of`. */
export type DocumentDeleteInit = {
  document?: String,
  removedTargetIds?: Array<i32>,
  readTime?: Timestamp,
};

/**
 * A [Document][google.firestore.v1.Document] has been deleted.
 *
 * May be the result of multiple [writes][google.firestore.v1.Write], including
 * updates, the last of which deleted the
 * [Document][google.firestore.v1.Document].
 *
 * Multiple [DocumentDelete][google.firestore.v1.DocumentDelete] messages may be
 * returned for the same logical delete, if multiple targets are affected.
 *
 * Protobuf: `google.firestore.v1.DocumentDelete`.
 */
export final class DocumentDelete {
  #m: ProtoView;

  /** A message over `m`, which must hold an encoded `google.firestore.v1.DocumentDelete`. */
  new(m: ProtoView) : #m = m;

  /** Decodes `bytes`. Fields are decoded as they are read. */
  static decode(bytes: ByteArray): DocumentDelete {
    return new DocumentDelete(ProtoView.of(bytes));
  }

  /** Encodes `init` as a `google.firestore.v1.DocumentDelete`. */
  static of(init: DocumentDeleteInit): DocumentDelete {
    let w = new ProtoWriter();
    if (let {document as f1} = init) {
      w.string(1, f1);
    }
    if (let {removedTargetIds as f6} = init) {
      w.packed(6, f6, (pw, pv) => pw.rawInt32(pv));
    }
    if (let {readTime as f4} = init) {
      w.message(4, f4.protoView);
    }
    return new DocumentDelete(w.finish());
  }

  /** The encoded message. */
  protoView: ProtoView {
    get { return this.#m; }
  }

  /**
   * The resource name of the [Document][google.firestore.v1.Document] that was
   * deleted.
   */
  document: String {
    get { return this.#m.string(1); }
  }

  /** A set of target IDs for targets that previously matched this entity. */
  removedTargetIds: ProtoList<i32> {
    get { return this.#m.repeated(6, WIRE_VARINT, (v, p) => v.int32At(p)); }
  }

  /**
   * The read timestamp at which the delete was observed.
   *
   * Greater or equal to the `commit_time` of the delete.
   */
  readTime: Timestamp | null {
    get {
      let m = this.#m.message(4);
      return if (m == null) null else new Timestamp(m as ProtoView);
    }
  }
}

/** The fields of a `google.firestore.v1.DocumentRemove` to encode, for `DocumentRemove.of`. */
export type DocumentRemoveInit = {
  document?: String,
  removedTargetIds?: Array<i32>,
  readTime?: Timestamp,
};

/**
 * A [Document][google.firestore.v1.Document] has been removed from the view of
 * the targets.
 *
 * Sent if the document is no longer relevant to a target and is out of view.
 * Can be sent instead of a DocumentDelete or a DocumentChange if the server
 * can not send the new value of the document.
 *
 * Multiple [DocumentRemove][google.firestore.v1.DocumentRemove] messages may be
 * returned for the same logical write or delete, if multiple targets are
 * affected.
 *
 * Protobuf: `google.firestore.v1.DocumentRemove`.
 */
export final class DocumentRemove {
  #m: ProtoView;

  /** A message over `m`, which must hold an encoded `google.firestore.v1.DocumentRemove`. */
  new(m: ProtoView) : #m = m;

  /** Decodes `bytes`. Fields are decoded as they are read. */
  static decode(bytes: ByteArray): DocumentRemove {
    return new DocumentRemove(ProtoView.of(bytes));
  }

  /** Encodes `init` as a `google.firestore.v1.DocumentRemove`. */
  static of(init: DocumentRemoveInit): DocumentRemove {
    let w = new ProtoWriter();
    if (let {document as f1} = init) {
      w.string(1, f1);
    }
    if (let {removedTargetIds as f2} = init) {
      w.packed(2, f2, (pw, pv) => pw.rawInt32(pv));
    }
    if (let {readTime as f4} = init) {
      w.message(4, f4.protoView);
    }
    return new DocumentRemove(w.finish());
  }

  /** The encoded message. */
  protoView: ProtoView {
    get { return this.#m; }
  }

  /**
   * The resource name of the [Document][google.firestore.v1.Document] that has
   * gone out of view.
   */
  document: String {
    get { return this.#m.string(1); }
  }

  /** A set of target IDs for targets that previously matched this document. */
  removedTargetIds: ProtoList<i32> {
    get { return this.#m.repeated(2, WIRE_VARINT, (v, p) => v.int32At(p)); }
  }

  /**
   * The read timestamp at which the remove was observed.
   *
   * Greater or equal to the `commit_time` of the change/delete/remove.
   */
  readTime: Timestamp | null {
    get {
      let m = this.#m.message(4);
      return if (m == null) null else new Timestamp(m as ProtoView);
    }
  }
}

/** The fields of a `google.firestore.v1.ExistenceFilter` to encode, for `ExistenceFilter.of`. */
export type ExistenceFilterInit = {
  targetId?: i32,
  count?: i32,
  unchangedNames?: BloomFilter,
};

/**
 * A digest of all the documents that match a given target.
 *
 * Protobuf: `google.firestore.v1.ExistenceFilter`.
 */
export final class ExistenceFilter {
  #m: ProtoView;

  /** A message over `m`, which must hold an encoded `google.firestore.v1.ExistenceFilter`. */
  new(m: ProtoView) : #m = m;

  /** Decodes `bytes`. Fields are decoded as they are read. */
  static decode(bytes: ByteArray): ExistenceFilter {
    return new ExistenceFilter(ProtoView.of(bytes));
  }

  /** Encodes `init` as a `google.firestore.v1.ExistenceFilter`. */
  static of(init: ExistenceFilterInit): ExistenceFilter {
    let w = new ProtoWriter();
    if (let {targetId as f1} = init) {
      w.int32(1, f1);
    }
    if (let {count as f2} = init) {
      w.int32(2, f2);
    }
    if (let {unchangedNames as f3} = init) {
      w.message(3, f3.protoView);
    }
    return new ExistenceFilter(w.finish());
  }

  /** The encoded message. */
  protoView: ProtoView {
    get { return this.#m; }
  }

  /** The target ID to which this filter applies. */
  targetId: i32 {
    get { return this.#m.int32(1); }
  }

  /**
   * The total count of documents that match
   * [target_id][google.firestore.v1.ExistenceFilter.target_id].
   *
   * If different from the count of documents in the client that match, the
   * client must manually determine which documents no longer match the target.
   *
   * The client can use the `unchanged_names` bloom filter to assist with
   * this determination by testing ALL the document names against the filter;
   * if the document name is NOT in the filter, it means the document no
   * longer matches the target.
   */
  count: i32 {
    get { return this.#m.int32(2); }
  }

  /**
   * A bloom filter that, despite its name, contains the UTF-8 byte encodings of
   * the resource names of ALL the documents that match
   * [target_id][google.firestore.v1.ExistenceFilter.target_id], in the form
   * `projects/{project_id}/databases/{database_id}/documents/{document_path}`.
   *
   * This bloom filter may be omitted at the server's discretion, such as if it
   * is deemed that the client will not make use of it or if it is too
   * computationally expensive to calculate or transmit. Clients must gracefully
   * handle this field being absent by falling back to the logic used before
   * this field existed; that is, re-add the target without a resume token to
   * figure out which documents in the client's cache are out of sync.
   */
  unchangedNames: BloomFilter | null {
    get {
      let m = this.#m.message(3);
      return if (m == null) null else new BloomFilter(m as ProtoView);
    }
  }
}

/** The fields of a `google.protobuf.Empty` to encode, for `Empty.of`. */
export type EmptyInit = {
};

/**
 * A generic empty message that you can re-use to avoid defining duplicated
 * empty messages in your APIs. A typical example is to use it as the request
 * or the response type of an API method. For instance:
 *
 *     service Foo {
 *       rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty);
 *     }
 *
 * Protobuf: `google.protobuf.Empty`.
 */
export final class Empty {
  #m: ProtoView;

  /** A message over `m`, which must hold an encoded `google.protobuf.Empty`. */
  new(m: ProtoView) : #m = m;

  /** Decodes `bytes`. Fields are decoded as they are read. */
  static decode(bytes: ByteArray): Empty {
    return new Empty(ProtoView.of(bytes));
  }

  /** Encodes `init` as a `google.protobuf.Empty`. */
  static of(init: EmptyInit): Empty {
    let w = new ProtoWriter();
    return new Empty(w.finish());
  }

  /** The encoded message. */
  protoView: ProtoView {
    get { return this.#m; }
  }
}

/** The fields of a `google.protobuf.Timestamp` to encode, for `Timestamp.of`. */
export type TimestampInit = {
  seconds?: i64,
  nanos?: i32,
};

/**
 * A Timestamp represents a point in time independent of any time zone or local
 * calendar, encoded as a count of seconds and fractions of seconds at
 * nanosecond resolution. The count is relative to an epoch at UTC midnight on
 * January 1, 1970, in the proleptic Gregorian calendar which extends the
 * Gregorian calendar backwards to year one.
 *
 * All minutes are 60 seconds long. Leap seconds are "smeared" so that no leap
 * second table is needed for interpretation, using a [24-hour linear
 * smear](https://developers.google.com/time/smear).
 *
 * The range is from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59.999999999Z. By
 * restricting to that range, we ensure that we can convert to and from [RFC
 * 3339](https://www.ietf.org/rfc/rfc3339.txt) date strings.
 *
 * # Examples
 *
 * Example 1: Compute Timestamp from POSIX `time()`.
 *
 *     Timestamp timestamp;
 *     timestamp.set_seconds(time(NULL));
 *     timestamp.set_nanos(0);
 *
 * Example 2: Compute Timestamp from POSIX `gettimeofday()`.
 *
 *     struct timeval tv;
 *     gettimeofday(&tv, NULL);
 *
 *     Timestamp timestamp;
 *     timestamp.set_seconds(tv.tv_sec);
 *     timestamp.set_nanos(tv.tv_usec * 1000);
 *
 * Example 3: Compute Timestamp from Win32 `GetSystemTimeAsFileTime()`.
 *
 *     FILETIME ft;
 *     GetSystemTimeAsFileTime(&ft);
 *     UINT64 ticks = (((UINT64)ft.dwHighDateTime) << 32) | ft.dwLowDateTime;
 *
 *     // A Windows tick is 100 nanoseconds. Windows epoch 1601-01-01T00:00:00Z
 *     // is 11644473600 seconds before Unix epoch 1970-01-01T00:00:00Z.
 *     Timestamp timestamp;
 *     timestamp.set_seconds((INT64) ((ticks / 10000000) - 11644473600LL));
 *     timestamp.set_nanos((INT32) ((ticks % 10000000) * 100));
 *
 * Example 4: Compute Timestamp from Java `System.currentTimeMillis()`.
 *
 *     long millis = System.currentTimeMillis();
 *
 *     Timestamp timestamp = Timestamp.newBuilder().setSeconds(millis / 1000)
 *         .setNanos((int) ((millis % 1000) * 1000000)).build();
 *
 * Example 5: Compute Timestamp from Java `Instant.now()`.
 *
 *     Instant now = Instant.now();
 *
 *     Timestamp timestamp =
 *         Timestamp.newBuilder().setSeconds(now.getEpochSecond())
 *             .setNanos(now.getNano()).build();
 *
 * Example 6: Compute Timestamp from current time in Python.
 *
 *     timestamp = Timestamp()
 *     timestamp.GetCurrentTime()
 *
 * # JSON Mapping
 *
 * In JSON format, the Timestamp type is encoded as a string in the
 * [RFC 3339](https://www.ietf.org/rfc/rfc3339.txt) format. That is, the
 * format is "{year}-{month}-{day}T{hour}:{min}:{sec}[.{frac_sec}]Z"
 * where {year} is always expressed using four digits while {month}, {day},
 * {hour}, {min}, and {sec} are zero-padded to two digits each. The fractional
 * seconds, which can go up to 9 digits (i.e. up to 1 nanosecond resolution),
 * are optional. The "Z" suffix indicates the timezone ("UTC"); the timezone
 * is required. A ProtoJSON serializer should always use UTC (as indicated by
 * "Z") when printing the Timestamp type and a ProtoJSON parser should be
 * able to accept both UTC and other timezones (as indicated by an offset).
 *
 * For example, "2017-01-15T01:30:15.01Z" encodes 15.01 seconds past
 * 01:30 UTC on January 15, 2017.
 *
 * In JavaScript, one can convert a Date object to this format using the
 * standard
 * [toISOString()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString)
 * method. In Python, a standard `datetime.datetime` object can be converted
 * to this format using
 * [`strftime`](https://docs.python.org/2/library/time.html#time.strftime) with
 * the time format spec '%Y-%m-%dT%H:%M:%S.%fZ'. Likewise, in Java, one can use
 * the Joda Time's [`ISODateTimeFormat.dateTime()`](
 * http://joda-time.sourceforge.net/apidocs/org/joda/time/format/ISODateTimeFormat.html#dateTime()
 * ) to obtain a formatter capable of generating timestamps in this format.
 *
 * Protobuf: `google.protobuf.Timestamp`.
 */
export final class Timestamp {
  #m: ProtoView;

  /** A message over `m`, which must hold an encoded `google.protobuf.Timestamp`. */
  new(m: ProtoView) : #m = m;

  /** Decodes `bytes`. Fields are decoded as they are read. */
  static decode(bytes: ByteArray): Timestamp {
    return new Timestamp(ProtoView.of(bytes));
  }

  /** Encodes `init` as a `google.protobuf.Timestamp`. */
  static of(init: TimestampInit): Timestamp {
    let w = new ProtoWriter();
    if (let {seconds as f1} = init) {
      w.int64(1, f1);
    }
    if (let {nanos as f2} = init) {
      w.int32(2, f2);
    }
    return new Timestamp(w.finish());
  }

  /** The encoded message. */
  protoView: ProtoView {
    get { return this.#m; }
  }

  /**
   * Represents seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z. Must
   * be between -62135596800 and 253402300799 inclusive (which corresponds to
   * 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z).
   */
  seconds: i64 {
    get { return this.#m.int64(1); }
  }

  /**
   * Non-negative fractions of a second at nanosecond resolution. This field is
   * the nanosecond portion of the duration, not an alternative to seconds.
   * Negative second values with fractions must still have non-negative nanos
   * values that count forward in time. Must be between 0 and 999,999,999
   * inclusive.
   */
  nanos: i32 {
    get { return this.#m.int32(2); }
  }
}

/** The fields of a `google.protobuf.DoubleValue` to encode, for `DoubleValue.of`. */
export type DoubleValueInit = {
  value?: f64,
};

/**
 * Wrapper message for `double`.
 *
 * The JSON representation for `DoubleValue` is JSON number.
 *
 * Not recommended for use in new APIs, but still useful for legacy APIs and
 * has no plan to be removed.
 *
 * Protobuf: `google.protobuf.DoubleValue`.
 */
export final class DoubleValue {
  #m: ProtoView;

  /** A message over `m`, which must hold an encoded `google.protobuf.DoubleValue`. */
  new(m: ProtoView) : #m = m;

  /** Decodes `bytes`. Fields are decoded as they are read. */
  static decode(bytes: ByteArray): DoubleValue {
    return new DoubleValue(ProtoView.of(bytes));
  }

  /** Encodes `init` as a `google.protobuf.DoubleValue`. */
  static of(init: DoubleValueInit): DoubleValue {
    let w = new ProtoWriter();
    if (let {value as f1} = init) {
      w.double(1, f1);
    }
    return new DoubleValue(w.finish());
  }

  /** The encoded message. */
  protoView: ProtoView {
    get { return this.#m; }
  }

  /** The double value. */
  value: f64 {
    get { return this.#m.double(1); }
  }
}

/** The fields of a `google.protobuf.Int64Value` to encode, for `Int64Value.of`. */
export type Int64ValueInit = {
  value?: i64,
};

/**
 * Wrapper message for `int64`.
 *
 * The JSON representation for `Int64Value` is JSON string.
 *
 * Not recommended for use in new APIs, but still useful for legacy APIs and
 * has no plan to be removed.
 *
 * Protobuf: `google.protobuf.Int64Value`.
 */
export final class Int64Value {
  #m: ProtoView;

  /** A message over `m`, which must hold an encoded `google.protobuf.Int64Value`. */
  new(m: ProtoView) : #m = m;

  /** Decodes `bytes`. Fields are decoded as they are read. */
  static decode(bytes: ByteArray): Int64Value {
    return new Int64Value(ProtoView.of(bytes));
  }

  /** Encodes `init` as a `google.protobuf.Int64Value`. */
  static of(init: Int64ValueInit): Int64Value {
    let w = new ProtoWriter();
    if (let {value as f1} = init) {
      w.int64(1, f1);
    }
    return new Int64Value(w.finish());
  }

  /** The encoded message. */
  protoView: ProtoView {
    get { return this.#m; }
  }

  /** The int64 value. */
  value: i64 {
    get { return this.#m.int64(1); }
  }
}

/** The fields of a `google.protobuf.Int32Value` to encode, for `Int32Value.of`. */
export type Int32ValueInit = {
  value?: i32,
};

/**
 * Wrapper message for `int32`.
 *
 * The JSON representation for `Int32Value` is JSON number.
 *
 * Not recommended for use in new APIs, but still useful for legacy APIs and
 * has no plan to be removed.
 *
 * Protobuf: `google.protobuf.Int32Value`.
 */
export final class Int32Value {
  #m: ProtoView;

  /** A message over `m`, which must hold an encoded `google.protobuf.Int32Value`. */
  new(m: ProtoView) : #m = m;

  /** Decodes `bytes`. Fields are decoded as they are read. */
  static decode(bytes: ByteArray): Int32Value {
    return new Int32Value(ProtoView.of(bytes));
  }

  /** Encodes `init` as a `google.protobuf.Int32Value`. */
  static of(init: Int32ValueInit): Int32Value {
    let w = new ProtoWriter();
    if (let {value as f1} = init) {
      w.int32(1, f1);
    }
    return new Int32Value(w.finish());
  }

  /** The encoded message. */
  protoView: ProtoView {
    get { return this.#m; }
  }

  /** The int32 value. */
  value: i32 {
    get { return this.#m.int32(1); }
  }
}

/** The fields of a `google.rpc.Status` to encode, for `Status.of`. */
export type StatusInit = {
  code?: i32,
  message?: String,
  details?: Array<Any>,
};

/**
 * The `Status` type defines a logical error model that is suitable for
 * different programming environments, including REST APIs and RPC APIs. It is
 * used by [gRPC](https://github.com/grpc). Each `Status` message contains
 * three pieces of data: error code, error message, and error details.
 *
 * You can find out more about this error model and how to work with it in the
 * [API Design Guide](https://cloud.google.com/apis/design/errors).
 *
 * Protobuf: `google.rpc.Status`.
 */
export final class Status {
  #m: ProtoView;

  /** A message over `m`, which must hold an encoded `google.rpc.Status`. */
  new(m: ProtoView) : #m = m;

  /** Decodes `bytes`. Fields are decoded as they are read. */
  static decode(bytes: ByteArray): Status {
    return new Status(ProtoView.of(bytes));
  }

  /** Encodes `init` as a `google.rpc.Status`. */
  static of(init: StatusInit): Status {
    let w = new ProtoWriter();
    if (let {code as f1} = init) {
      w.int32(1, f1);
    }
    if (let {message as f2} = init) {
      w.string(2, f2);
    }
    if (let {details as f3} = init) {
      for (let item in f3) {
        w.message(3, item.protoView);
      }
    }
    return new Status(w.finish());
  }

  /** The encoded message. */
  protoView: ProtoView {
    get { return this.#m; }
  }

  /**
   * The status code, which should be an enum value of
   * [google.rpc.Code][google.rpc.Code].
   */
  code: i32 {
    get { return this.#m.int32(1); }
  }

  /**
   * A developer-facing error message, which should be in English. Any
   * user-facing error message should be localized and sent in the
   * [google.rpc.Status.details][google.rpc.Status.details] field, or localized
   * by the client.
   */
  message: String {
    get { return this.#m.string(2); }
  }

  /**
   * A list of messages that carry the error details.  There is a common set of
   * message types for APIs to use.
   */
  details: ProtoList<Any> {
    get { return this.#m.repeated(3, WIRE_LEN, (v, p) => new Any(v.messageAt(p))); }
  }
}

/** The fields of a `google.protobuf.Struct` to encode, for `Struct.of`. */
export type StructInit = {
  fields?: Map<String, ProtobufValue>,
};

/**
 * Represents a JSON object.
 *
 * An unordered key-value map, intending to perfectly capture the semantics of a
 * JSON object. This enables parsing any arbitrary JSON payload as a message
 * field in ProtoJSON format.
 *
 * This follows RFC 8259 guidelines for interoperable JSON: notably this type
 * cannot represent large Int64 values or `NaN`/`Infinity` numbers,
 * since the JSON format generally does not support those values in its number
 * type.
 *
 * If you do not intend to parse arbitrary JSON into your message, a custom
 * typed message should be preferred instead of using this type.
 *
 * Protobuf: `google.protobuf.Struct`.
 */
export final class Struct {
  #m: ProtoView;

  /** A message over `m`, which must hold an encoded `google.protobuf.Struct`. */
  new(m: ProtoView) : #m = m;

  /** Decodes `bytes`. Fields are decoded as they are read. */
  static decode(bytes: ByteArray): Struct {
    return new Struct(ProtoView.of(bytes));
  }

  /** Encodes `init` as a `google.protobuf.Struct`. */
  static of(init: StructInit): Struct {
    let w = new ProtoWriter();
    if (let {fields as f1} = init) {
      for (let entry in f1) {
        let e = new ProtoWriter();
        e.string(1, entry.key);
        e.message(2, entry.value.protoView);
        w.message(1, e.finish());
      }
    }
    return new Struct(w.finish());
  }

  /** The encoded message. */
  protoView: ProtoView {
    get { return this.#m; }
  }

  /** Unordered map of dynamically typed values. */
  fields: ProtoMap<String, ProtobufValue> {
    get { return this.#m.map(1, (e) => e.string(1), (e) => new ProtobufValue(e.messageOrEmpty(2))); }
  }
}

/**
 * The kind of value.
 *
 * The member of `google.protobuf.Value.kind` that is set, as `ProtobufValue.kind` reads it.
 */
export sealed class ProtobufValueKind {
  case ProtobufValueNullValue(value: NullValue)
  case ProtobufValueNumberValue(value: f64)
  case ProtobufValueStringValue(value: String)
  case ProtobufValueBoolValue(value: boolean)
  case ProtobufValueStructValue(value: Struct)
  case ProtobufValueListValue(value: ListValue)
  case ProtobufValueKindNotSet
}

/** The fields of a `google.protobuf.Value` to encode, for `ProtobufValue.of`. */
export type ProtobufValueInit = {
  nullValue?: NullValue,
  numberValue?: f64,
  stringValue?: String,
  boolValue?: boolean,
  structValue?: Struct,
  listValue?: ListValue,
};

/**
 * Represents a JSON value.
 *
 * `Value` represents a dynamically typed value which can be either
 * null, a number, a string, a boolean, a recursive struct value, or a
 * list of values. A producer of value is expected to set one of these
 * variants. Absence of any variant is an invalid state.
 *
 * Protobuf: `google.protobuf.Value`.
 */
export final class ProtobufValue {
  #m: ProtoView;

  /** A message over `m`, which must hold an encoded `google.protobuf.Value`. */
  new(m: ProtoView) : #m = m;

  /** Decodes `bytes`. Fields are decoded as they are read. */
  static decode(bytes: ByteArray): ProtobufValue {
    return new ProtobufValue(ProtoView.of(bytes));
  }

  /** Encodes `init` as a `google.protobuf.Value`. */
  static of(init: ProtobufValueInit): ProtobufValue {
    let w = new ProtoWriter();
    if (let {nullValue as f1} = init) {
      w.int32(1, f1 as i32);
    }
    if (let {numberValue as f2} = init) {
      w.double(2, f2);
    }
    if (let {stringValue as f3} = init) {
      w.string(3, f3);
    }
    if (let {boolValue as f4} = init) {
      w.bool(4, f4);
    }
    if (let {structValue as f5} = init) {
      w.message(5, f5.protoView);
    }
    if (let {listValue as f6} = init) {
      w.message(6, f6.protoView);
    }
    return new ProtobufValue(w.finish());
  }

  /** The encoded message. */
  protoView: ProtoView {
    get { return this.#m; }
  }

  /** Represents a JSON `null`. */
  nullValue: NullValue {
    get {
      if (this.#whichKind() != 1) {
        return 0 as NullValue;
      }
      return this.#m.int32(1) as NullValue;
    }
  }

  /** Whether `nullValue` is set. */
  hasNullValue: boolean {
    get { return this.#whichKind() == 1; }
  }

  /**
   * Represents a JSON number. Must not be `NaN`, `Infinity` or
   * `-Infinity`, since those are not supported in JSON. This also cannot
   * represent large Int64 values, since JSON format generally does not
   * support them in its number type.
   */
  numberValue: f64 {
    get {
      if (this.#whichKind() != 2) {
        return 0.0;
      }
      return this.#m.double(2);
    }
  }

  /** Whether `numberValue` is set. */
  hasNumberValue: boolean {
    get { return this.#whichKind() == 2; }
  }

  /** Represents a JSON string. */
  stringValue: String {
    get {
      if (this.#whichKind() != 3) {
        return '';
      }
      return this.#m.string(3);
    }
  }

  /** Whether `stringValue` is set. */
  hasStringValue: boolean {
    get { return this.#whichKind() == 3; }
  }

  /** Represents a JSON boolean (`true` or `false` literal in JSON). */
  boolValue: boolean {
    get {
      if (this.#whichKind() != 4) {
        return false;
      }
      return this.#m.bool(4);
    }
  }

  /** Whether `boolValue` is set. */
  hasBoolValue: boolean {
    get { return this.#whichKind() == 4; }
  }

  /** Represents a JSON object. */
  structValue: Struct | null {
    get {
      if (this.#whichKind() != 5) {
        return null;
      }
      let m = this.#m.message(5);
      return if (m == null) null else new Struct(m as ProtoView);
    }
  }

  /** Represents a JSON array. */
  listValue: ListValue | null {
    get {
      if (this.#whichKind() != 6) {
        return null;
      }
      let m = this.#m.message(6);
      return if (m == null) null else new ListValue(m as ProtoView);
    }
  }

  /** The member of `kind` that is set. */
  kind: ProtobufValueKind {
    get {
      let which = this.#whichKind();
      if (which == 1) {
        return new ProtobufValueNullValue(this.#m.int32(1) as NullValue);
      }
      if (which == 2) {
        return new ProtobufValueNumberValue(this.#m.double(2));
      }
      if (which == 3) {
        return new ProtobufValueStringValue(this.#m.string(3));
      }
      if (which == 4) {
        return new ProtobufValueBoolValue(this.#m.bool(4));
      }
      if (which == 5) {
        return new ProtobufValueStructValue(new Struct(this.#m.message(5) as ProtoView));
      }
      if (which == 6) {
        return new ProtobufValueListValue(new ListValue(this.#m.message(6) as ProtoView));
      }
      return new ProtobufValueKindNotSet();
    }
  }

  #whichKind(): i32 {
    return this.#m.whichOf([1, 2, 3, 4, 5, 6]);
  }
}

/** The fields of a `google.protobuf.ListValue` to encode, for `ListValue.of`. */
export type ListValueInit = {
  values?: Array<ProtobufValue>,
};

/**
 * Represents a JSON array.
 *
 * Protobuf: `google.protobuf.ListValue`.
 */
export final class ListValue {
  #m: ProtoView;

  /** A message over `m`, which must hold an encoded `google.protobuf.ListValue`. */
  new(m: ProtoView) : #m = m;

  /** Decodes `bytes`. Fields are decoded as they are read. */
  static decode(bytes: ByteArray): ListValue {
    return new ListValue(ProtoView.of(bytes));
  }

  /** Encodes `init` as a `google.protobuf.ListValue`. */
  static of(init: ListValueInit): ListValue {
    let w = new ProtoWriter();
    if (let {values as f1} = init) {
      for (let item in f1) {
        w.message(1, item.protoView);
      }
    }
    return new ListValue(w.finish());
  }

  /** The encoded message. */
  protoView: ProtoView {
    get { return this.#m; }
  }

  /** Repeated field of dynamically typed values. */
  values: ProtoList<ProtobufValue> {
    get { return this.#m.repeated(1, WIRE_LEN, (v, p) => new ProtobufValue(v.messageAt(p))); }
  }
}

/** The fields of a `google.type.LatLng` to encode, for `LatLng.of`. */
export type LatLngInit = {
  latitude?: f64,
  longitude?: f64,
};

/**
 * An object that represents a latitude/longitude pair. This is expressed as a
 * pair of doubles to represent degrees latitude and degrees longitude. Unless
 * specified otherwise, this object must conform to the
 * <a href="https://en.wikipedia.org/wiki/World_Geodetic_System#1984_version">
 * WGS84 standard</a>. Values must be within normalized ranges.
 *
 * Protobuf: `google.type.LatLng`.
 */
export final class LatLng {
  #m: ProtoView;

  /** A message over `m`, which must hold an encoded `google.type.LatLng`. */
  new(m: ProtoView) : #m = m;

  /** Decodes `bytes`. Fields are decoded as they are read. */
  static decode(bytes: ByteArray): LatLng {
    return new LatLng(ProtoView.of(bytes));
  }

  /** Encodes `init` as a `google.type.LatLng`. */
  static of(init: LatLngInit): LatLng {
    let w = new ProtoWriter();
    if (let {latitude as f1} = init) {
      w.double(1, f1);
    }
    if (let {longitude as f2} = init) {
      w.double(2, f2);
    }
    return new LatLng(w.finish());
  }

  /** The encoded message. */
  protoView: ProtoView {
    get { return this.#m; }
  }

  /** The latitude in degrees. It must be in the range [-90.0, +90.0]. */
  latitude: f64 {
    get { return this.#m.double(1); }
  }

  /** The longitude in degrees. It must be in the range [-180.0, +180.0]. */
  longitude: f64 {
    get { return this.#m.double(2); }
  }
}

/** The fields of a `google.protobuf.Any` to encode, for `Any.of`. */
export type AnyInit = {
  typeUrl?: String,
  value?: ByteArray | ProtoBytes,
};

/**
 * `Any` contains an arbitrary serialized protocol buffer message along with a
 * URL that describes the type of the serialized message.
 *
 * In its binary encoding, an `Any` is an ordinary message; but in other wire
 * forms like JSON, it has a special encoding. The format of the type URL is
 * described on the `type_url` field.
 *
 * Protobuf APIs provide utilities to interact with `Any` values:
 *
 * - A 'pack' operation accepts a message and constructs a generic `Any` wrapper
 *   around it.
 * - An 'unpack' operation reads the content of an `Any` message, either into an
 *   existing message or a new one. Unpack operations must check the type of the
 *   value they unpack against the declared `type_url`.
 * - An 'is' operation decides whether an `Any` contains a message of the given
 *   type, i.e. whether it can 'unpack' that type.
 *
 * The JSON format representation of an `Any` follows one of these cases:
 *
 * - For types without special-cased JSON encodings, the JSON format
 *   representation of the `Any` is the same as that of the message, with an
 *   additional `@type` field which contains the type URL.
 * - For types with special-cased JSON encodings (typically called 'well-known'
 *   types, listed in https://protobuf.dev/programming-guides/json/#any), the
 *   JSON format representation has a key `@type` which contains the type URL
 *   and a key `value` which contains the JSON-serialized value.
 *
 * The text format representation of an `Any` is like a message with one field
 * whose name is the type URL in brackets. For example, an `Any` containing a
 * `foo.Bar` message may be written `[type.googleapis.com/foo.Bar] { a: 2 }`.
 *
 * Protobuf: `google.protobuf.Any`.
 */
export final class Any {
  #m: ProtoView;

  /** A message over `m`, which must hold an encoded `google.protobuf.Any`. */
  new(m: ProtoView) : #m = m;

  /** Decodes `bytes`. Fields are decoded as they are read. */
  static decode(bytes: ByteArray): Any {
    return new Any(ProtoView.of(bytes));
  }

  /** Encodes `init` as a `google.protobuf.Any`. */
  static of(init: AnyInit): Any {
    let w = new ProtoWriter();
    if (let {typeUrl as f1} = init) {
      w.string(1, f1);
    }
    if (let {value as f2} = init) {
      w.bytes(2, f2);
    }
    return new Any(w.finish());
  }

  /** The encoded message. */
  protoView: ProtoView {
    get { return this.#m; }
  }

  /**
   * Identifies the type of the serialized Protobuf message with a URI reference
   * consisting of a prefix ending in a slash and the fully-qualified type name.
   *
   * Example: type.googleapis.com/google.protobuf.StringValue
   *
   * This string must contain at least one `/` character, and the content after
   * the last `/` must be the fully-qualified name of the type in canonical
   * form, without a leading dot. Do not write a scheme on these URI references
   * so that clients do not attempt to contact them.
   *
   * The prefix is arbitrary and Protobuf implementations are expected to
   * simply strip off everything up to and including the last `/` to identify
   * the type. `type.googleapis.com/` is a common default prefix that some
   * legacy implementations require. This prefix does not indicate the origin of
   * the type, and URIs containing it are not expected to respond to any
   * requests.
   *
   * All type URL strings must be legal URI references with the additional
   * restriction (for the text format) that the content of the reference
   * must consist only of alphanumeric characters, percent-encoded escapes, and
   * characters in the following set (not including the outer backticks):
   * `/-.~_!$&()*+,;=`. Despite our allowing percent encodings, implementations
   * should not unescape them to prevent confusion with existing parsers. For
   * example, `type.googleapis.com%2FFoo` should be rejected.
   *
   * In the original design of `Any`, the possibility of launching a type
   * resolution service at these type URLs was considered but Protobuf never
   * implemented one and considers contacting these URLs to be problematic and
   * a potential security issue. Do not attempt to contact type URLs.
   */
  typeUrl: String {
    get { return this.#m.string(1); }
  }

  /** Holds a Protobuf serialization of the type described by type_url. */
  value: ProtoBytes {
    get { return this.#m.bytes(2); }
  }
}

/** The fields of a `google.protobuf.Duration` to encode, for `Duration.of`. */
export type DurationInit = {
  seconds?: i64,
  nanos?: i32,
};

/**
 * A Duration represents a signed, fixed-length span of time represented
 * as a count of seconds and fractions of seconds at nanosecond
 * resolution. It is independent of any calendar and concepts like "day"
 * or "month". It is related to Timestamp in that the difference between
 * two Timestamp values is a Duration and it can be added or subtracted
 * from a Timestamp. Range is approximately +-10,000 years.
 *
 * # Examples
 *
 * Example 1: Compute Duration from two Timestamps in pseudo code.
 *
 *     Timestamp start = ...;
 *     Timestamp end = ...;
 *     Duration duration = ...;
 *
 *     duration.seconds = end.seconds - start.seconds;
 *     duration.nanos = end.nanos - start.nanos;
 *
 *     if (duration.seconds < 0 && duration.nanos > 0) {
 *       duration.seconds += 1;
 *       duration.nanos -= 1000000000;
 *     } else if (duration.seconds > 0 && duration.nanos < 0) {
 *       duration.seconds -= 1;
 *       duration.nanos += 1000000000;
 *     }
 *
 * Example 2: Compute Timestamp from Timestamp + Duration in pseudo code.
 *
 *     Timestamp start = ...;
 *     Duration duration = ...;
 *     Timestamp end = ...;
 *
 *     end.seconds = start.seconds + duration.seconds;
 *     end.nanos = start.nanos + duration.nanos;
 *
 *     if (end.nanos < 0) {
 *       end.seconds -= 1;
 *       end.nanos += 1000000000;
 *     } else if (end.nanos >= 1000000000) {
 *       end.seconds += 1;
 *       end.nanos -= 1000000000;
 *     }
 *
 * Example 3: Compute Duration from datetime.timedelta in Python.
 *
 *     td = datetime.timedelta(days=3, minutes=10)
 *     duration = Duration()
 *     duration.FromTimedelta(td)
 *
 * # JSON Mapping
 *
 * In JSON format, the Duration type is encoded as a string rather than an
 * object, where the string ends in the suffix "s" (indicating seconds) and
 * is preceded by the number of seconds, with nanoseconds expressed as
 * fractional seconds. For example, 3 seconds with 0 nanoseconds should be
 * encoded in JSON format as "3s", while 3 seconds and 1 nanosecond should
 * be expressed in JSON format as "3.000000001s", and 3 seconds and 1
 * microsecond should be expressed in JSON format as "3.000001s".
 *
 * Protobuf: `google.protobuf.Duration`.
 */
export final class Duration {
  #m: ProtoView;

  /** A message over `m`, which must hold an encoded `google.protobuf.Duration`. */
  new(m: ProtoView) : #m = m;

  /** Decodes `bytes`. Fields are decoded as they are read. */
  static decode(bytes: ByteArray): Duration {
    return new Duration(ProtoView.of(bytes));
  }

  /** Encodes `init` as a `google.protobuf.Duration`. */
  static of(init: DurationInit): Duration {
    let w = new ProtoWriter();
    if (let {seconds as f1} = init) {
      w.int64(1, f1);
    }
    if (let {nanos as f2} = init) {
      w.int32(2, f2);
    }
    return new Duration(w.finish());
  }

  /** The encoded message. */
  protoView: ProtoView {
    get { return this.#m; }
  }

  /**
   * Signed seconds of the span of time. Must be from -315,576,000,000
   * to +315,576,000,000 inclusive. Note: these bounds are computed from:
   * 60 sec/min * 60 min/hr * 24 hr/day * 365.25 days/year * 10000 years
   */
  seconds: i64 {
    get { return this.#m.int64(1); }
  }

  /**
   * Signed fractions of a second at nanosecond resolution of the span
   * of time. Durations less than one second are represented with a 0
   * `seconds` field and a positive or negative `nanos` field. For durations
   * of one second or more, a non-zero value for the `nanos` field must be
   * of the same sign as the `seconds` field. Must be from -999,999,999
   * to +999,999,999 inclusive.
   */
  nanos: i32 {
    get { return this.#m.int32(2); }
  }
}

/** The fields of a `google.firestore.v1.BitSequence` to encode, for `BitSequence.of`. */
export type BitSequenceInit = {
  bitmap?: ByteArray | ProtoBytes,
  padding?: i32,
};

/**
 * A sequence of bits, encoded in a byte array.
 *
 * Each byte in the `bitmap` byte array stores 8 bits of the sequence. The only
 * exception is the last byte, which may store 8 _or fewer_ bits. The `padding`
 * defines the number of bits of the last byte to be ignored as "padding". The
 * values of these "padding" bits are unspecified and must be ignored.
 *
 * To retrieve the first bit, bit 0, calculate: `(bitmap[0] & 0x01) != 0`.
 * To retrieve the second bit, bit 1, calculate: `(bitmap[0] & 0x02) != 0`.
 * To retrieve the third bit, bit 2, calculate: `(bitmap[0] & 0x04) != 0`.
 * To retrieve the fourth bit, bit 3, calculate: `(bitmap[0] & 0x08) != 0`.
 * To retrieve bit n, calculate: `(bitmap[n / 8] & (0x01 << (n % 8))) != 0`.
 *
 * The "size" of a `BitSequence` (the number of bits it contains) is calculated
 * by this formula: `(bitmap.length * 8) - padding`.
 *
 * Protobuf: `google.firestore.v1.BitSequence`.
 */
export final class BitSequence {
  #m: ProtoView;

  /** A message over `m`, which must hold an encoded `google.firestore.v1.BitSequence`. */
  new(m: ProtoView) : #m = m;

  /** Decodes `bytes`. Fields are decoded as they are read. */
  static decode(bytes: ByteArray): BitSequence {
    return new BitSequence(ProtoView.of(bytes));
  }

  /** Encodes `init` as a `google.firestore.v1.BitSequence`. */
  static of(init: BitSequenceInit): BitSequence {
    let w = new ProtoWriter();
    if (let {bitmap as f1} = init) {
      w.bytes(1, f1);
    }
    if (let {padding as f2} = init) {
      w.int32(2, f2);
    }
    return new BitSequence(w.finish());
  }

  /** The encoded message. */
  protoView: ProtoView {
    get { return this.#m; }
  }

  /**
   * The bytes that encode the bit sequence.
   * May have a length of zero.
   */
  bitmap: ProtoBytes {
    get { return this.#m.bytes(1); }
  }

  /**
   * The number of bits of the last byte in `bitmap` to ignore as "padding".
   * If the length of `bitmap` is zero, then this value must be `0`.
   * Otherwise, this value must be between 0 and 7, inclusive.
   */
  padding: i32 {
    get { return this.#m.int32(2); }
  }
}

/** The fields of a `google.firestore.v1.BloomFilter` to encode, for `BloomFilter.of`. */
export type BloomFilterInit = {
  bits?: BitSequence,
  hashCount?: i32,
};

/**
 * A bloom filter (https://en.wikipedia.org/wiki/Bloom_filter).
 *
 * The bloom filter hashes the entries with MD5 and treats the resulting 128-bit
 * hash as 2 distinct 64-bit hash values, interpreted as unsigned integers
 * using 2's complement encoding.
 *
 * These two hash values, named `h1` and `h2`, are then used to compute the
 * `hash_count` hash values using the formula, starting at `i=0`:
 *
 *     h(i) = h1 + (i * h2)
 *
 * These resulting values are then taken modulo the number of bits in the bloom
 * filter to get the bits of the bloom filter to test for the given entry.
 *
 * Protobuf: `google.firestore.v1.BloomFilter`.
 */
export final class BloomFilter {
  #m: ProtoView;

  /** A message over `m`, which must hold an encoded `google.firestore.v1.BloomFilter`. */
  new(m: ProtoView) : #m = m;

  /** Decodes `bytes`. Fields are decoded as they are read. */
  static decode(bytes: ByteArray): BloomFilter {
    return new BloomFilter(ProtoView.of(bytes));
  }

  /** Encodes `init` as a `google.firestore.v1.BloomFilter`. */
  static of(init: BloomFilterInit): BloomFilter {
    let w = new ProtoWriter();
    if (let {bits as f1} = init) {
      w.message(1, f1.protoView);
    }
    if (let {hashCount as f2} = init) {
      w.int32(2, f2);
    }
    return new BloomFilter(w.finish());
  }

  /** The encoded message. */
  protoView: ProtoView {
    get { return this.#m; }
  }

  /** The bloom filter data. */
  bits: BitSequence | null {
    get {
      let m = this.#m.message(1);
      return if (m == null) null else new BitSequence(m as ProtoView);
    }
  }

  /** The number of hashes used by the algorithm. */
  hashCount: i32 {
    get { return this.#m.int32(2); }
  }
}

/**
 * The Cloud Firestore service.
 *
 * Cloud Firestore is a fast, fully managed, serverless, cloud-native NoSQL
 * document database that simplifies storing, syncing, and querying data for
 * your mobile, web, and IoT apps at global scale. Its client libraries provide
 * live synchronization and offline support, while its security features and
 * integrations with Firebase and Google Cloud Platform accelerate building
 * truly serverless apps.
 *
 * A client for `google.firestore.v1.Firestore`. Not generated, because they stream both ways: `Write`, `Listen`.
 */
export final class FirestoreClient {
  #transport: ProtoTransport;

  new(transport: ProtoTransport) : #transport = transport;

  /** Gets a single document. */
  async getDocument(request: GetDocumentRequestInit): Future<Document> {
    let metadata = new RpcMetadata();
    let routing = new RoutingHeader();
    let r0 = request.name;
    routing.add('name', r0);
    routing.addTo(metadata);
    let response = await this.#transport.unary(new RpcMethod('google.firestore.v1.Firestore', 'GetDocument'), GetDocumentRequest.of(request).protoView, metadata);
    return new Document(response);
  }

  /** Lists documents. */
  async listDocuments(request: ListDocumentsRequestInit): Future<ListDocumentsResponse> {
    let metadata = new RpcMetadata();
    let routing = new RoutingHeader();
    let r0 = request.parent;
    routing.add('parent', r0);
    if (let {collectionId as r1} = request) {
      routing.add('collection_id', r1);
    }
    routing.addTo(metadata);
    let response = await this.#transport.unary(new RpcMethod('google.firestore.v1.Firestore', 'ListDocuments'), ListDocumentsRequest.of(request).protoView, metadata);
    return new ListDocumentsResponse(response);
  }

  /** Updates or inserts a document. */
  async updateDocument(request: UpdateDocumentRequestInit): Future<Document> {
    let metadata = new RpcMetadata();
    let routing = new RoutingHeader();
    let r0 = request.document;
    let r1 = r0.name;
    routing.add('document.name', r1);
    routing.addTo(metadata);
    let response = await this.#transport.unary(new RpcMethod('google.firestore.v1.Firestore', 'UpdateDocument'), UpdateDocumentRequest.of(request).protoView, metadata);
    return new Document(response);
  }

  /** Deletes a document. */
  async deleteDocument(request: DeleteDocumentRequestInit): Future<Empty> {
    let metadata = new RpcMetadata();
    let routing = new RoutingHeader();
    let r0 = request.name;
    routing.add('name', r0);
    routing.addTo(metadata);
    let response = await this.#transport.unary(new RpcMethod('google.firestore.v1.Firestore', 'DeleteDocument'), DeleteDocumentRequest.of(request).protoView, metadata);
    return new Empty(response);
  }

  /**
   * Gets multiple documents.
   *
   * Documents returned by this method are not guaranteed to be returned in the
   * same order that they were requested.
   */
  batchGetDocuments(request: BatchGetDocumentsRequestInit): ProtoStream<BatchGetDocumentsResponse> {
    let metadata = new RpcMetadata();
    let routing = new RoutingHeader();
    let r0 = request.database;
    routing.add('database', r0);
    routing.addTo(metadata);
    return new ProtoStream<BatchGetDocumentsResponse>(
      this.#transport.serverStream(new RpcMethod('google.firestore.v1.Firestore', 'BatchGetDocuments'), BatchGetDocumentsRequest.of(request).protoView, metadata),
      (view) => new BatchGetDocumentsResponse(view)
    );
  }

  /** Starts a new transaction. */
  async beginTransaction(request: BeginTransactionRequestInit): Future<BeginTransactionResponse> {
    let metadata = new RpcMetadata();
    let routing = new RoutingHeader();
    let r0 = request.database;
    routing.add('database', r0);
    routing.addTo(metadata);
    let response = await this.#transport.unary(new RpcMethod('google.firestore.v1.Firestore', 'BeginTransaction'), BeginTransactionRequest.of(request).protoView, metadata);
    return new BeginTransactionResponse(response);
  }

  /** Commits a transaction, while optionally updating documents. */
  async commit(request: CommitRequestInit): Future<CommitResponse> {
    let metadata = new RpcMetadata();
    let routing = new RoutingHeader();
    let r0 = request.database;
    routing.add('database', r0);
    routing.addTo(metadata);
    let response = await this.#transport.unary(new RpcMethod('google.firestore.v1.Firestore', 'Commit'), CommitRequest.of(request).protoView, metadata);
    return new CommitResponse(response);
  }

  /** Rolls back a transaction. */
  async rollback(request: RollbackRequestInit): Future<Empty> {
    let metadata = new RpcMetadata();
    let routing = new RoutingHeader();
    let r0 = request.database;
    routing.add('database', r0);
    routing.addTo(metadata);
    let response = await this.#transport.unary(new RpcMethod('google.firestore.v1.Firestore', 'Rollback'), RollbackRequest.of(request).protoView, metadata);
    return new Empty(response);
  }

  /** Runs a query. */
  runQuery(request: RunQueryRequestInit): ProtoStream<RunQueryResponse> {
    let metadata = new RpcMetadata();
    let routing = new RoutingHeader();
    let r0 = request.parent;
    routing.add('parent', r0);
    routing.addTo(metadata);
    return new ProtoStream<RunQueryResponse>(
      this.#transport.serverStream(new RpcMethod('google.firestore.v1.Firestore', 'RunQuery'), RunQueryRequest.of(request).protoView, metadata),
      (view) => new RunQueryResponse(view)
    );
  }

  /** Executes a pipeline query. */
  executePipeline(request: ExecutePipelineRequestInit): ProtoStream<ExecutePipelineResponse> {
    let metadata = new RpcMetadata();
    let routing = new RoutingHeader();
    let r0 = request.database;
    routing.match('project_id', 'projects/{project_id=*}/**', r0);
    let r1 = request.database;
    routing.match('database_id', 'projects/*/databases/{database_id=*}/**', r1);
    routing.addTo(metadata);
    return new ProtoStream<ExecutePipelineResponse>(
      this.#transport.serverStream(new RpcMethod('google.firestore.v1.Firestore', 'ExecutePipeline'), ExecutePipelineRequest.of(request).protoView, metadata),
      (view) => new ExecutePipelineResponse(view)
    );
  }

  /**
   * Runs an aggregation query.
   *
   * Rather than producing [Document][google.firestore.v1.Document] results like
   * [Firestore.RunQuery][google.firestore.v1.Firestore.RunQuery], this API
   * allows running an aggregation to produce a series of
   * [AggregationResult][google.firestore.v1.AggregationResult] server-side.
   *
   * High-Level Example:
   *
   * ```
   * -- Return the number of documents in table given a filter.
   * SELECT COUNT(*) FROM ( SELECT * FROM k where a = true );
   * ```
   */
  runAggregationQuery(request: RunAggregationQueryRequestInit): ProtoStream<RunAggregationQueryResponse> {
    let metadata = new RpcMetadata();
    let routing = new RoutingHeader();
    let r0 = request.parent;
    routing.add('parent', r0);
    routing.addTo(metadata);
    return new ProtoStream<RunAggregationQueryResponse>(
      this.#transport.serverStream(new RpcMethod('google.firestore.v1.Firestore', 'RunAggregationQuery'), RunAggregationQueryRequest.of(request).protoView, metadata),
      (view) => new RunAggregationQueryResponse(view)
    );
  }

  /**
   * Partitions a query by returning partition cursors that can be used to run
   * the query in parallel. The returned partition cursors are split points that
   * can be used by RunQuery as starting/end points for the query results.
   */
  async partitionQuery(request: PartitionQueryRequestInit): Future<PartitionQueryResponse> {
    let metadata = new RpcMetadata();
    let routing = new RoutingHeader();
    let r0 = request.parent;
    routing.add('parent', r0);
    routing.addTo(metadata);
    let response = await this.#transport.unary(new RpcMethod('google.firestore.v1.Firestore', 'PartitionQuery'), PartitionQueryRequest.of(request).protoView, metadata);
    return new PartitionQueryResponse(response);
  }

  /** Lists all the collection IDs underneath a document. */
  async listCollectionIds(request: ListCollectionIdsRequestInit): Future<ListCollectionIdsResponse> {
    let metadata = new RpcMetadata();
    let routing = new RoutingHeader();
    let r0 = request.parent;
    routing.add('parent', r0);
    routing.addTo(metadata);
    let response = await this.#transport.unary(new RpcMethod('google.firestore.v1.Firestore', 'ListCollectionIds'), ListCollectionIdsRequest.of(request).protoView, metadata);
    return new ListCollectionIdsResponse(response);
  }

  /**
   * Applies a batch of write operations.
   *
   * The BatchWrite method does not apply the write operations atomically
   * and can apply them out of order. Method does not allow more than one write
   * per document. Each write succeeds or fails independently. See the
   * [BatchWriteResponse][google.firestore.v1.BatchWriteResponse] for the
   * success status of each write.
   *
   * If you require an atomically applied set of writes, use
   * [Commit][google.firestore.v1.Firestore.Commit] instead.
   */
  async batchWrite(request: BatchWriteRequestInit): Future<BatchWriteResponse> {
    let metadata = new RpcMetadata();
    let routing = new RoutingHeader();
    let r0 = request.database;
    routing.add('database', r0);
    routing.addTo(metadata);
    let response = await this.#transport.unary(new RpcMethod('google.firestore.v1.Firestore', 'BatchWrite'), BatchWriteRequest.of(request).protoView, metadata);
    return new BatchWriteResponse(response);
  }

  /** Creates a new document. */
  async createDocument(request: CreateDocumentRequestInit): Future<Document> {
    let metadata = new RpcMetadata();
    let routing = new RoutingHeader();
    let r0 = request.parent;
    routing.add('parent', r0);
    let r1 = request.collectionId;
    routing.add('collection_id', r1);
    routing.addTo(metadata);
    let response = await this.#transport.unary(new RpcMethod('google.firestore.v1.Firestore', 'CreateDocument'), CreateDocumentRequest.of(request).protoView, metadata);
    return new Document(response);
  }
}
  • protobuf protobuf.zena-lang.pkg.zena-lang.dev ~0.0.1-preview.1
VersionPublishedDependenciesApproved by
0.0.1-preview.1 2026-11-19
  • protobuf protobuf.zena-lang.pkg.zena-lang.dev ~0.0.1-preview.1